首页 > 代码库 > unity3d中自动补全字段值(数组,list除外)
unity3d中自动补全字段值(数组,list除外)
做UI过程中,经常会有对应父物体上面挂载相关脚本,脚本里面定义对应的UILabel、UISprite等,可开发过程中经常会遇到对应的Object拖动到了错误的位置,所以写了如下小工具,便于将物体快速,准确,无误的赋值到对应位置,注:字段名字必须和物体名字一致。
代码如下:
using UnityEngine; using System.Collections; using UnityEditor; using System.Reflection; /** * 脚本用于自动填充字段值 * 要求物体名字和字段名字保持一致 */ public class SetFields : EditorWindow { private string strTemp = ""; [MenuItem ("CTool/SetFields")] static void Init () { SetFields window = (SetFields)EditorWindow.GetWindow (typeof(SetFields)); } void OnGUI () { EditorGUILayout.BeginVertical (); ComponentSelector.Draw<MonoScript> (null, _selectorCallBack, false); strTemp = EditorGUILayout.TextField ("输入脚本名字", strTemp); if (GUILayout.Button ("SetValue")) { SetScriptFields (); } EditorGUILayout.EndVertical (); } private void _selectorCallBack (object obj) { if (obj != null) { strTemp = ((TextAsset)obj).name; } } void OnInspectorUpdate () { this.Repaint (); } void SetScriptFields () { Transform[] obj = Selection.GetTransforms (SelectionMode.Unfiltered); for (int i = 0; i < obj.Length; i++) { Component info = obj [i].GetComponent (strTemp); if (info != null) { System.Type t = Types.GetType (strTemp, "Assembly-CSharp"); FieldInfo[] fileldList = t.GetFields (); for (int j = 0; j < fileldList.Length; j++) { _setFieldInfo (obj [i], fileldList [j].Name); } } } } private void _setFieldInfo (Transform trans, string fieldName) { System.Type type = trans.GetComponent (strTemp).GetType (); FieldInfo fieldInfo = type.GetField (fieldName); GameObject objTemp = GetGameObjectByName (trans.gameObject, fieldName); if (objTemp != null) { fieldInfo.SetValue (trans.GetComponent (strTemp), objTemp.GetComponent (fieldInfo.FieldType.ToString ())); } } private GameObject GetGameObjectByName (GameObject parent, string objName) { if (parent.name == objName) { return parent; } if (parent.transform.childCount < 1) { return null; } GameObject objTemp = null; for (int i = 0; i < parent.transform.childCount; i++) { GameObject obj = parent.transform.GetChild (i).gameObject; objTemp = GetGameObjectByName (obj, objName); if (objTemp != null) { break; } } return objTemp; } }
菜单栏中找到 CTool/SetFields点击打开,可看到如下界面,将父物体上面挂载的脚本拖动到图示位置,或直接输入脚本名字,点击SetValue按钮即可自动将字段赋值。
unity3d中自动补全字段值(数组,list除外)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。