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中。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

平杨猪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值