- Home /
Enemy Pooling on a Terrain
I use an object pooling system
height = Terrain.activeTerrain.SampleHeight (enemy.transform.position)
+ Terrain.activeTerrain.transform.position.y;
Vector3 spawnPoint = new Vector3();
spawnPoint.x = Random.Range (2000, 600);
spawnPoint.y = (height.y);
spawnPoint.z = Random.Range (1500, 3500);
This is what I try to use^
But because I use NavMesh it needs to be instantiated ON the terrain. My solution above does not work.
The question I pose is: How would I script a bumpy terrains vector 3 height like I did above except work?
Answer by Puck · Mar 13, 2017 at 09:37 PM
I'm pretty sure you have the right idea, you just need to subtract the terrain's position. You want your enemy's position to be relative to your terrain, so you nullify the terrain's position by subtracting it so that if your terrain were at [-10, 0, -10] the result would be to add [10, 0, 10] to the enemy position.
Try this:
// TerrainSpawner.cs
using UnityEngine;
public class TerrainSpawner : MonoBehaviour {
public void Spawn(Terrain terrain, GameObject template)
{
Bounds box = terrain.terrainData.bounds;
// Get random position in terrain space
Vector3 pos = new Vector3(Random.Range(box.min.x, box.max.x), 0, Random.Range(box.min.z, box.max.z));
// Transform to world space
pos += terrain.transform.position;
// Sample height
pos.y = terrain.SampleHeight(pos);
Instantiate(template, pos, Quaternion.identity);
}
}
Sample Usage:
public GameObject obj;
private void Start()
{
for (var i = 0; i < 1000; i++)
GetComponent<TerrainSpawner>().Spawn(Terrain.activeTerrain, obj);
}
Sadly, not. (also I changed the first word: height to height.y to fix an error) but despite the terrain's Y being 0 the Enemy's always spawn at 337 unless it luckily lands on the terrain which in that case it will not spit out errors and will resume it's navmesh duties as usual. But the chances of the enemies actually landing on the terrain and not floating in the sky spitting a stupid amount of errors just collapsing the game down to staggeringly bad framerates. Thanks for trying though.
It sounds like your problem is no longer finding the height of the terrain, and more finding the bounds. I updated my answer with a complete solution for you so give that a try and if it's helpful don't forget to accept the answer. Good luck with your project!
By golly, it works. There is a weird issue which is making the enemies spawn in a herd despite the terrain being massive but that I can fix, Thanks for fixing this problem which is not touched upon in Unity Answers for whatever reason.