Instatiation problems with photon
Hi, i am learning unity3d with usage of Photon and got to a problem where PhotonNetwork. 2player connect then instatial 3 object so how can i solved it.please help me.
here my code: using UnityEngine; using System.Collections.Generic; using System.Collections; using UnityEngine.SceneManagement; using System.IO;
public class NetworkManagersite :MonoBehaviour {
public bool spawn = false;
private int maxPlayer = 1;
public GameObject SpawnSpot;
private Room[] game;
private string roomName = "DEFAULT ROOM NAME";
bool connecting = false;
List<string> chatMessages;
int maxChatMessages = 5;
private string maxPlayerString ="2";
public string Version = "Version 1";
private Vector3 up;
private Vector2 scrollPosition;
public static NetworkManagersite inst;
private PhotonView PhotonView;
private int PlayersInGame = 0;
public static GameObject localPlayer;
public string PlayerName { get; private set;}
//private PlayerMovement CurrentPlayer;
void Awake()
{
inst = this;
PhotonView = GetComponent<PhotonView>();
PlayerName = "Distul#" + Random.Range(1000, 9999);
SceneManager.sceneLoaded += OnSceneFinishedLoading;
}
public void OnSceneFinishedLoading(Scene scene, LoadSceneMode mode)
{
if (scene.name == "GameMobile") {
if (PhotonNetwork.isMasterClient) {
//Debug.Log ("detapass");
MasterLoadedGame();
}else {
NonMasterLoadedGame ();
}
}
}
private void MasterLoadedGame()
{
PhotonView.RPC("RPC_LoadedGameScene",PhotonTargets.MasterClient,PhotonNetwork.player);
PhotonView.RPC("RPC_LoadGameOthers",PhotonTargets.Others);
Debug.Log ("supermaster");
}
private void NonMasterLoadedGame()
{
PhotonView.RPC("RPC_LoadedGameScene", PhotonTargets.MasterClient, PhotonNetwork.player);
Debug.Log ("normalmaster");
}
void Start (){
DontDestroyOnLoad (gameObject.transform);
PhotonNetwork.player.name = PlayerPrefs.GetString("Username", "My Player name");
chatMessages = new List<string>();
}
void OnDestroy(){
PlayerPrefs.SetString("Username", PhotonNetwork.player.name);
}
public void AddChatMessage(string m){
GetComponent<PhotonView>().RPC("AddChatMessage_RPC", PhotonTargets.AllBuffered, m);
}
// [PunRPC]
// void AddChatMessage_RPC(string m){ //
// while(chatMessages.Count >= maxChatMessages){ // chatMessages.RemoveAt(0); // } // chatMessages.Add(m); // } [PunRPC] private void RPC_LoadGameOthers() { PhotonNetwork.LoadLevel("GameMobile"); }
[PunRPC]
private void RPC_LoadedGameScene(PhotonPlayer photonPlayer)
{
//PlayerManagement.Instance.AddPlayerStats(photonPlayer);
Debug.Log("playername"+photonPlayer);
//OnJoinedInstantiate.inst.AddPlayerStats(photonPlayer);
PlayersInGame++;
if (PlayersInGame == PhotonNetwork.playerList.Length)
{
Debug.Log (" playernamepass"+PhotonNetwork.playerList.Length);
PhotonView.RPC("RPC_CreatePlayer", PhotonTargets.All);
}
}
[PunRPC]
private void RPC_CreatePlayer( )
{
//Vector3 vect=new Vector3(OnJoinedInstantiate.inst.SpawnSpot.transform.position.x,OnJoinedInstantiate.inst.SpawnSpot.transform.position.y,OnJoinedInstantiate.inst.SpawnSpot.transform.position.z);
//float randomValue = Random.Range(0f, 5f);
//Transform startPos = GameManager.GetInstance().teams[PhotonNetwork.player.GetTeam()].spawn;
Vector3 vect=new Vector3(-2.51f,-0.07f,-3.91f);
//for(int i=0;i<PhotonNetwork.playerList.Length;i++){
//if(PlayersInGame==PhotonNetwork.playerList.Length)
// {
GameObject obj = PhotonNetwork.Instantiate(Path.Combine("Prefabs", "MYPREFAB"),vect, Quaternion.identity, 0);
//obj.name = PlayerName;
// }
//}
}
void Connect(){
if(!PhotonNetwork.connected)
PhotonNetwork.ConnectUsingSettings(Version);
}
void OnGUI(){
GUI.color = Color.grey;
if(PhotonNetwork.connected == false && connecting == false ) {
GUILayout.BeginArea( new Rect(0, 0, Screen.width, Screen.height) );
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.BeginVertical();
GUILayout.FlexibleSpace();
GUILayout.BeginHorizontal();
GUILayout.Label("Username:");
PhotonNetwork.player.name = GUILayout.TextField(PhotonNetwork.player.name);
GUILayout.EndHorizontal();
if( GUILayout.Button("Multi Player") ){
connecting = true;
Connect();
}
GUILayout.FlexibleSpace();
GUILayout.EndVertical();
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.EndArea();
}
if(PhotonNetwork.connected == true && connecting == false) {
GUILayout.BeginArea( new Rect(0, 0, Screen.width, Screen.height) );
GUILayout.BeginVertical();
GUILayout.FlexibleSpace();
foreach(string msg in chatMessages) {
GUILayout.Label(msg);
}
GUILayout.EndVertical();
GUILayout.EndArea();
}
if (PhotonNetwork.insideLobby == true) {
GUI.Box(new Rect(Screen.width/2.5f , Screen.height /3f , 400, 550),"");
GUI.color = Color.white;
GUILayout.BeginArea (new Rect(Screen.width/2.5f , Screen.height /3 , 400, 500));
GUI.color = Color.cyan;
GUILayout.Box ("Lobby");
GUI.color = Color.white;
GUILayout.Label("Session Name:");
roomName = GUILayout.TextField(roomName);
GUILayout.Label ("Max amount of players 1 - 4:");
//maxPlayerString = GUILayout.TextField (maxPlayerString,4);
maxPlayerString=4.ToString();
if (maxPlayerString != "") {
maxPlayer = int.Parse(maxPlayerString);
if (maxPlayer > 20) maxPlayer = 20;
if (maxPlayer ==0) maxPlayer = 1;
}
else
{
maxPlayer = 1;
}
if ( GUILayout.Button ("Create Room ") ) {
if (roomName != "" && maxPlayer > 0) {
PhotonNetwork.CreateRoom(null, new RoomOptions() { MaxPlayers = 2}, null);
}
}
GUILayout.Space (20);
GUI.color = Color.yellow;
GUILayout.Box("Sessions Open");
GUI.color = Color.red;
GUILayout.Space(20);
scrollPosition = GUILayout.BeginScrollView(scrollPosition, false,true,GUILayout.Width(400), GUILayout.Height(300));
foreach (RoomInfo game in PhotonNetwork.GetRoomList ())
{
GUI.color = Color.green;
GUILayout.Box (game.name + " " + game.playerCount + "/" + game.maxPlayers + " " + game.visible);
if ( GUILayout.Button ("Join Session") ) {
//PhotonNetwork.automaticallySyncScene = false;
if(!PhotonNetwork.inRoom)
PhotonNetwork.JoinRoom(game.name);
}
}
GUILayout.EndScrollView();
GUILayout.EndArea();
}
}
void OnJoinedLobby(){
Debug.Log("OnJoinedLobby");
}
void OnPhotonRandomJoinFailed(){
Debug.Log("OnPhotonRandomJoinFailed");
PhotonNetwork.CreateRoom(null, new RoomOptions() { MaxPlayers = 2}, null);
}
void OnJoinedRoom(){
Debug.Log("OnJoinedRoom");
connecting = false;
PhotonNetwork.LoadLevel("GameMobile");
spawn = true;
}
void Update(){
if(spawn == true){
spawn = false;
//PhotonNetwork.LoadLevel("GameMobile");
//GameObject MyCharacter = (GameObject)PhotonNetwork.Instantiate("MYPREFAB", SpawnSpot.transform.position, Quaternion.identity, 0);
}
}
}
Answer by ChristianSimon · Oct 17, 2017 at 08:47 AM
Hi,
if I'm not mistaken, the RPC to create the player is called twice on the MasterClient and once on the remote client, which is caused by multiple unwanted RPC calls from OnSceneFinishedLoading callback. Please try another option for synchronizing the current scene instead of sending RPCs. Therefore you can set PhotonNetwork.automaticallySyncScene = true; which automatically synchronizes the active scene whenever the MasterClient uses PhotonNetwork.LoadLevel(...);. To instantiate objects, you can for example use the OnJoinedRoom() callback. If this doesn't work because you are loading another scene after the client has joined the room, you can also use MasterClient to send a RPC or raise an event to notify all clients, to instantiate their objects.
How can I get rid of that multiple spawning by a client when he leaves and rejoins the room.
You can for example create a boolean which is set to true, if the client has created his player object. When you later rejoin the game, you can check that value and continue related to whatever the value describes.
Your answer
Follow this Question
Related Questions
NullReferenceException 0 Answers
Unity Audio Networking Stops Playing after 10s 0 Answers
Both players reach same time how to get result draw in photon unity 1 Answer
Photon Weapon View 1 Answer