FindObjectsOfType troubles.

Hiya,

Sorry if this is an obvious question. I’ve tried various searches for FindObjectsOfType (which I think is what I need) but nothing I’ve found cleared the issue up for me.

I’m trying to send a message to ALL objects of a certain type in a scene. I’ve been using the code below to send the message to ONE instance of the Object, but when I make duplicates it only sends the message to the first one it finds (I guess…)

GameObject.Find("My_GameObject").GetComponent("My_Script").SendMessage("My_Function");

I need to send the message to ALL instances of the object. I figure this has something to do with FindObjectsOfType but I’ve got no idea how to use it. I couldn’t really decipher the Script Reference entry for it either… I’m a total coding noob.
Any help greatly appreciated!

Translating the example on the reference page for your specific page gives:

// find all scripts of type "My_Script"
allScripts = FindObjectsOfType(My_Script);

// Go over all the scripts
for (var script : My_Script in allScripts)
{
    // and call "My_Function" on them
    script.My_Function();
}

Note that because you know the type of script, you don’t need to use SendMessage. You can call the function directly.

(disclaimer: I did not test the code at all, so it may contain typos, etc…)

Great, thanks Tom!