I have two gameobjects in my game. I want to make one of them after ball collides with that in red color. And another in white color. Right now they both become red after collide with my projectile(ball). How to share this ?
CodePudding user response:
This sounds like you are basically asking "How to handle a collision only on one of the colliding parties?"
Collisions happen in the physics update routine so basically after FixedUpdate
.
See Execution Order of event Messages where you can see that FixedUpdate
is always executed before all OnCollisionXY
are handled.
So what you can do is store a reference in the first OnCollisionEnter
to the other object and then ignore the second one if the object is the se you already collided with.
Then simply reset the field in the next FixedUpdate
call.
Something like e.g.
public class CollisionDetection : MonoBehaviour
{
public Color color1 = Color.red;
public Color color2 = Color.white;
private GameObject ignoreCollisionWith
void OnCollisionEnter(Collision col)
{
if(col.gameObject == ignoreCollisionWith) return;
if(col.gameObject.TryGetComponent<CollisionDetection>(out var other))
{
// Set the color for both involved objects
GetComponent<Renderer>(). material.color = color1;
other.GetComponent<Renderer>(). material.color = color2;
// Tell the other object to do nothing for this collision with you
other.ignoreCollisionWith = gameObject;
}
}
void FixedUpdate()
{
ignoreCollisionWith = null;
}
}
CodePudding user response:
Because your two objects share the same material.
You need to duplicate the material and assign the new one to one of your object.
Now, you can change the colors independently but you also added a draw call.