Quantcast
Channel: Photon Unity Networking (PUN) — Photon Engine
Viewing all 8947 articles
Browse latest View live

PhotonNetwork.Time = 0

$
0
0
From time to time in the first two OnPhotonSerializeView method calls PhotonNetwork.Time is 0. In the beginning, I couldn't understand the occasional strange behaviour of the remote player until I could detect it in the debugging process.. Very rarely but still it happens that PhotonNetwork.Time continues to be 0 for a long time. What could be the reason for this and how to handle it?

RPC for client

$
0
0
Hello, I have big problem. I have variable synchronization (OnPhotonSerializeView). Who now execute my RPC metod. My clientMaster is good, but my client execute this metod "fast ms" more time (no only one). How wait for RPC in client? Thank you very much for answer

Ball Sync Issue

$
0
0
Hey Guys, I am syncing a ball (like when the player kicks the ball, to shoot or pass). It works really well for the master client and is synced pretty well on the non-master clients as well. The issue is when any non-master client kicks the ball, the sync is not accurate enough and the ball behaves in a weird way for all clients connected to a room. I am using RPC calls when any player client kicks the ball to send the information to add force to the ball with respective direction and force parameters. This is the RPC call. this.photonView.RPC("ShootBallRPC", RpcTarget.All, direction, height, directionPower, heightPower); This is the RPC Method. private void ShootBallRPC(Vector3 direction, Vector3 height, float directionPower, float heightPower) { owner = null; rb.AddForce(((direction * directionPower) + (height * heightPower)), ForceMode.Impulse); } I can't really understand what might be the issue here. One issue I can think of is adding the force in non FixedUpdate() so that may be resulting in weird ball movement when the client kicks the ball. Can anyone please help me out or give me some guidance on what alternate thing I can do to resolve or sort out such issue? Thanks!

Why PUN does not support communications between photon rooms?

$
0
0
I think it is a very common feature, for example, two persons are friends but now they are not in the same photon room,I want to invite him to join my room.I need send him a message to tell in which photon room I am now, he can just click a button to join me automatically. Without the feature, we must implement the client and server logic by ourselves. I want to know under what considerations this feature is not implemented?

Undocumented breaking change in StreamBuffer (upgrading PUN 1.92 -> 1.96)

$
0
0
Hi there, we've encountered a breaking change when upgrading from 1.92 to 1.96. Unfortunately I can't work out how browse code in the releases between these two via the asset store, but I'm sure the developers will know what I'm talking about. We relied on ExitGames.Client.Photon.StreamBuffer inheriting from System.IO.Stream. Our message handling is wired up using this helper class:
public class Message {
    readonly Serializer _serializer;
    public readonly byte Id;

    public Message(MessageId id, Serializer serializer) {
        PhotonPeer.RegisterType(
            typeof(T),
            (byte) id,
            Serialize,
            Deserialize
        );
        Id = (byte) id;
        _serializer = serializer;
    }

    public void Send(T payload, bool sendReliable, RaiseEventOptions options) {
        PhotonNetwork.RaiseEvent(Id, payload, sendReliable, options);
    }

    short Serialize(StreamBuffer outStream, object obj) {
        var writer = new BinaryWriter(outStream);
        var prevLength = outStream.Length;
        _serializer.Serialize(writer, (T) obj);
        return (short) (outStream.Length - prevLength);
    }

    object Deserialize(StreamBuffer inStream, short length) {
        var reader = new BinaryReader(inStream);
        return _serializer.Deserialize(reader);
    }
}
This relies on the ability to pass the StreamBuffer to both BinaryWriter and BinaryReader. Somewhere between PUN 1.92 and 1.96 StreamBuffer was changed such that it no longer inherits from System.IO.Stream. I came up with this solution because I couldn't work out how to serialize strings through the RaiseEvent method, and instead leaned on C#'s BinaryWriter which has this functionality out of the box. For example:
public class PlayerSerializer : Serializer {
    public override void Serialize(BinaryWriter writer, Player instance) {
        writer.Write(instance.Name);
        writer.Write((byte) instance.PhotonPlayerId);
        writer.Write((byte) instance.LocalInputId);
        writer.Write(instance.IsReady);
        writer.Write(instance.IsJoined);
        writer.Write((byte) instance.TeamId);
        writer.Write((byte) instance.MaterialId);
        writer.Write(instance.ClientId);
    }

