- Home /
Three Spots For Three Random Objects
I've three spots in a row at the top of the screen (represented by the 'slideSpots' array.) My goal is to press play and then have three objects (astronaut, rocket, satellite) from a list (represented by the 'objects' array) instantiate in each of those three spots. So, I want an astronaut in one of the spots. I want a rocket in another one of the spots, and I want the satellite in the last available spot. What's happening currently when I press play is that three objects instantiate, but often I get repeats (two astronauts for example) and I've more than one object instantiated on one spot (overlap.)
Here's my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomItems : MonoBehaviour {
public GameObject[] slideSpots;
public GameObject[] objects;
public GameObject theSpot;
public void Start()
{
SpawnSlideSpots();
SpawnSlideSpots();
SpawnSlideSpots();
}
void SpawnSlideSpots()
{
int spawn = Random.Range(0, slideSpots.Length);
int stuff = Random.Range(0, objects.Length);
theSpot = GameObject.Instantiate(objects[stuff], slideSpots[spawn].transform.position, Quaternion.identity);
}
}
Answer by GamitusLabs · Oct 29, 2018 at 03:05 AM
The reason is that you are never verifying that you've used the randomly selected object. If you are randomly selecting one (object or spot) there's no real reason to randomize the other.
for ( i = 1 - 3) // loop through your 3 spots
{
object = random object
if ( i > 1 )
{
while(array[1] == object || array[2] == object) //if the object is already used, try another
{
object = random object
}
array[i] = object
}
else
array[1] = object
}
It should be obvious, but this is pseudo-code. And, if you decide to up your spot count, you'll have to modify the while loop. Additionally, it could be more optimized to check what's been used but this would do what you need it to.
I'm getting the same problem. @GamitusLabs Here's my current code now:
public GameObject[] slideSpots;
public GameObject[] objects;
GameObject theSpot;
GameObject obj;
int i;
public void Start()
{
SpawnSlideSpots();
SpawnSlideSpots();
SpawnSlideSpots();
}
void SpawnSlideSpots()
{
int spawn = Random.Range(0, slideSpots.Length);
int stuff = Random.Range(0, objects.Length);
theSpot = GameObject.Instantiate(objects[stuff], slideSpots[spawn].transform.position, Quaternion.identity);
for (i = 0; i >= 3; i++)
{
theSpot = objects[stuff];
i++;
if (i > 0)
{
while (slideSpots[1] == theSpot || slideSpots[2] == theSpot || slideSpots[3] == theSpot)
{
theSpot = objects[stuff];
Debug.Log(i);
}
slideSpots[i] = theSpot;
}
else
slideSpots[1] = theSpot;
}
}
}
What am I missing?