get a variable through GetComponent

hey everyone, my problem is the following: i want several scripts to have a variable that has the same value in every script, and if the variable changes in game i need them all to change. looking for a way to do this i stumbled upon SendMessage and GetComponent. The option that was aparentaly better to use the GetComponent method so i wrote the following peice of script

void Update () {
	//Get Mineral Amount
		minerals = nexusScript.GetComponent<nexus>().minerals;
		energy = nexusScript.GetComponent<nexus>().energy;	

}

in the script called nexus there is a variable named minerals and an other one named energy. but i get the following warnung message:

NullReferenceException: Object reference not set to an instance of an object
place_stuff.Update () (at Assets/Scripts/place_stuff.cs:32)

(in line 32 of place stuff is the minerals portion of the code above)
and i dont recieve a message for the energy one. ts most likely a noob mistake so hope you guys can help ty.

1 Answer

1

It is hard to give an exact answer given such a small amount of your code. You are getting the null reference exception because either 1) nexusScript is not initialized to a game object, or 2) the game object nexusScript is initialized to does not have a ‘nexus’ script attached.

As for your problem of modifying a variable in multiple different scripts to match some value, since you are using C#, you can use events and delegates to solve it. It is a bit more advance topic, but if you take the time with the following video, you should be able to use them:

http://www.youtube.com/watch?v=N2zdwKIsXJs

If all the variables are in the same script (but attached to multiple game objects), and if the variable must be the same for all the gameObjects, consider using a ‘static’ variable. Variables declared static share a single value among all instances of that class. There are certain “evils” that can come from using static variables, but your problem might be a good place to use them.

thank you it was realy healpful, its awesome how there are so many people in the comunity who are willing to share their kniledge.

–