Unity 通过类名挂载脚本

本文介绍了游戏开发中如何通过类名动态挂载脚本,包括运行时通过Type.GetType()方法和编辑器下获取Assemblies进行类型加载。重点展示了强转类型和组件添加的操作过程。

一、游戏运行的时候通过类名挂载脚本

1、获取脚本的类型

//获取脚本的类型
Type type = Type.GetType(scriptName);
if(type != null)
{
	var common = gameObject.AddComponent(type);
}

2、如果你想要挂载的脚本位于命名空间中

//如果你想要挂载的脚本位于命名空间中
Type scriptType = Type.GetType("MyNamespace.MyScript");

3、强制转换

//将脚本强转, HeadCom继承自UIComponentBase
Type type = Type.GetType("HeadCom");
if(type != null)
{
	var common = gameObject.AddComponent(type);
	if(common != null)
	{
		var head = (UIComponentBase)common;
	}
}

4、挂载到指定对象

		// 获取游戏对象
        GameObject myGameObject = GameObject.Find("MyGameObject");

        // 获取脚本的类型
        Type scriptType = Type.GetType("MyScript");

        // 检查类型是否正确
        if (scriptType != null)
        {
            // 挂载脚本到游戏对象上
            myGameObject.AddComponent(scriptType);
        }
        else
        {
            Debug.LogError("无法找到名为 MyScript 的脚本类型。");
        }

二、编辑器下可以通过类名挂载脚本

 		string scriptName = "xxxCom";
        Debug.Log(scriptName);

        var assemblies = AppDomain.CurrentDomain.GetAssemblies();
        var defaultAssembly = assemblies.First(assembly => assembly.GetName().Name == "Assembly-CSharp");

		//string nameSpaceName = "xxxCom";
        //var type = defaultAssembly.GetType(nameSpaceName + "." + scriptName);//可以判断是否需要命名空间
        
        var type = defaultAssembly.GetType(scriptName);
        if (type == null)
        {
            Debug.Log("添加失败" + scriptName);
            return;
        }

        var scriptComponent = obj.GetComponent(type);
        if (!scriptComponent)
        {
            scriptComponent = obj.AddComponent(type);
        }
        Debug.Log("完成添加" + scriptName);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值