Changing and Int value in script from another script

I’m trying to change an integer in a script from another script.
In my case I want force fields to spawn where I click, but the game cannot have more than three force fields on screen at any time. After 3 seconds I want a forcefield to be destroyed, thereby allowing another one to take its place.
My force field destroy script is separate from my force field create script, so whenever the force field gets destroyed I want to change the value of an interger in the force field create script. So far I have this (code below), but the “clickedNum” value only gets changed when I end and then play the game again (not when the game is actually running).

Any help would be appreciated.
Thanks :slight_smile:
Script where force fields are created:

using UnityEngine;

public class Force_Field_Spawning : MonoBehaviour
{
public GameObject Forcefield;
public int clickedNum = 0;

void Update()
{
//checks if left clicked and if there are three forcefield created
if (Input.GetMouseButtonDown(0) && clickedNum < 3)
{
//Spawn forcefield at mouse position
Vector2 clickPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Instantiate(Forcefield, new Vector3(clickPos.x, clickPos.y, 0), Quaternion.identity);

clickedNum += 1;
}
}
}[/code]

Script where force fields are destroyed:

using UnityEngine;

public class Destroy_forcefield : MonoBehaviour
{
public float lifeTime = 10f;
public GameObject Forcefield;
void Update()
{
//Checks if allocated time has past
if (lifeTime > 0)
{
lifeTime -= Time.deltaTime;
if (lifeTime <= 0)
{
Destruction();
//I want to subtract one from the “clickedNum” interger from in “Force_Field_Spawning” over here
// Tried using this, and it didn’t work:
//Forcefield.GetComponent<Force_Field_Spawning>().clickedNum -= 1;
}
}
}

void Destruction()
{
Destroy(this.gameObject);
}
}[/code]

Referencing variables, fields, methods (anything non-static) in other script instances:

https://discussions.unity.com/t/833085/2

https://discussions.unity.com/t/839310

The basic gist is that you first need to get a reference to the Force_Field_Spawning script, and then you can very simply access it via forceFieldSpawnerReference.clickedNum -= 1;

The key of course is, how to get that reference? There are many ways. Some of the most common and effective ways are explained here:

1 Like