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

Photon RPC for synching gameobjects' active/inactive status across all players

$
0
0
Hi all!

I'm new to Photon, and am currently using it to develop a simple shared experience in mixed reality (Microsoft Hololens 1), where everyone can see a human body in the scene and it can be moved around / different body parts (gameObjects) can be toggled on or off via voice command. Currently, I have the voice command implemented locally via MRTK in Unity (Speech Commands in MRTK Inputs + using MRTK SpeechInputHandler; no C# scripts involved), and can have these actions done locally.

I'm looking to use Photon RPC so that all people in the room can see the current state of the gameObject if one person (the owner of the server / first person that created and entered the room) calls for a change via voice command. For reference, the gameObject is a human body with various elements (skin, muscles, skeleton) etc. When they're toggled on or off, it's simply via GameObject.SetActive being toggled or not. I'd like it so that if I said "show skin", for example, everyone in the room can see the updated body model with its skin showing. If someone knows what the script for implementing this would look like, please help me out, thanks so much!

Keeping loaded AssetBundles when Player joins or leave the room

$
0
0
Hello,

I would like to load AssetBundles in multiplayer, it already works very well. But my problem is that when a new participant joins or leaves the room, the scene is reloaded for all participants and the AssetBundles have all disappeared again. How do I go about that the scene is only reloaded for the new participant and builds up correctly and not for all participants? And especially don't reload the scene when someone leaves the room.

Many thanks and best regards,
Sebastian

How to solve this synchronization issue? Item pickup being delayed on non-master clients

$
0
0
The master client owns the majority of items in the game and is responsible for both creating them and destroying them.
The issue is when one of the other players besides the master walks over an item owned by the master, there is a noticeable delay (due to ping) before the item disappears on the non-master screens (this is because the master only removes the item when it thinks someone has picked it up and then it takes some time for all clients to be notified that the item has been destroyed).

How do you network programmers deal with this synchronization issue?

My idea was to stop rendering the item locally on any client as soon as that client thinks someone walked over it, and then if they do NOT get notification that the item has been destroyed on the network by the master within like 1 second, start rendering the item again. Obviously if we do get notification within 1 second that the item was in fact destroyed it will never be rendered again. This will mean more instant feedback that an item has been picked up.

Any ideas welcome on how to deal with this possibly common problem?

How do we get the region we are connected to in the case that Photon is picking the best region?

$
0
0
So when FixedRegion is null or empty in the settings then Photon will simply pick the best region to connect to right?

How do we know which region that is? I want to be able to access it in script. I know of PhotonNetwork.ServerAddress that gives the IP, but I would like the country code rather: e.g. asia, za, jp etc. so I can display to the user where they are connecting. Is that possible?

Error in PhotonSteamQueue.cs-->ReceiveNext().

$
0
0
Hello!
Sorry for my English! :)

Why do I get this error when one player (IsMasterClient = false) enters another player(IsMasterClient = true)'s room? The error occurs at player (IsMasterClient = true).

Thanks!

Error.png
A.png
B.png
C.png

Mobile inactive players is automatically kicked after a time

$
0
0
Hello,

I am using PUN2 in a realtime multiplayer cardgame. On mobile devices, managing inactive players (changing App, receiving a call, ...) is not so easy but I managed to do it using OnApplicationPause, MasterClient switching, ...

However I see that the inactive player is kicked after a time which seems to be 15 seconds.

Is this the normal behavior ? Is this because I still send RaiseEvent to him and once the queue is too long, the inactive player is kicked ?

Anyway, is there a way to increase the before-being-kicked time ?

Best regards

Stéphane

IndexOutOfRangeException: Index was outside the bounds of the array. Photon.Pun.PhotonStream.Receive

$
0
0
Hi,

I am getting this Exception "IndexOutOfRangeException: Index was outside the bounds of the array.
Photon.Pun.PhotonStream.ReceiveNext () (at Assets/Photon/PhotonUnityNetworking/Code/PunClasses.cs:717)"

Let me explain why, I have a snake character with body parts like head, body and tail. I am generating this snake in runtime. so while generating these parts I have added photon components in run time. the code snippet is mention below please check that.

