- Home /
is this correct way to change var from other script?
Hello, is this correct way to change var from other script?
//Health.js
static var lives : int =10;
Then, in other script:
//Enemy.js
Health.lives -= 1;
-Thanks
He doesn't have to use PlayerPref.
PlayerPref is used to "save".
If he doesn't want to save his data to be persistent between play sessions then he doesn't need it.
You might want to use GameObject.GetComponent
Very generally, never use static
It is very confusing to new programmers. Just don't use it.
Answer by oferei · Sep 03, 2013 at 12:27 PM
Technically, yes, that would work - if you're working with static variables. But the power of object-oriented programming comes from instantiation (having multiple copies of the class in memory.)
By creating a Health.js script you actually defined a class called Health which extends MonoBehaviour. In your example it has a static variable, lives. To work with instances you should:
Remove the static keyword
Add the public keyword instead, so it is accessible from other classes
Instantiate the class by attaching the script to a game object in the scene
Now, in order to access lives you need to have a reference to the game object. For example, let's say you attached the script to the object Enemy. There are various ways to get a reference to this object. You can set it up in advance by adding a public variable (of type Health) to the calling script and drag-and-dropping the Enemy object to it. Or you can get a reference during gameplay, for example in a collision between a weapon and the Enemy game object. You can find it by name, etc.
Once you have a reference to the game object, call that object's GetComponent method:
var enemyHealth : Health = enemyGameObject.GetComponent(Health);
enemyHealth.lives -= 1;
There, done.
Now to make things a little more complicated, you could leave the lives variable private and instead add a public method that would access it, for example, DoDamage. This method could decrease lives by one, and any other script can call DoDamage:
var enemyHealth : Health = enemyGameObject.GetComponent(Health);
enemyHealth.DoDamage();
This is better because it encapsulates the inner works of the Health class - nobody needs to know how to handle lives or what to do when it reaches zero. You also get the benefit of using Unity methods such as SendMessage, SendMessageUpwards and BroadcastMessage, which call a game object's method by name, without needing to know which class. For example:
enemyGameObject.SendMessage("DoDamage");
Note that these methods are easy to use, but are slightly slower.