Instance(?) problems

This is a REALLY dumb question.

So I made a script on a cube called Stats.js. Stats.js sets the stats for that “Creature” in the game.

#pragma strict


public var EnemyName = "Rat";
public var EnemyHealth = 10;
public var EnemyAttack = 5;
public var EnemyDefense = 0;
public var EnemyBurn = 0;
public var EnemyFreeze = 0;
public var EnemyShock = 0;

When you initiate a battle, it executes a script called EnemyFight.js. This script tries to reference the Stats.js variables

#pragma strict

if (Stats.EnemyName === "Rat"){

	print("My hand is a dolphin");

}

But I get an error that says “BCE0020: An instance of type ‘Stats’ is required to access non static member ‘EnemyName’.”

I’ve tried a lot of things.I’m not the sharpest tool in the shed so please babify the explanation if necessary.

The error is telling you that you’re trying to statically access the class member called “EnemyName”, but it can’t, because that variable is not marked static.

A static variable is one which does not require an instance of the object to be accessed; it is instead globally available and has but one value across the entire scope of the application. A typical example of a static variable (in this case a property) is Vector3.up. It requires no instance of the Vector3 type but is directly accessible and means (0,1,0) everywhere no matter where you call it.

An “object instance” is what you have whenever you create something with the “new” keyword. The “new” keyword invokes an object’s constructor and returns an instance of it based on the class’s definition. A class may thus be said to be a blueprint of the object. But in this particular case, “Stats” is a script, which just means it is an object of a type that inherits from MonoBehavior. MonoBehaviors are always attached to a GameObject in your scene. Unity takes care of instantiating the object for you in this case, so for scripts, you will never use the new keyword to create instances of them. Instead, you acquire a reference to the object using the GetComponent method:

Stats yourStatsScript = GetComponent<Stats>();

This line of code returns the Stats script if executed in a script that is attached to the same gameobject as the Stats script. If not, you must run GetComponent on a reference to the gameobject that has the Stats script.

Once you have the object reference, you can access the EnemyName through that instead:

if (yourStatsScript.EnemyName === "Rat"){ 
    print("My hand is a dolphin"); 
}

If, in the future, you truly wish for a class member to be static, you simply mark it with the static keyword:

public static var EnemyName = "Rat";

After this, it will be accessible the way you did in your script, that is, by writing “Stats.EnemyName”. But Stats appears to be something that is specific to the individual enemy type, so I’m guessing the EnemyName will not be the same for every instance of the Stats object. Therefore, it should not be static.