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

InvalidCastException: Specified cast is not valid

$
0
0
InvalidCastException: Specified cast is not valid.
Photon.Pun.PhotonStream.Serialize (System.Boolean& myBool) (at Assets/Photon/PhotonUnityNetworking/Code/PunClasses.cs:779)

Looks like bug. Sometimes. Sometimes not.
PUN v 2.20.1 Photon lib 4.1.4.4
Unity v 2018.2.8f1

Best Practices for Networked PvE

$
0
0
TLDR: what is the best way of having a bunch of AI-controlled enemies without killing the msgs/sec from a bunch of views.

So I've tried out some sample projects and have a good idea of how to handle PvP and deal with lag compensation on projectiles.

I want to do Co-Op PvE though, and based on the message traffic and the number of enemies I want onscreen at once can't give them all views. I was hoping I could get some feedback on how I THINK this should be handled and if I am completely off-base.

Instead of having a view per enemy, there would be a single manager object with a view. It would transmit updates about the position and health of enemies from the master client. Everyone else would keep track of the "true position" of the enemies in this manager object when the receive the update and then lerp enemies towards where they should be.

Their behavior is fairly deterministic assuming their targets are all synced. So I was thinking that the master client, instead of having the enemies move right away, would instead, after having them all pick a target wait 100ms (or somewhere around there), then make the RPC. That way all clients could all have the start of enemy motion be synced, minimizing any effects from lag. I could then hide this short delay by varying the animation speeds.

Does this make sense? Is this how other people do it? Trying to do research it seemed like most of what I found was focused on basically just having Players with views and mostly just PvP. If people who have done this sort of thing before could give me some feedback it would be greatly appreciated.

Thanks!

(The project is basically a top-down dungeon crawler).

Help with Player Input and PUN 2

$
0
0
In my game im using the new Player Input system with two control schemes: Touch and Keyboard. One is meant for the target platform: mobile, the other is to test on the editor.

I handle my input in a PlayerInputManager.cs script, that is attached to my player object which is child to a playerHolder object that has the Photon View component.

I run the typical photonView.IsMine check before executing the input callback in the InputManager script, but for some reason, when I use the keyboard inputs and the input callback is triggered, photonView.IsMine returns false always.
Anyone knows a possible common mistake im making thats causing this? If not, I can share the code of course. Thanks in advance.

Beginner Help! How to access a Component from the other player in the same room

$
0
0
Hi All!

Beginner Unity user here. I am making a simple multiplayer card game prototype. Two players join the same room (Max num of players in room set to 2). Game scene is loaded.

The game scene has a logic in start method, which randomly picks a list of sprites and displays it on screen. The problem is for both the players the list of sprites are different. (meaning the scene is independently loaded in both devices and random logic is causing different sprites)

Is there some way that the second user who connects to the room access the list of sprites generated for the master in the room? so that the sprites displayed for both the users are the same.

Appreciate your help

Thanks,
Karthik

How do I show a list of players in a room without joining the room?

$
0
0
Hi, first of all I apologize if this has been mentioned. I spent a whole day yesterday searching for a question with the answer and had no luck. I really need to figure out how I can fetch a list of players inside a room WITHOUT joining the room. In my case, this would actually save the bandwidth from players having to constantly get in and out of rooms. And of course, I would limit the player count in any rooms created from RoomInfo room.PlayerCount parameter since PhotonNetwork.PlayersList only work in rooms. I want to be able to show the players while I scroll through multiple rooms in the lobby before a player decide to join it. PhotonNetwork.PlayerList is not possible because you have to be in the room, can someone please show me the workaround, maybe using RPC? or CustomProperties that can fetch the list of players in the room while OnRoomListUpdate is getting called. I think it's an important feature to have. Please help.

How to prevent player join rooms at different clients

$
0
0
My game use userID get from web server as the AuthenticationValues.userId for PUN.
When a player login at two different devices, he can still join two different rooms in same lobby from two devices. How to detect and prevent its happen?
Thanks for help.

