accessing a child

Really simple thing to do. Unity wont let me.

I have a game object with a light attached to it as a child as in:

Block
    Light

I want to attach a script to the light object using a script on the Block object. I put this in my script on the block object. Simple:

myLight.AddComponent(lightScript);

This does not work. The unity manual suggests I use Find object which is strange because I know the name of the object I'm trying to address. But okay here goes:

a = gameObject.Find("myLight")
a.AddComponent(lightScript);

This also does not work. The unity manual also says that I can "find child and parent objects to an existing object through the Transform component of a game object". Okay I'll try that:

a = transform.Find("myLight");
a.AddComponent(lightScript);

This also does not work. I am out of ideas. This should be easy.

1 Answer

1

You can only add components to game objects, not transforms...transforms are components themselves. So you'd use

a = transform.Find("myLight").gameObject;
a.AddComponent(NewBehaviourScript);

However,

a = gameObject.Find("myLight");
a.AddComponent(NewBehaviourScript);

works fine. You left a semicolon out of your code.