Search Unity

how to instantiate a certain gameobject from an array

Discussion in 'Scripting' started by Mansmart10, Oct 12, 2017.

  1. Mansmart10

    Mansmart10

    Joined:
    Dec 24, 2015
    Posts:
    43
    I want to instantiate a certain gameobject from an array. For example if I have a dog round I don't want zombies to spawn on the round/wave.
     
  2. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,521
    So have two different arrays. One with dogs, one with zombies. During dog round, spawn from DogList, etc.
     
  3. Mansmart10

    Mansmart10

    Joined:
    Dec 24, 2015
    Posts:
    43
    No they are in the same array.
     
  4. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,521
    So how do you intend to identify which index is what you want?
     
  5. Mansmart10

    Mansmart10

    Joined:
    Dec 24, 2015
    Posts:
    43
    That's what i'm trying to figure out if there is way to do that.
     
  6. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,521
    Use different arrays.
     
  7. Mansmart10

    Mansmart10

    Joined:
    Dec 24, 2015
    Posts:
    43
    Im trying to do it with one array.
     
  8. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,521
    Then you have to loop over the array and check each item for some sort of identifier that says whether it is a Dog or Zombie.

    This is a bad way to do it, considering the alternatives.
     
  9. BlackPete

    BlackPete

    Joined:
    Nov 16, 2016
    Posts:
    970
    I'm guessing you have an array of prefabs?

    You could try having it both ways by having an array of prefabs, then on startup, walk through the list of prefabs and build a Dictionary<Type, List<GameObject>> based on what you're looking for, to better organize the prefabs.

    Of course, this is assuming you have a Dog component that you can use GetComponent<Dog> with.

    It doesn't even need to be a Dog component, it could be some Entity component with an enum value to identify it as Dog.

    I personally prefer this over using tags.
     
  10. Mansmart10

    Mansmart10

    Joined:
    Dec 24, 2015
    Posts:
    43
    oh ok
     
  11. Mansmart10

    Mansmart10

    Joined:
    Dec 24, 2015
    Posts:
    43
    ok