公司开发需求,在Unity启动时弹一次提示框以显示一些开发规范。
查询得知unity拥有属性 [InitializeOnLoad],用该属性标记过的静态类会在unity启动和重新编译时调用一次构造函数,在此构造函数中调用弹框方法即可实现需求。
但是为了去掉重新编译时反复弹框的功能,第一次弹框后记录“StartUp”值,之后检测该值不再弹框,关闭unity时清除该值,保证下次启动弹框功能正常。
贴上代码:
using UnityEngine;
using UnityEditor;
[InitializeOnLoad]
public class OnUnityStartTest : Editor
{
static OnUnityStartTest()
{
EditorApplication.quitting -= Quit;
EditorApplication.quitting += Quit;
EditorApplication.update -= Update;
EditorApplication.update += Update;
}
static void Update()
{
int startKey = PlayerPrefs.GetInt("StartUp", 0);
if (startKey <= 0)
{
startKey++;
WelcomeScreen.ShowWindow();
PlayerPrefs.SetInt("StartUp", startKey);
EditorApplication.update -= Update;
}
}
static void Quit()
{
PlayerPrefs.SetInt("StartUp", 0);
}
}
public class WelcomeScreen : EditorWindow
{
private Rect textRect = new Rect(15f, 15f, 200f, 100f);
public void OnGUI()
{
GUIStyle style = new GUIStyle();
style.fontSize = 20;
style.normal.textColor = Color.white;
GUI.Label(this.textRect, "Hello!!!!zahll1993", style);
}
public static void ShowWindow()
{
WelcomeScreen window = EditorWindow.GetWindow<WelcomeScreen>(true, "Start!");
window.minSize = window.maxSize = new Vector2(300f, 300f);
DontDestroyOnLoad(window);
}
}
|