Unity's management of Layer

This is a suggestion to avoid pitfalls for some medium-sized and above projects that cooperate with multiple people, that is, layer management.

insert image description here

That's right, it's the thing as shown in the picture. Most people should know that there is such a thing and its general purpose, but they basically haven't touched it much. Of course, in most projects, there is no need to deal with this thing. At most, add a level and set the corresponding level for some objects. The API of this part is also very simple.

insert image description here

However, for projects that generally use layer, everyone prefers direct assignment. It should not be difficult for us to see similar codes in the project

 	public static void SetLayerContainsChildren(Transform transform, int layer)
    {
    
    
        transform.gameObject.layer = layer;
        transform.GetComponentsInChildren<Transform>().ForEach(t => t.gameObject.layer = layer);
    }

    public static void SetLayer(GameObject gameObject, int layer)
    {
    
    
        gameObject.layer = layer;
    }

Now let’s talk about what problems will arise in this way. For example, in the later stage, you need to adjust the order of some layers. After you change the layer order in the settings, you find that the displayed effect is fragmented. Because the int value corresponding to the layer you set has changed. All the layers of various objects set by your code are cool. Then you search for the layer and find that there are thousands of lines of Player code.

Therefore, in order to avoid later pitfalls, it is still necessary to manage layers at the beginning of the project.

Here are my two simple ideas.

Solution 1, increase the enumeration of layer levels, all layers are converted through enumeration, and if the layer changes, update the corresponding enumeration.
Scheme 2, assignment is assigned by name. LayerMask is actually a bitcode operation. There are a total of 32 Layer layers in Unity3D and cannot be increased. So we only need to traverse it once and find the int of the layer corresponding to the name to assign a value to ensure that my level is always consistent with my expectations.

    public static void SetLayerByName(GameObject gameObject, string layername)
    {
    
    
        int layer = 0;
        for (int i = 0; i < 32; i++)
        {
    
    
            if (LayerMask.LayerToName(i) == layername)
            {
    
    
                layer = i;
                break;
            }
        }
        gameObject.layer = layer;
    }

that's all.

Guess you like

Origin blog.csdn.net/qq_39860954/article/details/125912692