- Home /
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.
Answer by dmg0600 · Sep 20, 2014 at 03:58 PM
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.
Thanks dmg.
I thought it wasn't working. Just had to adjust the Physics Layer Collision $$anonymous$$atrix as well to get it to work. (Also kept changing the Physics2D matrix ins$$anonymous$$d of just Physics, I'm using cubes...duh!)
Thanks again. $$anonymous$$uch appreciated.
Your welcome! It's a very common error when you are working your way through Unity. If you can, accept the answer! Thanks!
Your answer
