Search Unity

Ignore line of code if gameobject is not found

Discussion in 'Scripting' started by ChuckieGreen, Feb 14, 2018.

  1. ChuckieGreen

    ChuckieGreen

    Joined:
    Sep 18, 2017
    Posts:
    358
    I have my code working fine for one level, but i wanted just to reuse it for the next, working with limited time. So now there is a few lines of code that are not needed by level 2, is there some way i can tell the code to basically ignore the instantiate line if the gameobject is not found

    Code (CSharp):
    1. void SpawnDoor2()
    2.     {
    3.         if (!DoorIsCreated2)
    4.         {
    5.             var Rm_2_door1Spawn = GameObject.Find("Rm_2_B_Door").transform;
    6.             Rm2_door1 = Instantiate(Door, Rm_2_door1Spawn.position, Rm_2_door1Spawn.rotation) as GameObject;
    7.  
    8.             var Rm_2_door2Spawn = GameObject.Find("Rm_2_T_Door").transform;
    9.             Rm2_door2 = Instantiate(Door, Rm_2_door2Spawn.position, Rm_2_door2Spawn.rotation) as GameObject;
    10.  
    11.             //var Rm_2_door3Spawn = GameObject.Find("Rm_2_R_Door").transform;
    12.            // Rm2_door3 = Instantiate(Door, Rm_2_door3Spawn.position, Rm_2_door3Spawn.rotation) as GameObject;
    13.  
    14.  
    15.             audioSource.PlayOneShot(DoorSpawnAudio, 1f);
    16.  
    17.             DoorIsCreated2 = true;
    18.         }
    19.     }
    This is the code, I need all that for room 1, but i dont need the commented out part for room 2. Please if someone can help with this I would really appreciate it.
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Well, it returns a game object. So, if the variable is null, it wasn't found.

    You should try to avoid Game Object 'Find' whenever possible, btw. I won't get into it in detail here, but there are many posts about it. I just mention it in case you weren't aware.
     
  3. ChuckieGreen

    ChuckieGreen

    Joined:
    Sep 18, 2017
    Posts:
    358
    Ok i set it to if it doesn't return null then to spawn. And its working :) . Was very much panicking there. And, I know I should use find object, think it is because it needs to search for that object every time the function is run, correct? But for Uni, the small amount of time we get to do these projects, we basically just need to fling stuff together, which is sort of unfortunate as we are not learning how to use the engine to out full advantage.
    Thanks for the answer ;)
     
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Not entirely sure how to respond to that, but you're welcome. :) lol
     
    ChuckieGreen likes this.
  5. ChuckieGreen

    ChuckieGreen

    Joined:
    Sep 18, 2017
    Posts:
    358
    Oh, meant should not* use find object :D