首页 > 代码库 > 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除外)