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

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:

  1. Remove the static keyword
  2. Add the public keyword instead, so it is accessible from other classes
  3. 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.