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
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Best practice.

Discussion in 'General Discussion' started by TheCodez, May 25, 2015.

  1. TheCodez

    TheCodez

    Joined:
    Sep 19, 2014
    Posts:
    14
    So I have a game object that generates a a game board (the level) and one of the things it creates is a player object from a player prefab. I also have a camera that will target the player. I can't set the camera to target the prefab but I can set it to target the player. The problem with this is that the player object does not exist until the generator has created it. The easiest solution is to have the camera GameObject.Find the player but I heard that this is a bad practice. How do most people handle problems like this?

    Thanks,
    Philip
     
  2. ShilohGames

    ShilohGames

    Joined:
    Mar 24, 2014
    Posts:
    2,985
    There is nothing wrong with using GameObject.Find in the Startup or Awake functions, since that would cause a brief performance hit when the game first loads. Just don't use GameObject.Find in the Update or FixedUpdate functions, because that will reduce the performance of your game.
     
  3. Nicrom

    Nicrom

    Joined:
    Nov 17, 2013
    Posts:
    419
    Another way you could do this is to place the code that sets the camera target in a separate method in the script that is attached to the camera and call this method from the Start method of a script attached to the player. This way the camera target will be set only after the player is instantiated.
     
  4. TheCodez

    TheCodez

    Joined:
    Sep 19, 2014
    Posts:
    14
    I think I like this way best since it will still work even if the names of the objects are changed (the reason I did not like GameObject.Find). Thanks!
     
    Nicrom likes this.