关于动态修改Layer层,修改对象以及子对象的layer层总结

using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.AI;
public class Example : MonoBehaviour
{
    void ChangeLayer(Transform trans, string targetLayer)
    {
        if (LayerMask.NameToLayer(targetLayer)==-1)
        {
            Debug.Log("Layer中不存在,请手动添加LayerName");
            
            return;
        }
        //遍历更改所有子物体layer
        trans.gameObject.layer = LayerMask.NameToLayer(targetLayer);
        foreach (Transform child in trans)
        {
            ChangeLayer(child, targetLayer);
            Debug.Log(child.name +"子对象Layer更改成功!");
        }
    }
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            //NewLayer必须新建,否则更改失败
            ChangeLayer(gameObject.transform, "NewLayer");
        }
    }
    
}

posted @ 2018-06-09 17:55  低小调  阅读(1349)  评论(0编辑  收藏  举报