How to use if statement properly

This is a script to set an object to true if a script from another game object is false. The error comes in the line with "if ( " and the error is a null reference exception.

function Update(){
    if (
    (GameObject.FindWithTag("coin").GetComponent("Destroy")as MonoBehaviour).enabled == false
    	)
    	{
    	GameObject.FindWithTag("gameoverbg").SetActive (true);
    	}

}

I looked through this post Null Reference Exception confusion - Unity Answers and couldn’t find an answer. There IS a gameobject with the tag cointop, and there is a script attached to it in the inspector called Destroy.

Theory: There might be an issue with having the objects turning false at almost the same time as the gameoverbg is being set to active. If you think that might be an issue, let me know what i can use to get this working

Thanks

Try: if (!GameObject.FindWithTag("coin").GetComponent(Destroy).enabled)

nope, that nullrefernceexception is still alive and annoying

1 Answer

1

Your null reference will be appearing because FindWithTag only gets active GameObjects. So it will always be null with your set up.

Here are some ways around the problem.

  • Don’t disable your GameObject, just disable all the components on it
  • Assign a reference to the GameObject via the inspector. Use that.
  • Get a reference to the GameObject before it is disabled. In one of my projects every GameObject spends one frame active at the start of the scene. This allows the references I need to be set up via script using Find.