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

Why the movements is not smooth when the player jumpa

$
0
0
Here is the gameplay of my game that ive created

image

When the player jumpa. Its not smooth. Maybe it because photon transform view? What is the best settings? Do ihave to set by script to get super smooth movements? Please help.... I want the movements smooth like another moba game.

How can I add multiplayer function in my Offline Chess game

$
0
0
Hello I was coverting An Offline Chess Game into multiplayer game using photon pun plugin and I am not able to change it into multiplyer so can you help with me can you please suggest the next step of this script . how can I Instantiate Chess piece in this script (Sorry for incorrect english).

SCRIPT !!!!!!!!!!!!!!!!!!!!!!!!!!!!!

using System.Collections; using System.Collections.Generic; using UnityEngine; using Photon.Pun; using UnityEngine.SceneManagement; using UnityEngine.UI;

public class Game : MonoBehaviourPunCallbacks { //Reference from Unity IDE public GameObject chesspiece;

//Matrices needed, positions of each of the GameObjects
//Also separate arrays for the players in order to easily keep track of them all
//Keep in mind that the same objects are going to be in "positions" and "playerBlack"/"playerWhite"
private GameObject[,] positions = new GameObject[8, 8];
private GameObject[] playerBlack = new GameObject[16];
private GameObject[] playerWhite = new GameObject[16];
//current turn
private string currentPlayer = "white";
//Game Ending
private bool gameOver = false;
//Unity calls this right when the game starts, there are a few built in functions
//that Unity can call for you
public void Start()
{
if(base.photonView.Owner.IsMasterClient)
{
playerWhite = new GameObject[] { Create("white_rook", 0, 0), Create("white_knight", 1, 0),
Create("white_bishop", 2, 0), Create("white_queen", 3, 0), Create("white_king", 4, 0),
Create("white_bishop", 5, 0), Create("white_knight", 6, 0), Create("white_rook", 7, 0),
Create("white_pawn", 0, 1), Create("white_pawn", 1, 1), Create("white_pawn", 2, 1),
Create("white_pawn", 3, 1), Create("white_pawn", 4, 1), Create("white_pawn", 5, 1),
Create("white_pawn", 6, 1), Create("white_pawn", 7, 1) };
}
playerBlack = new GameObject[] { Create("black_rook", 0, 7), Create("black_knight",1,7),
Create("black_bishop",2,7), Create("black_queen",3,7), Create("black_king",4,7),
Create("black_bishop",5,7), Create("black_knight",6,7), Create("black_rook",7,7),
Create("black_pawn", 0, 6), Create("black_pawn", 1, 6), Create("black_pawn", 2, 6),
Create("black_pawn", 3, 6), Create("black_pawn", 4, 6), Create("black_pawn", 5, 6),
Create("black_pawn", 6, 6), Create("black_pawn", 7, 6) };
//Set all piece positions on the positions board
for (int i = 0; i < playerBlack.Length; i++)
{
SetPosition(playerBlack);
SetPosition(playerWhite);
}
}
public GameObject Create(string name, int x, int y)
{
GameObject obj = PhotonNetwork.Instantiate("chesspiece", new Vector3(0, 0, -1), Quaternion.identity);
Chessman cm = obj.GetComponent<Chessman>(); //We have access to the GameObject, we need the script
cm.name = name; //This is a built in variable that Unity has, so we did not have to declare it before
cm.SetXBoard(x);
cm.SetYBoard(y);
cm.Activate(); //It has everything set up so it can now Activate()
return obj;
}
public GameObject CreateBlackPlayer(string name, int x, int y)
{
GameObject obj = PhotonNetwork.Instantiate("chesspiece", new Vector3(0, 0, -1), Quaternion.identity);
Chessman cm = obj.GetComponent<Chessman>(); //We have access to the GameObject, we need the script
cm.name = name; //This is a built in variable that Unity has, so we did not have to declare it before
cm.SetXBoard(x);
cm.SetYBoard(y);
cm.Activate(); //It has everything set up so it can now Activate()
return obj;
}
public void SetPosition(GameObject obj)
{
Chessman cm = obj.GetComponent<Chessman>();
//Overwrites either empty space or whatever was there
positions[cm.GetXBoard(), cm.GetYBoard()] = obj;
}
public void SetPositionEmpty(int x, int y)
{
positions[x, y] = null;
}
public GameObject GetPosition(int x, int y)
{
return positions[x, y];
}
public bool PositionOnBoard(int x, int y)
{
if (x < 0 || y < 0 || x >= positions.GetLength(0) || y >= positions.GetLength(1)) return false;
return true;
}
public string GetCurrentPlayer()
{
return currentPlayer;
}
public bool IsGameOver()
{
return gameOver;
}
public void NextTurn()
{
if (currentPlayer == "white")
{
currentPlayer = "black";
}
else
{
currentPlayer = "white";
}
}
public void Update()
{
if (gameOver == true && Input.GetMouseButtonDown(0))
{
gameOver = false;
//Using UnityEngine.SceneManagement is needed here
SceneManager.LoadScene("Game"); //Restarts the game by loading the scene over again
}
}

public void Winner(string playerWinner)
{
gameOver = true;
//Using UnityEngine.UI is needed here
GameObject.FindGameObjectWithTag("WinnerText").GetComponent<Text>().enabled = true;
GameObject.FindGameObjectWithTag("WinnerText").GetComponent<Text>().text = playerWinner + " is the winner";
GameObject.FindGameObjectWithTag("RestartText").GetComponent<Text>().enabled = true;
}

Create room error

$
0
0
Got an error while creating any room:
Server couldn't create a room: Newtonsoft.Json.JsonReaderException : Unexpected character encountered while parsing value: h. Path '', line 0, position 0.

Tried on empty projects(+ PUN v2.33.3) with unity versions 2020.3.14f1 and 2021.1.15f1. Photon demos also dosn't work with same error.
I'm able to connect to master server and to lobby, but not to rooms.

Full log:
Server couldn't create a room: Newtonsoft.Json.JsonReaderException : Unexpected character encountered while parsing value: h. Path '', line 0, position 0.
Stack Trace:
at Newtonsoft.Json.JsonTextReader.ParseValue()
at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
at Photon.Hive.Plugin.WebHooks.WebHooksPlugin.SetupInstance(IPluginHost host, Dictionary`2 config, String& errorMsg)
at Photon.Hive.Plugin.WebHooks.PluginFactory.Create(IPluginHost gameHost, String pluginName, Dictionary`2 config, String& errorMsg)
at Photon.Hive.Plugin.PluginManager.CreatePluginWithFactory(IPluginHost sink, String pluginName)
at Photon.Hive.Plugin.PluginManager.GetGamePlugin(IPluginHost sink, String pluginName)

UnityEngine.Debug:LogFormat (string,object[])
Networking.NetworkingManager:OnCreateRoomFailed (int16,string) (at Assets/Scripts/Networking/NetworkingManager.cs:26)
Photon.Realtime.MatchMakingCallbacksContainer:OnCreateRoomFailed (int16,string) (at Assets/ThirdParty/Photon/PhotonRealtime/Code/LoadBalancingClient.cs:4163)
Photon.Realtime.LoadBalancingClient:CallbackRoomEnterFailed (ExitGames.Client.Photon.OperationResponse) (at Assets/ThirdParty/Photon/PhotonRealtime/Code/LoadBalancingClient.cs:2583)
Photon.Realtime.LoadBalancingClient:OnOperationResponse (ExitGames.Client.Photon.OperationResponse) (at Assets/ThirdParty/Photon/PhotonRealtime/Code/LoadBalancingClient.cs:2724)
ExitGames.Client.Photon.PeerBase:DeserializeMessageAndCallback (ExitGames.Client.Photon.StreamBuffer) (at D:/Dev/Work/photon-dotnet-sdk/PhotonDotNet/PeerBase.cs:871)
ExitGames.Client.Photon.EnetPeer:DispatchIncomingCommands () (at D:/Dev/Work/photon-dotnet-sdk/PhotonDotNet/EnetPeer.cs:563)
ExitGames.Client.Photon.PhotonPeer:DispatchIncomingCommands () (at D:/Dev/Work/photon-dotnet-sdk/PhotonDotNet/PhotonPeer.cs:1863)
Photon.Pun.PhotonHandler:Dispatch () (at Assets/ThirdParty/Photon/PhotonUnityNetworking/Code/PhotonHandler.cs:221)
Photon.Pun.PhotonHandler:FixedUpdate () (at Assets/ThirdParty/Photon/PhotonUnityNetworking/Code/PhotonHandler.cs:147)

PUN 2++ upgrading from 2.27 to 2.33. Unknown operation code 227.

$
0
0
Hi!

Yesterday I updated PUN 2+ from version 2.27 to version 2.33 and the photon stopped creating a room. Up to this point, everything worked on version 2.27 without problems (since about the beginning of the year). The Unity version has also not been updated since the beginning of the year - Unity 2020.2.3f1. And so I decided to update PUN 2+ and it stopped working. :(

A.png
B.png

The code is the same as it was in version 2.27 - I didn't change anything.
RoomOptions roomOps = new RoomOptions() {
     IsVisible = true,
     IsOpen = true,
     MaxPlayers = map.MaxPlayers,
     PublishUserId = true
};

PhotonNetwork.CreateRoom(
     uniqueRoomName,
     roomOps,
     TypedLobby.Default
);


Please tell me what could be the problem in the new version 2.33? How can I fix this so that everything works as before?

Thank you!

Photon Pun 2 - Steam Game Server

$
0
0
I'm using Photon Pun 2 to handle Lobbies and Rooms, however, I am also passing along the user's Steam userID. For a Steam Ticket Authorized and Authenticated user via the client, I am unable to read the usernames and avatar of other Steam Users once I receive their UserID.

Is there a way to make steam point to the Photon Game Server so that I when a user authenticates, it fetch non-friend steam members usernames/avatars? I am using Heathen's Steamworks from the Unity Store to handle everything with Steam such as game ownership, vac bans, achievements and such.

Dynamic scoreboard - Order score from Highest to Lowest with Player name

$
0
0
Hi,

I wanna show a in game scoreboard which show top 3 players along with their score and name dynamically.
score and order should be updated dynamically.

I did this on game with fixed AI count. when it comes to multiplayers, i have no idea how to get it done.
Any hints ? I will develop from there

Photon Pun 2 Player View Issue

$
0
0
I have an issue that occurs after spawning 2 Players.
I connect in the Editor first, and then spawn the first Player in a Map, which works fine until here.
But then, when I spawn in a second Player, from my mobile device, I can see the two Players in the Editor, but on my mobile I see just 1 Player.

The Player Character has these components:
Rigidbody, Capsule Collider, SingleAttack (Script), AnimalTigerRoar (Script),
PhotonView, PhotonTransformView, PhotonRigidbodyView, PhotonAnimatorView,
and a custom Script I created for synchronizing the Player´s position/rotation/animations, named "NetworkPlayerPhoton".

This is the Script:

using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using System.Collections;
using System.Collections.Generic;
 
public class NetworkPlayerPhoton : MonoBehaviourPun, IPunObservable
{
    private Transform character;
    private Transform personalCamera;
    private JoystickController joystickController;
    private SingleAttack singleAttack;
    private AnimalTigerRoar animalRoar;
 
    //Fix lag
    private Rigidbody r;
 
    //For smoothing the Movement of other Characters
    Vector3 latestPos;
    Quaternion latestRot;
    Vector3 velocity;
    //Vector3 angularVelocity;
 
    bool valuesReceived = false;
 
    //Link the Animator
    private Animator animator;
 
 
    private void Start()
    {
        if (photonView.IsMine)
        {
            personalCamera.gameObject.SetActive(true);
            joystickController.GetComponent<JoystickController>().enabled = true;
            GetComponent<SingleAttack>().enabled = true;
            GetComponent<AnimalTigerRoar>().enabled = true;
        }
        else
        {
            Destroy(character);
            Destroy(this);
        }
    }
 
    private void FixedUpdate()
    {
        GetNeededComponents();
        Start();
    }
 
    private void GetNeededComponents()
    {
        GameObject temporaryPlayer = GameObject.FindGameObjectWithTag("Player");
        character = temporaryPlayer.transform.GetChild(0);
 
        //GameObject temporaryCamera = GameObject.FindGameObjectWithTag("Camera");
        //personalCamera = temporaryCamera.transform.GetChild(0);
        personalCamera = GameObject.Find("-----ThirdPersonCamera-----").transform.Find("FreeLookCameraRig");
 
        GameObject temporaryJoystick = GameObject.FindGameObjectWithTag("Joystick");
        joystickController = temporaryJoystick.GetComponentInChildren<JoystickController>();
 
        singleAttack = GetComponent<SingleAttack>();
 
        animalRoar = GetComponent<AnimalTigerRoar>();
 
        animator = GetComponent<Animator>();
 
        r = GetComponent<Rigidbody>();
    }
 
 
    //Send the Character Position and Rotation through the Server
    public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
    {
        if (stream.IsWriting)
        {
            // We own this player: send the others our data
            stream.SendNext(transform.position);
            stream.SendNext(transform.rotation);
            stream.SendNext(r.position);
            stream.SendNext(r.rotation);
            stream.SendNext(r.velocity);
            //stream.SendNext(r.angularVelocity);
            stream.SendNext(animator.GetBool("Walk"));
            stream.SendNext(animator.GetBool("Run"));
            stream.SendNext(animator.GetBool("Sound"));
            stream.SendNext(animator.GetBool("Attack"));
        }
        else
        {
            // Network player, receive data
            latestPos = (Vector3)stream.ReceiveNext();
            latestRot = (Quaternion)stream.ReceiveNext();
            r.position = (Vector3)stream.ReceiveNext();
            r.rotation = (Quaternion)stream.ReceiveNext();
            r.velocity = (Vector3)stream.ReceiveNext();
            //r.angularVelocity = (Vector3)stream.ReceiveNext();
            animator.SetBool("Walk", (bool)stream.ReceiveNext());
            animator.SetBool("Run", (bool)stream.ReceiveNext());
            animator.SetBool("Sound", (bool)stream.ReceiveNext());
            animator.SetBool("Attack", (bool)stream.ReceiveNext());
 
            float lag = Mathf.Abs((float)(PhotonNetwork.Time - info.SentServerTime));
            r.position += r.velocity * lag;
 
            valuesReceived = true;
        }
    }
 
    private void Update()
    {
        if (!photonView.IsMine && valuesReceived)
        {
            //Update Object position and Rigidbody parameters
            transform.position = Vector3.Lerp(transform.position, latestPos, Time.deltaTime * 5);
            transform.rotation = Quaternion.Lerp(transform.rotation, latestRot, Time.deltaTime * 5);
            r.velocity = velocity;
            //r.angularVelocity = angularVelocity;
        }
    }
 
    void OnCollisionEnter(Collision contact)
    {
        if (!photonView.IsMine)
        {
            Transform collisionObjectRoot = contact.transform.root;
            if (collisionObjectRoot.CompareTag("MeshPlayer"))
            {
                //Transfer PhotonView of Rigidbody to our local player
                photonView.TransferOwnership(PhotonNetwork.LocalPlayer);
            }
        }
    }
}

Time lag (unity)

$
0
0
If I start the game on one instance of the game it can take even 5 minutes to sync on the other instances that the game has started

[PunRPC]
void StartGame()
{
StartCoroutine(Delay());
//StartButton.SetActive(false);
}
thats the function im using the regural PunRpc but that doesnt happen only with the start of the game it can happen with the transform of the players which im using the normal photon transform view. I wonder is thats my fault of doing something or i dont have the right settings or Its that im just using the free version of the services that photon provides. If you can help please do. Thanks for reading if you have any questions let me know. Its my first ever time using photon with unity

Connecting to the same server with two different applications

$
0
0
Hello everyone,

I am currently trying to set up two different applications (One in AR and one on a Desktop PC) that can interact through the same PUN App.
I tried to provide the same App ID for both, connected with "ConnectUsingSettings()" and searched for PhotonViews in the second application. When I logged the Server IP, I got different ones and I assume this is the problem? But how can I force them to use the same Server Address? I tried to do it with "ConnectToMaster()", where I provided the IP of the application that started first, but then I got an authentication error.

Thank you very much for helping out.

How to do Additive scene loading

$
0
0
Hi all!

Over the last few days I’ve been trying to implement something that allows me to additively load scenes, which should be synchronized over the network. I’ve been hitting the wall for most of that time now. I really can’t seem to get how I can do this. I hope someone can offer some advice.

Why
I want to get additive scene loading because I think there’s great value in having one (or multiple) ‘base’ scenes, which can hold core game logic. I want to be able to load scenes additively on top of those, which might only hold a new level, or the UI.

Here’s the things I’ve tried, and what happened:
I created a GameObject called ManageScenes with a PhotonView attached to it. This had a script ManageScenes.cs, which registered to the attached PhotonView. Additive scene loading was done via a small method chain:
1.
public void PUNLoadSceneAdditively(string sceneName)
{
	photonView.RPC("LoadSceneAdditively", RpcTarget.All, sceneName);
}
2.
[PunRPC] private void LoadSceneAdditively(string sceneName)
{
	StartCoroutine(AsyncLoadSceneAdditively(sceneName));
}
3.
private IEnumerator AsyncLoadSceneAdditively(string sceneName)
{
	yield return SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive); 
}

I hoped that the RpcTarget.All would make sure the additive levels were loaded individually on each client. However, I must be doing something wrong.

One issue I encountered was that the PhotonView ViewID was not generated automatically, resulting in conflicting ViewIDs. I solved this by creating a Prefab of the ManageScenes, and having that be loaded via PhotonNetwork.Instantiate during early runtime. This also gave me issues, because now multiple of the ManageScenes prefab spawned in the scene. I tried using various forms of DoNotDestroyOnLoad or Static Instance versions, but none seemed to work the way I needed to. For instance, if at some point I didn’t get multiple of these spawned ManageScenes prefabs, I did end up with multiple identical scenes loaded additively…

I had PhotonNetwork.AutomaticallySyncScene = true, is that correct? I didn't think it would matter, since I wasn’t using PhotonNetwork.LoadScene anymore. However, I didn’t really understand that documentation of that call:
If the Master Client loads a level directly via Unity's API, PUN will notify the other players after the scene loading completed (using SceneManager.sceneLoaded).
Even though it says that PUN deals with it, does that mean I should still register to SceneManager.sceneLoaded? Should then all (non-Master) clients still load those new scenes individually? How does this relate to the PunRPC call?

How should I be fixing this? Should I keep trying to use PunRPC , or should I try the Photon Events? Should I be calling to the PhotonView.IsMine == true, and get that to PhotonNetwork.Instantiate the ManageScenes prefab, and assign it as the Static object? Should that entire GameObject only be Instantiated for the Master Client? Should these calls only be made by the MasterClient, or by all clients?

Without the additive scene loading I can make it work, but I really don’t like it: core logic lives in a DoNotDestroyOnLoad + Static gameobject. I can drop this GameObject into any scene and start the game from whereever, which I suppose is nice. I use PhotonNetwork.LoadScene to load a single scene. All scenes can either hold everything the game needs, or I use DoNotDestroyOnLoad + Static instances, resulting in needing to move through scenes in a predetermined order. I feel that using this current approach is going to clutter up and complicate development later on. It forces me to construct prefabs and scenes in (to me) inefficient ways, and provides all kinds of constraints for using persistent data (such as on Scriptable Objects etc).

It works. However… it just feels blegh.

That might sound stupid, but I’ve been trying to follow my gut a lot more (from suggestions by Uncle Bob from Clean Coding and the guys from Pragmatic Programmer). And seeing this video by Game Dev Guide, really locked down my desire to get these additive scenes done right.

It seems like something fundamentally possible to load scenes additively, and I just can’t seem to wrap my head around why this is not working out, or why this is not a native Photon functionality.

What should I be doing? Do you have additive scene loading working in your game? How did you do this?
Your expertise would be greatly appreciated!

Thank you!

How to fix matchmaking when only a few users are existing?

$
0
0
Hi Photon Community!

In my project, matchmaking works in a way now is that it search for available rooms and checks if there's any user in them. And if not, then it starts a room itself and wait for users to join.

It works perfectly when one of the users waits until it has created its room, and when it starts to joining, it finds the room and joins. No waiting would be needed if there would be more rooms to join, so there would be 5-10 users.

But the problem is for example when there're only two players, and the two players start the matchmaking at the same time, there's a chance that they can't find each other. They both try to find a different room, and they both create a room on their own.

What is the best practice of solving this? Creating room and waiting first, and joining to a different room after a few seconds?

CompilationPipeline.assemblyCompilationStarted' is obsolete warning

$
0
0
I am getting the following warning from PhotonEditor.cs

'CompilationPipeline.assemblyCompilationStarted' is obsolete: 'Use compilationStarted, compilationFinished or assemblyCompilationFinished instead. Note that using any of these functions to do time measurements is a bad idea as they run async to actual compilation.' [PhotonUnityNetworking.Editor]

It is being triggered by both of the lines:
CompilationPipeline.assemblyCompilationStarted -= OnCompileStarted;
CompilationPipeline.assemblyCompilationStarted += OnCompileStarted;

I tried swapping "assemblyCompilationStarted" with "compilationStarted" and got an error saying:

No overload for 'OnCompileStarted' matches delegate 'Action<object>' [PhotonUnityNetworking.Editor]

I am using PUN version: 2.33.3 Photon Lib: 4.1.6.3 and Unity version 2021.1.15f1

Before I dig myself to far into a hole, I just wanted to check if there is a known fix for this warning.

Thank you.

Simulating connection loss (temporary, not timeout)

$
0
0
My game relies on master client to handle concurrency and race conditions.

So I need a way to simulate if the master loses connection for a fixed amount of seconds.

I know of PhotonNetwork.NetworkingClient.SimulateConnectionLoss(true), that works but it times out the client, I need a temporary loss of connection.

Also is there a way to change the timeout time, i think it is 10 seconds now?

Client is on MasterServer (must be Master Server for matchmaking)but not ready for operations

$
0
0
Help!!
I have looked everywhere but cannot find a solution.
I'm trying to make a super simple multiplayer game, but this error come up when I attempt to connect to a room: Client is on MasterServer (must be Master Server for matchmaking)but not ready for operations (State: Joining). Wait for callback: OnJoinedLobby or OnConnectedToMaster.

This is my code for a loading scene which when it connects sends you to a lobby, where it attempts to send you to a room.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using UnityEngine.SceneManagement;

public class ConnectToServer : MonoBehaviourPunCallbacks
{
// Start is called before the first frame update
void Start()
{
PhotonNetwork.ConnectUsingSettings();
}

public override void OnConnectedToMaster()
{
PhotonNetwork.JoinLobby();
}

public override void OnJoinedLobby()
{
SceneManager.LoadScene("Lobby");
}

}

And here is the lobby code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.Pun;

public class CreateAndJoinRooms : MonoBehaviourPunCallbacks
{

private void Awake()
{
PhotonNetwork.AutomaticallySyncScene = true;
}
public void CreateRoom()
{
PhotonNetwork.CreateRoom("Room");
}

public void JoinRoom()
{
if (PhotonNetwork.IsConnected)
{
PhotonNetwork.JoinRoom("Room");
}

}

public override void OnJoinedRoom()
{
PhotonNetwork.LoadLevel("Game");
}
}

Why can I not get userIDs?

$
0
0
I am trying to create a multiplayer RPG using PUN. I am hoping for the master to have each player's tagobject associated with their respective player gameobject. I am thinking I need this so the master client can dish out XP, loot, etc - so the master will need to access player's stat scripts etc from their player userID which I hope to pass around. Feel free to let me know if that's a stupid way of going about things...

Now I have set share UserID to true when creating the room, however when the master is printing all of the players in the playerlist it does not print other player's userID...

https://imgur.com/a/iasg3xD

Thank you!

photonView is null?

$
0
0
I'm trying to call RPC from the script, but it throws a null reference exception.
using UnityEngine;
using UnityEngine.UI;
using Photon.Pun;

public class HitVFX : MonoBehaviourPun {
    [SerializeField] private Slider m_HPSlider = null;
    private Health m_Health = null;

