Untiy 反射(Reflect)详解

       本文主要实现了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)的结构图。重要,增进对程序集的理解。

所以

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

一只小蔡鸡

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

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

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

打赏作者

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

抵扣说明:

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

余额充值