- Home /
How to add new instance of a script to a game object?
I'm trying to have separate instances of a script called HealthScaling so that each player has its own health, and they're not all updating the same hp, which is my current problem. I thought the solution was for me to use the Instantiate(HealthScaling), set that to a variable name, and then add that variable name as a component. AddComponent() doesn't like that however. So I tried gameObject.AddComponent(HealthScaling), but then my script went a little wack when I test ran the game. How should I make a new instance of a script and attach it to a game object? *Variables have all been declared beforehand.
First try
hpScript = Instantiate(HealthScaling);
hpBar.AddComponent(hpScript);
Second try
hpScript = hpBar.AddComponent("HealthScaling") as HealthScaling;
Answer by sabliao · Oct 03, 2011 at 08:34 PM
Nevermind, I realized my problem was that, in an attempt to make it easier for another script to access the variable, I made hp static, which meant all instances of HealthScaling would share that variable. Now I just have to figure out how to pass that hp variable to my second script in another way...
Answer by aldonaletto · Oct 03, 2011 at 08:35 PM
When you instantiate a prefab, it comes with its own script instances. The same occurs when you add a script via AddComponent - its a whole new instance. Your problem seems to be another thing: probably the health variable is declared as static. Static variables are created only once, and no matter how many different instances of the script are running, all of them will read and write the same variable.
To avoid this problem you could remove the static declaration from the variable declaration - but since static variables are referenced as ScriptName.VariableName, all scripts accessing them should be modified to use that boring GetComponent method.
haha, yeah, I figured it out a couple $$anonymous$$utes later, but thanks for responding anyway. (:
I just spent forever looking at why a variable wasn't updating and I had forgotten about it being static until i read this. Thanks :)