Am I misunderstanding how this code should function?
Hello, I am fairly new to Unity and I am trying to implement a system where as the player touches tiles on the ground, it changes to a certain color and after "x" amounts of times, they lose this ability and have to reload at home base to continue to be able to paint the ground.
Here is the code snippet of what I have; I've also tried initializing and setting the value at the very top, having "public int counter = 10;" instead of separating it out like I did.
The ground changes from white to red like it should, but after running to Debug.Log(), it appears that the counter is held up at 9, sometimes going to 8 for a split second before going back up to 9. I feel like this should work, but I think that I am misunderstanding something about Unity and how it works.
public Material[] material;
Renderer rend;
public int counter;
void Start()
{
rend = GetComponent<Renderer>();
rend.enabled = true;
rend.sharedMaterial = material[0];
//Player is able to paint 10 floor tiles
counter = 10;
}
void update()
{
}
void OnCollisionEnter(Collision col)
{
//If player touches a tile, and has enough paint, and the tile is not already red
if ( (col.gameObject.tag == "Player") && (counter > 0) && (rend.sharedMaterial != material[1]) )
{
counter--; //As player paint the floor tiles, it decreases "ammo"
Debug.Log(counter);
rend.sharedMaterial = material[1]; //Changes the floor tile from white to red
}
}
}
If you've put this script on each tile, then, each tile has its own counter.
If you want a shared counter, you can:
use the
static
keyword (not really advised),have another script managing the counter (maybe on the player?)
Or you could also rething your system and make the player handle the painting, meaning the script is attached to the player and OnCollisionEnter
checks for the Tile
tag (for instance) and checks for the color of the colliding tile.
Answer by Gizza_Impact · Mar 08 at 05:07 PM
I fixed the issue; making the variable a static variable fixed my problem.