Sending Global Events

ObjectNet provides a full API to allow the developer to send and listen to events by code.

That event can be global or local. Global Events can be listened to or sent by any part of your code, on the other hand, Local Events can only be sent or caught by the object who sends and listens to this event.

This section will cover Global Event, the Object Event is covered on Sending Events section.

Sending

This section covers how to send events over the network.

First, you need to create a unique identifier for this event, this identifier shall be a positive integer number.

const int CUSTOM_EVENT = 10000;

Events provide the possibility to send data, for example, in an event to restart a player position you may wish to send position information in the message. ObjectNet allows us to do this by using DataWritter.

This code illustrates how to send an event over the network, you can include data on the message to be received at the target destination.

       using (DataStream writer = new DataStream()) {
             writer.Write(this.targetPosition); // Vector3
             writer.Write(this.remaingLife); // float
             writer.Write(this.money); // int
             // Send event using the NetworkManager
             NetworkManager.Instance().Send(CUSTOM_EVENT, writer, DeliveryMode.Reliable);
       }

Listening

You can listen to events sent by other network peers and execute some action based on this event, this process is called by ObjectNet a Listener on an event.

This code illustrates how to listen to some network events, read data on these events, and take some action.

       public void Start() {
             NetworkManager.RegisterEvent(CUSTOM_EVENT, this.OnCustomEventReceived);
       }

      private void OnCustomEventReceived(IDataStream reader) {
            Vector3 receivedTargetPosition      = reader.Read<Vector3>();
            float   remaningLife                = reader.Read<float>();
            int     money                       = reader.Read<int>();
            // Update player with received information
            this.UpdatePlayer(receivedPosition, remaningLife, money);           
       }

On this piece of code, the CUSTOM_EVENT is registered to execute "OnCustomEventReceived" arrives.

The code of OnCustomEventReceived the first extract parameter in the same order that was sent. With this information, some method must be called to update an object, change status, create or destroy items, and another code to make your multiplayer game work.

Note: "OnCustomEventReceived" will not be triggered on the sender. Events are broadcast to other clients, not to the sender itself. You will need to execute `this.UpdatePlayer()` manually if thats what you want.

Full Code Example
using UnityEngine;
using com.onlineobject.objectnet;

public class SendGlobalEventExample : MonoBehaviour
{
        const int CUSTOM_EVENT = 10000;

        //Subscribe the reciever method to the event
       public void Start() {
           NetworkManager.RegisterEvent(CUSTOM_EVENT, this.OnCustomEventReceived);
       }
       
      private void Update(){
         //makes sure only the active running this code
         if (IsPassive()) return;
         // sends the event when ever the user press T
         if (Input.GetKeyDown(KeyCode.T)){
             using (DataStream writer = new DataStream()) {
                   writer.Write(this.targetPosition); // Vector3
                   writer.Write(this.remaingLife); // float
                   writer.Write(this.money); // int
                   // Send event
                   NetworkManager.Instance().Send(CUSTOM_EVENT, writer, DeliveryMode.Reliable);
             }
         }
      }
      
      //Event will trigger this method
      private void OnCustomEventReceived(IDataStream reader) {
            Vector3 receivedTargetPosition      = reader.Read<Vector3>();
            float   remaningLife                = reader.Read<float>();
            int     money                       = reader.Read<int>();
            // Update player with received information
            this.UpdatePlayer(receivedPosition, remaningLife, money);           
       }
       
       //regular method
       private void UpdatePlayer(Vector3 position, float remaingLife, int money){
           //any logic
        }
            
}
Replace

Global Events only accepts one Method to be subscribed to one event code at a time. So make sure if the object is destroyed and respawned to set Replace parameter to true. (for examle when scene is restarted).

BroadCast

When registering the event you have an option to broadcast the event to other clients. other wise the event will only be triggered on the server.

This tells the server to propagate the message coming from one client to all other clients.

Note: if the sender is the Server then all clients will recive the message regardless if broadcast was true or false, broadcast option is only for clients that want to communicate with other clients.

Supported Data Types

You can include the following data types on the event message.

int   uint   long   ulong   short   ushort   float   double 
-------------------------------------------------------------
byte   sbyte   byte[]   bool   string   char   char[]   enum
-------------------------------------------------------------
Vector2   Vector3   Vector4   Quaternion   Color   Matrix4x4

FAQ:

Show me an Example on how to send a list using DataStream

Here is an example that illustrate the write and read of a full list.

private List<int> Numbers = new List<int>();
        //any where in you script
        using (DataStream writer = new DataStream()){
           //write the length of the list
            writer.Write(this.Numbers.Count); // int
            //write each value on the list
            for (int i = 0; i < Numbers.Count; i++){
                writer.Write(Numbers[i]);
            }
            // Send event
            NetworkManager.Instance().Send(LOCAL_CUSTOM_EVENT, writer, DeliveryMode.Reliable);
        }

     //On the reciver
   private void OnCustomEventReceivedOnObject(IDataStream reader){
       //read the length
       int listLength = reader.Read<int>();
       //read and update each value on the list 
       for (int i = 0; i < listLength; i++){
           Numbers[i] = reader.Read<int>();
       }
   }
Why the Event is not triggered on the sender?

Events will not be triggered on the sender. Custom events are broadcast to other clients, not to the sender itself.

When a client sends a DataStream message, the message is not looped back to the sender. This means the sender will not receive or trigger the event locally.

If you want the sender to also process the logic, you’ll need to manually invoke the logic on the sender’s side after sending.

//for example
 using (DataStream writer = new DataStream()) {
       writer.Write(this.targetPosition); // Vector3
       writer.Write(this.remaingLife); // float
       writer.Write(this.money); // int
       // Send event
       NetworkManager.Instance().Send(CUSTOM_EVENT, writer, DeliveryMode.Reliable);
       }
  //execute locally
  this.UpdatePlayer(this.targetPosition, this.remaingLife, this.money);     

Last updated