Don't know how to get enemy's health

前端 未结 3 1780
遇见更好的自我
遇见更好的自我 2021-01-07 02:49

I have this code and I don\'t know why hit.collider.gameObject.GetComponent(\"health\") is returning null

void Shoot() {
        Vector2 mousePo         


        
3条回答
  •  一生所求
    2021-01-07 03:08

    You need to get a reference to the script attached to the Enemy. Then use that script to manipulate the health.

    Find the GameObject.

     GameObject g = hit.collider.gameObject;
    

    Get the reference to the script.

     EnemyAI e = g.GetComponent();
    

    Manipulate the health.

     e.health = 0f;
    

    In one line if you want to be badass.

     hit.collider.gameObject.GetComponent().health = 0.0f;
    

    Bonus tip: health should be private and EnemyAI should have a setter and a getter for that variable.

提交回复
热议问题