Scripts on GameObjects

I just wanted to know. If I make one script, lets say for Machine Guns and I have multiple variations of machine guns, can I apply that machine gun script to each machine gun and change some variables on only that gun in each instance? Or will it change that variable for all guns with the Machine gun script?

I guess what I'm trying to say is that when you apply a script to a GameObject, does it act as an instance of the original script, or is everything mirroring the original script.

I hope this makes since.

A script attached to a game object is an instance and has its own variables.

At run-time, Unity will create separate instances of the script class for each GameObject which you attach the script to.

At design-time, if your script has public member variables, you can modify those values in the script component UI in the inspector panel.

Attach this little `JavaScript` to three different `GameObject` and check your `Console` log.

var gunID: int = 0;
var bullets: int = 8;

function Start() {
    gunID = Random.Range(0, 10);
    bullets = Random.Range(8, 32);
}

function Update () {
    Debug.Log(gunID + ": " + bullets);
}

You'll notice that it's printing out 3 different value pairs and you can also change these values during run-time, simply by selecting the Object and edit the value from the Inspector.

More from Unify Community Wiki:

Each .js File Implements A Class (By Default)

It's important to understand that when you write a behavior script in JavaScript you are actually writing a class implementation, where:

  1. The name of the class is the name of the script file (so if it's foo.js you can instance it elsewhere by saying `var x = new foo()`).

  2. Certain "magic" method names will in fact implement event handlers (e.g. `Start()`, `FixedUpdate()` etc.). In any event, a function declaration is a method of the class you've written.

  3. Code written outside function definitions inside your file are executing in the class's body. Variables declared in it are members of the class.
  4. static functions and variables in a class are, in essence, class functions and variables.