本文主要实现了Unity高级特性中的反射特性。配有案例和详细讲解。
前言:因为最近学习HybridCLR(华佗热更),里面用到了反射,但是反射这个特性之前用的很少,基本上都忘了,所以现在系统性的学习下。
1.首先,什么是反射(Reflect)?它的的作用是什么?
定义:在计算机科学中,反射指的是在运行时动态地获取、检查和操作程序中的类型信息,而在我们的Unity中反射允许开发者在运行时通过代码来访问和修改对象的属性、方法和字段,而不需要提前知道这些成员的具体信息。
作用:通过使用反射,开发者可以编写更加灵活和通用的代码,能够在运行时对不同类型的对象进行操作,从而增强了游戏的可扩展性和适应性。
2.反射(Reflect)在Unity中的使用
案例1:通过反射给物体添加脚本
ReflectClassName 脚本内容
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
public class ReflectClassName : MonoBehaviour
{
private void Start()
{
//加载当前程序集
Assembly asmb = System.Reflection.Assembly.Load(Assembly.GetExecutingAssembly().GetName());
//获取程序集里面的 TestReflect类
Type t = asmb.GetType("TestReflect");
gameObject.AddComponent(t);
}
}
TestReflect 脚本内容
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestReflect : MonoBehaviour
{
void Start()
{
Debug.Log("我是测试反射的脚本");
}
}
运行后结果:
可以看到,TestReflect脚本添加成功,脚本内start方法执行成功。我们的反射是成功了。
总结:反射步骤主要就是,1加载程序集,2获取程序集内需要反射的类,3执行具体操作。
案例2:反射调用方法(静态方法和非静态方法)
ReflectClassName 类
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
public class ReflectClassName : MonoBehaviour
{
private void Start()
{
//加载当前程序集
Assembly asmb = System.Reflection.Assembly.Load(Assembly.GetExecutingAssembly().GetName());
//获取程序集里面的 TestReflect类
Type t = asmb.GetType("TestReflect");
object instance = Activator.CreateInstance(t); //非静态方法要先实例化
t.GetMethod("Run1").Invoke(null, null);
t.GetMethod("Run").Invoke(instance, null); //非静态方法,穿参
gameObject.AddComponent(t);
}
}
TestReflect类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestReflect : MonoBehaviour
{
void Start()
{
Debug.Log("我是测试反射的脚本");
}
public void Run() //非静态方法
{
Debug.Log(111111);
}
public static void Run1()
{
Debug.Log(22222);
}
}
为了方便理解,这里补一张程序集(Assembly)的结构图。重要,增进对程序集的理解。
所以