Search Unity

Help with Instantiating a Loaded Resource

Discussion in 'Scripting' started by ArrogantPride, Feb 11, 2016.

  1. ArrogantPride

    ArrogantPride

    Joined:
    Feb 11, 2016
    Posts:
    6
    So in my current game, I have to instantiate the player's character model from a prefab that is kept in the "Resources" folder. Here is the current portion of my script:

    Code (CSharp):
    1. void SelectedCharacter2 ()
    2.     {
    3.         Application.LoadLevel("Battlefield");
    4.         Debug.Log ("Onion Selected");
    5.         SelectedCharacter = 2;
    6.         Instantiate (Resources.Load ("Onion") as GameObject);
    The "Battlefield" scene is supposed to load in and immediately the code is supposed to instantiate and load in the "Onion" object from its folder (This happens after the player clicks a certain object, but I don't believe that is important). Unity currently loads in the scene correctly, but the object will not instantiate into the scene. I have double checked and the prefab is both named "Onion" and is contained in the folder "Resources" which is contained in the Assets folder. Any idea what I might be doing wrong?
     
  2. ArrogantPride

    ArrogantPride

    Joined:
    Feb 11, 2016
    Posts:
    6
    I should add that I never get any error in my code when this happens, it simply seems to just not instantiate.
     
  3. pixpusher2

    pixpusher2

    Joined:
    Oct 30, 2013
    Posts:
    121
    My guess would be that the Onion object was destroyed along with your current level before the new Battlefield level was loaded in. Try moving the object instantiation to a script that's called at the start of Battlefield level instead.
     
    ArrogantPride likes this.
  4. ArrogantPride

    ArrogantPride

    Joined:
    Feb 11, 2016
    Posts:
    6
    Thank you, it seems you were correct in that it was instantiating the object before the scene loaded. I made it load in a separate script and it did the job.
     
  5. iPLEOMAX

    iPLEOMAX

    Joined:
    Feb 16, 2014
    Posts:
    17