Room does not support rejoing. PlayerTTL is 0

$
0
0
Hi there! I'm using PhotonNetwork.ReconnectAndRejoin() to rejoin the room if the client was disconnected with timeout. But I get this error:
OnJoinRoomFailed(-3,Room does not support rejoing. PlayerTTL is 0).
I couldn't find any information about it. What does this error mean?

Thanks

How to store names and scores and send them back to players in next level?

$
0
0
Hi,

In my multiplayer tournament game the last survivor wins the match and top three get points (medals) in each level of the tournament. There are 10 levels to play through in each tournament.

When a new level loads, all players respawn and I gave them all slots for medals that appear in said slots if a player ends in the top three, but those obviously disappear when a new level loads, so:

How do I store what players ended where in the top three in a script that has don't destroy on load in it, and then RPC back to each player what medals (if any) they should have and in what slot?

After all ten levels have been played through the list needs to be sorted to find the clear top three of the tourney.

Manual Instantiation Initialize Late

$
0
0
I'm using manual instantiation and addressable to decrease ram usage, but I can't make it stable.
When a player joined the room he can't get buffered rpc's because his photon view not initialized yet. It was working with PhotonNetwork.Instantiate but not working with manual instantiation.

Objects with the same RaiseEvent, call just for one?

$
0
0
Hi everybody :smile: I'm doing a 2D game with photon and now i'm trying to learn how "Raise Event" work I have in my scene 10coin (for the exemple), but i don't want to use Photonview with them , because they don't need to receive RPC ( if i have to multiple the send rate by the amount of these coin it's will be a nightmare ..) i just want to call a event, when one of them is get , to tell to other player that this specific coin can't be get anymore. But all of my 10 coins have the same Event on them, So if i get a coin, will all coins receive the event ? If what i do is the wrong way, someone can help me with that ? Have a good day ! Edit : In other word, i can say that i want to find a solution to all player to have the same ID for all coins , without photonview . The other solution that i found, is when a player connect to the room , the master client enable the photonview of all coin for him and the new player, send to him all ID of coin . and when the new player have check with master if ID are the same, he can disable all photonview's coins withthe master Client . So, after , player can use simple RPC to tell to other which coin is get :dizzy: EDIT 2: I think about a other way, there is possible to use 2 different network group? to avoid coin to receive RPC by other player's rpc ( Movement RPC for exemple) ? To minimize rpc exchange ^^'

Displaying a gameobject to only certain players

$
0
0
I am trying to display a death message to the player who died and the player who killed them.

To do this I am using PunRPC called from the player who died.

The problem is that while the player who died sees the death message, the player who killed them does not.
// Called with the player dies.
void Die ()
{
    // killByName is the nickname of the player who killed the local player.
    // killedById is the ViewID of the player who killed the local player.
    photonView.RPC(nameof(UpdateDeathText), RpcTarget.All, killedByName, killedById, deathMessage);
}

// Enables the death text. Only visible to the local player and the player who killed them.
[PunRPC]
void UpdateDeathText (string killedByName, int killedById, string deathMessage)
{
    healthBarSprite.parent.gameObject.SetActive(false);

    if (photonView.IsMine) // Local player.
    {
        deathText.gameObject.SetActive(true);
        deathText.text = "<color=#D4CBCC>Killed by " + killedByName + "!</color>";
    }
    else if (killedById == photonView.ViewID) // Player who killed the local player.
    {
        deathText.gameObject.SetActive(true);
        deathText.text = deathMessage;
    }
   // Else we do nothing as the player is not relevant.
}

To my understanding a RPC is called on all players on the network. I got this code working by comparing local players nickname with the nickname of the player who got the kill, but this was only for testing as that style of code would cause problems if two players in the room had the same nickname.

Am I approaching this problem wrong, or am I missing something?

Thanks,
Wzd.

How to use triggers with PUN?

$
0
0
I've been going at this for 3 days but I can't find any tutorial of how to get triggers working. I'm making a simple game, I've managed to get the players to join a room. I place a trigger and an AI has to go to its position. The AI goes to the trigger alright but the player cannot interact with it. Both the trigger and AI are running on local machine.

My bool keeps resetting to false

$
0
0
Hi, I'm new to photon and I'm trying to understand how it all works.

So i have this bool HasTheBall which keeps resetting to false.
I have a script for detecting when i'm touching the ball to "collect" it.

private void OnCollisionEnter(Collision collision)
{
if (collision.collider.tag == "GameBall")
{
ball = collision.collider.gameObject;
photonView.RPC("Destroy", RpcTarget.All);
collected.BallCollected(); //here i'm calling the shooting script to set the bool HasTheBall to true

}
}

this is where i set the bool to true

public void BallCollected()
{
HasTheBall = true;
Debug.LogError("HasTheBall= " + HasTheBall);
}

but literally on the next update the bool becomes false.

I notice this happens only if there are 2+ ppl on the server, the first one to connect to the server works perfectly fine, then if another person join it doesn't work.
I think it's a master problem but idk how to resolve it.

Syncing runtime rigidbodies

$
0
0
Hi,

My setup is this: I have multiple players in a room. Each player has a rigidbody and is controlled locally. To reflect its transformations across the network, when its added to the scene from the network I set the rigidbody to kinematic.

These players can catch and drop rigidbody collectibles in the scene using a fixed joint.

My problem is syncing the collectibles across the network. They are added at runtime. They have a Photon View, Transform view and Transform Rigidbody view. Since they are controlled locally only on the Master Client, they can't be moved by other clients. I can't set them to kinematic because this will prevent them from being picked by later players.

Thanks.

Steam Co Op

$
0
0
Hello, I have a question about PUN in general and Steam regarding CCU and pricing.

Say I made a game that has a max player limit of 10 players max per 'host'.

Does the 20 CCU Limit apply to 2 'worlds' being played and it is now capped at 20 CCU? Or is each host their own 20 CCU?

Example game: A party style game where friend play together. 9 friends on one host and another host , who has 9 friends with them totally 20 total players playing the game on separate host who are not related or in the same session.

A Co-op game bascially.

Does this apply the 20 CCU Limit or is it 20 max players per host since the host is the 'server'.

Invalid worldAABB. Object is too large or too far away from the origin.

$
0
0
Hi guys,
As I see this error mostly happening when I disconnect photon and after connect.(Not reconnect/reconnectandrejoin)
When the game start kind of RPC's and serialize view not working. Client object spawning middle of the screen (0,0,0) but must be something like (5,0,0). Title error logging on master when client data received for sync.

1)Is it about PhotonNetwork.automaticallySyncScene or my disconnection setup?
2)Do I need to wait OnDisconnectedFromPhoton callback?
Btw this is my disconnect function:
        PhotonNetwork.NetworkingClient.LoadBalancingPeer.OpLeaveLobby();
        PhotonNetwork.NetworkingClient.LoadBalancingPeer.OpLeaveRoom(false);
        PhotonNetwork.Disconnect();

       SceneManager.LoadScene("Main");

