如何在Unity中运行时更改对象的图层?

时间:2016-11-29 15:25:52

标签: c# unity3d runtime

我已经有了WallCreator脚本在Unity中放置墙,另一个是WallCreatorSwitcher通过检查切换来打开/关闭WallCreator。我还想通过使用GetComponent<WallCreator>().wallPrefab.layer = LayerMask.NameToLayer("LayerName");更改wallPrefab的图层,因此当选中切换(WallCreator ON)图层时,#34; Ignore Raycast&#34; - 并且它可以工作,如果未选中切换(WallCreator OFF)图层是&#34;默认&#34; - 问题是,在这种情况下,它没有改变图层。

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<WallCreator>().enabled = true;
        Debug.Log("Wall Creator is ON");
        text.enabled = true;
        GetComponent<WallCreator>().wallPrefab.layer = LayerMask.NameToLayer("Ignore Raycast");

    }

    else
    {
        GetComponent<WallCreator>().enabled = false;
        Debug.Log("Wall Creator is OFF");
        text.enabled = false;
        GetComponent<WallCreator>().wallPrefab.layer = LayerMask.NameToLayer("Default");

       }

   }    

}

2 个答案:

答案 0 :(得分:4)

新的墙壁在放置后,在预制件中更换后位于Default层中,这是因为更改预制件会更改创建墙壁时放置的墙壁,而不是已经存在的墙壁。要更改所有墙的图层,您可以执行以下操作(假设墙有标记墙)

GetComponent<WallCreator>().wallPrefab.gameObject.layer = LayerMask.NameToLayer("Default");
GameObject[] walls = GameObject.FindGameObjectsWithTag("wall");
foreach(GameObject wall in walls)
{
    wall.layer = LayerMask.NameToLayer("Default");
}

这将循环遍历场景中的每个墙,并将其图层更改为您想要的图层。同样重要的是,WallCreator的属性也会更改,因此在此更改之后放置的墙将保留在新图层而不是旧图层上

答案 1 :(得分:1)

看起来好像你没有引用wallPrefab的gameObject,这可能是问题所在。变化:

GetComponent<WallCreator>().wallPrefab.layer = LayerMask.NameToLayer("Ignore Raycast");

要:

GetComponent<WallCreator>().wallPrefab.gameObject.layer = LayerMask.NameToLayer("Ignore Raycast");

如果没有看到其他脚本,我无法确定这会解决问题。