private void Set_PhotonComponents()
{
if (PetSnake_Body_Parts.Count > 0)
{
for (int i = 0; i < PetSnake_Body_Parts.Count; i++)
{
if (i == 0)
{
PetSnake_Body_Parts.gameObject.AddComponent<PhotonRigidbodyView>();
}
PetSnake_Body_Parts.gameObject.AddComponent<PhotonTransformView>();
}
}
}

private void Update_PhotonComponents()
{
if (PetSnake_Body_Parts.Count > 0)
{
for (int i = 0; i < PetSnake_Body_Parts.Count; i++)
{

if (i == 0)
{
PetSnake_Body_Parts.GetComponent<PhotonRigidbodyView>().m_SynchronizeVelocity = true;
}
PetSnake_Body_Parts.GetComponent<PhotonTransformView>().m_SynchronizePosition = true;
PetSnake_Body_Parts.GetComponent<PhotonTransformView>().m_SynchronizeRotation = true;
PetSnake_Body_Parts.GetComponent<PhotonTransformView>().m_SynchronizeScale = true;
}
}
}

so these components will be observed by a parent gameobject which has photon view. the concept it the body parts of the snake will scale and shrink when triggered, but when i trigger the action, I am running into this exception, "IndexOutOfRangeException: Index was outside the bounds of the array.
Photon.Pun.PhotonStream.ReceiveNext () (at Assets/Photon/PhotonUnityNetworking/Code/PunClasses.cs:717)"

photon assets randomly reimported

$
0
0
hello guys,

im having this bug where the photon asset files are reimported ramdomly in unity and this lealds to multiple files of the same type and then creates errors, i have been temporarily getting over this by deleting the photon folder and reimporting from the app store but eventuallly unity will just randomly reimport the package and create errosrs, has anyone experienced thi?

Reset 'Best Region Preference' from script

$
0
0
So somehow my 'Best Region Preference' got stuck on Japan even thought it is by far the best ping for me. When a region is not explicitly specified I understand it will connect to this one.

By clicking 'Reset' in my next to 'best region preference' in PhotonServerSettings it recalculated the best region to the correct one. I am worried that a client may also get their 'best region preference' stuck on something that isnt actually the best region, so I would like to reset it every time the program is run.

Is there a way to reset the best region preference in script? Or perhaps there is a more elegant way to handle this?

No WebGL possible with PUN 2

$
0
0
Hello everyone,

I am new to Photon/PUN and also quite new to unity. I have a problem using PUN 2 and could not find a solution up to now:

I just wanted to test if PUN 2 works also in WebGL Builds, as far as I know it should. But I am not able to get a working WebGL Build with PUN 2. I tried it also with the Demos (especially the SlotCar Demo) you can get with PUN (to be sure, that nothing in my Project creates the problem), but even then I can't get a working WebGL Build. When I build the Demo as Windows Standalone, everything works fine and I also can get a connection to the server from different clients.
When I want to build WebGL, I first got a build, but it never left the Unity/WebGL loading screen. And now after I updated Unity and PUN 2 to the current version I am not even able to get a build.

I give you a short history of what I tried:

When I open an empty unity (3D) project, I already get a warning:
Assembly for Assembly Definition File 'Packages/com.unity.collab-proxy/Tests/Editor/Unity.CollabProxy.EditorTests.asmdef' will not be compiled, because it has no scripts associated with it.
UnityEditor.Scripting.ScriptCompilation.EditorCompilationInterface:TickCompilationPipeline(EditorScriptCompilationOptions, BuildTargetGroup, BuildTarget, String[])

after importing PUN 2, there are several warnings:
Unity is only able to load mdb or portable-pdb symbols. Assets/Photon/PhotonLibs/Metro/Photon3Unity3D.pdb is using a legacy pdb format.
UnityEngine.Debug:LogWarning(Object)
Microsoft.Unity.VisualStudio.Editor.VisualStudioEditor:SyncIfNeeded(String[], String[], String[], String[], String[]) (at Library/PackageCache/com.unity.ide.visualstudio@2.0.2/Editor/VisualStudioEditor.cs:154)
UnityEditor.AssetPostprocessingInternal:PostprocessAllAssets(String[], String[], String[], String[], String[])

