- Home /
Increase a variable of an other script
Hi, I just want to increase a variable of an other script. scriptname.variablename ++; doesnt work.
Answer by Piflik · Jul 10, 2012 at 04:27 PM
scriptname.variablename works only with static variables. With standard public variables you need to first get the object, then the componentn and then you can edit the variables.
Answer by tw1st3d · Jul 11, 2012 at 02:12 AM
I had this problem too. This was my solution.
The first script, I made my portrait layout for things like Health, Ammo, etc.(I am including only what is necessary. The first file is called Portrait.js)
public var ammo;
var usedammo;
ammo = 100;
usedammo = 0;
remainingammo = ammo*1;
function OnGUI(){
GUI.Label(Rect(480,Screen.height-45,80,75),"Ammo:", ammofont);
}
if(ammo <= 10){
function Update(){
if(ammo >= 0){
reloadfont.normal.textColor = Color.yellow;
GUI.Label(Rect(Screen.width-760,Screen.height-500,750,30), "Low Ammo", reloadfont);
}
}
}
This is the second script, Shoot.js
var bullet : Rigidbody;
var speed : float = 10.0f;
var muzzlePoint : Transform;
var getammo;
getammo = GameObject.FindWithTag("Portrait").GetComponent(portrait);
Debug.Log(getammo);
function Update() {
if(Input.GetButtonDown("Fire1")) {
if(getammo.ammo > 0){
if(Time.timeScale == 1){
bullet.useGravity = false;
var instance : Rigidbody = Instantiate(bullet, muzzlePoint.position, Quaternion.identity);
instance.velocity = muzzlePoint.forward * 100;
}
}
}
}
What this does, is allows you to call a variable outside of the current script, using
GameObject.FindWithTag("objectag")GetComponent("otherscript.js");
My first variable:
getammo
This brings the first .js file into the scripting. To use it, all I do is:
getammo.otherscriptvariable
That's all there is to it. Hope this helped.
Your answer
![](https://koobas.hobune.stream/wayback/20220613074003im_/https://answers.unity.com/themes/thub/images/avi.jpg)