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

RPC Flooding

$
0
0
Hi, so I have a bit of a dilemma. Currently, I'm creating a GameObject (very simple, I'm just calling PhotonNetwork.Instantiate), but I also need to use that same object to set it's parent to something, on all clients, once it's spawned. So to set the parent, I'm using an RPC call (that's buffered so that later joiners can receive it) after I instantiate the GameObject. My fear is that if there's a large number of players swapping and removing weapons during the session that later joiners will get blasted with hundreds of RPC's that were buffered trying to parent/unparent weapons that may no longer even exist (of course I could just handle this with a simple if check). I'm afraid that this will cause a lot of performance issues later on.

Does anyone know the best way to handle this? I hope I've given a detailed enough description of the issue.
Regards!

Here's the code if you're curious:

void CreateWeapon(WeaponInfo weaponInfo)
{
    if (weaponInfo == null)
        return;

    if (PhotonNetwork.IsConnected)
    {
        GameObject weaponObject = PhotonNetwork.Instantiate(weaponInfo.GameObject.name, Vector3.zero, Quaternion.identity);
        int id = weaponObject.GetComponent<PhotonView>().ViewID;
        photonView.RPC("SetupWeaponRPC", RpcTarget.AllBuffered, id);
    }
    else
    {
        GameObject weaponObject = Instantiate(weaponInfo.GameObject);
        SetupWeapon(weaponObject);
    }
}

[PunRPC]
[UsedImplicitly]
void SetupWeaponRPC(int viewID)
{
    PhotonView v = PhotonNetwork.GetPhotonView(viewID);
    if (v == null)
    {
        Debug.LogError("For some reason the weapon object is null?");
        return;
    }
    GameObject weaponObject = v.gameObject;
    SetupWeapon(weaponObject);
}
void SetupWeapon(GameObject weaponObject)
{
    SetWeaponParent(weaponObject);
    currentWeapon = weaponObject.GetComponent<Weapon>();
    currentWeapon.Init(photonView.Owner);
}
void SetWeaponParent(GameObject weaponObject)
{
    weaponObject.transform.SetParent(animator.GetBoneTransform(HumanBodyBones.RightHand));
    weaponObject.transform.localPosition = Vector3.zero;
    weaponObject.transform.localEulerAngles = Vector3.zero;
}

What is my local PhotonPlayer?

$
0
0
I have joined a room and so presumably I am a PhotonPlayer within the room.

How do I obtain a handle to my PhotonPlayer other than instantiating an object such that I can read who owns the PhotonView?

PUN2 Failed to instantiate Prefab must have PhotonView Component

$
0
0
I'm creating a SteamVR multiplayer game and I have been following the PUN tutorial (making changes as needed since the tutorial is for PUN1). When I load the scene OnlineRoom1 I have
PhotonNetwork.Instantiate(this.playerPrefab.name, new Vector3(0f, 5f, 0f), Quaternion.identity, 0);
in the Start(). This is in the GameManager script which I've attached to the GameObject named "Game Manager" which spawns in the scene. in the public GameObject field I placed the prefab Player from the Project>Resources folder. Despite this prefab having a PhotonView component attached to it I get the error

Failed to Instantiate prefab:Player. Prefab must have a PhotonView component.

This error comes from the script PhotonNetwork.cs Instantiate() function.
if (prefabGo.GetComponent() == null)
{
Debug.LogError("Failed to Instantiate prefab:" + prefabName + ". Prefab must have a PhotonView component.");
return null;
}

Any ideas?

What is the best way to use the NetworkBehaviour OnStartLocalPlayer in Photon?

$
0
0
I was making a game using Unity's NetworkBehaviour, and switched to Photon, but I don't see a good way of using OnStartLocalPlayer yet.

Here is the line:

public override void OnStartLocalPlayer()
{
player.GetComponent ().material.color = Color.blue;
}

Photon Unity Networking > Utility Scripts > PhotonPlayer > PlayerRoomIndexing strange results

$
0
0
Has anyone used this utility? It seems to work fine upon creating and joining a room, but after leaving , and creating and joining a new room the results become somewhat random.

