- Home /
Calling a function of another object's child?
I got an individual script attached to two different weapon-objects: weapon_1 and weapon_2. Both scripts have a different version of the same function called Fire(). Both are children of the parent-object: weapons.
Here's the problem: The fire-button is placed outside this hierarchy, but I want to be able to reach whatever weapon's script is active at a given time (either weapon_1 or weapon_2).
Since the name of the script varies depending on which weapon is active, I can't use the method of searching for the script's name:
var myWeapons : weapons = FindObjectOfType(weapons);
myWeapons.Fire();
Another method I tried was using the "BroadcastMessage", but since that only works for the object itself or its children, and in my case I want to reach it from outside the hierarchy, I tried this approach:
var weapons : GameObject;
...
weapons = GameObject.Find("weapons");
weapons.BroadcastMessage("Fire");
Unfortunately this won't work. It seems when using the "BroadcastMessage" on another object than the one making the call, the function skips checking the children of the targeted object.
So, is there another way of targeting the child of another object dynamically like in the second proposed but invalid method above?
Answer by Daniel 1 · Jul 14, 2010 at 01:01 AM
It appears the error was due to my own stupidity of having renamed the "weapons"-object without editing the second line in the second sample. Having done so the "BroadcastMessage" does indeed look for functions in the targeted object's children.