    public override void Deserialize(BinaryReader reader) {
        var instance = new Player();
        instance.Name = reader.ReadString();
        instance.PhotonPlayerId = reader.ReadByte();
        instance.LocalInputId = reader.ReadByte();
        instance.IsReady = reader.ReadBoolean();
        instance.IsJoined = reader.ReadBoolean();
        instance.TeamId = reader.ReadByte();
        instance.MaterialId = reader.ReadByte();
        instance.ClientId = reader.ReadString();
        return instance;
    }
}
This is all working perfectly in 1.92. Is Stream support likely to be restored in future? If not, is there a guide/example for serializing complex objects, arrays and strings? Thanks.

OnRoomPropertiesUpdate not triggered on local Photon Loadbalancer

$
0
0
Hello there, I'm updating one RoomProperty to be sure one specific data is the same for everyone, and update the UI in the "OnRoomPropertiesUpdate" event. Setting the property like this:
    /// 
    /// Sets the Tracer Bonus value
    /// 
    public static void SetTracerBonusValue(this Room p_Room, float[] _value)
    {
        p_Room.SetCustomProperties(new Hashtable() { { TracerBonusKey, _value } });
    }
And managing the event like this:
    /// 
    /// Called when a room's custom properties changed
    /// 
    public override void OnRoomPropertiesUpdate(ExitGames.Client.Photon.Hashtable propertiesThatChanged)
    {
        base.OnRoomPropertiesUpdate(propertiesThatChanged);

        if (propertiesThatChanged.ContainsKey(PhotonRoomExtension.TracerBonusKey) && TracerBonusGenerator.instance != null)
        {
            TracerBonusGenerator.instance.UpdateUI();
        }
    }
This is working fine when connected to the PhotonCloud, or when using Offline mode. However, the event OnRoomPropertiesUpdate is never triggered when connected to a self-hosted Loadbalancer (currently on my own PC). I checked with some Debug.Logs to be sure the function was not called at all. Everyting else is working as intended, so the connection to the server is OK. The property is also well setted, as I have another way of updating the UI on specific events. The UI does something like this:
public void UpdateUI()
    {
        float[] _values = PhotonNetwork.CurrentRoom.GetTracerBonusValue();

        // Do things with the values
    }
Getting the value is this (and get the correct values):
    /// 
    /// Gets the Tracer Bonus value
    /// 
    public static float[] GetTracerBonusValue(this RoomInfo p_RoomInfo)
    {
        object f_tracerBonus;
        if (p_RoomInfo.CustomProperties.TryGetValue(TracerBonusKey, out f_tracerBonus))
            return (float[])f_tracerBonus;
        return new float[2] { 0f, 0f };
    }
Is it a bug in Photon or something I can fix by modifying the local server? Thanks !

Back to the Basic 3 - Use of CoRoutine

$
0
0
Hi I notice that in many examples (for example the asteroid methods) during a change scene when is needed to instantiate the prefab of the player, the instantiation is made with a Coroutine and never instantiate the prefab from the Awake callback. There's a reason because Coroutine are a convenient for instantiation? thanks Paolo

2 Payer random matchmaking