Culling prevents scene syncronization on new players

$
0
0
Hi to all. I'm making multiplayer mobile game in Unity. For optimization I decided to use culling bout only for sending, clients must receive everything. I set up everything and customized NetworkCullingHandler so it call PhotonNetwork.SetSendingEnabled instead of PhotonNetwork.SetInterestGroups. Everithing works fine for players , connected at the beginning of match, but when new player connected later, it doesn't received actual position of objects on the scene and their actual owners, that's for objects that group (photonView.group) is changed.

1. It was work fine before i started to work on culling. And still work at another scene, where culling not added.
2. After connection client receives messages as usual: changing ownership and syncronizing objects, that correct ownership he already received.
3. I manually call PhotonNetwork.SetSendingEnabled to allow all groups to receive. I call it earlier then connected to the room. Checked later, allowedReceivingGroups contains all the groups possible.
4. I was looking in the method NetworkingPeer.OnEvent at moment, client connected to the room, to be sure that sync events not just filtered, but not received at all. I saw only sync events from objects with group 0.

My assumption is that photon cloud not sending syncronization from objects in group different from 0 to new clients at connection. Can anybody help me with that? I found very few information about culling as well as about group.

I use:
Unity 2018.1.3f1, PUN plugin 1.90, Photon cloud.

Players not joining already created room

$
0
0
I integrated photon pun 2 unity free version in my game, it was working fine and i can play on two different devices and proper match making is done. Few bugs were there so i started fixing it.
But somehow now when i tried to start match on two devices, they don't join in single room and creating own rooms, also room list is empty when first player joins the room.

Even your demo projects are giving same problem in my project.

Can you please help me on this. I try to revert things but still same thing happening.

OnPhotonPlayerReconnected() ?

$
0
0
Hello is there a way for me to check if the player is reconnected to game?

GetRoomList not working

$
0
0
Hello,
Today I was trying to getRoomList but it's not working
I make If the room exist then make another room but its not work , it give me it's doesn't exist and when make a room give me error " Operation failed: OperationResponse 227: ReturnCode: 32766 (A game with the specified id already exist.). Parameters: {} Server: MasterServer "

this is the code
private void RoomCheck(string CheckName  , string ElseName) {
	OnReceivedRoomListUpdate();
List<RoomInfo> roomList = PhotonNetwork.GetRoomList().ToList();
RoomInfo room  = roomList.FirstOrDefault(r => r.Name == CheckName);
bool exists = (room != null);
Debug.Log(exists);
if (exists == false ) {
var RoomOptions = new  RoomOptions {MaxPlayers = 1 , IsOpen = true , isVisible = true};
	PhotonNetwork.CreateRoom(CheckName,RoomOptions,null);
} else if (exists == true) {
	var RoomOptions = new  RoomOptions {MaxPlayers = 1 , IsOpen = true , isVisible = true};
	PhotonNetwork.CreateRoom(ElseName,RoomOptions,null);
} 
}
and this is OnReceivedRoomListUpdate

public override void OnReceivedRoomListUpdate() 
{
List<RoomInfo> roomList = PhotonNetwork.GetRoomList().ToList();
} 

Basic Scoreboard

$
0
0
Ok so I had this posted before but I don't know what happened to my post after I edited it so I'm posting it again. I'm trying to create a very basic scoreboard for just a few players in my game. Since I know I will only have 2 players in my game I have a pre-created scoreboard (UI based) in the multiplayer level. It has text for a generic name and points. Right now I'm checking for when a player enters the room using their player ID.

I then change the name and give them starting points of 0. This works fine locally on both computers I've tested this on, but it never syncs up. So player one will have their name properly displayed, but the second player on the scoreboard doesn't show a change. Same is true for the second player. Their name shows up under "player 2" but the first slot for player 1 doesn't show a change.