Thanks in advance.

Creation of 3 always visible rooms until I decide.

$
0
0
Hello, I have the following question regarding the use of Photon.
I want to know if it'd be possible to create 3 rooms by the press of a button,
and have these rooms always visible, even if they 0 players. I don't want these rooms erased,
only if I decide at some point.

The idea of my videogame is that before players enter my app, I want to have control of creating these 3 rooms,
with different scenarios and maximum number of players and leave them ready so that they only have access to just these rooms.

On each of these rooms I expect to gather around 64-100 players max. My game wouldn't be sending much messages other than player
position, photon voice and photon chat. Basically I'm trying to make a virtual expo or virtual conference.

I am aware about Photon SpaceHub, but at the moment I cannot afford the kit and would like to try to achieve it through Photon PUN.

What do you recommend for this kind of video game?

Thank!

ERROR

$
0
0
Assets\Kodlar\MainMenu.cs(99,30): error CS0115: 'MainMenu.OnPhotonPlayerConnected(Player)': no suitable method found to override


my code:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.Pun;
using Photon.Realtime;
using System.Security.Cryptography.X509Certificates;

namespace HungerGames.Menus
{
public class MainMenu : MonoBehaviourPunCallbacks
{
[SerializeField] private GameObject findOpponentPanel = null;
[SerializeField] private GameObject waitinStatusPanel = null;
[SerializeField] private Text waitinStatusText = null;

private bool isConnecting = false;

private const string GameVersion = "0.0.1";
private const int MaxPlayerPerRoom = 10;

private void Awake() => PhotonNetwork.AutomaticallySyncScene = true;

public void FindOpponent()
{
isConnecting = true;
findOpponentPanel.SetActive(false);
waitinStatusPanel.SetActive(true);

waitinStatusText.text = "Aranıyor ...";

if (PhotonNetwork.IsConnected)
{
PhotonNetwork.JoinRandomRoom();

}
else
{
PhotonNetwork.GameVersion = GameVersion;
PhotonNetwork.ConnectUsingSettings();

}

}

public override void OnConnectedToMaster()
{
print("Servera Bağlandı");

if (isConnecting)
{
PhotonNetwork.JoinRandomRoom();



}

}

public override void OnDisconnected(DisconnectCause cause)
{
waitinStatusPanel.SetActive(false);
findOpponentPanel.SetActive(true);

print($"Şu sebebten dolayı bağlanılamadı : {cause}");

}

public override void OnJoinRandomFailed(short returnCode, string message)
{
print("Yaratılmış oda yok, yada tüm odalar dolu, yeni oda yaratılıyor");
PhotonNetwork.CreateRoom(null, new RoomOptions { MaxPlayers = MaxPlayerPerRoom });

}

public override void OnJoinedRoom()
{
print("Odaya başarılı bir şekilde katıldınız");

int playerCount = PhotonNetwork.CurrentRoom.PlayerCount;

if (playerCount != MaxPlayerPerRoom)
{
waitinStatusText.text = "Diğer Oyuncular Bekleniyorr";
print("Diğer Oyuncular Bekleniyorr");
}
else
{
waitinStatusText.text = "Rakip Bulundu";
print("Maça Hazır");

}


}

public override void OnPlayerEnteredRoom(Player newPlayer) // MY ERROR
{
if (PhotonNetwork.CurrentRoom.PlayerCount == MaxPlayerPerRoom)
{
PhotonNetwork.CurrentRoom.IsOpen = false;
waitinStatusText.text = "Rakip Maçta";

PhotonNetwork.LoadLevel("MainScene");
}

}

}
}

