How to instantiate object a certain distance away from all objects with a certain tag?

I’ve run into a bump with random spawn points. I’m able to spawn any prefab in a random location within a given radius and as long as the spawn point is an X distance away from the player. However, my game also has the ability to build walls/houses/etc and if I build a house with walls surrounding it and then leave that area, then there is a chance that a prefab (aka enemy) will spawn inside of the walls that were built. I can’t for the life of me figure out how to make sure that doesn’t happen. Any suggestions? I tried tagging each builded object as “Structure” and before the objSpawner spawns the object, make sure the distance is X distance from the closes object tagged “Structure”. I couldn’t figure it out seeing how findobjectswithtag kept returning only the first object in hiearchy tagged “Structure”, not the closest one to the spawn point.

Here is a snippet of code;

while (enemySpawned < maxEnemyAmount) {
	Vector3 pos = new Vector3 (Random.Range (-groundXValue, groundXValue), 2, Random.Range (-groundZValue, groundZValue));
	if (Vector3.Distance (pos, player.transform.position) < 30) {
		return;
	} else {
		Instantiate (enemy, pos, Quaternion.Euler(Random.Range(30, 150), 0, (Random.Range(30, 150))));
		enemySpawned++;
	}
}

You need to learn how to use the 101/010 button to format your code. If you do not do that no one will help you with your questions. I did it for you this time.

1 Answer

1

Could moderators please delete this question? My question was vague and not concise enough. Thank you.

Does my answer not match your question? I can close your question. You can delete your own question.