- Home /
Sprite Color Change upon collision
Hey everyone I have a problem. I tried many different methods to access the sprite's color and change it upon collision. Nothing I tried is working
I tried the following
GetComponent().color = Color.red;
SpriteRenderer renderer = GetComponent(); renderer.color = new Color(0.5f, 0.5f, 0.5f, 1f);
The code I have is when the numberofhits equal a certain number it becomes that color, but I need to access the sprite Renderer to change the color.
Below is my function:
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "BlueBlock")
{
if (numberOfHits == 1)
{
SpriteRenderer renderer = GetComponent<SpriteRenderer>();
renderer.color = new Color(0.5f, 0.5f, 0.5f, 1f); // Set to opaque gray
}
}
}
I just tested your code for changing the color:
SpriteRenderer renderer = GetComponent<SpriteRenderer>();
renderer.color = new Color(0.5f, 0.5f, 0.5f, 1f); // Set to opaque gray
...and it worked fine. So maybe the issue is your 'numberOfHits' or your you are not generating 2D collisions. Note that using 'renderer' for a variable name is not necessarily a good idea since this is the short cut name to the renderer for a game object.
Answer by AndreCrid · May 09, 2017 at 05:20 AM
Hello KG3,
I was facing the same issue when trying to build a block breaker game. In which should change the color of the game object on collision (different blocks should be hit different times before destroyed). Here's the solution I've found:
public class Brick : MonoBehaviour {
public int life;
void OnCollisionEnter2D(Collision2D collision)
{
life--;
if (life == 2)
{
GetComponent<SpriteRenderer>().color = new Color(1f,0.30196078f, 0.30196078f);
}
if (life == 1)
{
GetComponent<SpriteRenderer>().color = new Color(0.388235229f, 0.3372549f, 1f);
}
if (life <=0)
{
Destroy(gameObject);
}
}
}
I hope it helps.
Your answer
Follow this Question
Related Questions
Trigger a color change via collide 1 Answer
Object collision change colour 2 Answers
Detect collision by color? 1 Answer
Make a quad glow on collision? 1 Answer
How to change colors in turn? 1 Answer