I. Introduction
Custom components have been introduced before, the article link is here:
Unity3D Editor custom window, custom component, Inspector, menu, etc. https://blog.csdn.net/q764424567/article/details/80908614
Today I learned a new attribute InitializeOnLoad
and record it.
Second, use
The main function of this attribute is to run the editor script when starting Unity. The vernacular is that I want to run my script as soon as the project is opened, such as using my plug-in. Once opened, let you know that my plug-in has been updated.
Looking at its official example, we know that it needs a static constructor
using UnityEngine;
using UnityEditor;
[InitializeOnLoad]
public class Startup {
static Startup()
{
Debug.Log("Up and running");
}
}
3. Examples
Example 1: Call the script after the project is loaded
using UnityEditor;
using UnityEngine;
[InitializeOnLoad]
class MyClass
{
static MyClass ()
{
EditorApplication.update += Update;
}
static void Update ()
{
Debug.Log("Updating");
}
}
Example 2: Close the call after loading the window
using UnityEditor;
using UnityEngine;
[InitializeOnLoad]
class MyClass
{
static MyClass ()
{
EditorApplication.update += Update;
}
static void Update ()
{
bool isSuccess = EditorApplication.ExecuteMenuItem("Welcome");
if (isSuccess) EditorApplication.update -= Update;
}
}
Example three: window customization
using UnityEditor;
using UnityEngine;
[InitializeOnLoad]
public class MyClass
{
static MyClass()
{
bool hasKey = PlayerPrefs.HasKey("welcome");
if (hasKey == false)
{
PlayerPrefs.SetInt("welcome", 1);
WelcomeScreen.ShowWindow();
}
}
}
public class WelcomeScreen : EditorWindow
{
private Texture mSamplesImage;
private Rect imageRect = new Rect(30f, 90f, 350f, 350f);
private Rect textRect = new Rect(15f, 15f, 380f, 100f);
public void OnEnable()
{
mSamplesImage = LoadTexture("wechat.jpg");
}
Texture LoadTexture(string name)
{
string path = "Assets/Editor/";
return (Texture)AssetDatabase.LoadAssetAtPath(path + name, typeof(Texture));
}
public void OnGUI()
{
GUIStyle style = new GUIStyle();
style.fontSize = 14;
style.normal.textColor = Color.white;
GUI.Label(textRect, "欢迎扫一扫,关注微信号\n这个页面只会显示一次", style);
GUI.DrawTexture(imageRect, mSamplesImage);
}
public static void ShowWindow()
{
WelcomeScreen window = GetWindow<WelcomeScreen>(true, "Hello");
window.minSize = window.maxSize = new Vector2(410f, 470f);
DontDestroyOnLoad(window);
}
}