x


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;

more ▼

asked Oct 03 '11 at 08:15 PM

sabliao gravatar image

sabliao
1 2 2 4

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

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...

more ▼

answered Oct 03 '11 at 08:34 PM

sabliao gravatar image

sabliao
1 2 2 4

(comments are locked)
10|3000 characters needed characters left

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.

more ▼

answered Oct 03 '11 at 08:35 PM

aldonaletto gravatar image

aldonaletto
41.4k 16 42 197

haha, yeah, I figured it out a couple minutes later, but thanks for responding anyway. (:

Oct 03 '11 at 08:54 PM sabliao

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 :)

Aug 26 '12 at 02:09 AM RackyMac
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x3325
x2083
x202
x80
x77

asked: Oct 03 '11 at 08:15 PM

Seen: 1458 times

Last Updated: Aug 26 '12 at 02:09 AM