$
0
0
Hello everyone, I am developing a game using Photonnetwork. I want to do this, 2 players enter the room when the game begins. Yes the game starts but the player who created the room cannot spawn.Other player can spawn. Only one player participates in the game. I'm spawning the user in the "updateOtherPlayerStatus()" method, where am I making mistakes? Thanks already for your help. My code;
 public void Connect()
    {
        car[CarSelected].carObj.GetComponent().enabled = true;
        PhotonNetwork.automaticallySyncScene = true;

        PhotonNetwork.PhotonServerSettings.HostType = ServerSettings.HostingOption.BestRegion;
        PhotonNetwork.ConnectToBestCloudServer(appVersion);
    }

    public override void OnFailedToConnectToPhoton(DisconnectCause cause)
    {
        if (connectionFailedEvent != null)
            connectionFailedEvent();
    }

    private IEnumerator requestJoinRandomRoom()
    {
        while (!PhotonNetwork.connectedAndReady)
        {
            yield return new WaitForEndOfFrame();
        };
        PhotonNetwork.JoinRandomRoom();
    }

    public void StartMatching()
    {
        StartCoroutine(requestJoinRandomRoom());
    }

    private void updateOtherPlayerStatus()
    {
        if (PhotonNetwork.room.PlayerCount == 2)
        {
            //messageLabel.text = @"Rakip Bulundu";
            //statusLabel.text = @"rakip: " + PhotonNetwork.otherPlayers[0].NickName;
            //cancelButton.interactable = false;
            //SpawnPlayer();
            PhotonNetwork.LoadLevel(1);

            if (!PhotonNetwork.isMasterClient)
                return;

            this.photonView.RPC("AddPlayer",PhotonTargets.All);
        }
    }
    /// 
    /// Called when something causes the connection to fail (after it was established).
    /// See the official Photon docs for more details.
    /// 
    public override void OnConnectionFail(DisconnectCause cause)
    {
        if (connectionFailedEvent != null)
            connectionFailedEvent();
    }

    public override void OnConnectedToMaster()
    {
        //set my own name and try joining a game
        PhotonNetwork.playerName = "Player"+ UnityEngine.Random.Range(1,9999);
        PhotonNetwork.JoinLobby();
    }

    public override void OnPhotonRandomJoinFailed(object[] codeAndMsg)
    {
        Debug.Log("Photon did not find any matches on the Master Client we are connected to. Creating our own room... (ignore the warning above).");

        PhotonNetwork.CreateRoom(null, new RoomOptions() { MaxPlayers = 2}, null);
    }

    public override void OnPhotonCreateRoomFailed(object[] codeAndMsg)
    {
        if (connectionFailedEvent != null)
            connectionFailedEvent();
    }

    public override void OnCreatedRoom()
    {
        Debug.Log("OnCreatedRoom");

        Hashtable roomProps = new Hashtable();
        roomProps.Add(RoomExtensions.size, new int[RoomExtensions.initialArrayLength]);
        roomProps.Add(RoomExtensions.score, new int[RoomExtensions.initialArrayLength]);
        PhotonNetwork.room.SetCustomProperties(roomProps);

    }

    public override void OnJoinedLobby()
    {
        Debug.Log("OnJoinedLobby");
        //statusLabel.text = @"Sen: " + PhotonNetwork.playerName;
        StartMatching();
    }

    public override void OnJoinedRoom()
    {
        PhotonPlayer player = GetComponent().owner;
        Debug.Log("Joined player(id: { player.ID }) in this room.");
        updateOtherPlayerStatus();
    }

    //IEnumerator WaitForSceneChange()
    //{
    //    while (SceneManager.GetActiveScene().buildIndex != onlineSceneIndex)
    //    {
    //        yield return null;
    //    }

    //    //we connected ourselves
    //    OnPhotonPlayerConnected(PhotonNetwork.player);
    //}
    public override void OnPhotonPlayerConnected(PhotonPlayer player)
    {
        updateOtherPlayerStatus();
    }


    //received from the master client, for this player, after successfully joining a game
    [PunRPC]
    void AddPlayer()
    {
        RCC_CarControllerV3 testArac;

        GameObject[] point = GameObject.FindGameObjectsWithTag("spawnpoint");
        int spawPointindex = UnityEngine.Random.Range(0, point.Length);

        testArac = PhotonNetwork.Instantiate(car[CarSelected].name, point[spawPointindex].transform.position, point[spawPointindex].transform.rotation, 0).GetComponent();

        RCC.RegisterPlayerVehicle(testArac);
        RCC.SetControl(testArac, true);

        if (RCC_SceneManager.Instance.activePlayerCamera)
            RCC_SceneManager.Instance.activePlayerCamera.SetTarget(testArac.gameObject);

        Gunes.instance.playerNameText = PhotonNetwork.playerName;
    }
    public override void OnPhotonPlayerDisconnected(PhotonPlayer player)
    {
        //only let the master client handle this connection
        if (!PhotonNetwork.isMasterClient)
            return;

        Gunes.instance.target = null;
    }

    public override void OnDisconnectedFromPhoton()
    {
        if (SceneManager.GetActiveScene().buildIndex != offlineSceneIndex)
            SceneManager.LoadScene(offlineSceneIndex);
    }

}

