Making a Collider only collide with objects that don't share the same material color.

Without messing with physics layers(as I’d need different ones for every possible color) what is the best way to do this? I don’t want to enable/disable the collider based on what is touching it as if two objects hit it at the same it would cause problems.

Any suggestions appreciated, preferably in JS.

Instead of using basic collision, use OnCollisionEnter() and give tags to your different objects based on material. Then you can create exceptions by checking for the tag in OnCollisionEnter()

But then what do i do to make it not collide with that object?

Use that during OnCollisionEnter to tell the physics engine to ignore the collisions between the two colliders if their colors are the same. If colors can change then you to disable that when OnCollisionExit is invoked.

I have the following:

function OnCollisionExit (thingHit : Collision)
{
if(thingHit.gameObject.renderer.material.color == renderer.material.color)
Physics.IgnoreCollision(collider, thingHit.collider, false);

if(thingHit.gameObject == player)
manager.GetComponent(ColourChangeScript).switcherEnabled = true;
}

function OnCollisionEnter (thingHit : Collision)
{

if(thingHit.gameObject.renderer.material.color == renderer.material.color)
Physics.IgnoreCollision(gameObject.collider, thingHit.collider, true);

if(thingHit.gameObject == player)
manager.GetComponent(ColourChangeScript).switcherEnabled = false;
}

It isn’t ignoring the collisions at all. Any ideas?

It appears to work for me when I test it out, I’d confirm that your conditional is triggering like you think it is with either a log statement or a breakpoint. Also, it might be worth considering to always turn back on collisions when you exit instead of doing a check otherwise you might get in a state where OnCollisionEnter won’t be invoked when you expect it to?

Though, while testing I noticed that even though I disable the collision between the two objects during OnCollisionEnter, there is still one frame where they collide and it can cause unwanted effects. You might be better off (if it’s a relatively small number of possible colors) to place the object in a specific layer once its color changes and just set up to have layers ignore themselves with physics at the beginning of the game.

If this sounds desirable, take a look at: Unity - Scripting API: Physics.IgnoreLayerCollision