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

How to change object's layer at runtime in Unity?

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

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");

       }

   }    

}

您似乎没有引用 wallPrefab 的游戏对象,这可能是问题所在。变化:

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

收件人:

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

在没有看到其他脚本的情况下,我不能确定这是否会解决问题。

较新的墙在放置时位于 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 的 属性 也发生了变化,因此 这一变化之后放置的墙将保留在新层上,而不是旧的