How to access variables from a different script on a different GameObject?

I have a game object Called PistolAmmo with a script called AmmoPistol.js attached to it, i also have the player game object with a script called WeaponManagerScript.js(this script manages the ammo count for all weapons), i want AmmoPistol.js to be able to access and modify variables inside of WeaponManagerScrit.js. I have been trying for the past eighteen hours to get this to work but the closet i have gotten is this.

var weaponManager : WeaponManagerScript;

function Start ()
	weaponManager = gameObject.GetComponent("WeaponManagerScrip");
	Debug.Log ("Hello");

 function OnTriggerEnter (collider : Collider) 
	Debug.Log ("Something is flipping my trigger!!!!");
		Debug.Log ("Oh babay you Just Flipped My Trigger!!!");
		if (weaponManager.ammoCountPistol <= 48)
				Debug.Log ("Its Dangerous Ahead You'll Need This!");
				weaponManager.ammoCountPistol += 8;

The above code gives me this error.

NullReferenceException: Object reference not set to an instance of an object
PistolAmmo.OnTriggerEnter (UnityEngine.Collider collider) (at Assets/WeaponScripts/PistolAmmo.js:17)

If anyone knows a way to do this or fix any current problems in my script i would appreciate the help, thanks.

This line:

weaponManager = gameObject.GetComponent("WeaponManagerScrip");

is spelled wrong, I believe. Unless your script is actually called “WeaponManagerScrip”. But more importantly, you haven’t referenced the gameObject that WeaponManagerScript.js is attached to. You’ve just used the generic “gameObject”, which means you are trying to get the instance of WeaponManagerScript.js that is attached to the PistolAmmo object. If you wanted to get the instance of WeaponManagerScript.js that is on a different gameObject, you would need to either reference it directly through a public variable, or find it, like this:

weaponManager = GameObject.Find ("TheObjectWIthWeapnManager").GetComponent(WeaponManagerScript);

You also need to make sure the variable you’re trying to access is public, and not protected.


Set the variables as “static”;


public static var score:int = 2;


//prints out the value in the console