NGUI源码分析

#if UNITY_EDITOR
private
void OnValidate () {   // 这个函数在当监视面板上有数据被修改时调用 }
#endif
//添加宏定义后有利于代码清晰。
private void OnDrawGizmosSelected(){
  Mathf.Clamp01(float x ) //x 在0到1 之间
  Mathf.Round(float x) //四舍五入
  Gizmos.color = Color.yellow;//接下来的Gizmos的颜色
  Gizmos.DrawSphere(p, 0.2F);//在P点画一个R=0.5f的球
}

 private void OnDrawGizmos(){
     Gizmos.color = Color.yellow;
   Gizmos.DrawWireCube (transform.position, new Vector3 (1,1,0f));
  }

  // 上一个函数选中时才被调用,无论是否选中都调用。

 添加工具栏按钮

 

    [MenuItem("NGUI/Open/Atlas Maker", false, 9)]
    [MenuItem("Assets/NGUI/Open Atlas Maker", false, 0)]//这个例子说明给同一个功能添加多个功能按钮
    static public void OpenAtlasMaker ()
    {
        EditorWindow.GetWindow<UIAtlasMaker>(false, "Atlas Maker", true).Show();
    }
   [ContextMenu("save data")] //添加菜单,详见官网

 

using UnityEngine;
using System.Collections;
using UnityEditor;
[CanEditMultipleObjects]//此属性用于定义同时可编辑多个对象的数值。
[CustomEditor(typeof(DataInEditer))]
public class EditorData : Editor {
    public override void OnInspectorGUI (){
        NGUIEditorTools.SetLabelWidth(100f);
        NGUIEditorTools.DrawProperty("Scaling Style", serializedObject, "int_Editer");
        NGUIEditorTools.DrawProperty("Scaling Style", serializedObject, "int_Editer");
        NGUIEditorTools.SetLabelWidth(80f);
        NGUIEditorTools.DrawProperty("today", serializedObject, "today");
        NGUIEditorTools.DrawProperty("curve", serializedObject, "curve");
        serializedObject.ApplyModifiedProperties();//应用所修改的数据
    }

    void OnSceneGUI(){// 选中对象时在Scene视图被调用,在此函数中可以捕捉键盘事件
        GUI.Label(new Rect(10f,10f, 20f, 20f), "hehe", "PreLabel");
        //GUI.Box(new Rect(0f, 0f, 1f, 2f), "", "WinBtnInactiveMac");
    }
}

 

using UnityEngine;
using UnityEditor;
using System.Collections;
public class createCube : EditorWindow {
    Rect windowRect;
    [MenuItem("Window/CreateCube")]
    public static void showMyWindow(){
        EditorWindow.GetWindow(typeof(createCube));
    }
    void OnGUI()
    {
        windowRect = new Rect(0, 0, Screen.width, Screen.height);
        if(Event.current.type == EventType.ContextClick)
        {
            Vector2 mousePos = Event.current.mousePosition;
            if(windowRect.Contains(mousePos))
            {
                GenericMenu menu = new GenericMenu();
                menu.AddItem(new GUIContent("CreateCube"), false, createMenu, "createCube");
                menu.ShowAsContext();
            }
        }
    }

    void createMenu(object obj){
        GameObject.CreatePrimitive(PrimitiveType.Cube);
    }
}
View Code

窗口编程扩展

    [MenuItem("Tools/程序/测试Slection/创建目录")]//目录操作接口,需要引入相应的命名空间  using System.IO
static void CreatDirection() { string prefabsPath = "Assets/Prefabs/luocr"; if (!Directory.Exists(prefabsPath)) { Directory.CreateDirectory(prefabsPath); } AssetDatabase.Refresh(); }

 

    static void GetSortingLayerNames()   {  
        Type t = typeof(InternalEditorUtility);  
        PropertyInfo prop = t.GetProperty("sortingLayerNames", BindingFlags.Static | BindingFlags.NonPublic);  
        string[] x=(string[])prop.GetValue(null, null);
        foreach(string ms in x){
            Debug.Log("<color=yellow>"+ms.ToString()+"</color>");
        }
    }//反射出所有的sortingLayerNames 添加命名空间 System.Reflacting, UnityEditorInteral
    static void LearnOperation(){
        Texture2D selectObj=Selection.activeObject as Texture2D;
        Debug.Log(AssetDatabase.GetAssetPath(selectObj.GetInstanceID()));//获取当前对象物理路径
        bool a=true,b=false;
        Debug.Log(a&=b);//a&=b  =>  a=a&b; 当且仅当a=ture,b=true 是返回ture. 与 && 不同的是 a&&b 是只要a 为false 则不再计算b 直接返还false
        //importer.GetNPOTScale() == TextureImporter::kNPOTKeep 错误,产生原因:NGUI合成图集的时候图片的格式必须是Texture
    }
using UnityEngine;
using System.Collections;
using UnityEditor;
public class LuoTestAccess : AssetPostprocessor {
    static void OnPostprocessAllAssets(string[] importedAssets,string[] deletedAssets,string[] movedAssets,string[] movedFromAssetPaths)
    {
        for(int a=0;a<importedAssets.Length;a++)
        {
            Debug.Log(importedAssets[a]+"importedAssets");
        }
        for(int b=0;b<deletedAssets.Length;b++)
        {
            Debug.Log(deletedAssets[b]+"deletedAssets");
        }
        for(int c=0;c<movedAssets.Length;c++)
        {
            Debug.Log(movedAssets[c]+"movedAssets");
        }
        for(int d=0;d<movedFromAssetPaths.Length;d++)
        {
            Debug.Log(movedFromAssetPaths[d]+"movedFromAssetPaths");
        }
    }
}// 导入资源设置

 粒子控制

using UnityEngine;
using System.Collections;
public class Sysqwe : MonoBehaviour {
    ParticleSystem m_System;
    ParticleSystem.Particle[] m_Particles;
    public float m_Drift = 0.01f;
    SpriteRenderer render;
    private int dong=0;
    bool kaishi;
    void Start(){
        render=GetComponent<SpriteRenderer>();
        TimerMgr.Instance.AddTimer(2,()=>{
            InitializeIfNeeded();
            // GetParticles is allocation free because we reuse the m_Particles buffer between updates
            int numParticlesAlive = m_System.GetParticles(m_Particles);
            // Change only the particles that are alive
            for (int i = 0; i < numParticlesAlive; i++){
                Color c=new Color((float)i/(float)numParticlesAlive,1-(float)i/(float)numParticlesAlive,1,1);
                m_Particles[i].color=ren(i/64,i%64);
                m_Particles[i].position=new Vector3((float)(i/64)/10,(float)(i%64)/10,0);
            }
            m_System.SetParticles(m_Particles, numParticlesAlive);
            kaishi=true;
        });
    }

    private void LateUpdate(){
        if(!kaishi)return;
        int numParticlesAlive = m_System.GetParticles(m_Particles);
        dong+=64;
        if(dong>numParticlesAlive)return;
        for (int i = 0; i < dong; i++)
        {
            m_Particles[7231-i].velocity += Vector3.right * m_Drift;
        }
        // Apply the particle changes to the particle system
        m_System.SetParticles(m_Particles, numParticlesAlive);
    }
    
    void InitializeIfNeeded(){
        if (m_System == null)
            m_System = GetComponent<ParticleSystem>();
        
        if (m_Particles == null || m_Particles.Length < m_System.maxParticles)
            m_Particles = new ParticleSystem.Particle[m_System.maxParticles]; 
    }

    private Color ren(int x,int y){
        Texture2D d=render.sprite.texture;
        return d.GetPixel(x,y);
    }


}

 打包资源

using UnityEngine;
using System.Collections;
using UnityEditor;
public class SysqweEditor : Editor {
    [MenuItem("Tools/程序/打包资源")]
    static void BuildAb(){
        Object[] selectobj=Selection.GetFiltered(typeof(Object),SelectionMode.DeepAssets);
        foreach(Object obj in selectobj){
            string targetPath=Application.dataPath+"/StreamingAssets/"+obj.name+".assetbundle";//注意后缀
            if (BuildPipeline.BuildAssetBundle (obj, null, targetPath, BuildAssetBundleOptions.UncompressedAssetBundle | BuildAssetBundleOptions.CollectDependencies,BuildTarget.StandaloneWindows)){//最后一个参数是目标平台,针对不同平台打的资源包是不一致的,标记为PC则Android不能用,IOS也不能用
                Debug.Log(obj.name +"资源打包成功");
            } 
            else 
            {
                Debug.Log(obj.name +"资源打包失败");
            }
            AssetDatabase.Refresh();
        }
    }
}

读取资源包

using UnityEngine;
using System.Collections;
public class Sysqwe : MonoBehaviour {
    public Rect mRect=new Rect(10,10,10,10);
    GameObject c0009;
    void Update(){
        if(Input.GetKeyDown(KeyCode.B)){
            string path=Application.streamingAssetsPath + "/" + "C0009.assetbundle";//注意后缀
            Debug.Log("path  "+path);
            AssetBundle ab =AssetBundle.CreateFromFile(path);//使用此方法加载资源包是资源在打包的过程中是不能被压缩的
            if(null==ab){
                Debug.Log("ab is null");
            }
            GameObject go= ab.Load("C0009")as GameObject;
            c0009=Instantiate(go)as GameObject;
        }
        if(Input.GetKeyDown(KeyCode.V)){
            c0009.GetComponent<Animator>().SetInteger("animsCondition",1);
        }
    }
}

日志

/*
 * File: Assets/Scripts/Game/Utility/LoggerUtility.cs
 * Project: ****
 * Company: Lucky
 * Code Porter: D.S.Qiu 
 * Create Date: 10/9/2015 10:11:53 PM
 */

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
#if UNITY_EDITOR
using System.Reflection;
using UnityEditor;
using UnityEditor.Callbacks;
#endif
using UnityEngine;
using Debug = UnityEngine.Debug;

namespace Utility
{
    public class LogUtility
    {
        public enum LogLevel : byte
        {
            None = 0,
            Exception = 1,
            Error = 2,
            Warning = 3,
            Info = 4,
        }
        
        public static LogLevel logLevel = LogLevel.Info;
        public static string infoColor = "#909090";
        public static string warningColor = "orange";
        public static string errorColor = "red";
        
        public static void LogBreak(object message, UnityEngine.Object sender = null)
        {
            LogInfo(message, sender);
            Debug.Break();
        }
        
        public static void LogFormat(string format, UnityEngine.Object sender, params object[] message)
        {
            if (logLevel >= LogLevel.Info)
                LogLevelFormat(LogLevel.Info, string.Format(format, message), sender);
        }
        
        public static void LogFormat(string format, params object[] message)
        {
            if (logLevel >= LogLevel.Info)
                LogLevelFormat(LogLevel.Info, string.Format(format, message), null);
        }
        
        public static void LogInfo(object message, UnityEngine.Object sender = null)
        {
            if(logLevel >= LogLevel.Info)
                LogLevelFormat(LogLevel.Info,message,sender);
        }
        
        public static void LogWarning(object message, UnityEngine.Object sender = null)
        {
            if (logLevel >= LogLevel.Warning)
                LogLevelFormat(LogLevel.Warning, message,  sender);
        }
        
        public static void LogError(object message, UnityEngine.Object sender = null)
        {
            if (logLevel >= LogLevel.Error)
            {
                LogLevelFormat(LogLevel.Error, message, sender);
            }
        }
        
        public static void LogException(Exception exption, UnityEngine.Object sender = null)
        {
            if (logLevel >= LogLevel.Exception)
            {
                LogLevelFormat(LogLevel.Exception, exption, sender);
            }
        }
        
        private static void LogLevelFormat(LogLevel level, object message, UnityEngine.Object sender)
        {
            string levelFormat =  level.ToString().ToUpper();
            StackTrace stackTrace = new StackTrace(true);
            var stackFrame = stackTrace.GetFrame(2);
            #if UNITY_EDITOR
            s_LogStackFrameList.Add(stackFrame);
            #endif
            string stackMessageFormat = Path.GetFileName(stackFrame.GetFileName()) + ":" + stackFrame.GetMethod().Name + "():at line " + stackFrame.GetFileLineNumber();
            string timeFormat = "Frame:" + Time.frameCount + "," + DateTime.Now.Millisecond + "ms";
            string objectName = string.Empty;
            string colorFormat = infoColor;
            if (level == LogLevel.Warning)
                colorFormat = warningColor;
            else if (level == LogLevel.Error)
                colorFormat = errorColor;
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("<color={3}>[{0}][{4}][{1}]{2}</color>", levelFormat, timeFormat, message, colorFormat, stackMessageFormat);
            Debug.Log(sb,sender);
        }
        
        #if UNITY_EDITOR
        private static int s_InstanceID;
        private static int s_Line = 104;
        private static List<StackFrame> s_LogStackFrameList = new List<StackFrame>();
        //ConsoleWindow
        private static object s_ConsoleWindow;
        private static object s_LogListView;
        private static FieldInfo s_LogListViewTotalRows;
        private static FieldInfo s_LogListViewCurrentRow;
        //LogEntry
        private static MethodInfo s_LogEntriesGetEntry;
        private static object s_LogEntry;
        //instanceId 非UnityEngine.Object的运行时 InstanceID 为零所以只能用 LogEntry.Condition 判断
        private static FieldInfo s_LogEntryInstanceId;
        private static FieldInfo s_LogEntryLine;
        private static FieldInfo s_LogEntryCondition;
        static LogUtility()
        {
            s_InstanceID = AssetDatabase.LoadAssetAtPath("Assets/ZLuoXiaoLong/Script/Loglong.cs",typeof(MonoScript)).GetInstanceID();
            s_LogStackFrameList.Clear();
            
            GetConsoleWindowListView();
        }
        
        private static void GetConsoleWindowListView()
        {
            if (s_LogListView == null)
            {
                Assembly unityEditorAssembly = Assembly.GetAssembly(typeof(EditorWindow));
                Type consoleWindowType = unityEditorAssembly.GetType("UnityEditor.ConsoleWindow");
                FieldInfo fieldInfo = consoleWindowType.GetField("ms_ConsoleWindow", BindingFlags.Static | BindingFlags.NonPublic);
                s_ConsoleWindow = fieldInfo.GetValue(null);
                FieldInfo listViewFieldInfo = consoleWindowType.GetField("m_ListView", BindingFlags.Instance | BindingFlags.NonPublic);
                s_LogListView = listViewFieldInfo.GetValue(s_ConsoleWindow);
                s_LogListViewTotalRows = listViewFieldInfo.FieldType.GetField("totalRows", BindingFlags.Instance | BindingFlags.Public);
                s_LogListViewCurrentRow = listViewFieldInfo.FieldType.GetField("row", BindingFlags.Instance | BindingFlags.Public);
                //LogEntries
                Type logEntriesType = unityEditorAssembly.GetType("UnityEditorInternal.LogEntries");
                s_LogEntriesGetEntry = logEntriesType.GetMethod("GetEntryInternal", BindingFlags.Static | BindingFlags.Public);
                Type logEntryType = unityEditorAssembly.GetType("UnityEditorInternal.LogEntry");
                s_LogEntry = Activator.CreateInstance(logEntryType);
                s_LogEntryInstanceId = logEntryType.GetField("instanceID", BindingFlags.Instance | BindingFlags.Public);
                s_LogEntryLine = logEntryType.GetField("line", BindingFlags.Instance | BindingFlags.Public);
                s_LogEntryCondition = logEntryType.GetField("condition", BindingFlags.Instance | BindingFlags.Public);
            }
        }
        private static StackFrame GetListViewRowCount()
        {
            GetConsoleWindowListView();
            if (s_LogListView == null)
                return null;
            else
            {
                int totalRows = (int)s_LogListViewTotalRows.GetValue(s_LogListView);
                int row = (int)s_LogListViewCurrentRow.GetValue(s_LogListView);
                int logByThisClassCount = 0;
                for (int i = totalRows - 1; i >= row; i--)
                {
                    s_LogEntriesGetEntry.Invoke(null, new object[] { i, s_LogEntry });
                    string condition = s_LogEntryCondition.GetValue(s_LogEntry) as string;
                    //判断是否是由LoggerUtility打印的日志
                    if (condition.Contains("][") && condition.Contains("Frame"))
                        logByThisClassCount++;
                }
                
                //同步日志列表,ConsoleWindow 点击Clear 会清理
                while (s_LogStackFrameList.Count > totalRows)
                    s_LogStackFrameList.RemoveAt(0);
                if (s_LogStackFrameList.Count >= logByThisClassCount)
                    return s_LogStackFrameList[s_LogStackFrameList.Count - logByThisClassCount];
                return null;
            }
        }
        
        [UnityEditor.Callbacks.OnOpenAssetAttribute(0)]
        public static bool OnOpenAsset(int instanceID, int line)
        {
            if (instanceID == s_InstanceID && s_Line == line)
            {
                var stackFrame = GetListViewRowCount();
                if (stackFrame != null)
                {
                    string fileName = stackFrame.GetFileName();
                    string fileAssetPath = fileName.Substring(fileName.IndexOf("Assets"));
                    AssetDatabase.OpenAsset(AssetDatabase.LoadAssetAtPath(fileAssetPath,typeof(MonoScript)),stackFrame.GetFileLineNumber());
                    return true;
                }
            }
            
            return false;
        }
        #endif
    }
    
}

 单个文件产生MD5码方法

using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Collections.Generic;  
using System.Text;  
using System.Security.Cryptography;  
using System.IO;  
public class MyMD5: Editor {
    public static string getFileHash(string filePath)  
    {             
        try  
        {  
            FileStream fs = new FileStream(filePath, FileMode.Open);  
            int len = (int)fs.Length;  
            byte[] data = new byte[len];  
            fs.Read(data, 0, len);  
            fs.Close();  
            MD5 md5 = new MD5CryptoServiceProvider();  
            byte[] result = md5.ComputeHash(data);  
            string fileMD5 = "";  
            foreach (byte b in result)  
            {  
                fileMD5 += b.ToString();  
            }  
            return fileMD5;     
        }  
        catch (FileNotFoundException e)  
        {  
            Debug.Log(e.Message);
            return "";  
        }                                   
    } 
    [MenuItem("Tools/程序/输出MD5")]
    static void ShuChuMd5()
    {  
        string md5 = getFileHash(@"E:\Working\trunk\code\Werther Quest Project\Assets\Resources\Perfab\NPC\C0003.prefab");  
        Debug.Log(md5);
        Debug.Log(md5.Length);
    }  
}

 图片导入进程截获

public class TextureImport:AssetPostprocessor
{
    void OnPreprocessTexture()
    {
        Debug.Log("导入图片时被调用");
    } 
}

 

 posted on 2016-04-19 14:59  1039781968  阅读(270)  评论(0)    收藏  举报