Search Unity

Creating a new GameObject by code without an inspector prefab

Discussion in 'Scripting' started by CultHero77, Jul 9, 2020.

  1. CultHero77

    CultHero77

    Joined:
    Oct 22, 2019
    Posts:
    7
    So In this game the player can find chests, these chests can have, at ramdom, one of ten different items.

    So when the player opens a chest this happens:

    Code (CSharp):
    1.  
    2. // Mockup code
    3. [SerializeField] GameObject[] items;
    4.  
    5. void OpenChest()
    6. {
    7.   int index = Random.Range(0, items.Lenght);
    8.  
    9.   Instantiate(items[index]);
    10. }
    11.  
    The problem with this solution is that I need to drag the 10 items (gameobjects) to the chest's script, and that's for every chest in the game. It seems like a waste of resources. Is there a way to Instantiate or create an gameobject on the fly, without having an instance in the inspector. For example:

    Code (CSharp):
    1.  
    2. int index = Random.Range(0, items.Lenght);
    3.  
    4. switch(index)
    5. {
    6.  case 0: Create(BlueCoin); break;
    7.  case 1: Create(Sword); break;
    8. ...
    9. }
    10.  
     
  2. MatrixQ

    MatrixQ

    Joined:
    May 16, 2020
    Posts:
    87
    You can use Resource.Load() to get a prefab by name. You could also use something like a scriptable object that holds all the prefabs and links them to, for example, an index.
     
  3. CultHero77

    CultHero77

    Joined:
    Oct 22, 2019
    Posts:
    7
    Thanks a lot, that was very useful.