Unity is only able to load mdb or portable-pdb symbols. Assets/Photon/PhotonLibs/netstandard2.0/Photon3Unity3D.pdb is using a legacy pdb format.
UnityEngine.Debug:LogWarning(Object)
Microsoft.Unity.VisualStudio.Editor.VisualStudioEditor:SyncIfNeeded(String[], String[], String[], String[], String[]) (at Library/PackageCache/com.unity.ide.visualstudio@2.0.2/Editor/VisualStudioEditor.cs:154)
UnityEditor.AssetPostprocessingInternal:PostprocessAllAssets(String[], String[], String[], String[], String[])

Unity is only able to load mdb or portable-pdb symbols. Assets/Photon/PhotonLibs/Photon3Unity3D.pdb is using a legacy pdb format.
UnityEngine.Debug:LogWarning(Object)
Microsoft.Unity.VisualStudio.Editor.VisualStudioEditor:SyncIfNeeded(String[], String[], String[], String[], String[]) (at Library/PackageCache/com.unity.ide.visualstudio@2.0.2/Editor/VisualStudioEditor.cs:154)
UnityEditor.AssetPostprocessingInternal:PostprocessAllAssets(String[], String[], String[], String[], String[])

after loading the SlotCar Demo Scene, there is another warning:
Scene 'PunCockpit-Scene' couldn't be loaded because it has not been added to the build settings or the AssetBundle has not been loaded.
To add a scene to the build settings use the menu File->Build Settings...
UnityEngine.SceneManagement.SceneManager:LoadScene(String, LoadSceneMode)
Photon.Pun.Demo.Cockpit.<Start>d__6:MoveNext() (at Assets/Photon/PhotonUnityNetworking/Demos/PunCockpit/Scripts/ThirdParty/PunCockpitEmbed.cs:53)
UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)

If I build the Demo now as Windows Standalone, everything works fine despite the several warnings.

If I switch the platform to WebGL i get another 3 warnings:
Assets\Photon\PhotonRealtime\Code\PhotonPing.cs(449,17): warning CS0618: 'WWW' is obsolete: 'Use UnityWebRequest, a fully featured replacement which is more efficient and has additional features'

Assets\Photon\PhotonRealtime\Code\PhotonPing.cs(456,35): warning CS0618: 'WWW' is obsolete: 'Use UnityWebRequest, a fully featured replacement which is more efficient and has additional features'

Assertion failed on expression: 'ins.second || ins.first->second == targetHash || (ins.first->second == CircularDependencyHash() && !targetHash.IsValid()) || GetPathFromAssetGuidV2(key.GetGUID()).ends_with(".cs")'

now, if I click on "Build" I get another 4 messages:
Assets\Photon\PhotonLibs\WebSocket\WebSocket.cs(5,7): error CS0246: The type or namespace name 'WebSocketSharp' could not be found (are you missing a using directive or an assembly reference?)

Error building Player because scripts had compiler errors

Build completed with a result of 'Failed'
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)

UnityEditor.BuildPlayerWindow+BuildMethodException: 2 errors
at UnityEditor.BuildPlayerWindow+DefaultBuildMethods.BuildPlayer (UnityEditor.BuildPlayerOptions options) [0x0027c] in <d1bec46880064709a5e713ad543e6d96>:0
at UnityEditor.BuildPlayerWindow.CallBuildMethods (System.Boolean askForBuildLocation, UnityEditor.BuildOptions defaultBuildOptions) [0x00080] in <d1bec46880064709a5e713ad543e6d96>:0
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)

Do you know what is wrong? Why is unity not even able to build the Demo of PUN 2 in WebGL?
As I already said I have the newest version of Unity and PUN 2.
I hope my request is not confusing or stupid.

PhotonView gets lost when built to Android

$
0
0
I have a car that has a PhotonView, a Photon RigidBodyView and a PhotonTransformView and while working in the Unity editor my game works fine but when I build to Android Car1 while not be able to ".GetComponent<PhotonView>()".

I'm not sure what else to say. My PhotonView is "Unreliable" and has Auto Found the RigidBody and the Transform. The RigidBody View says "Unable to find a PhotonView on the GameObject or any parent GameObject" even though the PhotonView is directly above it on the same GameObject.

