Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Multiplayer Cameras

Discussion in 'Multiplayer' started by Speed2411, Feb 11, 2015.

  1. Speed2411

    Speed2411

    Joined:
    Jan 20, 2015
    Posts:
    4
    Hi! I'm kinda of new to unity and c# all together, so please forgive my lack of understanding about codes. Anyway, I'm trying to create a network option in my game. When a player joins, I use a prefab to make him join. The prefab that spawns "Player(clone)" into unity. However, I can not get the main camera to follow the new player prefab that spawns. I've tried everything, but the Main Camera won't pick up "Player(Clone)." I have NO idea what I'm doing here, and I really need some help. I'm using three scripts. My Player control script, my network manager (to spawn the player) and my net cam control script. I've tried just about everything I could imagine. Should I spawn new cameras with the player, or should I have just one camera in the scene. Bottom line, I need help. Can someone here please help me?

    Player Control Script
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class NetworkPlayer : MonoBehaviour
    5. {
    6.     public float speed;
    7.     public GUIText countText;
    8.     public GUIText winText;
    9.     private int count;
    10.  
    11.  
    12.     void Start ()
    13.     {
    14.         count = 0;
    15.         setCountText ();
    16.         winText.text = "";
    17.     }
    18.  
    19.  
    20.  
    21.        
    22.         void Update()
    23.     {
    24.     if (networkView.isMine)
    25.         {
    26.                     InputMovement ();
    27.  
    28.  
    29.         }
    30.  
    31.         }      
    32.  
    33.         void InputMovement()
    34.         {
    35.         float moveHorizontal = Input.GetAxis("Horizontal");
    36.         float moveVertical = Input.GetAxis("Vertical");
    37.        
    38.         Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
    39.        
    40.         rigidbody.AddForce(movement * speed * Time.deltaTime);
    41.         }
    42.  
    43.  
    44.  
    45.     void OnTriggerEnter(Collider other)
    46.     {
    47.                 if (other.gameObject.tag == "PickUp") {
    48.                         other.gameObject.SetActive (false);
    49.                         count = count + 1;
    50.                         setCountText ();
    51.  
    52.                 }
    53.  
    54.                 if (other.gameObject.tag == "ND") {
    55.                         transform.position = new Vector3 (0, 0, 0);
    56.                         Vector3 p = transform.position;
    57.            
    58.                 }
    59.         }
    60.  
    61.  
    62.  
    63.        
    64.  
    65.  
    66.    
    67.     void setCountText()
    68.            
    69.     {
    70.         countText.text = "Cube's Collected: " + count.ToString ();
    71.         if(count >= 12)
    72.         {
    73.             winText.text = "You Win!";
    74.         }
    75.     }
    76.  
    77.  
    78.  
    79.     void OnSerializeNetworkView(BitStream stream, NetworkMessageInfo info)
    80.     {
    81.         Vector3 syncPosition = Vector3.zero;
    82.         if (stream.isWriting)
    83.         {
    84.             syncPosition = rigidbody.position;
    85.             stream.Serialize(ref syncPosition);
    86.         }
    87.         else
    88.         {
    89.             stream.Serialize(ref syncPosition);
    90.             rigidbody.position = syncPosition;
    91.         }
    92.     }
    93.  
    94.  
    95.  
    96.  
    97. }
    98.  


    Network Manager Script
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class NetworkManager : MonoBehaviour
    5. {
    6.     private const string typeName = "BallHub";
    7.     private const string gameName = "Join Server";
    8.    
    9.     private void StartServer()
    10.     {
    11.         Network.InitializeServer(4, 25000, !Network.HavePublicAddress());
    12.         MasterServer.RegisterHost(typeName, gameName);
    13.     }
    14.  
    15.     void OnServerInitialized()
    16.     {
    17.         Debug.Log("Server Initializied");
    18.         SpawnPlayer ();
    19.  
    20.  
    21.     }
    22.  
    23.     void OnGUI()
    24.     {
    25.         if (!Network.isClient && !Network.isServer)
    26.         {
    27.             if (GUI.Button(new Rect(100, 100, 250, 100), "Start Server"))
    28.                 StartServer();
    29.         }
    30.         {
    31.             if (!Network.isClient && !Network.isServer)
    32.             {
    33.                 if (GUI.Button(new Rect(100, 100, 250, 100), "Start Server"))
    34.                     StartServer();
    35.                
    36.                 if (GUI.Button(new Rect(100, 250, 250, 100), "Refresh Hosts"))
    37.                     RefreshHostList();
    38.                
    39.                 if (hostList != null)
    40.                 {
    41.                     for (int i = 0; i < hostList.Length; i++)
    42.                     {
    43.                         if (GUI.Button(new Rect(400, 100 + (110 * i), 300, 100), hostList[i].gameName))
    44.                             JoinServer(hostList[i]);
    45.                     }
    46.                 }
    47.             }
    48.         }
    49.     }
    50.  
    51.  
    52.     private HostData[] hostList;
    53.    
    54.     private void RefreshHostList()
    55.     {
    56.         MasterServer.RequestHostList(typeName);
    57.     }
    58.    
    59.     void OnMasterServerEvent(MasterServerEvent msEvent)
    60.     {
    61.         if (msEvent == MasterServerEvent.HostListReceived)
    62.             hostList = MasterServer.PollHostList();
    63.     }
    64.  
    65.  
    66.  
    67.  
    68.     private void JoinServer(HostData hostData)
    69.     {
    70.         Network.Connect(hostData);
    71.     }
    72.    
    73.     void OnConnectedToServer()
    74.     {
    75.         Debug.Log("Server Joined");
    76.         SpawnPlayer();
    77.  
    78.  
    79.  
    80.     }
    81.    
    82.  
    83.  
    84.     public GameObject playerPrefab;
    85.  
    86.  
    87.  
    88.     private void SpawnPlayer()
    89.     {
    90.                 Network.Instantiate (playerPrefab, new Vector3 (0f, 5f, 0f), Quaternion.identity, 0);
    91.  
    92.  
    93.         }
    94.  
    95.  
    96.  
    97.    
    98.  
    99.  
    100. }

    Camera Follow Script
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class NetCam : MonoBehaviour
    5. {
    6.     public GameObject target;
    7.     public Vector3 offset;
    8.     public GameObject enabled;
    9.  
    10.  
    11.  
    12.  
    13.  
    14.  
    15.  
    16.  
    17.     void Start ()
    18.     {
    19.         offset = transform.position;
    20.  
    21.     }
    22.    
    23.  
    24.     void LateUpdate ()
    25.     {
    26.         transform.position = target.transform.position + offset;
    27.         }
    28.  
    29.        
    30.  
    31.    
    32.  
    33.  
    34. }
     
  2. Brent_Farris

    Brent_Farris

    Joined:
    Jul 13, 2012
    Posts:
    881
    Does your camera spawn with the player? If the camera is already in the scene how do you assign the player as the target once it spawns? You may want to do some extra logic when the player connects to make the camera find the player that it needs to assign as its target. It could be possible for you to make it so that inside of the players start it will look for the main camera (assuming that this is the main camera) Camera.main then use the GetComponent<NetCam>().MyInitializeMethod(this);

    That is one of many solutions :)

    I didn't double check this, but something along these lines:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. public class NetCam : MonoBehaviour
    4. {
    5.     using UnityEngine;
    6.     using System.Collections;
    7.  
    8.     public class NetCam : MonoBehaviour
    9.     {
    10.         public GameObject target;
    11.         public Vector3 offset;
    12.         public GameObject enabled;
    13.     }
    14.  
    15.     public void MyInitializeMethod(NetworkPlayer player)
    16.     {
    17.         target = player.gameObject;
    18.     }
    19.  
    20.     void Start ()
    21.     {
    22.         offset = transform.position;
    23.     }
    24.  
    25.  
    26.     void LateUpdate ()
    27.     {
    28.         transform.position = target.transform.position + offset;
    29.     }
    30. }
     
    Last edited: Feb 11, 2015
    jshuntley likes this.
  3. Speed2411

    Speed2411

    Joined:
    Jan 20, 2015
    Posts:
    4
    Oh my gosh, thanks man. You have NO idea how many topics I went through to fix this problem. I shall remember your name forever firasit. Seriously though, many thanks to you.
     
    Brent_Farris likes this.
  4. Brent_Farris

    Brent_Farris

    Joined:
    Jul 13, 2012
    Posts:
    881
    :D No problem, glad it worked out!

    XD

    No problem, if you have any other networking questions feel free to ask! Chances are I have ran into the problem and found a solution already since I am developing my own system as well :).
     
  5. Speed2411

    Speed2411

    Joined:
    Jan 20, 2015
    Posts:
    4
    I might have ONE more question lol...

    I'm making a chat window using another code that was posted on a topic similar to this one. I have my code but I keep getting four errors.

    Assets/ChatMaster.cs(69,65): error CS1525: Unexpected symbol `Event'

    Assets/ChatMaster.cs(77,65): error CS1525: Unexpected symbol `Event'

    Assets/ChatMaster.cs(76,14): error CS0116: A namespace can only contain types and namespace declarations

    Assets/ChatMaster.cs(86,41): error CS8025: Parsing error

    As you can see, I'm EXTREMELY knew to unity and I should not be doing something as complicated as networking. Buuuuuut, I'm doing it anyway. =P.

    I'm trying to figure out how to fix these errors considering the code looks pretty okay to me.


    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4.  
    5. public class ChatMaster : MonoBehaviour {
    6.    
    7.     class ChatEntry{
    8.         public string name = "";
    9.         public string message = "";
    10.         public string timeTag = "";
    11.     }
    12.    
    13.     ArrayList entries;
    14.     Vector2 currentScrollPos = new Vector2();
    15.     string inputField = "";
    16.     bool chatInFocus = false;
    17.     string inputFieldFocus = "CIFT";
    18.     bool absPos = false;
    19.    
    20.     void Awake () {
    21.         InitializeChat();
    22.     }
    23.    
    24.     void InitializeChat(){
    25.         entries = new ArrayList();
    26.         unfocusChat();
    27.     }
    28.    
    29.     //draw the chat box in size relative to your GUIlayout
    30.     public void Draw(){
    31.         ChatWindow();
    32.     }
    33.    
    34.     void ChatWindow(){
    35.         GUILayout.BeginVertical();
    36.         currentScrollPos = GUILayout.BeginScrollView(currentScrollPos, GUILayout.MaxWidth(1000), GUILayout.MinWidth(1000)); //limits the chat window size to max 1000x1000, remove the restraints if you want
    37.        
    38.         foreach(ChatEntry ent in entries){
    39.             GUILayout.BeginHorizontal();
    40.             GUI.skin.label.wordWrap = true;
    41.             GUILayout.Label(ent.timeTag + " "+ ent.name + ": "+ent.message);
    42.             GUILayout.EndHorizontal();
    43.             GUILayout.Space(3);
    44.         }
    45.        
    46.         GUILayout.EndScrollView();
    47.         if(chatInFocus){
    48.             GUI.SetNextControlName(inputFieldFocus);
    49.             inputField = GUILayout.TextField(inputField, GUILayout.MaxWidth(1000), GUILayout.MinWidth(1000));
    50.             GUI.FocusControl(inputFieldFocus);
    51.         }
    52.         GUILayout.EndVertical();
    53.        
    54.         if(chatInFocus){
    55.             HandleNewEntries();
    56.         } else {
    57.             checkForInput();
    58.         }
    59.        
    60.     }
    61.    
    62.     void unfocusChat(){
    63.         //Debug.Log("unfocusing chat");
    64.         inputField = "";
    65.         chatInFocus = false;
    66.     }
    67.    
    68.     void checkForInput(){
    69.         if(Event.current.type == EventType.KeyDown  Event.current.character == '\n'  !chatInFocus){
    70.             GUI.FocusControl(inputFieldFocus);
    71.             chatInFocus = true;
    72.             currentScrollPos.y = float.PositiveInfinity;
    73.         }
    74.     }
    75.    
    76.     void HandleNewEntries(){
    77.         if(Event.current.type == EventType.KeyDown  Event.current.character == '\n')
    78.         {
    79.             if(inputField.Length <= 0)
    80.             {
    81.                 unfocusChat();
    82.                 Debug.Log("unfocusing chat (empty entry)");
    83.                 return;
    84.             }
    85.  
    86.             networkView.RPC ("AddChatEntry", RPCMode.All, "Cookie monster", inputField);
    87.             //AddChatEntry("Cookie monster", inputField); //for offline testing
    88.             unfocusChat();
    89.             //Debug.Log("unfocusing chat and entry sent");
    90.         }
    91.     }
    92.    
    93.     [RPC]
    94.     void AddChatEntry(string name, string msg){
    95.         ChatEntry newEntry = new ChatEntry();
    96.         newEntry.name = name;
    97.         newEntry.message = msg;
    98.         newEntry.timeTag = "["+System.DateTime.Now.Hour.ToString()+":"+System.DateTime.Now.Minute.ToString()+"]";
    99.         entries.Add(newEntry);
    100.         currentScrollPos.y = float.PositiveInfinity;
    101.     }
    102. }
    103.  
     
  6. Brent_Farris

    Brent_Farris

    Joined:
    Jul 13, 2012
    Posts:
    881
    XD Good stuff!

    Looks like on line 69 you are missing your and/or (&&/||) operators from the statement (same on line 77)

    I'm guessing that the one on line 69 is suppose to be:

    Code (CSharp):
    1. Event.current.type == EventType.KeyDown && Event.current.character == '\n' && !chatInFocus

    I created a networking tutorial series a while back, here is the video that is particular to chat, just in case:

     
  7. Speed2411

    Speed2411

    Joined:
    Jan 20, 2015
    Posts:
    4
    I started from scratch using your tutorial lol. I still have more questions though. Is there like a PM thing in the forums, or a skype maybe? You seem to know a LOT about this stuff.
     
  8. Brent_Farris

    Brent_Farris

    Joined:
    Jul 13, 2012
    Posts:
    881
    Awesome! Thanks for the complement, I really enjoy the field of networking. As for PM, yeup :) just click this link: Start a Conversation
     
  9. jshuntley

    jshuntley

    Joined:
    May 5, 2016
    Posts:
    1

    I've been searching for hours for a solution and this finally solved it. Thank you!
     
    Brent_Farris likes this.