I have three objects from one prefab with trigger box collider. When Player collide with one of them, it change color. My script below:
void OnTriggerEnter2d(Collider2d collision)
{
if (collision.gameObject.name == “Player”)
{ getComponent().color = new Color (x,y,z); }
}
And I want to do this - all three objects have color Y. When Player collide with one of objects, it change color to X and the rest of objects change color to standard Y. When Player collide with another, it change color to X and previous object with X color change it to standard color Y.
How can I do that?
seems like a good situation for a static variable.
Inside your script that you posted, make a static variable for “CurrentlyChanged” (doesn’t matter what you name it)
Then, when you activate this trigger, do something like this:
// near the top, where you declare your variables
static GameObject CurrentlyChanged;
// after check for player, in the trigger method...
if(CurrentlyChanged != null && CurrentlyChanged != gameObject) CurrentlyChanged.GetComponent<SpriteRenderer>().color = new Color(standard colour Y);
CurrentlyChanged = gameObject;
// rest of code to change this object's colour to standard X
I’m completely noob, can U modify my code? When I wrote it like below it doesn’t work:
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
if (CurrentlyChange != null && CurrentlyChange != gameObject)
{
CurrentlyChange.GetComponent<SpriteRenderer>().color = new Color(1f, 1f, 1f);
CurrentlyChange = gameObject;
}
respawnerPointsManager.UpdateStartPoint(this.gameObject.transform);
GetComponent<SpriteRenderer>().color = new Color(0.3f, 0.6f, 0.6f);
}
}
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
respawnerPointsManager.UpdateStartPoint(this.gameObject.transform);
GetComponent<SpriteRenderer>().color = new Color(0.3f, 0.6f, 0.6f);
}
if (CurrentlyChange != null && CurrentlyChange != gameObject)
{
CurrentlyChange.GetComponent<SpriteRenderer>().color = new Color(1f, 1f, 1f);
CurrentlyChange = gameObject;
}
the part where it says If(CurrentlyChange != null etc…
put the : CurrentlyChange = gameObject after you close the braces { } not inside.
Try again and write back if it works/doesn’t