Strangely enough an exact;y the same build Car2 works fine while Car1 doesn't work (Because I can't FindComponent PhotonView). Any thoughts or things to try?

Thanks

Keeping Lobby Scene when loading Room Scene

$
0
0
In my game I want to have a Spaceship Scene as the Lobby where players can join and look at each others customized character. When everyone is ready and a Room was found it should load the Room and keep the Lobby Spaceship Scene loaded. So the Spaceship can land and the players can walk out into the world.

The easy way would be to copy the Spaceship into the Room Scene for a seamless transition but I always used a multi Scene workflow to keep UI and such separated.

Is there a way to additively load Scenes?

Rooms not showing up!

$
0
0
For some reason I can no longer see created rooms. Everything was working before but now even my backups which worked fine don't show created rooms. I set the Dev Region to usw. I have both the Player Settings and PhotonServerSettings App Version set to 0.1. Using Name Server, UDP.. I have no Errors. SupportLogger tells me OnRoomListUpdate is being called and showing 0 rooms even when I have a created room running on my Oculus Quest. Here is my lobby script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine.SceneManagement;
using System.IO;
using MEC;
using Hashtable = ExitGames.Client.Photon.Hashtable;

/// <summary>
/// to know where the player is in each connecting stage
/// </summary>
public enum connectionState
{
notconnected,
inLobby,
inRoom
}


/// <summary>
/// to know the game Mode
/// </summary>
public enum gameMode
{
Cooperative,
Teams,
battleRoyale
}


