Don't know how to get enemy's health

前端 未结 3 1781
遇见更好的自我
遇见更好的自我 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:19

    However you would have to get the reference of the script that is attached to the GameObject. To do this you would need to use the following code.

    GameObject target;
    

    Then in your shoot method you update the reference to the target.

    if(hit.collider.gameObject != target) 
    {
        target = hit.collider.gameObject.GetComponent();
    }
    

    The reaason I put an if() statement around it is so that you're not overloading the CPU with GetComponent requests if the target hasn't already changed.

    From here you would simply change the value by using things such as

    target.value = newValue;
    target.SomeFunction();
    

提交回复
热议问题