Unity 项目中委托Delegate用法案例

简介: Unity中Delegate的用法场景本文提供全流程,中文翻译。 Chinar 坚持将简单的生活方式,带给世人!(拥有更好的阅读体验 —— 高分辨率用户请根据需求调整网页缩放比例) China...

Unity中Delegate的用法场景


本文提供全流程,中文翻译。

Chinar 坚持将简单的生活方式,带给世人!

(拥有更好的阅读体验 —— 高分辨率用户请根据需求调整网页缩放比例)



Chinar —— 心分享、心创新!

助力快速理解 C# Delegate的基本用法

为新手节省宝贵的时间,避免采坑!


Chinar 教程效果:
这里写图片描述



全文高清图片,点击即可放大观看 (很多人竟然不知道)


1

Delegate —— 委托


Unity 中,委托多用于当某个值,或者物体状态发生改变的时候

其他一些操作需要同时进行监听

一旦状态发生,改变,所有注册在委托中的函数,都会被调用

举个栗子黑白88
当警察出来的时候,小偷就得逃跑

当服务员叫餐叫号的时候,叫到谁,就该谁取餐

等等,诸如此类的场景


2

Store Model —— 商店模式


这里以一个简单的 商店模式 来模拟流程

用委托实现,群体的函数、方法注册到对象中

注意:

我们需要 1 个主脚本用来管理 :服务员

3 个顾客类:顾客 A/B/C

为了更加生动, Chinar 用了 iTween 来处理动画效果

页面布局如下
举个栗子黑白88
这里写图片描述
采用委托的方式,通知所有顾客,谁该干什么

分别通知对应群体对象
这里写图片描述


3

Waiter —— 服务员脚本


服务员脚本,用于管理委托对象,并在相应的按钮中调用对象

然后委托对象,状态发生改变,就会通知所有注册到对象中的函数,都被调用
举个栗子黑白88
这里写图片描述

using System.Collections;
using UnityEngine;
using UnityEngine.UI;


//委托传递的是方法/函数
public delegate void CallNumber(); //使用时,必须要声明委托对象;返回值类型,要与将要注册到委托对象中的函数,返回值类型保持一致!


public delegate int GetOuntHandler(); /*也就是:委托方法和被委托方法的类型必须保持一致*/


public delegate bool SomeFood(string food);
/*以上是委托函数的声明方式*/


/// <summary>
/// Chinar委托测试类
/// </summary>
public class ChinarDelegate : MonoBehaviour
{
    //方法是引用类型的对象
    //委托将一个函数 转换成了一个函数对象
    //可以将 这个函数 以 对象 的形式进行传递
    public CallNumber callNumber;  //定义委托对象   这里定义的是一个委托对象
    public SomeFood   someFood;    //定义一个有参数有返回值的委托
    public Text       WaiterSpeak; //服务员说话内容文本
    public Text       BigScreen;   //服务员说话内容文本
    public GameObject G2GameObject;

    /// <summary>
    /// 叫号方法 —— 绑定按钮
    /// </summary>
    public void OnClickCallNumber()
    {
        callNumber();
        Content(Color.red, "叫号啦!!!", "请100号顾客取餐!");
    }


    /// <summary>
    /// 汉堡包 —— 绑定按钮
    /// </summary>
    public void OnClickHamburger()
    {
        if (!GameObject.Find("Hamburger(Clone)")) Instantiate(Resources.Load("Hamburger"));
        someFood("汉堡");
        Content(UserTwo.temporaryText.color, "谁的汉堡?", "请B号顾客取餐!");
    }


    /// <summary>
    /// 可乐 —— 绑定按钮
    /// </summary>
    public void OnClickCola()
    {
        someFood("可乐");
        Content(UserTwo.temporaryText.color, "谁点的可乐?", "请C号顾客取餐!");
    }


