- Home /
AddComponent with exposed
When I want to add a new script to a GameObject I do:
var newGO = new GameObject("new name");
var thisInstance = newGO.AddComponent(MyScriptName);
But if MyScriptName has public/exposed parameters (the ones that appear in the Inspector window), how can I tell AddComponent their values?
Thanks
Answer by Muuskii · Aug 19, 2012 at 08:35 PM
Usually I have to set the variables manually:
var newGO = new GameObject("new name");
var thisInstance = newGO.AddComponent(MyScriptName);
thisInstance.somePubVar = myValue;
If you have a ton of variables to set, it's probably better off to setup a public function that you pass all the values to. This is great for many reasons; You won't forget how many varibles need to be set because the prototype will remind you. And you can setup tests in the function to see if the values make sense.
Also, it let's you set private values.
$$anonymous$$onoDev Editor didn't show up my component's public variables in the auto-complete list, so I never thought that was possible that way. Its strange how the auto-complete list is missing some stuff like most of local variables I have defined he doesn't show them up so I end up writting them all over again each time I use them. $$anonymous$$aybe I have it bad configured.
Thanks $$anonymous$$usskii! :)
Unity told me that my variables weren't members of "thisInstance", so I needed to make this cast:
var thisInstance = newGO.AddComponent($$anonymous$$yScriptName) as $$anonymous$$yScriptName;
thisInstance.somePubVar = myValue;
Ah, yeah I always forget that you have to cast when getting a script.
Btw when $$anonymous$$onodevelop isn't completing variables for me, it's usually a sign that I forgot to make them public or that script hasn't compiled yet.
$$anonymous$$ake sure to fix all errors in the script you're accessing and them try again.