1.はじめに
カスタムコンポーネントは以前に導入されています。記事のリンクはこちらです:
Unity3Dエディターのカスタムウィンドウ、カスタムコンポーネント、インスペクター、メニューなど。https : //blog.csdn.net/q764424567/article/details/80908614
今日、私は新しい属性InitializeOnLoadを学び、
それを記録しました。
第二に、使用
この属性の主な機能は、Unityの起動時にエディタースクリプトを実行することです。一般的には、プラグインを使用するなど、プロジェクトを開いたらすぐにスクリプトを実行したいというものです。一度開いたら、プラグインが更新されたことを知らせます。
公式の例を見ると、静的コンストラクタが必要であることがわかります
using UnityEngine;
using UnityEditor;
[InitializeOnLoad]
public class Startup {
static Startup()
{
Debug.Log("Up and running");
}
}
3.例
例1:プロジェクトが読み込まれた後にスクリプトを呼び出す
using UnityEditor;
using UnityEngine;
[InitializeOnLoad]
class MyClass
{
static MyClass ()
{
EditorApplication.update += Update;
}
static void Update ()
{
Debug.Log("Updating");
}
}
例2:ウィンドウをロードした後に呼び出しを閉じる
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;
}
}
例3:ウィンドウのカスタマイズ
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);
}
}