I have the following code that generates game objects, in my game. The problem with it is that some game objects are out of the terrain area. I want to place them at random, but also make sure they will be inside the terrain area.
I know that I get the terrain size with terrain.terrainData.size
, but I'm not sure how to use it. How do I create random game objects on a terrain, but only inside the terrain area?
Here is my current script:
using UnityEngine;
public class Teleport : MonoBehaviour
{
public Vector3 terrainArea;
public float spinSpeed = 2.0f;
public int cloneTeleportations;
public GameObject prefab;
private bool rotate = false;
private bool exited = false;
private Transform[] teleportations;
private Random rnd = new Random();
private void Start()
{
GameObject go = GameObject.Find("Terrain");
Terrain terrain = go.GetComponent(Terrain);
terrainArea = terrain.terrainData.size;
for (int i = 0; i < cloneTeleportations; i++)
{
GameObject Teleportaion = Instantiate(prefab,
new Vector3(Random.Range(i * 10.0F, i * 50.0F), 0,
Random.Range(i * 10.0F, i * 50.0F)), Quaternion.identity);
Teleportaion.transform.parent = this.transform;
Teleportaion.transform.tag = "Teleportation";
}
}
}