从另一个脚本销毁gameObject

时间:2020-07-06 23:06:08

标签: c# unity3d

我在尝试使用脚本1 中的脚本2 销毁敌人游戏对象时遇到麻烦,是包含常见敌人数据的脚本。

脚本1

public class BaseEnemy : MonoBehaviour
{
    [SerializeField]
    public int health = 4;
    public int speed = 0;
 
    public void TakeDamage(int damage)
    {
        health -= damage;
        Debug.Log("Damage Taken");
       
        if (health <= 0)
        {
            Destroy(??);
        }
    }
}

脚本2

public class EnemyPlayerFollow : BaseEnemy
{
 
    public Transform player;
    private Rigidbody2D rb;
    private Vector2 movement;
 
    void Start()
    {
        rb = this.GetComponent<Rigidbody2D>();
    }
 
    void Update()
    {
        Vector3 direction = player.position - transform.position;
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
        rb.rotation = angle;
        direction.Normalize();
        movement = direction;
 
        //if (health <= 0)
        //{
        //    Destroy(gameObject);
        //}
    }
 
    private void FixedUpdate()
    {
        moveCharacter(movement);
    }
 
    //public void TakeDamage(int damage)
    //{
    //    health -= damage;
    //    Debug.Log("Damage Taken");
    //}
 
    void moveCharacter(Vector2 direction)
    {
        rb.MovePosition((Vector2)transform.position + (direction * speed * Time.deltaTime));
    }
}

我想知道的是,当健康状况<= 0时,如何修改脚本1 以销毁脚本2 (基本上放在此处-> ??)

1 个答案:

答案 0 :(得分:0)

答案:

很容易销毁(this.gameObject);在脚本1上 感谢“纪事报”的指导。