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. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

[Beginner] Why can't you use Find to declare a variable in the main class?

Discussion in 'Scripting' started by Kyloman, Jul 15, 2018.

  1. Kyloman

    Kyloman

    Joined:
    Jul 15, 2018
    Posts:
    12
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class FollowPlayer : MonoBehaviour {
    6.  
    7.     GameObject plr = GameObject.Find("Player");
    8.     public Vector3 offset;
    9.  
    10.     void Update()
    11.     {
    12.         transform.position = plr.transform.position + offset;
    13.     }
    14.  
    15. }
    16.  
    17.  
    I saw that using Find in an Update is a big no no because it's slow and I don't want to make the habit, but I'm not sure how to go about creating a reference outside of the Update function without doing this.
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,140
    You should use Find in either Start or Awake if you plan to use it, but the better way is just declare a public GameObject variable and drag and drop in the inspector.
     
    Kyloman likes this.
  3. Peter77

    Peter77

    QA Jesus

    Joined:
    Jun 12, 2013
    Posts:
    6,419
    Kyloman likes this.
  4. Kyloman

    Kyloman

    Joined:
    Jul 15, 2018
    Posts:
    12
    That's the way I thought it should be too! In the tutorial I am watching, the instructor said that method of doing it is alright but if the object is removed from the scene and added back or something like that, the drag and drop references will be lost. The way he said it made me think that drag and drop references shouldn't typically be used.
     
  5. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,140
    Drag and drop is the preferred method. I don't know much about your instructor, but no matter how you set things up, if a gameobject is removed, you lose the reference anyways, so that doesn't really change how you set the initial part up.

    If you expect to remove something from the scene, you have to handle the references properly. Checking for null, changing what your variables point to, whatever is needed for your game.
     
    Kyloman likes this.