Read string from other script (C#)

I have one C# script named Anims and I have this public string:

public string CurrentWeapon = null;

In the update function, I have that string changed to different values like “Fists” and other things, on button down.

How would I go about checking if CurrentWeapon is equal to certain things, in a completely separate script? I’ve tried getcomponent and other ways but none have worked. This seems like it should be the simplest thing to do.

That’s because you may have many instances of the Anims script attached to different objects, thus you need a reference to the desired object (gameObject, transform, collider etc.) in order to get the right instance. The simplest way is to have a variable of type Anims (the script type) in each script that you want to access CurrentWeapon, and drag the object to which Anims is attached to them in the Inspector, like this:

public Anims animsScript; // drag the Anims owner object here

  // you can read animsScript.CurrentWeapon directly, like this:

  string curWeapon = animsScript.CurrentWeapon;

If there’s only one object in scene with the script Anims, another possibility is to find the desired object with GameObject.Find(“objectName”) or with GameObject.FindWithTag(“objectTag”) in Start, and use this reference with GetComponent when necessary - for instance:

GameObject player;

void Start(){
  player = GameObject.FindWithTag("Player");
}

// to read CurrentWeapon, use this:

  string curWeapon = player.GetComponent<Anims>().CurrentWeapon;

This approach is better when you don’t want or just can’t drag the Anims owner to each script where it will be needed.