Calling a function from a child GO

I know this is documented in the scripting tutorial but it’s not quite working out for me…

I have a Player GO that has a child GO “Spells” which has a child “Shield”. Player has a controller script containing:

if (Input.GetKeyDown(“e”)) {
transform.Find(“Shield”).GetComponent(CastShield).CastShield(“test”);
}

Shield has a script “CastShield.js” that has

function CastShield(jibber : String) {
print(“jibber”);
}

When “e” is pressed I get a Null Reference Exception on my transform line of my player controller.

HalP?

Also while im on the subject is this a good way to handle OO workflow in unity or can I access parent/child scripts in a different manner?

still looking for help on this

One way to do this is:

var cs : CastShield = GetComponentInChildren(CastShield);
cs.CastShield(“kerpow”);

You might have an issue if the component you’re trying to find is more than one level below since I’m pretty sure GetComponentInChildren is not recursive (which is lame.) Having a function name the same as the script name is also risky.

You could also experiment with the message sending system:

BroadcastMessage(“CastShield”, “kerpow”);

You’re searching for a child object named “Shield” directly under your parent object… when in fact, its two children deep. Your code should look like this…

if (Input.GetKeyDown("e")) {
transform.Find("Spells/Shield").GetComponent(CastShield).CastShield("test");
}

thanks for the replies. Find(“”) as I understand looks in the entire scene for the GameObject so I dont think it would make any difference using Spells/Shield. I’ll try both, thanks.

There’s a difference between GameObject.Find and transform.Find.

–Eric

Since you are using transform.Find and GetComponent every time anyway (and not storing a reference to the component somewhere), I suggest using BroadcastMessage instead. The performance will not be that different anyway, and your code will be simpler and more flexible.

Well, this is more of a relationship or association issue than an object oriented issue.
Regarding your OO question, if you have patterns that you’re used to in more familiar Objected Oriented languages like Java or C++, I’d recommend switching your scripting over to C#. The syntax is mostly like Java and everything from implementing interfaces to inheritance is done in a more familiar way. This Allowed me to design my interfaces and classes as I would in any other language/framework without worrying about how you emulate the concepts in JavaScript.
Makes for good encapsulation, reusability and decoupling.
However, there are probably more examples to get you started that are written in JavaScript.