Unity中的 MonoBehaviour ,默认情况下只能在 Play Mode 模式下执行。如果想在 Edit Mode 模式下执行可以使用 [ExecuteInEditMode】或 [ExecuteAlways] 两特性(代码如下)。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class TestExecuteInEditMode : MonoBehaviour
{
private void Awake()
{
Debug.Log("[ExecuteInEditMode] Awake");
}
private void OnEnable()
{
Debug.Log("[ExecuteInEditMode] OnEnable");
}
private void Start()
{
Debug.Log("[ExecuteInEditMode] Start");
}
private void Update()
{
Debug.Log("[ExecuteInEditMode] Update");
}
private void OnDisable()
{
Debug.Log("[ExecuteInEditMode] OnDisable");
}
private void OnDestroy()
{
Debug.Log("[ExecuteInEditMode] OnDestroy");
}
}
[ExecuteAlways]
public class TestExecuteAlways : MonoBehaviour
{
private void Awake()
{
Debug.Log("[ExecuteAlways] Awake");
}
private void OnEnable()
{
Debug.Log("[ExecuteAlways] OnEnable");
}
private void Start()
{
Debug.Log("[ExecuteAlways] Start");
}
private void Update()
{
Debug.Log("[ExecuteAlways] Update");
}
private void OnDisable()
{
Debug.Log("[ExecuteAlways] OnDisable");
}
private void OnDestroy()
{
Debug.Log("[ExecuteAlways] OnDestroy");
}
}
ExecuteInEditMode
添加 【ExecuteInEditMode】特性,脚本可以在 Play Mode 、Edit Mode 模式下执行(Prefab Mode模式下无法执行)。但是 update 函数在 Edit Mode 模式下不会一直执行,只有在我们一直移动鼠标才会执行。当停止移动鼠标也会跟着停止执行。Edit Mode 模式下支持执行以下几个常用函数。
- Awake
- OnEnable
- Start
- Update
- OnDisable
- OnDestroy
ExecuteAlways
添加【ExecuteInEditMode】特性,是【ExecuteInEditMode】的升级版,脚本可以在 Play Mode 、Edit Mode、Prefab Mode 模式下执行。其余的与 【ExecuteInEditMode】基本完全相同。
如何在 Edit Mode 模式下,让 Update 函数像在 Play Mode 模式下一直执行?
- 方法一
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class TestExecuteInEditMode : MonoBehaviour
{
private void Update()
{
Debug.Log("[ExecuteInEditMode] Update");
}
private void OnDrawGizmos()
{
#if UNITY_EDITOR
if (!Application.isPlaying)
{
UnityEditor.EditorApplication.QueuePlayerLoopUpdate();
UnityEditor.SceneView.RepaintAll();
}
#endif
}
}
[ExecuteAlways]
public class TestExecuteAlways : MonoBehaviour
{
private void Update()
{
Debug.Log("[ExecuteAlways] Update");
}
private void OnDrawGizmos()
{
#if UNITY_EDITOR
if (!Application.isPlaying)
{
UnityEditor.EditorApplication.QueuePlayerLoopUpdate();
UnityEditor.SceneView.RepaintAll();
}
#endif
}
}
- 方法二
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Reflection;
[InitializeOnLoad]
public class TestUpdate
{
static TestUpdate()
{
EditorApplication.update += Update;
}
static void Update()
{
Debug.Log("[InitializeOnLoad] Update");
}
}