title: DontDestroyOnLoad() in Unity and Referencing In Later Scenes (Using C#)
body: <p>I am building a clone of Doodle Jump in Unity to teach myself the basics and have come across a problem. The flow of this game goes:</p>
  
  <p><strong>Main menu</strong> ---(<em>click start</em>)--> <strong>Level select</strong> ---(<em>click level</em>)--> <strong>Selected level</strong></p>
  
  <p>The player controlled object is actually created in the main menu screen. It is controllable right from the very beginning with GameObject.DontDestroyOnLoad() stopping it from being destroyed throughout each scene transition. Once you get into your selected level, there is a script attached to the camera to get it to move with your character.</p>
  
  <p>I have some code in the LateUpdate method which handles the camera movement:</p>
  
  <pre><code>void LateUpdate () {
  
      if (gameObject.transform.position.y &gt; transform.position.y) {
  
          Vector3 newPosition = new Vector3(transform.position.x, gameObject.transform.position.y, transform.position.z);
          transform.position = Vector3.SmoothDamp(transform.position, newPosition, ref currentVelocity, smoothSpeed * Time.deltaTime);
  
      }
  
  }
  </code></pre>
  
  <p>but for this to work correctly, I need to be able to reference the the player (gameObject in the code above). I was originally doing this by using</p>
  
  <pre><code>GameObject gameObject = GameObject.Find("Doodler");
  </code></pre>
  
  <p>in the same LateUpdate method, but there is no reason for me to find the Doodler every frame as it should not be replaced until you hit game over. For this reason, I moved the GameObject.Find line into the Start method, but it doesn't seem to be finding the Doodler and as a result, the camera doesn't move. Can anybody help with this?</p>
  
  <p>EDIT:</p>
  
  <p>I've now changed my Start method to be like this:</p>
  
  <pre><code>private GameObject gameObject;
  
  void Start() {
      gameObject = GameObject.Find("Doodler");
      Debug.Log("START Found the Doodler: " + gameObject.GetInstanceID());
  }
  </code></pre>
  
  <p>rather than this:</p>
  
  <pre><code>void Start() {
      GameObject gameObject = GameObject.Find("Doodler");
      Debug.Log("START Found the Doodler: " + gameObject.GetInstanceID());
  }
  </code></pre>
  
  <p>and this seems to be working. I'm guessing the second method means gameObject is not accessible to LateUpdate?</p>
  
  <p><strong>Final Solution:</strong></p>
  
  <p>Whilst the code in the edit does work, it gives a warning because I called my GameObject gameObject and this is a predefined object referring to the object the script is attached to. The final code should look like this:</p>
  
  <pre><code>private GameObject doodler;
  
  void Start() {
      doodler = GameObject.Find("Doodler");
      Debug.Log("START Found the Doodler: " + doodler.GetInstanceID());
  }
  </code></pre>