how to link 1 var between 2 scripts ?


I want to link a variable from one script to the other.

What I try to do:
The Player can pick up a gun and a bullet. When he has them, he can reload. Once the gun is loaded he can shoot.

What I have:
I have two scripts:

The PickupScript (linked to Player)

function OnCollisionEnter(collision : Collision)
	if (collisionGun.gameObject.tag == "gun");		// collide with the Gun...
		carryingGun = true;							// pick it up
		Debug.Log( "YOU HAVE THE GUN" );			// "Find the bullet"

	if (collisionBullet.gameObject.tag == "bullet")	// collide with the Bullet...
		carryingBullet = true;						// pick it up
		Debug.Log( "YOU HAVE THE BULLET" );			// "Find the gun"

function Update ()
	if (carryingGun && carryingBullet)
		canReload = true;
		//Debug.Log( "YOU CAN RELOAD" );
		Reload ();

	if (gunLoaded)
		canFire = true;
		//Debug.Log( "YOU CAN FIRE" );

function Reload ()
		if (Input.GetKeyDown(KeyCode.R))
     		yield WaitForSeconds (reloadTime);		// wait 3 seconds
     		bullets = 1;
     		gunLoaded = true;						// there is one bullet in the Gun
     		Debug.Log( "THE GUN IS LOADED" );		// "The Gun is Loaded. Shoot the enemy !"   

and the ShootScript(linked to camera)

function Update ()
	if (Input.GetButton("Fire1"))

function Fire()

And so I would like that when the variable gunLoaded turns true in the pickupScript, to turn true in the shoot variable as well.

Please help me to understand what went wrong and how I can fix it.

You can have a look at : this

To be short, one of your script must know the other one and your variable should be accessible (not private).

You can give one of the scripts to the other one as a public variable (given threw the inspector) or if you prefer you can access it by script by searching it in the scene (find the game object, get the component)

Thank you for answering.

So finally, I have made ‘canFire’ a static var in ShootScript:

static var canFire = false;

and called it from the PickupScript to change it to true:

ShootScript.canFire = true;

Hope it can help.