当前位置:   article > 正文

unity进阶学习笔记:消息框架_unity 消息系统

unity 消息系统

1 使用消息框架的目的

对于小型游戏,可能不需要任何框架,而是让各个游戏脚本直接相互通信。如要实现玩家受到攻击血量减少,通过玩家控制类向血条脚本发送消息减少血量。但是这样直接通信会导致各脚本通信关系记为复杂,并且每一个脚本都和多个脚本有联系,导致维护和更新十分困难

我们利用上节课讲的管理类,可以将一类脚本由一个管理类控制,如将玩家的功能放在玩家管理类下,将血条,背包等UI组件放在UI管理类下。这样要减少玩家血量,可以让玩家控制类向UI管理类发消息,然后UI管理类来改变血条。该方案对大部分小型游戏适用,但对于大型游戏或者网游,一旦管理类过多依然难以管理

我们在管理类基础上再封装一层消息框架用于管理类间的通信。这样每一个类会和消息框架通信,由消息框架找到对于管理类,再由管理类控制对于脚本。
在这里插入图片描述

编写消息框架

1 消息类:用于保存要传输的消息类型及内容

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Message
{
   
    public byte Type;
    public int Command;
    public object Content;

    public Message(byte type, int command, object content) {
   
        Type = type;
        Command = command;
        Content = content;
    }

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

这里我们的消息类定义三个参数Type, Command, Content。其中Type代表消息类型,这类大概很少,因此使用byte型保存即可以减少传输数据量。Command为具体的消息命令,使用int保存,之后可以定义不同值所对应的命令内容。Content为要传入的消息参数,类型不确定故设为object

为了明确各个类型和指令的具体含义,我们一般设置一个全局参数库用于存储各个指令名称和对应值,如下:

public class MessageType {
   
    // type
    public static byte Type_Audio = 1;
    public static byte Type_UI = 2;
    public static byte Type_Player = 3;
    // sound command
    public static int Audio_Play = 100;
    public static int Audio_Stop = 101;
    public static int Audio_Pause = 102;
    // UI command
    public static int UI_ShowPanal = 201;
    public static int UI_AddScore = 202;
    public static int UI_ShowShop = 203;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

2 管理组件:

这里我们创建一个类MonoBase,里面多一个虚拟方法ReceiveMessage用于接受消息。之后的组件程序全部继承MonoBase类实现消息接受功能

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MonoBase : MonoBehaviour
{
   

    // override in child class
    public virtual void ReceiveMessage(Message message) {
   

    }

    // Start is called before the first frame update
    void Start()
    {
   
        
    }

    // Update is called once per frame
    void Update()
    {
   
        
    }
}
<
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/761617
推荐阅读
相关标签
  

闽ICP备14008679号