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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

How do I make this move camera script work with prefabs even if the previous prefab was destroyed?

Discussion in 'Scripting' started by switchluts, May 17, 2020.

  1. switchluts

    switchluts

    Joined:
    Mar 18, 2019
    Posts:
    45
    I was wondering how I would make this script work with my prefabs. Does anyone know?
    Code (CSharp):
    1. private Transform playerTransform;
    2.     // Start is called before the first frame update
    3.     void Start()
    4.     {
    5.         playerTransform = GameObject.FindGameObjectWithTag("Player").transform;
    6.     }
    7.  
    8.     // Update is called once per frame
    9.     void LateUpdate()
    10.     {
    11.         Vector3 temp = transform.position;
    12.  
    13.         temp.x = playerTransform.position.x;
    14.  
    15.         transform.position = temp;
    16.     }
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    I'm confused what this has to do with prefabs exactly? When you Instantiate a prefab, the instance is no longer a prefab. It's just a regular GameObject, and it's independent of any other instances you may have created or the prefab itself at that point.

    Are you running into a specific error? Can you describe it? Exact error messages would be helpful.
     
    Last edited: May 17, 2020
  3. switchluts

    switchluts

    Joined:
    Mar 18, 2019
    Posts:
    45
    MissingReferenceException: The object of type 'Transform' has been destroyed but you are still trying to access it.
    Your script should either check if it is null or you should not destroy the object.