- Home /
access GameObject only when instantiated
Hi, Im using a GetComponent and it is giving me a null reference because the object has not been instantiated. I tried this
if (GameObject.Find("MyObject")){
GameObject go = GameObject.Find ("MyObject");
MyScript myScript = (MyScript)go.GetComponent (typeof(MyScript));
}
and it works but then Id have to include the functions with the variables from the other script into this and that would result in a super complicated and ugly code.
I could also do something like this
if (GameObject.FindWithTag("MyObject") == null) {}
but how would I make the function stop until the GameObject is found? Thanks.
Answer by jann1 · Apr 11, 2014 at 04:31 PM
Hi again, I found out this wasnt working because I was using the Update function, which cannot be blocked. So I created a new function which contains the code I want to execute, only when four different GameObjects are found. My thought was to do it like this:
if (GameObject.FindWithTag ("Object1") && GameObject.FindWithTag ("Object2") && GameObject.FindWithTag ("Object3") && GameObject.FindWithTag ("Object4"))
and then call the function. This looks strange and is also not working. How would I make this work?
All right I solved it! It turned out that I used Find ("Object1") in a place even though they were created as Object1(clone). I changed it to FindWithTag and it worked like a charm.
Your answer
Follow this Question
Related Questions
Dictionary Function not responding to Key Calls 0 Answers
Best practice handling deleted object refences during SceneManager.LoadScene 0 Answers
Problem with checking if null 1 Answer
How do I nullreference this correctly? 1 Answer
NullReferenceException: Object reference not set to an instance of an object 1 Answer