Search Unity

what the best way to define object created in additive scene ?

Discussion in 'Scripting' started by MrSretthaNayak, Oct 18, 2019.

  1. MrSretthaNayak

    MrSretthaNayak

    Joined:
    Oct 15, 2019
    Posts:
    9
    Now I make public GameObject = number of type of object I need to define to create and pass variables to check the indexnumber of object I need to create
    Ex. Script
    if (Index = 1)
    {
    create object 1;
    }
    if (index = 2)
    {
    create object 2;
    }

    if I got 150 different object I need to create it 150 times, is anyway to make this shorter than the way like I do ?
     
  2. Chris-Trueman

    Chris-Trueman

    Joined:
    Oct 10, 2014
    Posts:
    1,261
    Use an array of the objects/prefabs. Then for loop through them creating them.
     
  3. MG

    MG

    Joined:
    Nov 10, 2012
    Posts:
    190
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class CreateObjects : MonoBehaviour
    4. {
    5.     // The 150 different objects you want to create
    6.     public GameObject[] objectToBeSpawned;
    7.  
    8.     // The index that define which object you want to create
    9.     public int index;
    10.  
    11.     // The amount of how many objects you want to create
    12.     public int amount;
    13.  
    14.     // Start is called before the first frame update
    15.     void Start()
    16.     {
    17.         // Assuming you only want to create the object(s) one time
    18.  
    19.         for (int i = 0; i < amount; i++)
    20.         {
    21.             Instantiate(objectToBeSpawned[index]);
    22.         }
    23.        
    24.     }
    25.  
    26. }
    27.  
     
  4. MrSretthaNayak

    MrSretthaNayak

    Joined:
    Oct 15, 2019
    Posts:
    9

    Ok, thank you ,so the first thing I need to do is make list of type object right ?
     
  5. MG

    MG

    Joined:
    Nov 10, 2012
    Posts:
    190
    Yes, a list or an array
     
    MrSretthaNayak likes this.