Search code examples
unity-game-enginemultiplayer

PUN 2 Unity Photon.LoadLevel, IOnEventCallback and RaiseEvent


I'm working on a multiplayer turn based game using PUN 2. I'm having a trouble with instantiating object after a scene was loaded using RaiseEvent.

Everything started from this problem: Synchronizing GameObjects with Players but it seems I have to fix other problems first. Let me explain a little.

I have a scene with a button "Join Queue" which creates a room if there isn't other available and MaxPlayerCount = 2. So after the second player joins, I'm using Photon.LoadLevel(sceneName) to load the game scene. On game scene I have a component which spawns some objects. On this component I'm using PhotonNetwork.RaiseEvent to send those objects position to the other players.

PhotonView photonView = containerTile.GetComponent<PhotonView>();
if(PhotonNetwork.AllocateViewID(photonView))
{
    object[] data = new object[]
    {
        containerTile.transform.position, containerTile.transform.rotation, photonView.ViewID
    };

    RaiseEventOptions raiseEventOptions = new RaiseEventOptions
    {
        Receivers = ReceiverGroup.Others,
        CachingOption = EventCaching.AddToRoomCache
    };

    SendOptions sendOptions = new SendOptions
    {
        Reliability = true
    };

    PhotonNetwork.RaiseEvent(CustomEvent, data, raiseEventOptions, sendOptions);
}

public void OnEvent(EventData photonEvent)
{        
    if(photonEvent.Code == CustomEvent)
    {
        object[] data = (object[])photonEvent.CustomData;

        GameObject containerTile = (GameObject)Instantiate(containerPrefab, (Vector3)data[0], (Quaternion)data[1]);
        PhotonView photonView = containerTile.GetComponent<PhotonView>();
        photonView.ViewID = (int)data[2];
    }
}

"CustomEvent" is a custom event which I'm trying to get by implementing "OnEvent" callback with IOnEventCallback interface. When OnEvent is called EventData code is "PropertiesChanged(253)" which from documentation it seems to be called when MasterClient changed the room, so I'm guessing PhotonNetwork.LoadLevel does this.

Their documentation says "When you call OpSetProperties with the broadcast option "on", this event is fired. It contains the properties being set." I'm trying to skip this 253 event code and I have no idea how should I set the "broadcast option" to off or which is the approach of what I'm trying to achieve.

Thanks for reading!


Solution

  • You can't instantiate yourself a network gameobject, PUN doesn't work like that.

    Instead:

    • use PhotonNetwork.Instantiate()

    • use the IPunPrefabPool interface to create your own system for generating network instances (check out the DefaultPool class for how it's done internally)

    Make sure you go through the basic tutorial first, to grasp the few important features of PUN and how to get started with it.

    https://doc.photonengine.com/en-us/pun/v2/demos-and-tutorials/pun-basics-tutorial/player-instantiation