- Home /
How to choose random spawn point and spawn within its limit?
Greetings,
I'm trying to have my GameManager object (wave spawner script) spawn enemies at set locations -- and at a random location inside them.
I have a public Transform[] Spawnpoints;
array in my manager in order to create more spawn points through the inspector. If I want to spawn enemies at these positions, then I can simply use this function:
private void SpawnEnemy(Transform enemy)
{
Debug.Log("Spawning Enemy" + enemy.name);
Transform SP = SpawnPoints[Random.Range(0, SpawnPoints.Length)];
SP.position = AreaSpawn.SpawnLocation();
Instantiate(enemy, SP.position, SP.rotation);
}
I use an empty game object to choose my spawn locations, which I've turned into a prefab. However, I have a separate script that is attached to the spawn locations that looks like this:
using UnityEngine;
public class AreaSpawnPoint : MonoBehaviour
{
public Vector3 Center;
public Vector3 Size;
public Vector3 SpawnLocation()
{
Vector3 Position = Center + new Vector3(Random.Range(-Size.x / 2, Size.x / 2), Random.Range(-Size.y / 2, Size.y / 2), Random.Range(-Size.z / 2, Size.z / 2));
return Position;
}
private void OnDrawGizmosSelected()
{
Gizmos.color = new Color(0, 0, 1, 0.7f);
Gizmos.DrawCube(Center, Size);
}
}
In a nut shell, the public Vector3 SpawnLocation()
returns a random location within the cube every time it's called. I apply this script to my spawn location objects, and create a specific size spawn area where they are allowed to spawn. (see below to get an idea)
Problem My issue is I'm not sure how I can choose a random spawn location and use the random spawn location inside it. Currently, (if you look at the screenshot above) I can reference only one of the spawn location objects and it works with just that one spawn location. How can I reference all of the locations? I'm sure there's a way, but I'm not quite sure how.
Thanks
Your answer
Follow this Question
Related Questions
Why doesn't my spawning code work? 2 Answers
Create GameObject On Click Not Working 0 Answers
Multi coulored Lighting and acid physics+ spawnpoints -1 Answers
wave spawn problems 1 Answer
Spawn object And assetId 0 Answers