After adding RPC methods to the script, PUN call backs stopped working.

$
0
0
Hello people!

After I add last 2 methods "public void SetReady(bool state){...}", "[PunRPC] private void RPC_ChangeReadyState(Player player, bool state){...}" and "OnEnable() { SetReady(false); }" PUN call backs e.g. OnPlayerEnteredRoom stopped working.
using Photon.Pun;
using Photon.Realtime;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerListings : MonoBehaviourPunCallbacks
{
    public GameObject list;
    public PlayerListing playerListing;

    private bool ready;
    private List<PlayerListing> listingsList = new List<PlayerListing>();

    private void Awake()
    {
        GetCurrentRoomPlayers();
    }
    private void OnEnable()
    {
        SetReady(false);
    }
    void GetCurrentRoomPlayers()
    {
        foreach (KeyValuePair<int, Player> playerInfo in PhotonNetwork.CurrentRoom.Players)
        {
            AddPlayerListing(playerInfo.Value);
        }
    }
    public void AddPlayerListing(Player player)
    {
        PlayerListing listing = Instantiate(playerListing, list.transform);
        if (listing != null)
        {
            listing.SetPlayerInfo(player);
            listingsList.Add(listing);
        }
    }
    public override void OnPlayerEnteredRoom(Player newPlayer)
    {
        AddPlayerListing(newPlayer);
    }
    public override void OnPlayerLeftRoom(Player otherPlayer)
    {
        int index = listingsList.FindIndex(x => x.Player == otherPlayer);
        if (index != -1)
        {
            Destroy(listingsList[index].gameObject);
            listingsList.RemoveAt(index);
        }
    }
    public void SetReady(bool state)
    {
        ready = state;
        Debug.Log(PhotonNetwork.LocalPlayer.NickName+ " is ready - " + ready);
        photonView.RPC("RPC_ChangeReadyState", RpcTarget.AllBuffered, PhotonNetwork.LocalPlayer, ready);
    }
    [PunRPC]
    private void RPC_ChangeReadyState(Player player, bool state)
    {
        int index = listingsList.FindIndex(x => x.Player == player);
        if (index != -1)
        {
            listingsList[index].ready = state;
            if (state)
                listingsList[index].readyText.text = "Ready";
            else
                listingsList[index].readyText.text = "Not Ready";
        }
    }
}

