- Home /
Accessing Multiple GameObjects' Script Functions
In my game, I have 4 cube Prefabs, each with the CubeMove.js script attatched. In the script there is a function called Move(), that I want to access from another script. So in the end I will have x number of Prefabbed (if that's a word...) cubes in the scene, and all of their Move() functions will react to a single call from another script. How would I do this? I tried using SendMessage, but nothing seemed to work. Maybe I'm just calling it in the wrong way?
Thanks in advance.
Answer by Statement · Mar 26, 2011 at 12:08 PM
See FindObjectsOfType, and take note about the warning of performance.
Please note that this function is very slow. It is not recommended to use this function every frame. In most cases you can use the singleton pattern instead.
function CallMoveOnAll ()
{
var cubeMoves : CubeMove[] = FindObjectsOfType(CubeMove) as CubeMove[];
for (var cubeMove : CubeMove in cubeMoves)
cubeMove.Move();
}
If you are certain you won't be adding more cubes runtime you could just cache the results of a find and work on that array instead of calling FindObjectsOfType every time you want to call Move.
Another solution would be to declare a static delegate which each script registers on.
Thank You so much! This script works perfectly in my game! Also thanks for quick answer :D
Your answer
