- Home /
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 http://answers.unity3d.com/questions/238135/null-reference-exception-confusion.html 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
Answer by Kiwasi · Oct 01, 2014 at 04:22 AM
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.
Your answer
Follow this Question
Related Questions
Instance of a object error after player death 0 Answers
I want some gameobjects are all unactive! 1 Answer
What do the "active" and "static" checkboxes do? 1 Answer
NullReference when accessing GameObject in array (C#) 1 Answer
Deactivate an object - and all scripts in that object deactivated? 1 Answer