首页 > 解决方案 > (Unity) 更改图层蒙版时向游戏对象添加脚本

问题描述

我希望能够在更改其 LayerMask 时向游戏对象添加脚本。我希望在编辑器中更改它而不是仅在运行时发生这种情况。

我该怎么做?我无法在 Google 上提出问题以找到任何可能对我有帮助的必要信息。

先感谢您。

标签: c#unity3d

解决方案


我认为没有任何内置功能,但您可以使用GameObject.layer,存储它并进行比较。

使用[ExecuteInEditMode]您可以使组件在编辑器中执行一些方法:

[ExecuteInEditMode]
public class LayerChecker : MonoBehaviour
{
    private int lastLayer;

    // could e.g be a UnityEvent (like onClick of buttons)
    public UnityEvent OnLayerChanged;

    private void Update()
    {
        // if layer didn't change do nothing
        if(lastLayer == gameObject.layer) return;

        // changed! -> what ever you want to happen 
        // e.g. invoke the event or call another method
        OnLayerChanged.Invoke();

        // store the new layer
        lastLayer = gameObject.layer;
    }    
}

如果您想限制发生这种情况的位置,您还可以检查Application.isEditor和/或Application.isPlaying


推荐阅读