Need some help for a 2d space trading game. This script is supposed to generate a group of stars within the “bounds” variables. Each star is placed one at a time at a set of random coords. However, before I spawn the next star, I want to check if there is a star in that location already, and if so, cancel the spawn and rerun the loop until I have the desired number of stars.
The code succesfully spawns the desired number of stars but the “if (starArray[j].collider.bounds.Contains (spawnLocation))” line never returns true, even if the spawn location is within the bounds of an existing collider. So stars are spawning on top of eachother…
The star prefab is a GameObject with only a box collider (is trigger set to on) and a child GameObject with a sprite renderer to display an image. I have tried setting the collider size to 1000, 1000, 1000 to ensure the spawn location is within the collider but its still spawning away.
using UnityEngine;
using System.Collections;
//using System.Collections.Generic;
public class GalaxyGenerator : MonoBehaviour
{
public GameObject starPrefab;
Vector3 spawnLocation;
float leftBounds;
float rightBounds;
float upperBounds;
float lowerBounds;
float xCoord;
float yCoord;
int currentStars;
bool starSpawnable;
GameObject[] starArray = new GameObject[10];
void Awake()
{
leftBounds = -20f;
rightBounds = 20f;
upperBounds = 410f;
lowerBounds = 390f;
currentStars = 0;
}
void Start ()
{
GenerateGalaxy (10);
}
void GenerateGalaxy(int numStars)
{
while (currentStars < numStars) //Keep generating stars until current number of stars reaches desired number
{
starSpawnable = true;
xCoord = Random.Range (leftBounds, rightBounds); //Selects a random set of coords within fixed bounds and sets spawn location to selected coords
yCoord = Random.Range (upperBounds, lowerBounds);
spawnLocation = new Vector3 (xCoord,yCoord,0f);
for (int j = 0; j < currentStars; j++) // Loops through each existing star to find if spawn location falls within collider of any existing star
{
if (starArray[j].collider.bounds.Contains (spawnLocation))
{
starSpawnable = false;
Debug.Log ("Spawn collision detected");
}
}
if (starSpawnable == true) //if spawn location does not fall within an existing collider, spawn the star
{
starPrefab.transform.position = spawnLocation;
Instantiate (starPrefab);
starArray[currentStars] = starPrefab;
currentStars++;
Debug.Log ("Spawn successful");
}
}
}
}