UnityUnity V3 to Unity V4 Migration Guide

 

These docs are for PubNub 4.x for Unity which is our latest and greatest! For the docs of the older versions of the SDK, please check PubNub 3.x for Unity.

If you have questions about the PubNub for Unity SDK, please contact us at support@pubnub.com.

  • V3 exposes PubNubMessaging.Core
  • V4 exposes PubNubApi
  • V3 initiates via:
    Pubnub pubnub = new Pubnub(
        "my_pubkey",
        "my_subkey",
        "",
        "",
        true
    );
  • V4 initiates via:
    PNConfiguration pnConfiguration = new PNConfiguration();
    pnConfiguration.SubscribeKey = "my_subkey";
    pnConfiguration.PublishKey = "my_pubkey";
    pnConfiguration.Secure = true;
    
    pubnub = new PubNub(pnConfiguration);
The V4 SDK changes how PubNub handles callbacks for Subscribeand Presencecalls. Instead of passing the callback with every call, the SDK introduces a SubscribeCallback event, which is instantiated in a global manner. Furthermore, it receives various messages from PubNub, e.g. state and presence events, as well as published messages.
  • void SusbcribeCallbackHandler(object sender, EventArgs e) {
        SusbcribeEventEventArgs mea = e as SusbcribeEventEventArgs;
    
        if (mea.Status != null) {
            switch (mea.Status.Category) {
                case PNStatusCategory.PNUnexpectedDisconnectCategory:
                case PNStatusCategory.PNTimeoutCategory:
                    pubnub.Publish()
                        .Channel("my_channel")
                        .Message("Hello from the PubNub Unity SDK")
                        .Async((result, status) => {
                            if (!status.Error) {
                                Debug.Log(string.Format("DateTime {0}, In Publish Example, Timetoken: {1}", DateTime.UtcNow , result.Timetoken));
                            } else {
                                Debug.Log(status.Error);
                                Debug.Log(status.ErrorData.Info);
                            }
                        });
                break;
            }
        }
        if (mea.MessageResult != null) {
            Debug.Log("SusbcribeCallback in message" + mea.MessageResult.Channel + mea.MessageResult.Payload);
        }
        if (mea.PresenceEventResult != null) {
            Debug.Log("SusbcribeCallback in presence" + mea.PresenceEventResult.Channel + mea.PresenceEventResult.Occupancy + mea.PresenceEventResult.Event);
        }
    }
  • pubnub.SusbcribeCallback += SusbcribeCallbackHandler;
  • V3 subscribe:
    pubnub.Subscribe<string>(
        "my_channel",
        DisplaySubscribeReturnMessage,
        DisplaySubscribeConnectStatusMessage,
        DisplayErrorMessage
    );
    void DisplaySubscribeReturnMessage(string result) {
        UnityEngine.Debug.Log("SUBSCRIBE REGULAR CALLBACK:");
        UnityEngine.Debug.Log(result);
        if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim())) {
            List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
            if (deserializedMessage != null && deserializedMessage.Count > 0) {
                object subscribedObject = (object)deserializedMessage[0];
                if (subscribedObject != null) {
                    //IF CUSTOM OBJECT IS EXCEPTED, YOU CAN CAST THIS OBJECT TO YOUR CUSTOM CLASS TYPE
                    string resultActualMessage = pubnub.JsonPluggableLibrary.SerializeToJsonString(subscribedObject);
                }
            }
        }
    }
    void DisplaySubscribeConnectStatusMessage(string result) {
        UnityEngine.Debug.Log("SUBSCRIBE CONNECT CALLBACK");
    }
    void DisplayErrorMessage(PubnubClientError pubnubError) {
        UnityEngine.Debug.Log(pubnubError.StatusCode);
    }
  • V4 subscribe:
    pubnub.Subscribe()
        .Channels(new List<string>() {
            "my_channel"
        })
        .Execute();
  • V3 unsubscribe:
    pubnub.Unsubscribe<string>(
        "my_channel",
        DisplayReturnMessage,
        DisplaySubscribeConnectStatusMessage,
        DisplaySubscribeDisconnectStatusMessage,
        DisplayErrorMessage
    );
    
  • V4 unsubscribe
    pubnub.Unsubscribe()
        .ChannelGroups(new List<string>(){
            "my_channel_group"
        })
        .Channels(new List<string>() {
            "my_channel"
        })
        .Async((result, status) => {
            if (status.Error) {
                Debug.Log(string.Format("In Example, Unsubscribe Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
            } else {
                Debug.Log(string.Format("DateTime {0}, In Unsubscribe, result: {1}", DateTime.UtcNow, result.Message));
            }
        });
  • V3 publish
    pubnub.Publish<string>(
        "my_channel",
        "Hello from the PubNub Unity SDK",
        PublishCallback,
        ErrorCallback
    );
  • V4 publish
    pubnub.Publish()
        .Channel("my_channel")
        .Message("Hello from the PubNub Unity SDK")
        .Async((result, status) => {
            if (!status.Error) {
                Debug.Log(string.Format("DateTime {0}, In Publish Example, Timetoken: {1}", DateTime.UtcNow , result.Timetoken));
            } else {
                Debug.Log(status.Error);
                Debug.Log(status.ErrorData.Info);
            }
        });
  • V3 here now:
    pubnub.HereNow <string>(
        "my_channel",
        DisplayReturnMessage,
        DisplayErrorMessage
    );
  • V4 here now:
    pubnub.HereNow()
        .Channels(new List<string>(){
            "my_channel"
        })
        .ChannelGroups(new List<string>() {
            "my_channel_group"
        })
        .IncludeState(true)
        .IncludeUUIDs(true)
        .Async((result, status) => {
            if (status.Error) {
                Debug.Log(string.Format("In Example, Time Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
            } else {
                Debug.Log(string.Format("DateTime {0}, In Example, Channels: {1} {2}", DateTime.UtcNow , result.TotalChannels, result.TotalOccupancy));
            }
            Debug.Log(status.Error);
        });
  • V3 presence:
    pubnub.Presence<string>(
        "my_channel",
        DisplayPresenceReturnMessage,
        DisplayPresenceConnectStatusMessage,
        DisplayErrorMessage1
    );
    
    void DisplayPresenceReturnMessage(string result) {
        UnityEngine.Debug.Log("PRESENCE REGULAR CALLBACK:");
        UnityEngine.Debug.Log(result);
    }
    void DisplayPresenceConnectStatusMessage(string result) {
        UnityEngine.Debug.Log("PRESENCE CONNECT CALLBACK:");
        UnityEngine.Debug.Log(result);
    }
    void DisplayErrorMessage1(PubnubClientError pubnubError) {
        UnityEngine.Debug.Log(pubnubError.StatusCode);
    }
  • V4 presence:
    pubnub.Subscribe()
        .Channels(new List<string>() {
            "my_channel"
        })
        .WithPresence()
        .Execute();
  • V3 history:
    // retrieve last 100 messages
    
    pubnub.DetailedHistory<string>(
        "history_channel",
        100,
        DisplayReturnMessage,
        DisplayErrorMessage
    );
    void DisplayReturnMessage(string result) {
        UnityEngine.Debug.Log(result);
        if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim())) {
            List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
            if (deserializedMessage != null && deserializedMessage.Count > 0) {
                object[] message = (from item in deserializedMessage select item as object).ToArray ();
                if ((message != null)&&(message.Length >= 0)) {
                    IList<object> enumerable = message [0] as IList<object>;
                    foreach (object item in enumerable) {
                        UnityEngine.Debug.Log (string.Format ("Message: {0}", item.ToString()));
                        //IF CUSTOM OBJECT IS EXCEPTED, YOU CAN CAST THIS OBJECT TO YOUR CUSTOM CLASS TYPE
                    }
                }
            }
        }
    }
    void DisplayErrorMessage(PubnubClientError pubnubError) {
        UnityEngine.Debug.Log(pubnubError.StatusCode);
    }
  • V4 history:
    pubnub.History()
        .Channel("history_channel")
        .Count(100)
        .Async ((result, status) => {
            if (status.Error) {
              Debug.Log(string.Format(" History Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
            } else {
                foreach (PNHistoryItemResult histItem in result.Messages) {
                    Debug.Log(string.Format("histItem: {0}, {1}", histItem.Entry.ToString(), histItem.Timetoken.ToString()));
                }
            }
        });
  • V3 set state:
    KeyValuePair<string, object> jsonUserState = new KeyValuePair<string, object>("Key", "Value");
    pubnub.SetUserState<string>(
        "my_channel",
        "jbonham",
        jsonUserState,
        userCallback,
        errorCallback
    );
  • V4 set state:
    Dictionary<string, object> state = new Dictionary<string, object>();
    state.Add ("Key", "Value");
    
    pubnub.SetPresenceState()
        .Channels(new List<string>() {
            "my_channel"
        })
        .UUID("jbonham")
        .State(state)
        .Async((result, status) => {
            if (status.Error) {
                Debug.Log(string.Format("In Example, SetPresenceState Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
            } else {
                Debug.Log(string.Format("DateTime {0}, In Example SetPresenceState, result:", DateTime.UtcNow));
                if (result != null) {
                    if (result.StateByChannels!= null) {
                        foreach (KeyValuePair<string, object> key in dict) {
                            Debug.Log(string.Format("Channel:{0}, State:{1}", key.Key, pubnub.JsonLibrary.SerializeToJsonString(key.Value)));
                        }
                    }
                }
            }
        });
  • V3 get state:
    pubnub.GetUserState<string>(
        "my_channel",
        "my_uuid",
        DisplayReturnMessage,
        DisplayErrorMessage
    );
    
    // NOTE: DisplayReturnMessage and DisplayErrorMessage are callback methods
  • V4 get state:
    pubnub.GetPresenceState()
        .Channels(new List<string> () {
          "my_channel"
        })
        .UUID("my_uuid")
        .Async((result, status) => {
            if (status.Error) {
                Debug.Log(string.Format(" GetPresenceState Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
            } else {
                Debug.Log(string.Format("DateTime {0}, In Example GetPresenceState, result:", DateTime.UtcNow));
                if (result != null) {
                    if (result.StateByChannels!= null) {
                        foreach (KeyValuePair<string, object> key in dict) {
                            Debug.Log(string.Format("Channel:{0}, State:{1}", key.Key, pubnub.JsonLibrary.SerializeToJsonString(key.Value)));
                        }
                    }
                }
            }
        });
  • V3 subscribe:
    pubnub.RegisterDeviceForPush<string>(
        "my_channel",
        PushTypeService.GCM,
        deviceId,
        DisplayReturnMessage,
        DisplayErrorMessage
    );
    
    //NOTE: DisplayReturnMessage and DisplayErrorMessage are callback methods
  • V4 subscribe:
    pubnub.AddPushNotificationsOnChannels()
        .Channels(new List<string> {
          "my_channel"
        })
        .DeviceID(<deviceId>)
        .PushType(PNPushType.GCM)
        .Async((result, status) => {
            Debug.Log ("in AddPushNotificationsOnChannels");
            if (status.Error) {
                Debug.Log(string.Format(" AddPushNotificationsOnChannels Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
            } else {
                Debug.Log(string.Format("DateTime {0}, In AddPushNotificationsOnChannels, result: {1}", DateTime.UtcNow, result.Message));
            }
        });
  • V3 unsubscribe:
    pubnub.RemoveChannelForDevicePush<string>(
        "my_channel",
        PushTypeService.GCM,
        deviceId,
        DisplayReturnMessage,
        DisplayErrorMessage
    );
    //NOTE: DisplayReturnMessage and DisplayErrorMessage are callback methods
  • V4 unsubscribe:
    pubnub.RemovePushNotificationsFromChannels()
        .Channels(new List<string>{
            "my_channel"
        })
        .DeviceID(<deviceId>)
        .PushType(PNPushType.GCM)
        .Async((result, status) => {
            Debug.Log("in RemovePushNotificationsFromChannels");
            if (status.Error) {
                Debug.Log(string.Format(" RemovePushNotificationsFromChannels Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
            } else {
            }
        });
  • V3 time
    pubnub.Time<string>(
        DisplayReturnMessage,
        DisplayErrorMessage
    );
    void DisplayReturnMessage(string result) {
        UnityEngine.Debug.Log("TIME CALLBACK");
        UnityEngine.Debug.Log(result);
    }
    void DisplayErrorMessage(PubnubClientError pubnubError) {
        UnityEngine.Debug.Log(pubnubError.StatusCode);
    }
  • V4 time
    pubnub.Time()
        .Async((result, status) => {
            if (status.Error) {
                PrintStatus(status);
                Debug.Log(string.Format("In Example, Time Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
            } else {
                Debug.Log(string.Format("DateTime {0}, In Example, result: {1}", DateTime.UtcNow ,result.TimeToken));
            }
        });
  • V3 destroy
    pubnub.EndPendingRequests();
    pubnub = null;
  • V4 destroy
    pubnub.CleanUp();