Search Unity

how can i reference my camera to a clone

Discussion in 'Scripting' started by Knello, Aug 5, 2020.

  1. Knello

    Knello

    Joined:
    Jul 27, 2020
    Posts:
    50
    Hey guys I've a problem. The reference of the camera to the player gets lost when i start the game because the Player gets cloned. If you can pls help me.

    Thank you! :=)
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    Depending on the need, you either "setup" the player when you clone it and attach the camera at this point. Or you use a manager script that holds a reference to the camera and the player simply accesses the camera through that manager script instead of holding it's own reference to the camera.
     
  3. Knello

    Knello

    Joined:
    Jul 27, 2020
    Posts:
    50
    Okay thank you, but how can i do it? :)
     
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    Fast and dirty way is to tag the player "Player" and then just find the player with GameObject.FindGameObjectWithTag("Player") in your camera script in Start()
     
    Knello likes this.
  5. Knello

    Knello

    Joined:
    Jul 27, 2020
    Posts:
    50
    Hey guys, now here is the code which i use. I still got the same problem the camera is not attached to the player.
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using System.Security.Cryptography;
    4. using UnityEngine;
    5.  
    6. public class followplayer : MonoBehaviour
    7. {
    8.     public Transform player;
    9.     public Vector3 offset;
    10.  
    11.     // Update is called once per frame
    12.     void Start()
    13.     {
    14.         GameObject.FindGameObjectWithTag("Player");
    15.     }
    16.  
    17.     void Update()
    18.     {
    19.         transform.position = player.position + offset;
    20.  
    21.     }
    22. }
    23.  
     
  6. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    You need to actually assign your player variable:
    Code (CSharp):
    1.     void Start()
    2.     {
    3.          player = GameObject.FindGameObjectWithTag("Player").transform;
    4.     }