/// <summary>
/// This is the most important script that allows the room/lobby connections
/// </summary>
public class PhotonLobby : MonoBehaviourPunCallbacks, IInRoomCallbacks
{
//singleton
public static PhotonLobby lobby;


// connecting/disconnecting icons
public GameObject connectedIcon;
public GameObject disconnectedIcon;

public Text roomLabel;
public Slider maxPlayers;
public Slider roundMinutes;
public RoomDisplay roomDisplay;
private int gameSceneIndex => roomDisplay.gameMapIndex;


//list of rooms used to join an specific room or create one
List<RoomInfo> roomsInfo;


public int Time_minutes => (int) roundMinutes.value > 0 ? (int) roundMinutes.value : 9999;

//the number of created rooms
[Header("The type of game selected", order = 0)]
public gameMode gameMode;


//the number of created rooms
[Header("Number of rooms in the game", order = 0)]
public int numberOfRooms;

//to know whether the player is in lobby

public string roomName;

//to set the number of maximum players of a room
//
int MaxPlayersRoom => (int) maxPlayers.value;

//used to know the connection state
[Header("Shows the connection state of the player", order = 0)]
public connectionState conState;

//photon view attached to this gameobject
private PhotonView PV;

// player variables
Player[] photonPlayers;

[Header("Shows the players in room", order = 0)]
public int playersInRoom;

[Header("The player prefab used to get the initial life", order = 0)]
public GameObject playerPrefab;

//buld index of current scene
int currentScene;

#region UNITY Functions

private void Awake()
{
conState = connectionState.notconnected;
//initialization
PV = GetComponent<PhotonView>();

}

public void Reconnect()
{
PhotonNetwork.Reconnect();
}

public void Disconnect()
{
PhotonNetwork.Disconnect();
}

public void FixedUpdate()
{
//find the connection buttons
connectedIcon = GameObject.FindGameObjectWithTag("connectedIcon");
disconnectedIcon = GameObject.FindGameObjectWithTag("disconnectedIcon");


// set the true or false in function of connection
if (PhotonNetwork.IsConnected)
{
if (connectedIcon != null && disconnectedIcon != null)
{
connectedIcon.SetActive(true);
disconnectedIcon.SetActive(false);
}
}
else
{
if (connectedIcon != null && disconnectedIcon != null)
{
connectedIcon.SetActive(false);
disconnectedIcon.SetActive(true);
}
}
}

public override void OnEnable()
{
base.OnEnable();

//set up singleton
if (PhotonLobby.lobby == null)
{
PhotonLobby.lobby = this;
}
else
{
if (PhotonLobby.lobby != this)
{
Destroy(PhotonLobby.lobby.gameObject);
PhotonLobby.lobby = this;
}
}

DontDestroyOnLoad(this.gameObject);


//// [!] [!] TO MAKE THIS LINE WORK
//CHANGE THE PhotonserverSettings
if (PhotonNetwork.IsConnected == false)
{
PhotonNetwork.ConnectUsingSettings(); //connects to the master photon server
}

//needed to perfom well
PhotonNetwork.AddCallbackTarget(this);

SceneManager.sceneLoaded += OnSceneFinishedLoading;
}

public override void OnDisable()
{
base.OnDisable();

//needed to perform well
PhotonNetwork.RemoveCallbackTarget(this);
SceneManager.sceneLoaded -= OnSceneFinishedLoading;
}

#endregion


#region FAIL EVENTS

// callbacks for errors in logging
public override void OnCreateRoomFailed(short returnCode, string message)
{
DebugOnCanvas.DC.Debug("Tried to create a new room but failed: room with same name exists");
StartCoroutine(restartConnexion());
}


// callbacks for errors in loging
public override void OnJoinRoomFailed(short returnCode, string message)
{
StartCoroutine(restartConnexion());
DebugOnCanvas.DC.Debug("Tried to join a room but failed: " + message);
}

#endregion


#region ON EVENTS

//get the information of the room
public override void OnRoomListUpdate(List<RoomInfo> roomList)
{
base.OnRoomListUpdate(roomList);

roomsInfo = roomList;

RoomDisplay.RD.updateRooms(roomsInfo);
}

// Reset user properties when connected to lobby
public override void OnJoinedLobby()
{
//get name of player
PhotonNetwork.NickName = PlayerInfo.PI.NickName;

//set connection state
conState = connectionState.inLobby;

base.OnJoinedLobby();

DebugOnCanvas.DC.Debug("Joined Lobby");


//set custom properties from player Info and reset the score, kills, etc
Player PY = PhotonNetwork.LocalPlayer;
SetCustomPlayerProp(PY, 0,
0,
0,
playerPrefab.GetComponentInChildren<PlayerHealth>().initialHealth,
PlayerInfo.PI.myHeight,
PlayerInfo.PI.mySkin,
PlayerInfo.PI.myTeam,
PlayerInfo.PI.myGameMode,
PlayerInfo.PI.myMesh);
}

//CALBACK USED to determine if the player is connected to the server
public override void OnConnectedToMaster()
{
DebugOnCanvas.DC.Debug("Player has connected to the photon server");

PhotonNetwork.AutomaticallySyncScene = false;
PhotonNetwork.JoinLobby();
}


// always join lobby to get user/player data
public override void OnLeftRoom()
{
base.OnLeftRoom();
PhotonNetwork.JoinLobby();
}

public void Refresh()
{
GameObject[] gos = GameObject.FindGameObjectsWithTag("roomInstance");
for (int ii = 0; ii < gos.Length; ii++)
{
Destroy(gos[ii]);
}

StartCoroutine(restartConnexion());
}

//this function allows the user to re-connect
IEnumerator restartConnexion()
{
DebugOnCanvas.DC.Debug("Refreshing");
if (PhotonNetwork.IsConnected)
{
PhotonNetwork.Disconnect();
}

while (PhotonNetwork.IsConnected == false)
{
yield return null;
}

yield return new WaitForSeconds(1);
PhotonNetwork.ConnectUsingSettings();
}

#endregion

#region ROOM EVENTS

public void Create()
{
//RETURN if not in lobby
if (PhotonNetwork.InLobby == false)
{
return;
}

//get the number of rooms
numberOfRooms = roomsInfo.Count;

roomName = roomLabel.text;

//we need to make public the variable "Gmode" in the hastable (matchmaking)
string[] str = new string[2];
str[0] = "Gmode";
str[1] = "Map";

// if the room does not exit, create one
RoomOptions roomOps = new RoomOptions()
{
IsVisible = true,
IsOpen = true,
MaxPlayers = (byte) MaxPlayersRoom,
CustomRoomProperties = (new Hashtable(2)
{
{
"Gmode", PlayerInfo.PI.myGameMode
},
{
"Map", roomDisplay.gameMapIndex
}
}),
CustomRoomPropertiesForLobby = str
};
// roomOps.CustomRoomProperties.Add("Map", roomDisplay.gameMapIndex);

//line to create the room
PhotonNetwork.CreateRoom(roomName, roomOps);

DebugOnCanvas.DC.Debug("Created room=" + roomName);

numberOfRooms = roomsInfo.Count;
}

IEnumerator<float> WaitForFade()
{
yield return Timing.WaitForSeconds(5f);
Create();
yield return 0f;
}

// THIS FUNCTION IS USED TO CREATE A ROOM IT WILL BE IN INCREASING ORDER
public void createRoom()
{
Timing.RunCoroutine(WaitForFade());
}

public void createOrJoinRoom(string roomName)
{
//RETURN if not in lobby
if (PhotonNetwork.InLobby == false)
{
return;
}

//we need to make public the variable "Gmode" in the hastable (matchmaking)
string[] str = new string[2];
str[0] = "Gmode";
str[1] = "Map";

// if the room does not exit, create one
RoomOptions roomOps = new RoomOptions()
{
IsVisible = true,
IsOpen = true,
MaxPlayers = (byte) MaxPlayersRoom,
CustomRoomProperties = (new Hashtable(2)
{
{
"Gmode", PlayerInfo.PI.myGameMode
},
{
"Map", roomDisplay.gameMapIndex
}
}),
CustomRoomPropertiesForLobby = str
};
// roomOps.CustomRoomProperties.Add("Map", roomDisplay.gameMapIndex);

//line to create the room
PhotonNetwork.JoinOrCreateRoom(roomName, roomOps, TypedLobby.Default);
}

// when a player joins a room
public override void OnJoinedRoom()
{
base.OnJoinedRoom();
conState = connectionState.inRoom;

DebugOnCanvas.DC.Debug("We are now in a room");

//obtain the players connected
photonPlayers = PhotonNetwork.PlayerList;


//THIS IS THE MAIN CALL
//DebugOnCanvas.DC.Debug("Starting the game");
DebugOnCanvas.DC.Debug("Actual players=" + (PhotonNetwork.PlayerList.Length) + " of possible=" +
(MaxPlayersRoom));

//set custom properties from player Info and reset the score, kills, etc
Player PY = PhotonNetwork.LocalPlayer;
SetCustomPlayerProp(PY, 0,
0,
0,
playerPrefab.GetComponentInChildren<PlayerHealth>().initialHealth,
PlayerInfo.PI.myHeight,
PlayerInfo.PI.mySkin,
PlayerInfo.PI.myTeam,
PlayerInfo.PI.myGameMode,
PlayerInfo.PI.myMesh);

StartGame();
}

//WHEN A NEW PLAYER IS ENTERING THE ROOM
public override void OnPlayerEnteredRoom(Player newPlayer)
{
base.OnPlayerEnteredRoom(newPlayer);


//get the player list information again
DebugOnCanvas.DC.Debug("A new player has joined: " + newPlayer.NickName);

//obtain the players connected
photonPlayers = PhotonNetwork.PlayerList;
playersInRoom = photonPlayers.Length;
}


//decreae the players in room variable when a player leaves the room
public override void OnPlayerLeftRoom(Player otherPlayer)
{
base.OnPlayerLeftRoom(otherPlayer);

DebugOnCanvas.DC.Debug(otherPlayer.NickName + " Has left the game");

//obtain the players connected
photonPlayers = PhotonNetwork.PlayerList;
playersInRoom = photonPlayers.Length;
}


void OnSceneFinishedLoading(Scene scene, LoadSceneMode mode)
{
currentScene = scene.buildIndex;
SceneManager.SetActiveScene(SceneManager.GetSceneByBuildIndex(scene.buildIndex));

//used tow know if the multiplayer scene has been loaded
if (currentScene > 1)
{
//PV.RPC("RPC_CreatePlayer", RpcTarget.All);
CreatePlayer();
}
}

#endregion


#region CREATE PLAYER PREFAB IN NETWORK

private void CreatePlayer()
{
int spawnPicker = Random.Range(0, GameSetUp.GS.spawnPoints.Length);
// [!] this is the directory used to get the most important players' prefab [!] --> playerAvatar
GameObject goInst = PhotonNetwork.Instantiate(Path.Combine("PhotonPrefabs", "PlayerAvatarNew"),
GameSetUp.GS.spawnPoints[spawnPicker].position, Quaternion.Euler(0, 0, 0));
}

#endregion

#region PUBLIC FUNCTIONS CALLED FROM BUTTONS

//called when editing name
public void ChangeName(Text nicknameText)
{
PhotonNetwork.NickName = nicknameText.text;
}

public void StartGame()
{
SceneManagerAsync.SM.goToMultiplayerScene(gameSceneIndex);
}

public void ReturnToLobby()
{
SceneManagerAsync.SM.goToLobby();
}

#endregion


public void SetCustomPlayerProp(Player py, int kills, int deaths, int score, int health, float height, int skin,
int team, string Gmode, int mesh)
{
py.SetCustomProperties((new ExitGames.Client.Photon.Hashtable(1)
{
{"kills", kills},
{"deaths", deaths},
{"score", score},
{"health", health},
{"height", height},
{"skin", skin},
{"team", team},
{"Gmode", Gmode},
{"mesh", mesh}
}));
}
}

