我有 WallCreator 脚本可以在 Unity 中放置墙壁,还有一个 WallCreatorSwitcher 可以通过选中开关来打开/关闭 WallCreator。我还想通过使用 GetComponent<WallCreator>().wallPrefab.layer = LayerMask.NameToLayer("LayerName");
更改 wallPrefab 的图层,所以当切换被选中时(WallCreator ON)层是“忽略光线转换” - 它工作,如果切换未被选中(WallCreator OFF)层是“默认” - 但问题是,它没有改变这个层案例。
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");
}
}
}
最佳答案
较新的墙在放置时位于 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
的属性仍然发生了变化,因此放置在此变化之后的墙将保留在新层上,而不是旧层上
关于c# - 如何在运行时在 Unity 中更改对象的图层?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40869566/