Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by bhavesh_patrel · Oct 14, 2017 at 04:50 AM · photon

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);
     }

 }

}

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
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.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image avi_spc · Mar 05, 2018 at 11:41 AM 0
Share

How can I get rid of that multiple spawning by a client when he leaves and rejoins the room.

avatar image ChristianSimon avi_spc · Mar 06, 2018 at 04:38 PM 0
Share

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

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

124 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

NullReferenceException 0 Answers

A MindBreaking MonoBehaviour Issue!. (Unity3D v5.1.0f Pro: unityserializer-ng VS Photon Unity Networking) 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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges