- Home /
Using GameObject.Find with hierarchies in cSharp
Using Unity 3.5.0b6 I have a game character GameObject called Player001Character, it has a child GameObject called TrackPlayer. If I use this code :
GameObject getTrackPlayer = GameObject.Find("/Player001Character/TrackPlayer");
It runs, but never finds TrackPlayer. For example, if I use this code :
getTrackPlayer.name = "New name";
I get an error message
NullReferenceException
How do I get the GameObject TrackPlayer if it is within a hierarchy (in the Hierarchy pane) ?
I've been to pages like this, which look like I'm doing it right : http://unity3d.com/support/documentation/ScriptReference/GameObject.Find.html?from=index
Answer by GameFreak · Mar 15, 2012 at 09:30 PM
Do This.
Add a tag to TackPlayer
http://unity3d.com/support/documentation/Components/Tags.html. Here is how to do that though I am sure you know.
Then use
GameObject getPlayerTrack= GameObject.FindWithTag("TrackPlayer");
Hope it helps
Thanks, I was trying to do it through a script which I found out wasn't picking up child gameobject ! Reading around, it seems I may have to add a tag anyhow to identify child - Tag all your children lol
Answer by DaveA · Mar 15, 2012 at 09:25 PM
This may be a dumb question, but you are sure that Player001Character is in the root of the scene, yes?
I would get into the debugger and make sure that GameObject.Find("/Player001Character") returns what you want, that it's transform has children, and that one of them is called "TrackPlayer", see what clues you get doing that.
yes, it all works until I save all gameobjects, then load the scene. I think it has to do with the code which looks at the TrackPlayer being executed before TrackPlayer is added to the scene.
I got it working, I added a yield command in my load script to ensure that all objects were loaded
Your answer
Follow this Question
Related Questions
Using Empty GameObjects to organize hierarchy? 2 Answers
Selecting transform in FBX hierarchy csharp script 1 Answer
Grouping objects without overhead? 1 Answer
Best workflow for DontDestroyOnLoad method regarding Unity Editor? 1 Answer
create a destroyer for 2d infinite runner game objects. 2 Answers