- Home /
GameObject.Find/WithTag returns null
I have a prefab called MapInfo, with a script attached, "MapInfo.cs". I also have a prefab called Data that I assign to a data prefab.
MapInfo.cs:
public GameObject data_prefab; //the prefab is assigned here through the inspector
void Start(){
DataInit();
}
void DataInit(){
Instantiate(data_prefab,Vector3.zero,Quaternion.identity);
}
This works just fine. Where the problem lies is in the script, Data.cs, that's attached to the data_prefab prefab.
Data.cs:
void Awake(){
GameObject go = GameObject.Find("MapInfo");
if(go==null) Debug.Log ("Can't find MapInfo");
}
When the data prefab is instantiated from MapInfo.cs in the DataInit function, its script tries to find the MapInfo GameObject that instantiated it, and it prints that Debug line every single time. Is it a mistake trying to find this GameObject? It must be in existence considering the Data script doesn't start without MapInfo creating it! I've tried FindWithTag as well with an appropriate tag assigned, no such luck. Has anyone else experienced this?
Is the GameObject ALSO named $$anonymous$$apInfo, cuz the GameObject.Find is looking for the GameObject name, not that of an attached script. As a side note, I find it a good habit to put references to other objects in Start() ins$$anonymous$$d of Awake() to avoid a racing condition. In the case of a parent/child instantiation it's not an issue, but just a good practice.
Yes, the GameObject is ALSO named $$anonymous$$apInfo (as well as the script), like I said. It's all over the documentation, that you should put references to other scripts in Awake().
(source: http://docs.unity3d.com/Documentation/ScriptReference/$$anonymous$$onoBehaviour.Awake.html)
Edit: Start vs. Awake shouldn't be the problem. I know that $$anonymous$$apInfo (the GameObject) exists when Data's awake function is called. If it makes any difference, changing Awake to Start in Data.cs didn't change anything.
I copied your code into a new scene and didn't get this behavior, the game object was found. Is it possible you are destroying the $$anonymous$$apInfo object somehow?
Take a screenshot of $$anonymous$$apInfo GameObject Inspector properties and post.
@callen, definitely not. @getyour411, http://imgur.com/$$anonymous$$TvUi0s
Answer by whydoidoit · Feb 14, 2014 at 07:07 AM
You are instantiating the MapInfo and so its name is not MapInfo it is MapInfo(Clone) (as you can see in your screenshot) - you should really find objects by type or use a singleton pattern to avoid any of the "finding" issues.
Ah, I see! Ok thanks, I've seen singleton patterns being used around the forums, I guess it's time I dug in. Thanks!
No problem. Tick the answer if it helps. Let me know if you want an example of singletons.