private Vector3 FindSpawnTarget() { RaycastHit2D hit = new RaycastHit2D(); Vector3 dropPos; List <int> usedValues = new List <int> (); GameObject[] enemies = AuxFunctions.FindGameObjectsWithLayer(LayerMask.NameToLayer("EnemyFormation")); foreach (GameObject go in enemies) { for (int p = (int)go.transform.position.x - 2; p < (int)go.transform.position.x + 2; p++) { usedValues.Add(p); } } int i = 0; do { // Create a random x coordinate for the delivery in the drop range. int dropPosX = UniqueRandomInt((int)leftmostSpawnEdge.position.x, (int)rightmostSpawnEdge.position.x, usedValues); //float dropPosX = Random.Range(dropRangeLeft.position.x,dropRangeRight.position.x); usedValues.Add(dropPosX); // Create a position with the random x coordinate. dropPos = new Vector3(dropPosX, leftmostSpawnEdge.position.y, transform.position.z); hit = new RaycastHit2D(); // Raycasting Enemies layer, to try to spawn where an enemy is not hit = Physics2D.Raycast(dropPos, -Vector2.up, 10f, LayerMask.NameToLayer("Enemies")); i++; if (i >= 100) { i = 0; //Debug.Log("Spawner error"); hit = new RaycastHit2D(); } } while (hit.collider != null); return(dropPos); }