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

标签 c# unity3d runtime

我有 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/

相关文章:

c++ - 协助 C++ 程序分析

C#音乐/声音同步

ios - Xcode 返回链接器错误 "library not found for -lFirebaseAuth"

c# - Unity中的简单键盘输入

android - Unity3D 使用用户提示退出 Android 游戏

python - 难以理解函数的运行时复杂性

c++ - Visual Studio 中Linux as/MTd 对应的库是什么?

c# - C#/.NET 中的图像重命名程序

c# - 应该尽可能使用静态方法吗?

c# - 如何在 C# 中以编程方式创建 WPF 可滚动 StackPanel 列表