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

被折叠的 条评论
为什么被折叠?



