Enemies spawning on top of each other,Enemies spawn on top of each other
I'm attempting to use Pooling to spawn enemies from an array and I want to make sure that they don't spawn in the same position as another and they are equally spread out at the top of the screen when they're all active. However, they are often spawning on top of each other, even when I am checking for collisions with layer 7, which is the layer used for all the enemies. Also, sorry some of the code is coming up as my description, I'm not sure how to change the formatting as I've never posted here before.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class EnemyMovement : MonoBehaviour { [SerializeField] private GameObject[] enemies; private bool spawnEnemy = true;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//if ((int)Time.time%5 == 0)
if (Input.GetKeyDown(KeyCode.Space))
{
spawnEnemy = true;
Spawn();
}
}
void Spawn()
{
while (spawnEnemy)
{
int rand = (int)(Random.value * 10);
int xPos = getPosition(rand);
GameObject e = enemies[FindEnemy()];
e.SetActive(true);
e.transform.position = new Vector3(xPos, e.transform.position.y, e.transform.position.z);
if (!e.gameObject.GetComponent<BoxCollider2D>().IsTouchingLayers(7))
{
spawnEnemy = false;
}
}
}
int getPosition(int pos)
{
return -10 + 2 * pos;
}
int FindEnemy()
{
for (int i = 0; i < enemies.Length; i++)
{
if (!enemies[i].activeInHierarchy)
return i;
}
return 0;
}
}
Your answer
Follow this Question
Related Questions
Jump off 2D platforms Smash brothers style. 1 Answer
Collision not working 1 Answer
OnTriggerEnter not being called 2 Answers
2D colliders doesnt work with Gravity Scale = 0 0 Answers
Unity 2D does not detect collisions 0 Answers