    /// <summary>
    /// 封装内容简化代码
    /// </summary>
    /// <param name="color"></param>
    /// <param name="speak"></param>
    /// <param name="bigScreen"></param>
    private void Content(Color color, string speak, string bigScreen)
    {
        WaiterSpeak.text  = speak;
        WaiterSpeak.color = color;
        BigScreen.text    = bigScreen;
        StopCoroutine(ClearText());
        StartCoroutine(ClearText());
    }


    /// <summary>
    /// 清理文本内容
    /// </summary>
    /// <returns></returns>
    IEnumerator ClearText()
    {
        yield return new WaitForSeconds(3);
        WaiterSpeak.text = "";
        BigScreen.text   = "";
    }


    public static void Move(GameObject gameObject)
    {
        iTween.MoveTo(gameObject, iTween.Hash("time",                                     .7f, "x",     6.69f,                         "y",        8.6f, "easetype", iTween.EaseType.easeOutCubic));
        iTween.MoveTo(gameObject, iTween.Hash("time",                                     .7f, "x",     -13.38f,                       "y",        2.8f, "easetype", iTween.EaseType.easeOutCubic, "delay", 2.4f));
        iTween.ScaleTo(gameObject.transform.Find("Speak").gameObject, iTween.Hash("time", .7f, "scale", new Vector3(0.3f, 0.3f, 0.3f), "easetype", iTween.EaseType.easeOutCubic));
        iTween.ScaleTo(gameObject.transform.Find("Speak").gameObject, iTween.Hash("time", .7f, "scale", new Vector3(1,    1,    1),    "easetype", iTween.EaseType.easeOutCubic, "delay", 2.4f));
        iTween.ScaleTo(gameObject,                                    iTween.Hash("time", .7f, "scale", new Vector3(3,    3,    3),    "easetype", iTween.EaseType.easeOutCubic));
        iTween.ScaleTo(gameObject,                                    iTween.Hash("time", .7f, "scale", new Vector3(1,    1,    1),    "easetype", iTween.EaseType.easeOutCubic, "delay", 2.4f));
        iTween.RotateTo(gameObject, iTween.Hash("time",                                   .7f, "z",     -360.01f,                      "easetype", iTween.EaseType.easeOutCubic));
    }
}

4

Client A/B/C Class —— 顾客A/B/C脚本


3 个顾客类:顾客 A/B/C
举个栗子黑白88
这里写图片描述

using System.Collections;
using UnityEngine;
using UnityEngine.UI;


/// <summary>
/// 顾客A
/// </summary>
public class UserOne : MonoBehaviour
{
    public  ChinarDelegate Cd;            //声明委托对象所在的类对象//实例化一个类对象 在内存中重新开辟一块内存空间 创建了一个新的类对象
    public static Text temporaryText; //临时文本,设置公有静态是为了 方便调用颜色属性,去改变服务员文本颜色



    void Start()
    {
        Cd            = GameObject.Find("MountScript").GetComponent<ChinarDelegate>(); //赋值
        Cd.callNumber += LookScreen;
        temporaryText = transform.Find("Speak/Text").GetComponent<Text>();

        //添加委托函数
        //委托函数的添加方式:可以用 = 号 
        //如果想添加多个委托 需要用 +=号
        //删除委托用: -=
    }


    /// <summary>
    /// 抬头看大屏幕
    /// </summary>
    public void LookScreen()
    {
        temporaryText.text = "顾客A看向大屏幕";
        StopCoroutine(ClearText());
        StartCoroutine(ClearText());
    }


    /// <summary>
    /// 清理文本内容
    /// </summary>
    /// <returns></returns>
    IEnumerator ClearText()
    {
        yield return new WaitForSeconds(3);
        temporaryText.text = "";
    }
}

顾客 B:

using System.Collections;
using UnityEngine;
using UnityEngine.UI;


/// <summary>
/// 顾客B
/// </summary>
public class UserTwo : MonoBehaviour
{
    public        ChinarDelegate Cd;
    public static Text           temporaryText; //临时文本,设置公有静态是为了 方便调用颜色属性,去改变服务员文本颜色


