Version: 2017.2

SyncEventAttribute

class in UnityEngine.Networking

切换到手册

描述

This is an attribute that can be put on events in NetworkBehaviour classes to allow them to be invoked on client when the event is called on the sserver.

[SyncEvent] events are called by user code on UNET servers, and then invoked on corresponding client objects on clients connected to the server. The arguments to the Event call are seriialized across the network, so that the client event is invoked with the same values as the function on the server. These events must begin with the prefix "Event".

using UnityEngine;
using UnityEngine.Networking;

public class DamageClass : NetworkBehaviour { public delegate void TakeDamageDelegate(int amount, float dir);

[SyncEvent] public event TakeDamageDelegate EventTakeDamage;

[Command] public void CmdDoMe(int val) { EventTakeDamage(val, 1.0f); } }

public class Other : NetworkBehaviour { public DamageClass damager; int health = 100;

void Start() { if (NetworkClient.active) damager.EventTakeDamage += TakeDamage; }

public void TakeDamage(int amount, float dir) { health -= amount; } }

SyncEvent 允许将网络化操作传播到附加到对象的其他脚本。在上面的示例中,Other 类在 DamageClass 上注册 TakeDamage 事件。当事件发生在服务器上的 DamageClass 上时,系统将在客户端对象上的 Other 类上调用 TakeDamage() 方法。这允许创建模块化网络感知系统,该系统可以通过响应自身生成的事件的新脚本进行扩展。

变量

channel应该用于发送此事件的 UNET QoS 通道。