- Home /
Help with OnCollisionEnter method.
Hello,
I am trying to have the color of a ball change when it hits a wall in my game. The if statement I have for this works but when I try to have it change to a different color after it hits the right wall again this is where I have run into issues. When the code runs right now, anytime the ball contacts another surface including the paddles it changes color. So how should I proceed forward? Should I move the color-changing part of the code to its own method or is there a way to help it run independently from the other collision parts of the code in the method?
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.name == "RacketLeft")
{
float y = hitFactor(transform.position, collision.transform.position, collision.collider.bounds.size.y);
Vector2 dir = new Vector2(1, y).normalized;
GetComponent<Rigidbody2D>().velocity = dir * speed;
}
if (collision.gameObject.name == "RacketRight")
{
float y = hitFactor(transform.position, collision.transform.position, collision.collider.bounds.size.y);
Vector2 dir = new Vector2(1, y).normalized;
GetComponent<Rigidbody2D>().velocity = dir * speed;
}
if (collision.gameObject.name == "Right Wall")
{
_renderer.sharedMaterial = materials[1];
}
else
{
_renderer.sharedMaterial = materials[0];
}
}
Answer by rage_co · Jul 06, 2021 at 03:41 AM
You can use layers for this.... like
if(collision.gameObject.layer == LayerMask.NameToLayer("wall"))
{
}
just put this under the OnCollisionEnter2D method.......and then appropriately tag all the walls............then you can use this if tag to trigger any event you want.....you can make a similar if() and layer for the paddles
Answer by Devster2020 · Jul 06, 2021 at 10:05 AM
The problem is here:
if (collision.gameObject.name == "Right Wall") {
_renderer.sharedMaterial = materials[1];
}
else {
_renderer.sharedMaterial = materials[0];
}
using "else", make change the color of the ball for every collision that not be "Right Wall"..
If I understand correctly your idea, you need to change the code like this:
if (collision.gameObject.name == "Right Wall") {
_renderer.sharedMaterial = materials[1];
}
else if(collision.gameObject.name == "Left Wall"){
_renderer.sharedMaterial = materials[0];
}
I am trying to have the ball change color only when it hits the "Right Wall".
Your answer
![](https://koobas.hobune.stream/wayback/20220613035856im_/https://answers.unity.com/themes/thub/images/avi.jpg)