Search Unity

Camera Target help

Discussion in 'Multiplayer' started by lukerussell0805, Mar 22, 2018.

  1. lukerussell0805

    lukerussell0805

    Joined:
    Mar 22, 2018
    Posts:
    1
    Hey so I have a camera follow script with a target which is my character. However in the networking when a player spawns in, they are considered a clone so I cant get the exact target. If I try to make the clone a target the clone gets deleted anyways. Is there a way so when someone spawns a camera is on them? Thanks I am new to unity so yeah.
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Put something like this in a NetworkBehaviour on your player object prefab.

    Code (csharp):
    1.  
    2. void Start()
    3. {
    4.     if (isLocalPlayer)
    5.     {
    6.         bool setCameraTarget = false;
    7.         GameObject mainCamera = GameObject.FindGameObjectWithTag("MainCamera");
    8.         if (mainCamera != null)
    9.         {
    10.             CameraControl cameraControlScript = mainCamera.GetComponent<CameraControl>();
    11.             if (cameraControlScript != null)
    12.             {
    13.                 cameraControlScript.Target = gameObject;
    14.                 setCameraTarget = true;
    15.             }
    16.         }
    17.  
    18.         if (setCameraTarget == false)
    19.         {
    20.             Debug.Log("Local player object unable to find main camera to set itself as Target");
    21.         }
    22.     }
    23. }
    24.  
    In the above, I'm assuming that your camera has been tagged with MainCamera, and has a camera control/follow script called CameraControl with a public variable named Target of type GameObject. Just change that to fit whatever script you're setting the target on.

    All the code does is when the player object is spawned, it checks if it is the local player on this client, as opposed to a player object representing another client. If it is then it finds the main camera, if successful it gets the CameraControl component (rename it to whatever your camera follow script is called), and if successful it sets itself as the Target (rename to whatever your target variable is called). If any of that fails you get a debug message.
     
    Last edited: Mar 22, 2018