I need to pass a parameter to an instantiated object but can’t do the usual: instantiate, get script from within object, set value.
The reason is; say I have 100 prefabs in the resource directory i want to instantiate each one in a loop then pass a value to each one. Each prefab has a different script attached so I can’t just exctract the script. Here is my code if that helps to give an idea why I can’t do it the usual way.
some prefabs share a script so once again the script can’t contain the variable already set up.
I just need to pass a parameter to unknown instantiated objects. There has to be a way.
for(i = 0; i < MAXBADTYPES; i++) /* go through each baddie type */
{
baddie = Instantiate(Resources.Load(baddies[i].Name), baddies[i].StartPos, Quaternion.identity) as GameObject;
// Pass a value to the object here!!//
}
it may be not best perf wise , but a simple way would be to have a identical function on your insatnce script, let say “Init” and use SendMessage fct in unity, doing so it doesnt matter what component the instance have, as long the named fct is found, it will execute
so something like
myInstance*.SendMessage(“Init”, paramters, SendMessageOptions.DontRequireReceivers);* at last untill you find clever way that will work after you could use an abstract class to encapsulate the script need to be set, those script will inherit from your abstract class and you can then access to the fct you implement in it, well only if you are using C#…
I’ve just used Broadcastmessage which seems to do the same job as you suggested. Both are a bit bad IMO. The instantiate function really should have a way to pass a parameter block to it on creation.
well you dont use constructor when using mono behavior tho…so hmm either you set your stuff in startfct of your instance or after you are left with abstract class , interface or hmm event stuff…or make a dedicated manager component that access to all your component, and from here set value on whatever you need ^^