x


Can't access public variables from a script on a different object

I have 2 objects, a gun and an ammo counter. The gun object has a public variable called "ammo" with a value of 10. On the ammo counter, I have this script:

var gunObject:GameObject;
gunObject = GameObject.Find("gun");

var ammo = gunObject.GetComponent(gunScript).ammo;

function Update () {
    guiText.text = "Ammo " + ammo;
}

This, however, doesn't seem to want to work. It always gives me an error saying

"NullReferenceException: Object reference not set to an instance of an object"

Anybody know what could be going wrong?

more ▼

asked Apr 02 '11 at 08:28 PM

billymcguffin gravatar image

billymcguffin
3 2 2 3

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

2 answers: sort voted first

Put the "gunObject = GameObject.Find("gun");" line inside a Start function. Only declare variables outside functions, never put any code that "does stuff" outside. The "var ammo = gunObject.GetComponent(gunScript).ammo;" line should be inside Update. Otherwise it would be set once and would never change.

Actually, the best way is not to use Update anyway. Just change the guiText.text when the ammo actually changes, that way you won't waste CPU cycles checking every frame for no reason. So you'd want to get a reference to the GUIText object from your ammo script, instead of the other way around.

more ▼

answered Apr 02 '11 at 08:51 PM

Eric5h5 gravatar image

Eric5h5
80.3k 42 132 521

I'm still learning :)

Apr 02 '11 at 08:55 PM Scribe

Thanks for the answer. Your solution sounds quite a bit better than mine. Solved.

Apr 02 '11 at 09:02 PM billymcguffin
(comments are locked)
10|3000 characters needed characters left

I think you need to add "" to this line:

var ammo = gunObject.GetComponent(gunScript).ammo;

should be

var ammo = gunObject.GetComponent("gunScript").ammo;

hopefully this helps but not totally sure

Scribe

more ▼

answered Apr 02 '11 at 08:39 PM

Scribe gravatar image

Scribe
1.4k 12 16 34

That doesn't work :/ Thanks for the suggestion though.

Apr 02 '11 at 08:41 PM billymcguffin

No, you should not add quotes. That makes it slower and makes any errors happen at runtime instead of compile-time, which is bad.

Apr 02 '11 at 08:47 PM Eric5h5

I didn't know that. Thanks. I still don't have a solution, however.

Apr 02 '11 at 08:48 PM billymcguffin
(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:

x1949
x822
x74

asked: Apr 02 '11 at 08:28 PM

Seen: 1462 times

Last Updated: Apr 02 '11 at 08:28 PM