Unity3d Development (18) monitor editor state changes, develop custom callbacks

Source: Internet
Author: User


article Songyang

This article is from the Asura road , prohibited for commercial purposes, reproduced please indicate the source.  

http://blog.csdn.net/fansongy/article/details/ 53318791


/span>

/p>





When I do the editor plugin, I always want to get the status change of the Listener editor. For example, open the editor to start running your own service. This will require the user to open the editor's event. For example, I want to cache some of the edits before the game exits the running mode, and then automate the processing of the data, so I need to exit the run-mode event. And so forth.

On the other hand, I want to use observer mode and be able to automate registration. Because I noticed that the callback when importing the resource AssetImporter was doing so. Users can receive callbacks only if they want to implement an interface. Greatly simplifies the process of expansion. Editor code does not have to consider efficiency issues, with the help of C # reflection, it is easy to implement this function.

Overview

The starting core of the entire framework is the attribute InitializeOnLoad . The script is reloaded when the Unity3d is run or started. When you use this macro, the editor automatically instantiates the labeled class into memory. So we can use this feature to pull up our entire service in its constructor. Here's a little trick. In the case of the Unity Editor, if you create an object in the constructor, it will be killed by other cleanup functions. I think it's the script initialization sequence, or the scene switching, for the exact reason that unity was asked. To solve this problem, I used the update function to jump a frame to execute the logic I should have.

Autoenrollment is the use of C # reflection, passing GetAssemblies and GetTypes getting all classes, and then creating the corresponding instance.

Packaging

I think there's a very good name for this class-- NightWatch . If you've never seen a song of Ice and Fire, it might be difficult to understand the framework. Overall, the framework tells the story of a teenager joining the night watchman and fighting outside the Great Wall ...

Realize

The interface classes are as follows:

public interface icrow{    //<summary>//Join the Nights Watch    ///</summary> void Enroll ( );    <summary>    //before to Enter Wild    //</summary> void Prepareforbattle ();    <summary>    //To the weirwood outside the wall    //</summary> void Faceweirwood ();    <summary>    //back to the Castle Black    //</summary> void Openthegate ();    <summary>    //Vow to the old God    //</summary> void Vow ();}

The instance classes are as follows:

Using unityengine;using system.collections;using system.collections.generic;using unityeditor; [Initializeonload]public class nightswatch{#region public Attributes #endregion #region Private Attributes PR    Ivate static list<icrow> m_crows = new list<icrow> (); #endregion #region Public Methods static Nightswatch () {if (!        Editorapplication.isplayingorwillchangeplaymode) {editorapplication.update + = Welcometocastleblack;        } else {editorapplication.update + = Beyondthewall;        }} static void Welcometocastleblack () {editorapplication.update-= Welcometocastleblack;        Debug.Log ("Welcome to Castle Black"); M_crows.        Clear ();        var crows = getallimplementtypes<icrow> (System.AppDomain.CurrentDomain);            foreach (Var eachcrow in Crows) {eachcrow.enroll (); M_crows.        ADD (Eachcrow); } editorapplication.update + = WAITFORwild; } static void Waitforwild () {if (Editorapplication.isplayingorwillchangeplaymode) {FOREAC            H (Var eachcrow in m_crows) {eachcrow.prepareforbattle ();        } editorapplication.update-= Waitforwild;        }} static void Beyondthewall () {editorapplication.update-= Beyondthewall;        Debug.Log ("Welcome to the Wild"); M_crows.        Clear ();        var crows = getallimplementtypes<icrow> (System.AppDomain.CurrentDomain);            foreach (Var eachcrow in Crows) {Eachcrow.faceweirwood (); M_crows.        ADD (Eachcrow);    } editorapplication.update + = Waitforcrowreturn; } static void Waitforcrowreturn () {if (!            Editorapplication.isplayingorwillchangeplaymode) {//debug.log ("Open the Door");            Editorapplication.update-= Waitforcrowreturn;        foreach (Var eachcrow in m_crows) {        Eachcrow.openthegate ();        } editorapplication.update + = Welcometocastleblack;        }} public static void Crowsvow () {foreach (var eachcrow in m_crows) {eachcrow.vow ();    }} [MenuItem ("Land/castleblack")] public static void Makevow () {nightswatch.crowsvow (); } #endregion #region Override Methods #endregion #region Private Methods public static t[] Getallimplementt        Ypes<t> (System.AppDomain aappdomain) where T:class {var result = new list<t> ();        var assemblies = Aappdomain.getassemblies (); foreach (var assembly in assemblies) {var types = assembly.            GetTypes (); foreach (var type in types) {if (typeof (T). IsAssignableFrom (type)) {if (!type). IsAbstract) {var tar = assembly. CreateInstance (type.         FullName) as T;               Result.                    ADD (TAR); }}}} return result.    ToArray (); } #endregion}

To explain briefly, all the interfaces are defined by the plot of the Song of Ice and Fire. When in the edit state, the corresponding instance class is created and the function is called, Enroll which is equivalent to Jon just entering Castleblack. When hit play runs, it is called First PrepareForBattle , which is equivalent to preparing for the battle in the castle. When the game starts to run, it will be called, which corresponds to the FaceToWeirWood outside of the city of the fish beam wood, generally before the trip is to pray for a bit. Then when the game is finished, it will be called OpenTheGate , corresponding to go back, shouting at the door under the Great Wall. Then there is an Vow interface, this is used to call the name of the Crow in the castle will be lined up to answer the word.

Use

Create two new instances: one is Jonsnow:

public class Jonsnow:  icrow{public    void Enroll ()    {        Debug.Log (this + "join the nightwatch!");    } Public    void Prepareforbattle ()    {        Debug.Log (this + "follow your lead!");    }    public void Faceweirwood ()    {        Debug.Log ("I ' m The Wolf in the");    }    public void Openthegate ()    {        Debug.Log (this + "request enter Castle Black");    }    public void Vow ()    {        Debug.Log (this + ' for the Watch ');}    }

One is Samwell:

public class Samwell:  icrow{public    void Enroll ()    {        Debug.Log (this + "I came form Lord Randyll Tarly,and I even his oldest son ... ");    public void Prepareforbattle ()    {        Debug.Log (this + "was not a ready yet ...");    public void Faceweirwood ()    {        Debug.Log ("I ' m a useless warrior,but * be ... helpful");    public void Openthegate ()    {        Debug.Log (this + "also want Enter");    }    public void Vow ()    {        Debug.Log (this + "for the. alive");}    
Test

When the code is written, it can be seen in the output that the two of them went to the Great Wall to report. Click to run the program, close the running program, there will be log output, the effect is as follows:


Where the red line is the Click Play action, the Green Line is the action to stop Unity running, and the log above the red line is output when unity is opened or recompiled. Everything is done as expected.

If you think this article is helpful to you, you can take a Top , not only do not want to be a father, but also let more people can see it ...

Unity3d Development (18) monitor editor state changes, develop custom callbacks

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.