Game Object be destroyed when swich scence (only client)

$
0
0
Hi, - I have 2 scence Menu and Game. In Menu i create room then start match( with 2 player) to load Game scence. Wait for all player in Game scence I create gameObject. First time it work. Then all player leave room, create a new room , join again and start match then gameObject be destroy( only client). + Note : I fixed this issue by DontDestroyOnLoad for gameObject but I show log when i call rpc to create gameObject, active scence is "Game". +This is my code: void OnSceneFinishedLoading(Scene scene, LoadSceneMode mode) { if(scene.name=="Game") { if (PhotonNetwork.IsMasterClient) OnMasterLoadedGame(); else OnNonMasterLoadedGame(); } } void OnMasterLoadedGame() { PV.RPC("RPC_LoadGameScence", RpcTarget.MasterClient); PV.RPC("RPC_LoadGameOthers", RpcTarget.Others); } void OnNonMasterLoadedGame() { PV.RPC("RPC_LoadGameScence", RpcTarget.MasterClient); } [PunRPC] void RPC_LoadGameOthers() { PhotonNetwork.LoadLevel(1); } [PunRPC] void RPC_LoadGameScence() { m_numPlayerInGame++; if(m_numPlayerInGame == PhotonNetwork.PlayerList.Length) { print("ALL layer are in game"); PV.RPC("RPC_CreatePlayer", RpcTarget.All); } } [PunRPC] void RPC_CreatePlayer() { Debug.Log("RPC_CreatePlayer"); Debug.Log(SceneManager.GetActiveScene().name);// game Debug.Log(PhotonNetwork.AutomaticallySyncScene);// true float r = Random.Range(-3, 3); PhotonNetwork.Instantiate("Tank", new Vector3(r, 0, 0), Quaternion.identity, 0); } - Anyone can help me (Sorry for bad English)

PUN2 - PhotonNetwork.JoinRandomRoom Timeout

$
0
0
Hi, Is there any timeout for PhotonNetwork.JoinRandomRoom in the callbacks for PUN2? I am just checking before I implement my own. It seems that there is none (after several tests). Otherwise, that might be a good addition to the codebase in a future update. Thank you.

Total Player Count in Lobby

$
0
0
Is there a way to get the total player counts for all the lobbies or per lobby? Trying to figure out how many players are in rooms vs how many players are currently in the lobby.

How to prevent unwanted connections?

$
0
0
Hello, We are planning an Android/iOS game, the problem we have is we don't want people to enter the game with modified .apk files. Is there a way that we could set a system like authentication with google apk signing?

Traffic used 2,154,900%

$
0
0
Hello i'm on the free tier just trying out photon i have barely begun but noticed i couldn't connect to the same room any more looking at my apps, the dashboard reads Traffic used 2,154,900%. so my questions are , is this correct , how did that happen , does it reset after a while.? thankyou for your time

PhotonNetwork.KeepAliveInBackground having no affect

$
0
0
Hi! PhotonNetwork.KeepAliveInBackground seems to be failing completly in our windows project, using PUN v2.13, Unity version 2018.2.21f1, .Net 4.0, Mono scripting backend.). No matter what I set it to (or if I leave it to default), our connection times out after the server side 10 seconds is up, so I assume the keep alive thread is not working at all. We noticed this happens when using a plugin (StandaloneFileBrowser) that opens a native windows file browser (which I think just essentially pauses the unity application while you browse for your file), but I can also make it happen at any time simply by pausing the Unity Editor for 10 seconds. The error we receive, as you might expect, is... SocketTcpAsync.EndReceive SocketException. State: Connected. Server: '92.38.154.5' ErrorCode: 10054 SocketErrorCode: ConnectionReset Message: An existing connection was forcibly closed by the remote host. System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host. at System.Net.Sockets.Socket.EndReceive (System.IAsyncResult asyncResult) [0x00012] in :0 at ExitGames.Client.Photon.SocketTcpAsync.ReceiveAsync (System.IAsyncResult ar) [0x00023] in :0 Is this a current bug? Cheers! Alex.