This is the script I'm using. I applied a PhotonView to the scoreboard in the game and I'm using an RPC to initialize the scoreboard in the start method:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ScoreManager : Photon.PunBehaviour
{


    public static ScoreManager Instance;
    public int player;
    public Text[] nameText;
    public Text[] scoreText;
    public int[] currentPoints;
    public int totalPoints = 10;


    void Start()
    {
            //Check if instance already exists
        if (Instance == null)
            Instance = this;  
        else if (Instance != this)
               Destroy(gameObject);

        player = PhotonNetwork.player.ID -1;
		photonView.RPC("InitScoreboard", PhotonTargets.AllBuffered);
    }



    [PunRPC]
    void InitScoreboard()
    {        
     
        nameText[player].text = "Player " + (player + 1);
        currentPoints[player] = 0;
        totalPoints = 10;
    }


    public void UpdateScore()
    {
        Debug.Log("You got hit");
        currentPoints[player] += 1;
        scoreText[player].text = currentPoints[player].ToString();
        CheckScore();
    }

    void CheckScore()
    {
        if (currentPoints[player] >= totalPoints)
        {
            currentPoints[player] = totalPoints;
            Debug.Log("Game Over " + "player " + player + " has Won");
        }
    }
}
I've done something somewhat similar with a game object in the level that has health as I wanted to test out RPCs and it works fine. Everything syncs up and change in health on one computer syncs across the network to the other. I just don't understand why it won't work for this. What am I missing here?

PUN RaiseEvent in FixedUpdate()

