Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Camera Following Instantiated Player

Discussion in 'Scripting' started by TheLouise, Jun 29, 2019.

  1. TheLouise

    TheLouise

    Joined:
    Jun 1, 2017
    Posts:
    5
    Hello!

    I'm having trouble with my CameraFollow script. It works fine if the Player is instantiated in the first spawn point, where the camera is pointed to. But now, if I try to Instantiate the Player in another location of the map, the CameraFollow script still follow it, but keep pointing to the first spawn point.

    I'm missing a function that set the camera initial position, but Idk how to do it.

    Here are my codes:
    Code (CSharp):
    1. public class CameraFollow : MonoBehaviour
    2. {
    3.     Vector3 offset;
    4.     Transform target;
    5.     public float smoothing;
    6.  
    7.     void Start()
    8.     {
    9.         target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
    10.         offset = transform.position - target.position;
    11.  
    12.     }
    13.  
    14.     void FixedUpdate()
    15.     {      
    16.         if(target != null){
    17.             Vector3 targetCamPos = target.position + offset;
    18.             transform.position = Vector3.Lerp(transform.position, targetCamPos, smoothing * Time.deltaTime);
    19.         }
    20.     }
    21. }
    Code (CSharp):
    1. public void SpawnPlayer(){
    2.         GameObject[] spawnPoints = GameObject.FindGameObjectsWithTag("SpawnPoint");
    3.  
    4.         int index = Random.Range(0, spawnPoints.Length);
    5.  
    6.         GameObject myPlayer = PhotonNetwork.Instantiate(playerPrefab.name, spawnPoints[index].transform.position, spawnPoints[index].transform.rotation);      
    7.     }
    The first spawn point
    upload_2019-6-29_16-0-32.png

    The others
    upload_2019-6-29_16-0-49.png

    What happens:
    upload_2019-6-29_16-1-26.png

    I'm sorry for my english and thank you very much!
     
  2. alexeu

    alexeu

    Joined:
    Jan 24, 2016
    Posts:
    257
    The Vector target (Transform) will have one and only one value because its referenced in the Start() methode and never updated.
    try this : declare target as public , reference it in the inspector and remove the line in Start() methode.
     
  3. TheLouise

    TheLouise

    Joined:
    Jun 1, 2017
    Posts:
    5
    Hi alexeu, I've tried it, but then the camera don't follow the player at all.
    Thanks!
     
  4. alexeu

    alexeu

    Joined:
    Jan 24, 2016
    Posts:
    257
    Ohh sorry its a TRANSFORM ... my bad
    If by pointing you mean looking in player's direction, you could use LookAt()