Exception: Write Failed. Custom type not found: UnityEngine.Transform

$
0
0
Hey,

i am currently in the process of building my first multiplayer application or rather adding a spectator mode to an aleady built VR application so other people can join and just watch what the main player in VR is doing.

The application heavily relies on events to progress the story, it basically has events that set the general story state and then other events that can trigger as side-events during that particular story step.

I managed to get the tracking to work after some initial hiccups, I'm at the point where spectators can join and watch through the players eyes.

My next goal is converting all the local events to RPC's. The method i tried is implementing the IOnEventCallback interface on a helper script which is supposed to trigger all local audioevents.
The idea was to trigger the event passing over a string and a transform, telling the receiving function which sound and where to play it.
Sadly it's throwing a pretty long and (for me) cryptic error message, i am not quite sure what to change or why he is complaining about the Transform in the first place, seems like the string is working just fine.

using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using ExitGames.Client.Photon;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine;

public class PhotonAudioEventHandler : MonoBehaviour
{
    public const byte TriggerMasterAudioOneShotEventCode = 1;

    public static PhotonAudioEventHandler Instance;

    void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        else
        {
            Debug.LogWarning("Already got one of these, destroying myself.");
            Destroy(this);
        }
    }

    public void TriggerMasterAudioEvent(string sfxName, Transform playbackPosition)
    {
        object[] content = new object[] {sfxName, playbackPosition};
        RaiseEventOptions raiseEventOptions = new RaiseEventOptions {Receivers = ReceiverGroup.All};
        PhotonNetwork.RaiseEvent(TriggerMasterAudioOneShotEventCode, content, raiseEventOptions, SendOptions.SendReliable);
    }
}

