Search Unity

Add list of gameobjects to array, assign int to each gameobject,spawn gameobject based off int?

Discussion in 'Scripting' started by Slaghton, Sep 12, 2018.

  1. Slaghton

    Slaghton

    Joined:
    Sep 9, 2013
    Posts:
    139
    Edit: Oh, I think i thought of a way. I could place a list of gameobjects into an array. Then I would spawn the gameobjects by their position in array and their position would be represented by ints recieved from outside database?


    I'm looking at putting a list of gameobjects I can instantiate into an array and then assigning them each an int.

    Say Cube / Int 1 . Sphere / Int 2 . Plane/Int 3

    I then get information back telling me which gameobjects to spawn based off ints recieved. So say if I get back a 2 and 3 I fire off some code that says to spawn a sphere and a plane.

    Wondering whats a good way to go about handling this? I first thought of using reflection and sending back a string which the string would then be converted into a variable name and instantiate objects doing that. I hear that's not a very secure way of doing it though and I can sort of see why.

    Any input on how to do this with any approach appreciated. Will continue looking around myself.
     
    Last edited: Sep 12, 2018
  2. GeorgeCH

    GeorgeCH

    Joined:
    Oct 5, 2016
    Posts:
    222
    You can indeed rely on List/Array position numbers, but it does have the disadvantage of you having to remember which position corresponds to which object. This may not be sustainable in the long run when you have more objects and is also prone to breaking whenever the sequencing of the array/list is rearranged for whatever reason.

    Instead, consider creating an enum to help categorize your object type:

    Code (CSharp):
    1. public enum ObjectType { Cube, Sphere, Plane }
    Then, as needed, create Lists/Arrays to store several instances of each object type:

    Code (CSharp):
    1. List<GameObject> cubes = new List<GameObject>();
    2. List<GameObject> spheres = new List<GameObject>();
    3. List<GameObject> planes = new List<GameObject>();
    Then, you can use switch to retrieve an object from its corresponding list:

    Code (CSharp):
    1. private GameObject GetObject(ObjectType type)
    2. {
    3.      switch (type)
    4.           case type == ObjectType.Cube: return cubes[0];
    5.           case type == ObjectType.Sphere: return spheres[0];
    6.           case type == ObjectType.Plane: return planes[0];
    7. }
     
    Slaghton likes this.