我在unity5中的enemyDamage脚本出现了问题,当我播放它并坚持与敌人在一起时,我立即死亡,即使敌人的伤害是10,我的生命值是100
好了,这是我第一次把这个东西统一起来,希望你能帮助我:
下面是我的代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemydmg : MonoBehaviour {
public float damage;
public float damagerate;
public float pushbackforce;
float nextdamage;
bool playerInRange = false;
GameObject theplayer;
playerHealth theplayerhealth;
// Use this for initialization
void Start () {
nextdamage = Time.time;
theplayer = GameObject.FindGameObjectWithTag ("Player");
theplayerhealth = theplayer.GetComponent<playerHealth> ();
}
// Update is called once per frame
void Update () {
if (playerInRange)
Attack ();
}
void OnTriggerEnter (Collider other)
{
if (other.tag == "Player")
{
playerInRange = true;
}
}
void OnTriggerExit (Collider other)
{
if (other.tag == "Player")
{
playerInRange = false;
}
}
void Attack()
{
if (nextdamage <= Time.time)
{
theplayerhealth.addDamage(damage);
nextdamage = Time.time + damagerate;
pushback (theplayer.transform);
}
}
void pushback(Transform pushObject)
{
Vector3 pushDirection = new Vector3 (0, (pushObject.position.y - transform.position.y), 0).normalized;
pushDirection *= pushbackforce;
Rigidbody pushedRB = pushObject.GetComponent<Rigidbody> ();
pushedRB.velocity = Vector3.zero;
pushedRB.AddForce (pushDirection, ForceMode.Impulse);
}
}这是我的球员健康
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerHealth : MonoBehaviour {
public float fullhealth;
float currentHealth;
// Use this for initialization
void Start () {
currentHealth = fullhealth;
}
// Update is called once per frame
void Update () {
}
public void addDamage(float damage)
{
currentHealth -= damage;
if (currentHealth <= 0) {
makeDead ();
}
}
public void makeDead()
{
Destroy (gameObject);
}
}发布于 2018-11-03 11:02:55
theplayerhealth = theplayer.GetComponent<playerHealth> ();我认为这行代码让您失望了,因为播放器是一个GameObject。播放器健康已经或应该已经在您的其他脚本中初始化。我认为你可以用一种更好的方式来处理多态性。
public class enemydmg : playerHealth{
}这将允许您直接从playerHealth脚本继承所需的所有内容,而不必获取额外的组件。您也可以在将来的其他脚本中使用此技术。
另一种可以使用的方法是直接调用您的类:
playerHealth.addDamage(damage);从现在开始,当你命名你的脚本时,使用大写。PlayerHealth、EnemyDamage等当你做这样的事情时,这只是一个让你的代码看起来更干净的专业技巧。(可选)
https://stackoverflow.com/questions/45533033
复制相似问题