Unity通过组件名称字符串添加脚本
一、说明(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中。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现