- Home /
how to link 1 var between 2 scripts ?
Hi,
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...
audio.PlayOneShot(pickupGunSound);
carryingGun = true; // ...to pick it up
Debug.Log( "YOU HAVE THE GUN" ); // "Find the bullet"
if (collisionBullet.gameObject.tag == "bullet") // collide with the Bullet...
audio.PlayOneShot(pickupBulletSound);
carryingBullet = true; // ...to 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(canReload)
{
if (Input.GetKeyDown(KeyCode.R))
{
audio.PlayOneShot(reloadGunSound);
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"))
Fire();
}
function Fire()
{
if(canFire==true)
{
canFire=false;
FireOneShot();
}
}
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.
Answer by Kaha · Nov 16, 2012 at 02:39 PM
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.
No problem. You are not forced to declare your var as static.
If my answer helped you, please validate it with the check mark next to it :)
I have tried to call it without it being a static var and got an error from the console. How do I do to use 1 variable in 2 different scripts ?
Answer by KiraSensei · Nov 16, 2012 at 01:56 PM
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)
Your answer
![](https://koobas.hobune.stream/wayback/20220613083954im_/https://answers.unity.com/themes/thub/images/avi.jpg)