- Home /
Invoking a function in multiple scripts...
Hi. If I have several instances of an object/script, how can I invoke a function in all of them (for example, each instance of Script A has variable B in it, each variable B has a different value, but I want to subtract 1 from every variable B)? I know that static functions cannot reference instance data (like variables that would have different values ...right?). Is there a way to work around this?
I'm confused. Do you think you could elaborate a bit?
Can you clarify ... do you have a Script A attached to multiple objects and what you are asking is for a function in the script to be executed once for each instance of the Script found in each of the objects that has it attached?
Answer by AchillesWF · Apr 25, 2012 at 04:18 AM
You could have all your objects with Script A be children of a single global game object and then send that global game object a BroadcastMessage indicating a Method in Script A that subtracts 1 from variable B.
http://unity3d.com/support/documentation/ScriptReference/GameObject.BroadcastMessage.html
Of, you could just use GameObject.FindGameObjectWithTag() and have tagged all the objects with Scipt As. Then, loop through the results and SendMessage() to them to call the Method subtracting 1 from variable B.
http://unity3d.com/support/documentation/ScriptReference/GameObject.FindGameObjectsWithTag.html
Thanks for the reply. $$anonymous$$y code has gotten more complex that just subtracting a value from a variable. I put everything in Script A that I want to invoke in function "Level". When I try to send the message, I get this error "GameObject.FindGameObjectsWithTag("Tiles").Send$$anonymous$$essage("Level");" What am I missing?
Answer by Fabkins · Apr 25, 2012 at 04:19 AM
What you want to use is : gameObject.sendMessage()
Think it may do what what you need:
http://unity3d.com/support/documentation/ScriptReference/GameObject.SendMessage.html
Your answer
Follow this Question
Related Questions
Are there restrictions on assigning GameObjects to Prefab script variables? 3 Answers
How do I reassign the result of a function back to the original arguments? 3 Answers
Access to script global var's from a transform object? (specific ? on something that should work) 2 Answers
Increasing a score value? 2 Answers