- Home /
C# - How do I increase the variable from another script?
Hey, just have a question. On my scr_player, I have it so when you press space you fire a bullet.
I was just wondering how to make it so when that player fires a bullet, a variable from my other script, ShotsFired, increases?
Here is my scr_player:
void Update ()
{
if (Input.GetKeyDown("space"))
{ //Fire projectile Vector3 position = new Vector3(transform.position.x, transform.position.y + (transform.localScale.y / 2)); Instantiate(ProjectilePrefab, position, Quaternion.identity); } }
Here is my scr_stats:
void Start () { var HP=HPMax; var ShotsFired=0; var Kills=0; }
void Update () { var i=ShotsFired; var ii=Kills;
if (TimeLeft<1) { TotalShotsFired+=i; i=0; TotalKills+=ii; ii=0; TimeLeft=MaxTimeLeft*1.5f; } }
Answer by Meltdown · Aug 10, 2012 at 05:39 PM
In your other class I'd suggest making a public method that allows you to increase the variable from another script. So do something like..
int _shotsFired = 0;
public void IncreaseShotsFired()
{
_shotsFired++;
}
Then from the script that calls it.. Get a reference to the above script and just call IncreaseShotsFired();
Answer by poncho · Aug 15, 2012 at 06:05 PM
if scr_stats is attached to the same object that your scr_player then use this.getComponent()._shotsFired += 1; and _shotsFired should be public if scr_stats its not in the same gameobject, then find the gameobject that contains it and use the getcomponent method