How to run a script in an instantiated object?
Hi guys,
I'm trying to call a script on a SceneObject which has been instantiated from a prefab. I would have expected something like the below to work, but I'm having no luck.. Any help would be super appreciated!
//script 1 - instantiate box prefab and try to call a script on it
var p1 = script.boxPrefab.instantiate(script.getSceneObject());
var cs = p1.getAllComponents();
for (var i = 0; i < cs.length; i++) {
if (sc.api.Init) {
sc.api.Init(groupID);
}
}
//script 2 - on boxPrefab
script.api.Init = function (groupID) {
print("Box.Init with groupID = " + groupID);
}
Thanks,
Isaac
Hey Isaac,
This is happening because the instantiated script hasn't run yet at this point - it will likely execute on the next frame. What you can do is leave some information in the instantiated object's api that it can access when it executes. Here's a way to do that using a callback function:
But you can also do it in a more simple way, like the first script just leaves information that the second script uses.
Hope this helps, let me know if you have any more questions!
Jacob
Hi Jacob, that was most helpful! Many thanks and glad to know you're hovering around the support forums. :)
Many thanks,
Isaac