一、说明(AddComponent(string)已被官方弃用)
1. 通过Type.GetType(string typeName)来得到字符串对应的Type。
public Component AddComponent(Type componentType)
2. Type.GetType(typeName)能获取到自定义类的类型,但是获取Unity的组件不行。
例如Type.GetType(“Rigidbody”)值为null,其实是少了程序集。
所以如下正确:
Type type = Type.GetType("UnityEngine.Rigidbody, UnityEngine.PhysicsModule")
3. 获取Unity的组件程序集全名,再通过Type.GetType()得到的就不为null了。
string qualifiedName = typeof(Rigidbody).AssemblyQualifiedName; type = Type.GetType(qualifiedName);
二:C#代码
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class NewBehaviourScript : MonoBehaviour { string coms = "BoxCollider"; void OnValidate() { transform.AddComponentToString(coms); } } public static class ExtensionMethod { public static Component AddComponentToString(this Transform transform,string ComponentName) { string qualifiedName; Dictionary<string, string> ComponentQualifiedName = new Dictionary<string, string>(); //获取Unity的组件的全名 qualifiedName = typeof(BoxCollider).AssemblyQualifiedName; ComponentQualifiedName.Add("BoxCollider", qualifiedName); qualifiedName = typeof(Rigidbody).AssemblyQualifiedName; ComponentQualifiedName.Add("Rigidbody", qualifiedName); //....需要添加Unity的组件自行再加 Type type = null; Component component = transform.GetComponent(ComponentName); if (component == null) { if (ComponentQualifiedName.ContainsKey(ComponentName)) { type = Type.GetType(ComponentQualifiedName[ComponentName]); component = transform.gameObject.AddComponent(type); } else { type = Type.GetType(ComponentName); component = transform.gameObject.AddComponent(type); } } return component; } }
ExtensionMethod是一个扩展类,我将它扩展到Transform中,后续可以直接调用transform.AddComponentToString(string s);
如还有需要添加Unity的组件,还需要自行添加到ComponentQualifiedName中。