(Unity)更改图层蒙版时将脚本添加到游戏对象

时间:2019-02-25 14:18:05

标签: c# unity3d

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

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

谢谢。

1 个答案:

答案 0 :(得分:0)

我认为没有内置的功能,但是您可以使用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