Accessing game objects, that are part of another game object

Hey guys

I am quite new to Unity and after playing around with some stuff, I have a small problem. Let’s say I create an empty GameObject and add some objects to it. For example I can have a GameObject, or Prefab called PlayerCharacter, which contains 3 objects:

  • Model
  • SpellSpawnpoint
  • Camera

Now I add a script to PlayerCharacter, for example one creating spells. I need to access SpellSpawnpoint object to instantiate spell, but… how?

3 Answers

3

How about:

GameObject.GetComponentInChildren()

He's looking for the sub gameObject though, not the component. Although, my guess is that he's looking to ultimately end up at some component ;)

If he just wants to find the game object, how about: [Transform.Find()][1] [1]: http://docs.unity3d.com/Documentation/ScriptReference/Transform.Find.html

Which is another solution, but if I had to guess at the implementation of that method, it's searches the entire scene graph for it; albeit cleaner than mine, I'd be nervous about performance depending how the frequency in which it's called.

It does not search the entire scene. It's an instance, not a class method, so it only searches from the given transform.

Welcome to Unity.

So you’ve hit a part that, for whatever reason, is not built in! It sucks, I know. Here’s how you can work around it thoughL

GameObject player = GameObject.Find("PlayerCharacter");
GameObject spellSpawnPoint = null;

foreach(Transform subTransform in player.transform) {
   if(subTransform.gameObject.name == "SpellSpawnpoint") {
      spellSpawnPoint = subTransform.gameObject;
      break;
   }
}

It’s not pretty by any means, but it works.

When the object is a child you can use transform.Find(“”) instead of gameObject.Find(“”), it will look under the group automatically.