Invoking a function in every instance of a script?

Hello. When something in a script happens, I want to invoke a function that is in aother script attached to several objects.

Every instance of the the object “Test” has “ScriptA” attached to it, which has the function “Go”. But, when I press the button, none of the instances of the function Go, are invoked…why?

function Update () {
    if (Input.GetKeyDown ("w")){
         GameObject.Find("Test").GetComponent(ScriptA).Go();
    }
}

Thanks

GameObject is singular and the Go method is not part of GameObject. An event would be handy for this. Also, if they all do it on that keypress, why don’t they poll input?

Yah
I notice two things.
One that Find may only call the first object that is named test, not all. But since you say it calls none of them I think a few things…

  1. that I call other components, by having a var, to represent the script and the object that script is attached to. Do you have these?
  2. You may want to consider having a single manager that has a single script, containing the function Go(). This way it can handle instructing each of the children “test” to “Go”.

Store all instances in a List and iterate through it or, as JRavey suggested, use an event.

Finding the script instances every time ‘w’ is pressed is quite inefficient.

I personally would Tag your gameobjects then use “FindGameObjectsWithTag”.

Then just use SendMessage(“Go”). That is the simplest approach that doesn’t require a singleton or C# and Events.

Also look at “FindObjectsOfType”. But it is slow and not best used within an Update.

Cheers.

You should avoid using Find (of any variant) in Update!

Pretty sure that’s in the performance docs

Right, identify the objects and keep track of them. The more objects you have, the worse it is.

Simple? Yes. Efficient? Not at all. It’s slower than GetComponent.

And FindGameObjectsWithTag is fast? :wink:

Wasn’t talking about performance was I? I was answering his question with code that will work. Talking Lists, singletons, events is out of scope of the problem. Performance optimising comes with familiarity with the API and programming paradigms. Something you will not teach easily in posts like this. Especially when they post basic noob JS code like above. So I was trying to help them get something that works and then let them take it from there.

It doesn’t hurt to offer code that incorporates performance improvements

He might not know anything about performance, so telling him that he should avoid using Find in his update function will help on his path to enlightenment…

Use a static function.

Here’s an example:
http://www.jtadeo.com/unity3d/staticfunction/

Here’s a download link:
http://dl.dropbox.com/u/8737340/unity3d/StaticFunctionExample3ByJames.zip