[Unity]代码动态添加GameObject的Layer并用摄像机进行屏蔽

这篇博客探讨了在Unity中如何通过代码动态为GameObject设置Layer,并且解决打包后Layer名丢失的问题。文章提到,Unity允许设置24个自定义Layer,尽管在编辑器中设置的Layer名可能在打包后不保留,但仍然可以通过序号进行操作。此外,作者建议利用Dictionary管理Layer,并提醒读者注意类名变化和确保场景中已添加相关设置。

 

 

 

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestLayer : MonoBehaviour
{
    void Start()
    {
        string layerName = "TestLayer";
        TagManagerAutoAdd.AutoAddLayer(layerName);
        this.gameObject.layer = LayerMask.NameToLayer(layerName);
        Debug.Log(LayerMask.NameToLayer(layerName));
        Debug.Log(this.gameObject.layer);
        //print(SortingLayer.GetLayerValueFromName(layerName));

        Camera.main.cullingMask &= ~(1 << this.gameObject.layer);
    }
}

 

参考资料1,2里面的

using UnityEditor;
using UnityEngine;
...
public class TagManagerAutoAdd//类的名字 与脚本的文件名称一致
...
public static void AutoAddLayer(string layer)//改为static void AutoAddLayer(string layer)
...

运行结束的时候,添加的Layer的名字会清空。

貌似只能在 Unity编辑器里面使用,不能在打包后进行使用。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值