about View ID999;How to break through limits?

$
0
0
Do I need a separate ID for all objects that I want to transform。 I want to know the mechanism of View id

Photon Network Traffic Reduction [URGENT]

$
0
0
Hi, We were trying to reduce the photon network traffic for a game we were working on. Our current game has a sendRate and sendRateOnSerialize values of 10. We are also using Unreliable instead of Unreliable on Change as of now. Changing that did help a bit, but in a case where players are continuously moving we needed further traffic reduction. We were using OnPhotonSerializeView to send 5 short values which as per https://doc.photonengine.com/en-us/realtime/current/reference/serialization-in-photon should result in a data packet of 15bytes (3 = type_info(short) + sizeof(short) per short). We wanted to optimize our total network traffic shown in Photon Stats GUI by further 40% so decided to send only an int and a short which should result in a data packet of 8bytes (5 for int, 3 for short). Our total network traffic after the above optimization seems to be reduced only by 7-10% when we were expecting about 40%. Isn't sending a different data type with a smaller size an important multiplying factor adding to network traffic? . Can we know what other major factors may affect the total network traffic shown in Photon Stats GUI. Thanks, Jay Kamat

Sync Constant Changing Variable

$
0
0
I am trying to sync a variable that is constantly changing, as in per frame. The variable starts to change when a player is near a certain object. The variable increases, and will increase quicker if more players were to be near it. How do I sync this accurately with every player without any sync issues?

Client Controls Wrong Character[VR]

$
0
0
I am working on a VR project, using .isMine on character script. When I open first client It seems okay player controls the right character but when second clients join first client starts to control second character. (Can't check the second client situation my other VR just went down). I can't post script due to privacy policy of company. Any help would be nice thanks.

Sync two players in VR

$
0
0
Hey guys, For my university project I have a setup of two HTC Vives and I use SteamVR, Photon Pun 2 and the VRTK plugin from Github. I followed the Photon Pun 2 Basic Tutorial successfully including step 4. What I want to achieve now is to have two players in one scene. Therefore I tried instantiating the player. What I got so far is the first player who can see and move his own controllers and the second player who sees the controllers of both player but only moves the ones from the first player. You can see the project on Github. Any help or ideas would be very much appreciated since I struggle with this problem for over a week now.

Jittering/out of order movement with PhotonRigidBodyView (PUN 2.13)

$
0
0
Hello, I have been sent a video of our game where objects are sometimes moving in a jittery way, jumping back and forth as if they received target coordinates out of order. I am using a PhotonView that is observing a PhotonRigidBodyView in "unreliable on change" mode. The PhotonRigidBodyView is configured with: - enable teleport: 12 - Synchronize velocity: yes - Synchronize Angular Velocity: yes The source RigidBody (where PhotonView.IsMine == true) has isKinematic == false, but on the other clients it is set to true. Do you have an idea of what the problem may be? Does Photon filter received position data to make sure old positions are not applied after more recent positions? Thanks!
Viewing all 8947 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>