# How to get a public int equal the same number when added in all object that have the same script?

I’m trying to make a game where tiles get added to the floor continuously but the colour of the tiles are random when added. I’ve done this by Instantiating the selected tiles into the level when they collide into a trigger like this;

`````` private int rndnum;

public int i = 2;
private in u = 10;
public GameObject Tile1;
public GameObject Tile2;
public GameObject Tile3;
public GameObject Tile4;
public GameObject Tile5;

private void Start()
{

}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
i = i++;
print(i);
{
rndnum = (Random.Range(1, 5));

if (rndnum == 1)
{

Instantiate(Tile1, new Vector3(0, u + -11,i * 27.5f), Quaternion.Euler(new Vector3(20, 0, 0)));

}
if (rndnum == 2)
{

Instantiate(Tile2, new Vector3(0, u + -11, i * 27.5f), Quaternion.Euler(new Vector3(20, 0, 0)));

}
if (rndnum == 3)
{

Instantiate(Tile3, new Vector3(0, u + -11, i * 27.5f), Quaternion.Euler(new Vector3(20, 0, 0)));

}
if (rndnum == 4)
{

Instantiate(Tile4, new Vector3(0,  u + -11, i * 27.5f), Quaternion.Euler(new Vector3(20, 0, 0)));

}
if (rndnum == 5)
{

Instantiate(Tile5, new Vector3(0,u + -11, i * 27.5f), Quaternion.Euler(new Vector3(20, 0, 0)));

}
}
}
}
}
``````

All of the box colliders have the same script but as the tiles are instantiated the ‘i’ value doesn’t change between one trigger with its script and the next trigger so the tiles just spawn on top of each other.

Edit: Sorry should have mentioned this, the ‘i’ value is used so that the tiles spawn at a new vector right next to each other.

Make the field static and it will belong to the class, not every instance of it separately.

``````public static int tileCounter = 2;
...

if (other.gameObject.CompareTag("Player"))
{
int i = tileCounter++;
print(i);
...
``````

(using the local variable `i` here is optional, you can just use tileCounter throughout the method)

Few other notes

`````` i = i++
``````

this doesn’t do anything because of the order in which things happen. It basically takes note of the value of x, increments x and then assigns to x the value it took note of before incrementing it.

`````` Random.Range(1, 5)
``````

Random.Range with integers is exclusive of the second parameter. You will never get a 5 with this. With floats Random.Range is inclusive of both arguments.

``````if (rndnum == 1)
{                 }
if (rndnum == 2)
{                 }
if (rndnum == 3)
{                 }
if (rndnum == 4)
{                 }
if (rndnum == 5)
{                 }
``````

If `rndnum ` equals 1, there’s no need to check if it equals 2, 3, 4 or 5.
You should add `else` to the latter checks or use a switch-case.

``````if (rndnum == 1)
{                 }
else if (rndnum == 2)
``````