title: How to change object's layer at runtime in Unity?
body: <p>I've got WallCreator script to place walls in Unity, and another one, WallCreatorSwitcher to turn WallCreator ON/OFF by checking the toggle. I also wanted to change wallPrefab's layer there by using <code>GetComponent&lt;WallCreator&gt;().wallPrefab.layer = LayerMask.NameToLayer("LayerName");</code>, so when the toggle is checked (WallCreator ON) layer is "Ignore Raycast" - and it works, and if the toggle is unchecked (WallCreator OFF) layer is "Default" - but the problem is, it's not changing the layer in this case.</p>
  
  <pre><code>public class WallCreatorSwitcher : MonoBehaviour {
  
  public Toggle toggle;
  public Text text;
  
  
  // Use this for initialization
  void Start () {
  
  }
  
  // Update is called once per frame
  void Update () {
      if (toggle.isOn)
      {
          GetComponent&lt;WallCreator&gt;().enabled = true;
          Debug.Log("Wall Creator is ON");
          text.enabled = true;
          GetComponent&lt;WallCreator&gt;().wallPrefab.layer = LayerMask.NameToLayer("Ignore Raycast");
  
      }
  
      else
      {
          GetComponent&lt;WallCreator&gt;().enabled = false;
          Debug.Log("Wall Creator is OFF");
          text.enabled = false;
          GetComponent&lt;WallCreator&gt;().wallPrefab.layer = LayerMask.NameToLayer("Default");
  
         }
  
     }    
  
  }
  </code></pre>