    void Start()
    {
        Cd            =  GameObject.Find("MountScript").GetComponent<ChinarDelegate>();
        Cd.callNumber += LookScreen; //2添加委托函数
        Cd.someFood   += WaitHamburger;
        temporaryText =  transform.Find("Speak/Text").GetComponent<Text>();
    }


    /// <summary>
    /// 服务员叫汉堡时,委托事件才会触发
    /// </summary>
    public bool WaitHamburger(string food)
    {
        if (food == "汉堡")
        {
            temporaryText.text = "这里,我要汉堡";
            ChinarDelegate.Move(gameObject);
            iTween.MoveTo(GameObject.Find("Hamburger(Clone)"), iTween.Hash("oncomplete", "DestroyHamburger", "oncompletetarget", gameObject,           "time",     .7f,                          "x",     -13.38, "y", 2.8f, "easetype", iTween.EaseType.easeOutCubic, "delay", 2.4f));
            iTween.ScaleTo(GameObject.Find("Hamburger(Clone)"), iTween.Hash("time",      .7f,                "scale",            new Vector3(0, 0, 0), "easetype", iTween.EaseType.easeOutCubic, "delay", 2.4f));

            StopCoroutine(ClearText());
            StartCoroutine(ClearText());
            return true;
        }
        return false;
    }


    private void DestroyHamburger()
    {
        Destroy(GameObject.Find("Hamburger(Clone)"));
    }


    /// <summary>
    /// 抬头看大屏幕
    /// </summary>
    public void LookScreen()
    {
        temporaryText.text = "顾客B看向大屏幕";
        StopCoroutine(ClearText());
        StartCoroutine(ClearText());
    }


    /// <summary>
    /// 清理文本内容
    /// </summary>
    /// <returns></returns>
    IEnumerator ClearText()
    {
        yield return new WaitForSeconds(3);
        temporaryText.text = "";
    }
}

顾客 C:

using System.Collections;
using UnityEngine;
using UnityEngine.UI;


/// <summary>
/// 顾客C
/// </summary>
public class UserThree : MonoBehaviour
{
    public        ChinarDelegate Cd;            //委托对象
    public static Text           temporaryText; //临时文本,设置公有静态是为了 方便调用颜色属性,去改变服务员文本颜色


    void Start()
    {
        Cd            =  GameObject.Find("MountScript").GetComponent<ChinarDelegate>(); //获取对象
        Cd.callNumber += LookScreen;                                                    //当 叫号的委托对象中,有多个方法调用时,需要用 += 添加
        Cd.someFood   += WaitCola;                                                      //委托对象添加 顾客3的可乐
        temporaryText =  transform.Find("Speak/Text").GetComponent<Text>();
    }


    /// <summary>
    /// 服务员叫可乐时,委托事件才会触发
    /// </summary>
    public bool WaitCola(string food)
    {
        if (food == "可乐")
        {
            temporaryText.text = "这里,我要的可乐";
            ChinarDelegate.Move(gameObject);
            StopCoroutine(ClearText());
            StartCoroutine(ClearText());
            return true;
        }

        return false;
    }


    /// <summary>
    /// 抬头看大屏幕
    /// </summary>
    public void LookScreen()
    {
        temporaryText.text = "顾客C看向大屏幕";
        StopCoroutine(ClearText());
        StartCoroutine(ClearText());
    }


    /// <summary>
    /// 清理文本内容
    /// </summary>
    /// <returns></returns>
    IEnumerator ClearText()
    {
        yield return new WaitForSeconds(3);
        temporaryText.text = "";
    }
}

5

Demo —— 演示样本


Chinar 提供了演示样本,节省大家搭建界面的时间

便于大家理解
举个栗子黑白88

Chinar 委托演示项目


支持

May Be —— 搞开发,总有一天要做的事!


拥有自己的服务器,无需再找攻略!

Chinar 提供一站式教程,闭眼式创建!

为新手节省宝贵时间,避免采坑!


先点击领取 —— 阿里全产品优惠券 (享受最低优惠)


