Unity:进入播放模式时,对象上的脚本消失

时间:2017-07-21 19:34:41

标签: c# unity3d

我将Zombie预制件附加到Zombie对象上;但是,当我按下Play时,脚本会在Zombie对象上消失。当我按播放时,如何确保脚本保留在对象上?

我声明了我的变量并对其进行了初始化。我知道这是基本的,但你的帮助将不胜感激!

public class PlayerLifeCollider : MonoBehaviour {

    public Zombie zombie; //declared
    public float damage = 1;

    public void Start()
    {
        zombie = GetComponent<Zombie>(); //instantiated
    }

    private void Update()
    {
        zombie.DamagePlayer(damage); //**Null error here**
    }   
}
public class Zombie : MonoBehaviour
{
    public int currentHealth;
    private Player player;
    private PlayerLifeCollider playerCollider;
    public int damage;

    public void Start()
    {
        playerCollider = GetComponent<PlayerLifeCollider>();
    }

    public void Damage(int damageAmount)
    {
        currentHealth -= damageAmount;
        if (currentHealth <= 0)
        {
            playerCollider.ObjectsInRange.Remove(gameObject);
            gameObject.SetActive(false);
        }

    }

   public void DamagePlayer(float damage)
    {
         player.Life(damage);
    }
}
public class Player : MonoBehaviour {

public float playerLife = 100;

public void Life (float damage)
    {
        playerLife -= damage;
        if (playerLife <=0)
        {
            playerLife = 100;
            SceneManager.LoadScene(2);
        }
}

Before Zombie Attached

After Zombie Not Attached

1 个答案:

答案 0 :(得分:1)

这里的问题是你在运行时覆盖File.Exists(fileLocation)的值,导致它被替换为空值。代码:

zombie

尝试从父GameObject(PlayerLifeCollider)中检索public void Start() { zombie = GetComponent<Zombie>(); //instantiated } 脚本组件 - 但是PlayerLifeCollider上没有Zombie脚本!因此它返回null并将其分配给变量Zombie

因为您已经通过将它拖到检查器中的公共变量上而为zombie指定了值,所以您不需要在运行时为其分配值。您可以安全地删除此行,并保留该值。

希望这有帮助!如果您有任何问题,请告诉我。