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. Dismiss Notice

Instantiating unknown (at compile time) prefabs at runtime

Discussion in 'Scripting' started by fstim82, Nov 14, 2011.

  1. fstim82

    fstim82

    Joined:
    May 4, 2010
    Posts:
    28
    Instantiate() seems to work great if you want to clone an object at runtime, assuming you know WHAT you're cloning. I have a situation where I have a bunch of prefabs and will determine which set of them to use at run time for a match 3 game. Then I need to dynamically generate a bunch of them. Is my only option to do a bunch of if/switch checks to get the correct prefab, or can I use a prefab name/ID to actually Instantiate somehow? I need to make this data driven, not hardcoded...
     
  2. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Assuming the prefabs all have unique names a Dictionary should work well for this.
     
  3. fstim82

    fstim82

    Joined:
    May 4, 2010
    Posts:
    28
    While that does help, I have to know all of the potential prefabs ahead of time. If my game introduces a new prefab, I have to change/add code.

    Maybe I'm going about this the wrong way. The only thing that really changes is the art assets, so perhaps I need a way to dynamically load and set that instead of prefabs themselves...
     
    Last edited: Nov 14, 2011
  4. Diviner

    Diviner

    Joined:
    May 8, 2010
    Posts:
    677
    You can put your assets on the Resources folder and load them with Resources.Load().

    Load ( )'s first argument is the file name you want to load of type String.

    If your dynamically generated prefabs return their name, you can use that string to load the correct prefab without having to know before hand which one it is.

    Example:

    Code (csharp):
    1.  
    2.  
    3. var myPrefab : Transform;
    4. var fileName : String;
    5.  
    6. myPrefab = Resources.Load(fileName, Transform);
    7.  
    8. Instantiate(myPrefab, transform.position, Quaternion.identity);
    9.  
    Every prefab that gets dynamically created can return its name to the fileName, which can either be a String as mentioned above, or an array of Strings (in case you want to instantiate more than one).