Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Only instantiate GameObjects with a certain tag from an array

Discussion in 'Scripting' started by Kinkku2, Apr 7, 2015.

  1. Kinkku2

    Kinkku2

    Joined:
    Sep 29, 2014
    Posts:
    106
    Hi. I'm trying to create a bit of code that instantiates only game objects from an array that are not already active in the game view. What I have at the moment is something that gives a tag to the spawned game object and I'm trying to exclude the ones with a Spawned tag from the random number generator's choices. Here's a some of the code:

    Code (CSharp):
    1. void SpawnPerson () {
    2.  
    3.         int randNum = RandomGen();
    4.  
    5.         Vector3 randomPosition = new Vector3
    6.             (
    7.                 Random.Range (boundary.xMin, boundary.xMax),
    8.                 Random.Range (boundary.yMin, boundary.yMax),
    9.                 -1.25f
    10.             );
    11.  
    12.         if(CubeMover.keepClosed == false)
    13.         {
    14.             GameObject person = Instantiate
    15.                 (
    16.                     personArray[randNum],
    17.                     randomPosition,
    18.                     Quaternion.identity
    19.                 )
    20.                     as GameObject;
    21.         }
    22.  
    23.         personArray[randNum].tag = "Spawned";
    24.     }
    25.  
    26.  
    27.     int RandomGen () {
    28.  
    29.         int i;
    30.  
    31.         i = Random.Range(0, personArray.Length);
    32.  
    33.         return i;
    34.  
    35.     }
    36. }
     
unityunity