    public Health Health {
        get {
            if (m_Health == null) {
                m_Health = GetComponent<Health>();
            }

            return m_Health;
        }
    }

    void Start() {
        m_Health = GetComponent<Health>();
        Initialize();
    }

    public void Initialize() {
        if (m_HPSlider) {
            SetHPSliderMinMaxValues();
            UpdateHPSlider(Health.Value);
        }
    }

    public void SetHPSliderMinMaxValues() {
        if (m_HPSlider == null) {
            return;
        }
        
        float maxHealth = Health.MaxValue;
        SetHPSliderMinMaxValuesInternal(maxHealth);

        print(photonView); // NULL HERE
        photonView.RPC("SetHPSliderMinMaxValuesInternal", RpcTarget.Others, maxHealth); // THROWING NULL REFERENCE EXCEPTION
    }

    [PunRPC]
    void SetHPSliderMinMaxValuesInternal(float maxValue) {
        m_HPSlider.minValue = 0;
        m_HPSlider.maxValue = maxValue;
    }
}

Tried refreshing the RPC list in resources doesn't change anything. Using Unity 2019.1.0f2 and PUN 2.33 Lib 4.1.6.3.

The prefab has PhotonView that already exists scene throws Illegal View ID: 0 on using RPC?

$
0
0
I have some prefab object that already exists in the scene, and there are several RPC calls when the scene is loaded to synchronize initial setups.

However, using RPC from these objects all throw the same error: Illegal view ID:0.

Is this intentional or just a glitch? Does RPC only works that the game object must be instantiated by PhotonNetwork.Instantiate?

Photon user objects destroyed on disconnect

$
0
0
I want to stop photon from destroying the user instantiated gameobjects when the user disconnects so that on reconnect they are still there.

MasterClient can't destroy the object

$
0
0
As far as I know, the master client can destroy the game object even it's not owned, but when the master attempts to destroy it, I got this error message:

Failed to 'network-remove' GameObject. Client is neither owner nor MasterClient taking over for owner who left: View 2004 on ThrowingExplosiveGrenade(Clone)

So to check the code actually invoked from the master, I simply added two print methods to check isMine and IsMasterClient:
print(photonView.IsMine);
print(PhotonNetwork.IsMasterClient);

PhotonNetwork.Destroy(gameObject);

If the master created and tries to delete it:
print(photonView.IsMine); -> true
print(PhotonNetwork.IsMasterClient); -> true

If the other player created but the master tries to delete it:
print(photonView.IsMine); -> false
print(PhotonNetwork.IsMasterClient); -> true

So the code is always invoked from the master client, not the others.

I don't know how the PUN works internally, but the code where the error was caught doesn't seem to have an additional check the player who tries to delete it is a master, but only checks it's owned or not.

Here's the code directly copy and pasted from PhotonNetworkPart.cs, line 794:
PhotonView viewZero = foundPVs[0];

// Don't remove GOs that are owned by others (unless this is the master and the remote player left)
if (!localOnly)
{
    //Debug.LogWarning("Destroy " + instantiationId + " creator " + creatorId, go);
    if (!viewZero.IsMine)
    {
        Debug.LogError("Failed to 'network-remove' GameObject. Client is neither owner nor MasterClient taking over for owner who left: " + viewZero);
        foundPVs.Clear();   // as foundPVs is re-used, clean it to avoid lingering references
        return;
    }
}

Have I misunderstood something or just PUN implemented it wrong? Using Unity 2019.1.0f2 and PUN 2 4.1.6.3

Order of events on instantiation

$
0
0
Hello!
So I instantiate an object, and it spawns on other clients. Then spawned object receives:
- bunch of data with OnPhotonInstantiate event
- RPCs sent right afrer the instantiation
- Buffered RPC sent right afrer the instantiation
I woud like to know the exact order of data received from those sources.
I mean, what will be called first? OnPhotonInstantiate? Or RPCs? Or buffered RPCs? And what will be called next and last?
Is the order of those events is fixed, or it can vary in some cases?
Could you guys please clarify this for me?
Thanks!




Viewing all 8947 articles
Browse latest View live