How do I move a gameObject to different layers?

Hi.

Been racking my brain trying to figure out how to do this but no such insight.

I want to have the player’s gameObject switch layers on material change so that it avoid colliding with objects of the same material but don’t know how.

I have the 2 materials in an array which are swapped on MouseDown. Here is the code I have so far:

void OnMouseDown()
{
index++;
if(index >= materials.Length)
index = 0;
renderer.material = materials[index];
}

void playerShift()
{

if (GameObject.FindGameObjectWithTag("Player").renderer.material.name == "White")
	{
	gameObject.layer = LayerMask.NameToLayer("White"); // move to white layer 
	Debug.Log("layer switched to W");
	}
	
	else //(GameObject.Find("Sphere").renderer.material.name == "Black")
	{
	gameObject.layer = LayerMask.NameToLayer("Black"); // move to black layer 
	Debug.Log("layer switched to B");
	}

}

I call the playerShift function in the Update.

On another note. Should I separate this into its own script because at the moment its part the playerMovement script.

Thanks for any help or insight you can provide.

As you are changing the materials its names are not “Black” and “White” but “Black (Instance)” and “White (Instance)”.

On your other question, yes, I think it would be better to have this code in a separate component, just for organizational purpose.