介绍
某些情况下需要在 Unity 进入播放模式运行前修改部分内容,退出播放模式后恢复修改。
环境
思路
Unity 虽然提供了 Unity - Scripting API: EditorApplication.playmodeStateChanged,但是此事件发生在播放状态改变之后,而实际是需要事件发生在播放状态改变之前。
但是 Unity 同时提供了 Unity - Scripting API: EditorApplication.update 与 Unity - Scripting API: EditorApplication.playmodeStateChanged,这样就可以实现了。
实现
To do something before and after Unity play - Gist
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
using UnityEngine;
using UnityEditor;
[InitializeOnLoad]
public class PlaymodeHook
{
static PlaymodeHook()
{
EditorApplication.update += Update;
EditorApplication.playmodeStateChanged += PlaymodeStateChanged;
}
private static void Update()
{
if (!EditorApplication.isPlaying &&
EditorApplication.isPlayingOrWillChangePlaymode)
{
BeforeEnterPlaymode();
}
}
private static void PlaymodeStateChanged()
{
if (!EditorApplication.isPlaying &&
!EditorApplication.isPlayingOrWillChangePlaymode)
{
AfterExitPlaymode();
}
}
private static void BeforeEnterPlaymode()
{
Debug.Log("BeforeEnterPlaymode");
}
private static void AfterExitPlaymode()
{
Debug.Log("AfterExitPlaymode");
}
}
|