0

When I try to use a gameObject, thats outside the "OnCollisionEnter" function it says "Object reference not set to an instance of an object"

private void OnCollisionEnter(Collision other) 
{
    if(other.gameObject.tag == "Finish")
    {
        //temporary object (created outside the function)
        tempGO = other.gameObject;
        Instantiate(particles, transform.position, Quaternion.identity);

        if(GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Gun>().fn90)
        {
            tempGO.GetComponent<Health>().Dmg(3);
        }
        else if(!GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Gun>().fn90)
        {
            tempGO.GetComponent<Health>().Dmg(10);
        }

        tempGO = null;
        Destroy(gameObject);
    }
}

There is an error on 20th line (first if, the script couldnt find the "other.gameObject")

  • An unusual way yo get the camera object. Normally Camera.main.gameObject would work – BugFinder Aug 01 '23 at 07:09
  • can you open the console(CTRL + Shift + C).., it may be easier o pinpoint where the null ref coming from – Hikari Aug 01 '23 at 07:10
  • are you sure particles is assigned? – BugFinder Aug 01 '23 at 07:22
  • btw your `else if(!GameObject.FindGameObjectWithTag("MainCamera").GetComponent().fn90)` could simply be `else`. You could even simplify it further using a ternary `tempGO.GetComponent().Dmg(Camera.main.GetComponent().fn90 ? 3 : 10);` – derHugo Aug 01 '23 at 08:06

0 Answers0