$
0
0
Hello!
I'm experiencing so many disconnects in the game.
In the game there are 2 players in a room. Let's say playerA and playerB, if it's playerA turn when he makes a move then he have to tell 20 objects' position to playerB so i RaiseEvent in the FixedUpdate() with the content of Vector3[] of every objects' position, rotation, and velocity and sendReliable = true. I tried to make some delay by counter.
void FixedUpdate() { if(a==1) { //RaiseEvent Here } a++; ifa>8) a=0; }
Is it because of the data sent are too much and sendReliable = true?
Thanks in advance.

Authentication Problem Following Photon Tutorial

$
0
0
I've been having a rough time following the PUN basic tutorial because currently I am having issues getting the display to say that I have connected to a room. Here are my current responses (typed word for word from the tutorial). I'm getting some error codes which I think have to do with authentication. Please help.

OnStatusChanged: Connect current State: ConnectingToNameServer
Connected to NameServer.
OnStatusChanged: EncryptionEstablished current State: ConnectingToNameServer
OperationResponse 230: ReturnCode: 0.
Received your UserID from server. Updating local value to: geg
OnStatusChanged: Disconnect current State: DisconnectingFromNameServer
OnStatusChanged: Connect current State: ConnectingToMasterserver
Connected to masterserver.
OnStatusChanged: EncryptionEstablished current State: Authenticating
OperationResponse 230: ReturnCode: 0.
DemoAnimator/Launcher: OnConnectedToMaster() was called by PUN
OnEvent: Event 226.
OnEvent: Event 226.

Synchronizing other Players when they fall in the same group

$
0
0
Hey guys! I apologize if this has been answered already but I have an issue going on currently.

I am working on a spaceshooter multiplayer in Unity and I am in the latest version. I just recently implemented Interest Groups so that only users in the same group send updates. The problem that I am having:

  1. - I have two ships. Ship A and Ship B
  2. - Ship A leaves the interest group of Ship B
  3. - Ship B start shooting infinitely into space
  4. - Ship A moves near Ship B
  5. - Ship A's client doesnt see Ship B shooting though for Ship B's client it is still shooting


How do I let Ship B's client know to synchronize Ship B from Ships A's client? Currently I am avoiding PhotonTargets.AllBuffered for RPC calls so that doesnt help. Wanted to know if there is good solution for this or maybe I am missing something.

Thanks again!

Basic Scoreboard System

$
0
0
I was really hoping there was a simplistic scoreboard tutorial in the docs or on the site somewhere but this seems to be hard to find. Currently I have a very simplistic scoreboard based around 2 players. Since I know exactly how many players will be in the game, I just enable the UI text that displays the name and the points.

So when player 1 joins the game, the first set of text elements are enabled and I change the text of both to the name of the player and the amount of points he has. When player 2 joins the same is supposed to happen for the next set of text elements. At the moment this kind of works, but it's not synced across the network. So player one only sees his name and points enabled, and player 2 only sees their name and points enabled. This is what I currently have at the moment:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ScoreManager : Photon.PunBehaviour
{


    public static ScoreManager Instance;
    public int player;
    public Text[] nameText;
    public Text[] scoreText;
    public int[] currentPoints;
    public int totalPoints = 10;


    void Start()
    {
        Instance = this;
        player = NetworkLauncher.Instance.avatarIndex;
    }



    [PunRPC]
    void InitScoreboard()
    {
        foreach (PhotonPlayer p in PhotonNetwork.playerList)
        {

            scoreText[player].enabled = true;
            nameText[player].enabled = true;
        }
        nameText[player].text = "Player " + (player + 1);
        currentPoints[player] = 0;
        totalPoints = 10;

    }


    public void UpdateScore()
    {
        Debug.Log("You got hit");
        currentPoints[player] += 1;
        scoreText[player].text = currentPoints[player].ToString();
<del class="Delete"></del>
        CheckScore();
    }

    void CheckScore()
    {
        if (currentPoints[player] >= totalPoints)
        {
            currentPoints[player] = totalPoints;
            Debug.Log("Game Over " + "player " + player + " has Won");
        }
    }
}
I used the first method as a RPC thinking that whenever someone joins the game they're going to enable one of the text groups to display a new name with points and that will then update for all players on the network. When I join a game they don't update across the network though. So one player sees their name and points but no one else. It's like it only enables it locally.

The scoreboard is already present in the level before starting, so does this need to be instantiated instead? Am I missing something in my script to enable/disable these game objects properly? It looks like the points work just fine, but I just need all this information to be available to all players.

Strange behavior when joining different scene with AutoSyncScene = true

$
0
0
In my game there is a matchmaking lobby, where players login to Photon and create or join a room. The game (room/level) itself can be joined in at any time. I use AutoSyncScene = true to sens all the clients to the scene controlled by the master client. Things work fine so long as all players are present in the room when the master client "starts the game" (clicking a button that performs the level change).

As the game can be joined in progress at any time though, it is possible for a player to come to the lobby, see the room/game and join it. Unlike a player who was there form the start, the player does not wait in the lobby for the scene to transistion. Upon clicking the room, they join the game and presumably AutoSyncScene does it's magic.

In this case, they DO transition to the correct level, however, and I wish I could be more specific as to the problems popping up, but one can be noted in this post.

https://forum.photonengine.com/discussion/12525/photon-unity-networking-utility-scripts-photonplayer-playerroomindexing#latest

Various other problems pop up, but this one is the most prevalent. Upon entering the new scene, the player returns an index of -1 indicating they are not in the room. It is not consistent, almost as if there is a race condition between the scene loading and Photon connecting them to the room.

What are best practices with Photon with joining a game already in progress with AutoSyncScene = true?

How to get scene load progress when using photonnetwork.loadlevel

$
0
0
Hi,

I use photonnetwork.loadlevel to load my scenes and I have it set up so that when the master client switches the other players in the room automatically switch as well.

Usually in unity to do a progress bar for loading a scene you would use async load and then check operation progress to see how far you had got in order to update your loading progress.

With photonetwork.loadlevel I'm not aware of how I would get the scene progress as there doesn't appear to be any way of checking load progress?
I'm aware photon doesn't have an async load so how do I go about getting the scene load progress for the master and the various joined hosts so they can be presented with some time line type information on how long they will need to wait for the scene to load?

The Photon tutorial needs to be tested, corrected and should have a video or GIF

$
0
0
Photon is such a great product but the tutorial is not very helpful to newcomers who want to invest in Photon. There are too many typos and missing information that we have to Google or figure it out. I think most of these problems would be resolved if someone just take some time to go through the tutorial with a few complete newcomers and make sure that they don't encounter any issues when going through the tutorial documentation. Another great way to make sure there are no mistakes on the documentation is to provide Videos or GIF for those sections. I was stuck for a while in part 3 and then again on part 4. I think it is understandable for a page or 2 but consecutively seems a bit too much.

I hope this isn't too much to ask. Thanks for your time.

Photon V2 -- PlayFab Webhooks

$
0
0
I'm tearing my hair out trying to figure out how to convert this PlayFab-- Photon connection sample method from Photon V1 to V2. Original document: https://api.playfab.com/docs/tutorials/landing-tournaments/photon-unity

In the V1 sample, RaiseEventOptions had a "ForwardToWebhook" option to tell the event handler to trigger a webhook, however I can't find information on how to convert it to the new Photon V2 Unity methods.

Here is the original custom event method (called when a button is pressed with the player logged into a room) :
    // Example code which raises custom room event, then sets custom room property
    private void ExecuteExample()
    {
        // Raise custom room event
        var data = new Dictionary<string, object>() { { "Hello", "World" } };
        var result = PhotonNetwork.RaiseEvent(15, data, true, new RaiseEventOptions()
        {
            ForwardToWebhook = true,
        });
        LogMessage("New Room Event Post: " + result);

        // Set custom room property
        var properties = new ExitGames.Client.Photon.Hashtable() { { "CustomProperty", "It's Value" } };
        var expectedProperties = new ExitGames.Client.Photon.Hashtable();
        PhotonNetwork.room.SetCustomProperties(properties, expectedProperties, true);
        LogMessage("New Room Properties Set");
    }

If I update it to clear the errors, I end up with the following (below), which obviously doesn't know to push to playfab in the current state -- anyone know how I can update it to push properly?
    // Example code which raises custom room event, then sets custom room property
    private void ExecuteExample()
    {

        // Raise custom room event
        var data = new Dictionary<string, object>() { { "Hello", "World" } };
        var result = PhotonNetwork.RaiseEvent(15, data, new RaiseEventOptions(), new SendOptions());
        LogMessage("New Room Event Post: " + result);

        // Set custom room property
        var properties = new ExitGames.Client.Photon.Hashtable() { { "CustomProperty", "It's Value" } };
        var expectedProperties = new ExitGames.Client.Photon.Hashtable();
        PhotonNetwork.CurrentRoom.SetCustomProperties(properties, expectedProperties);
        LogMessage("New Room Properties Set");
    }

Thank you in advance!

Why Aren't Game Object Positions Synced?

$
0
0
I have a game object that the player can move around with this script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PickUpItems : MonoBehaviour {

public Transform  throwables;
public PhotonView photonView;
public GameObject itemPos;
public GameObject item;
public Rigidbody  itemRB;
public bool 	  hasItem;
public RaycastHit hit;
public int 		  rayDist;
public int 		  power;

public void Update() {

	//Try to pick up item if player doesn't already have one and clicks
	if(Input.GetButtonDown("Fire1") && hasItem == false) {

		//Check for a throwable object
		Physics.Raycast(this.transform.position, this.transform.forward, out hit, rayDist, 1 << 8);

		if(hit.collider != null) {

			//Pick up object
			item = hit.collider.transform.gameObject.transform.parent.gameObject;
			item.transform.parent = itemPos.transform;
			item.transform.position = itemPos.transform.position;

			itemRB = item.GetComponent<Rigidbody>();
			itemRB.constraints = RigidbodyConstraints.FreezePositionZ | RigidbodyConstraints.FreezePositionY | RigidbodyConstraints.FreezePositionX;
			hasItem = true;

			//Transfer PhotonView
			photonView = item.GetComponent<PhotonView>();
			photonView.TransferOwnership(PhotonNetwork.player);
		}

		//Throw item if player has one and clicks
		} else if(Input.GetButtonDown("Fire1") && hasItem == true) {
			item.transform.parent = throwables;

			itemRB.AddForce(this.transform.forward * power, ForceMode.Impulse);
			itemRB.constraints = RigidbodyConstraints.None;
			hasItem = false;
		}
	}
}
I've experimented using different settings for the Photon View and Photon Transform View components on the game object that I'm trying to move. It moves perfectly fine for the player that's moving it however it has a weird affect for other players in the same room. The object just falls through the ground endlessly. Why does this happen?

Problem with tutorial - `GetActive' of type `UnityEngine.GameObject' could be found

Viewing all 8947 articles
Browse latest View live


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