Can you tell me where am I wrong?
Thank you very much!

PUN - Main Camera not working when more than one player exist

$
0
0
Hello everyone,

I would like to share my problem with PUN and looking for an explanation or solution if possible. I have used official PUN tutorial and extended it with my own prefabs with success. I can join rooms with multiple clients and instantiate my ship prefab.

Basic concept is that there is a gameobject called "CameraPivot" with "MainCamera" as its child object. Whenever, a player joins, the CameraPivot object has to be attached to the instantiated player ship locally. If there is only the host, it works OK. When a client joins, the camera works for the client side as well. However, the CameraPivot object with MainCamera gets reset to intial position for the host and camera gets locked. I connected up to 5 clients to the host, and all the clients work flawless but the host.

[img][/img]J6qtfOC.png

I have found that others have similar issues as in below link as well,
https://forum.unity.com/threads/photon-cameras-not-working-when-more-than-one-exist.691867/

Also, when I created and joined the scene with 6 players, the problem occured to be related only to the host player. I disconnected the host, the second player becomes the host. And right after the second player becomes host, it loses the camarapivot with maincamera. When I disconnected the second player which is the host now, the same happens with the 3rd player.

I tried assigning the camerapivot both from gamemanager and the player prefab. Below is the GameManager script that instantiates the players/cameras and the Camera script. So anyone has any idea why this happens or how to overcome this issue? (I am quite new to both Unity and Photon, so I might have overlooked something easy)

void Start()
{
Instance = this;
if (playerPrefab == null)
{
Debug.LogError("<Color=Red><a>Missing</a></Color> playerPrefab Reference. Please set it up in GameObject 'Game Manager'", this);
}
else if (ShipManager.LocalPlayerInstance == null)
{
Debug.LogFormat("We are Instantiating LocalPlayer from {0}", SceneManagerHelper.ActiveSceneName);
// we're in a room. spawn a character for the local player. it gets synced by using PhotonNetwork.Instantiate
GameObject LocalShip = PhotonNetwork.Instantiate(this.playerPrefab.name, new Vector3(UnityEngine.Random.Range(0, 200), 3, 0f), Quaternion.identity, 0);
if (!LocalShip.GetPhotonView().IsMine)
{
Camera.main.GetComponent<CameraOrbit>().enabled = false;
}
else
{
Camera.main.GetComponent<CameraOrbit>().enabled = true;

CamPivot = GameObject.Find("CameraPivot");

CamPivot.GetComponent<CameraSystem>().shipView = LocalShip.GetComponent<CameraAssign>().sView;
CamPivot.GetComponent<CameraSystem>().portsideView = LocalShip.GetComponent<CameraAssign>().prtView;
CamPivot.GetComponent<CameraSystem>().starboardView = LocalShip.GetComponent<CameraAssign>().stbView;

Camera.main.GetComponent<CameraOrbit>().victory = LocalShip;
}
}
else
{
Debug.LogFormat("Ignoring scene load for {0}", SceneManagerHelper.ActiveSceneName);
}
}
Viewing all 8947 articles
Browse latest View live


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