I’m doing everything I can to go WELL beyond what I’m challenged to do in this series. It’s an excellent learning experience for me, but it means I’m a doing advanced things compared to where this lesson is.
I need help with a RayCast that doesn’t appear to be working. Even though there aren’t any errors in the code, and the code will print hit ONLY when collisions occur, it continues to spawn enemies on top of each other, even after I’ve created a square trigger collider around the entire 1x1 frame of the enemy ship, as well as a polygonal collider for the enemy ship itself.
using UnityEngine;
using System.Collections;
using UnityEditor;
using UnityEngine.SceneManagement;
public class EnemySpawner1 : MonoBehaviour {
public static GameObject[] myObjects;
public GameObject enemyPrefab;
public GameObject myObj;
public Vector3 randomPosition;
public bool okToSpawn = false;
public RaycastHit2D hit;
public int numToSpawn;
public int numToSpawnPerTime;
public int timeToSpawn;
public bool finalLevel = false;
public int numWaves;
public int whichEnemy;
// Use this for initialization
void Start ()
{
Scene levelLoaded = SceneManager.GetActiveScene ();
if (levelLoaded.name == "level_1") {
timeToSpawn = 1; // x seconds - spawn rate
numToSpawnPerTime = Random.Range (1, 3); //this controls how many enemies to spawn per x seconds
numWaves = (15); //how many waves to spawn
}
GetRandomPosition ();
}
void GetRandomPosition () //control level flow - needs better name
{
if (numWaves > 0) {
FillList ();
CheckSpawn ();
} else {
//SceneManager.LoadScene ("Win");
print ("Level Complete");
}
}
void FillList ()
{
myObjects = Resources.LoadAll<GameObject> ("Prefabs/Enemies");
InvokeRepeating ("SpawnEnemy", timeToSpawn, timeToSpawn);
print ("Instantiated");
}
void SpawnEnemy ()
{
if (numWaves > 0) {
numWaves--;
whichEnemy = Random.Range (0, 4); //choose enemy prefab
myObj = Instantiate (myObjects [whichEnemy]) as GameObject;
// start number spawn block
if (numToSpawnPerTime == 1) { // if number to spawn per spawnTime = 1 IE level_1
randomPosition = new Vector3 (Random.Range (-6.65f, 5.7f), Random.Range (1.5f, 4.06f), 0); // generate random location in enemy gamespace
CheckSpawn (); //check to see if collision occurs and generate new location if so
myObj.transform.position = randomPosition; // spawn enemy
print ("Spawned");
}
} else {
GetRandomPosition ();
}
}
void CheckSpawn ()
{
print ("Spawn Checked");
hit = Physics2D.Raycast (randomPosition, Vector2.zero);
if (hit.collider != null) {
randomPosition = new Vector3 (Random.Range (-6.65f, 5.7f), Random.Range (1.5f, 4.06f), 0);
print ("Hit");
}
}
My original code is really long because it simulates difficulty with multiple if statements that are dependent on which level is loaded etc. This is a shortened code for the purposes of posting here.
Can you see why the ships spawn on each other? I’ll post the original if need be, but I’d at least rather it be in comments than on top.
Thanks.