And this is the receiver.
using System.Collections;
using System.Collections.Generic;
using ExitGames.Client.Photon;
using Photon.Realtime;
using UnityEngine;
using DarkTonic.MasterAudio;
using Photon.Pun;

public class PhotonAudioEventReceiver : MonoBehaviour, IOnEventCallback
{
    void OnEnable()
    {
        PhotonNetwork.AddCallbackTarget(this);
    }

    void OnDisable()
    {
        PhotonNetwork.AddCallbackTarget(this);
    }

    public void OnEvent(EventData photonEvent)
    {
        Debug.Log("OnEvent() was called!");
        if (photonEvent.Code == 1)
        {
            print("Received event with index 1!");
        }
    if (photonEvent.Code == PhotonAudioEventHandler.TriggerMasterAudioOneShotEventCode)
        {
            Debug.Log("Event is TriggerMasterAudioOneShotEvent.");
            object[] data = (object[])photonEvent.CustomData;
            string sfxName = data[0] as string;
            Transform playbackTransform = data[1] as Transform;

            MasterAudio.PlaySound3DAtTransformAndForget(sfxName, playbackTransform);
        }
    }

}

Then in another script i tried calling
PhotonAudioEventHandler.Instance.TriggerMasterAudioEvent(startSFX, Jan);

but ended up with an error message.

Exception: Write failed. Custom type not found: UnityEngine.Transform.