1 —— 云服务器超全购买流程 (新手必备!)

2 —— 阿里ECS云服务器自定义配置 - 购买教程(新手必备!)

3—— Windows 服务器配置、运行、建站一条龙 !

4 —— Linux 服务器配置、运行、建站一条龙 !



70

技术交流群:806091680 ! Chinar 欢迎你的加入


END

本博客为非营利性个人原创,除部分有明确署名的作品外,所刊登的所有作品的著作权均为本人所拥有,本人保留所有法定权利。违者必究

对于需要复制、转载、链接和传播博客文章或内容的,请及时和本博主进行联系,留言,Email: ichinar@icloud.com

对于经本博主明确授权和许可使用文章及内容的,使用时请注明文章或内容出处并注明网址
>

相关文章
|
9月前
|
图形学
|
1月前
|
C# 图形学
【Unity 3D】元宇宙案例之虚拟地球信息射线实战(附源码、演示视频和步骤 超详细)
【Unity 3D】元宇宙案例之虚拟地球信息射线实战(附源码、演示视频和步骤 超详细)
69 0
|
1月前
|
vr&ar C# 图形学
【Unity 3D】VR飞机拆装后零件说明功能案例实战(附源码和演示视频 超详细)
【Unity 3D】VR飞机拆装后零件说明功能案例实战(附源码和演示视频 超详细)
54 0
|
1月前
|
vr&ar C# 图形学
【Unity 3D】VR飞机动态拆装及引擎开关控制案例(附源码和演示视频 超详细)
【Unity 3D】VR飞机动态拆装及引擎开关控制案例(附源码和演示视频 超详细)
54 0
|
1月前
|
vr&ar 图形学
【Unity 3D】VR飞机起飞喷火游戏案例实战(附源码和演示视频 超详细)
【Unity 3D】VR飞机起飞喷火游戏案例实战(附源码和演示视频 超详细)
99 0
|
7月前
|
存储 运维 数据挖掘
服务器数据恢复—EMC Unity存储数据恢复案例
服务器数据恢复环境: EMC Unity某型号存储,连接了2台硬盘柜。2台硬盘柜上创建2组互相独立的POOL,2组POOL共有21块520字节硬盘。21块硬盘组建了2组RAID6,1号RAID6有11块硬盘. 2号RAID6有10块硬盘。 服务器故障&检测: 工作人员误操作,删除了2组POOL上的部分数据卷。
服务器数据恢复—EMC Unity存储数据恢复案例
|
10月前
|
数据可视化 C# 图形学
【unity造轮子】Unity ShaderGraph使用教程与各种特效案例
点关注不迷路,持续输出干货文章。 嗨,大家好,我是向宇。最近在玩ShaderGraph,决定把我自己实验的所有效果记录到这篇博客中,附带完整高清的连线动态图,希望对想要学习ShaderGraph的同学有所启发。后续有发现一些新的ShaderGraph我还会继续进行更新。
494 0
|
人工智能 算法 安全
开源游戏区块链项目分享:Unity开发的独立区块链
开源游戏区块链项目分享:Unity开发的独立区块 2023年了,区块链在这此时代热浪下都已经是即将燃尽的火苗了,而ChatGPT、Stable Diffusion等AI产品已经成为当下风口和热浪。然而区块链作为上一任浪热下的余晖,真的就这么完事了么?其实目前区块链在国内更多作为信用链存在,用于法律签约、物流运输、商务合作、加密合约等等公共底层方面。 而此文将不仅探讨区块链的其他实际用途,同时也开源了一个Unity3D C#编写的区块链代码,如果你是技术人员,刚好你做区块链项目,希望这个文章和代码能帮助到你。
569 0
|
前端开发 C# 图形学
unity入门必备的案例2.0
unity入门必备的案例你还不知道?
71 0
|
API 图形学
【unity实践demo】unity-2D游戏官方案例【2】
【unity实践demo】unity-2D游戏官方案例【2】
233 0