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

Question GameObject.Find(string) doesn't work the first time, but then works fine on each test afterward.

Discussion in 'Editor & General Support' started by orionk1, Jun 12, 2020.

  1. orionk1

    orionk1

    Joined:
    Dec 19, 2019
    Posts:
    4
    I have some code which tries to assign a GameObject:

    example1.GetComponent<Foo>().bar = GameObject.Find(barStr1);

    When I load up the editor and hit the Play button, the first time this line of code is executed it fails to assign the GameObject to <Foo>().bar. However, once I stop the game, then eventually press Play again, the game is restarted but the script runs perfectly and is able to assign the GameObject properly every time for the rest of my session. Until I quit out of the editor.
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    Is the object you're finding in the scene at edit time, or does it get generated by some script, maybe in a Start() or Awake() method?
     
  3. adrolter

    adrolter

    Joined:
    Jan 10, 2019
    Posts:
    5
    This sounds like a race condition, as alluded to by PraetorBlue. Can you provide at least the general structure of the code including the (presumably) scripted instantiation of the object named barStr1 and where you're calling GameObject.Find on it?