It goes on quite a bit longer with protocol18.Write statements I can't copy easily right now as i'm on the wrong computer, can post whole log if needed later. The last statement is:
"ExitGames.Client.Photon.Protocol18.WriteCustomType(ExitGames.Client.Photon.StreamBuffer stream, System.Object value, Boolean writeType)(at 'harddrive-location')

Does anyone quickly see what i'm doing wrong? Got a looming deadline, any kind of help would be highly appreciated! :)

Peace,
LaKawa

EDIT: Some typos :wink:

Unity Photon Steam Friend Invite

$
0
0
Hello, I am the founder of Partical Studios. Currently we're working on a new game. We're using Photon Networking for our new game. But i have a problem about Steam Invite. I am creating a room in game then i want to invite my steam friends to the room. For this; CSteamID invitedUserId = (CSteamID)0; SteamFriends.ActivateGameOverlayInviteDialog(invitedUserId); When he acceptes the invite, how can i bring him to my room? I want him to join my room directly. Please help me, thanks!

PhotonServerSettings Error in Editor

$
0
0
Hey Guys,
I get the following Error when selecting the ServerSettings Asset in the Editor:

IndexOutOfRangeException: Index was outside the bounds of the array.
ServerSettingsInspector.OnInspectorGUI () (at Assets/Photon/PhotonUnityNetworking/Code/Editor/ServerSettingsInspector.cs:133)
UnityEditor.UIElements.InspectorElement+<>c__DisplayClass58_0.<CreateIMGUIInspectorFromEditor>b__0 () (at <a0a9ad37e16b4f7cb955e1101b72d4cc>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

Working on Current PUN v2 with Unity 2019.4.1f1
Cheers.

Upgrading getting problem

$
0
0
hello there,
i am getting problem while upgrading photon server.
currently i am using photon unity networking classic - free.
and i am purchase Photon PUN 2+
While i import Photon PUN 2+ packages it getting error.

pls give me a steps how to upgrade Photon server.

Thank you

Why is the master client destoying children but the other clients are destroying parent game objects

$
0
0
I have several Scene Objects that destroy themselves after they do a thing. The script is on a child of the object that needs to be destroyed. Both the parent and the child object have Photon Views. These are Scene Objects so it is up to the Master Client to destroy them.

I look for the parent Photon View ID and use PhotonNetwork.Destroy.

This works great on all of the clients. For some reason, the master destroys the child and leaves the parent object.
while (condition == true)
	{
            //Do something
            //When done, break out of the loop
	}
            int viewID = GetComponentInParent<PhotonView>().ViewID;
            this.photonView.RPC("RPC_ForceMasterClientReplaceStumpWithAshes", RpcTarget.MasterClient, viewID);

[PunRPC]
    void RPC_ForceMasterClientReplaceStumpWithAshes(int viewID)
    {
        Debug.Log("RPC destroy stump ViewID: " + viewID);
        PhotonNetwork.Destroy(PhotonView.Find(viewID).gameObject);
        PhotonNetwork.InstantiateSceneObject("Ashes", transform.parent.position, transform.parent.rotation);
    }

How to reconnect and rejoin when mobile app goes to background. Best practice?

$
0
0
Hi guys, we are using PUN for almost a year and are very happy with it. The only problem we have is handling the case where the mobile app is going to the background and to trigger a successful reconnect and rejoin. We can’t seem to find some best practices or code snippets so we cooked up something ourselves. The following implementation seems to work most of the times but it’s not 100% reliable. We still have cases where the app is not successfully reconnecting and rejoining. We hope you could take the time and spot some problems with this script. We also hope you could provide us with a best practice for reconnecting and rejoining. https://pastebin.com/X83mubxf FYI: - The room we create has a PlayerTTL of 300000. - We are only targeting iOS. - PUN v2.7 - Unity 2018.3.5 Thanks!

Photon calling OnDisconnectedFromPhoton() instantly in mobile but not in editor PUN 1 Classic

$
0
0
Hello,
i'm trying to resolve the reconnection in pun 1 classic, can anyone help how to achieve. i tried PhotonNetwork.ReconnectandRejoin() also, this is not joining in the same room but creating new room. and please can anyone explain how i have to solve this.
Viewing all 8947 articles
Browse latest View live


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