using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
public class ClickOnKeys : MonoBehaviour
{
public Terrain terrain;
public float yOffset = 0.5f;
private float terrainWidth;
private float terrainLength;
private float xTerrainPos;
private float zTerrainPos;
public GameObject[] prefabs;
public int gap = 10;
private GameObject go;
void Start()
{
//Get terrain size
terrainWidth = terrain.terrainData.size.x;
terrainLength = terrain.terrainData.size.z;
//Get terrain position
xTerrainPos = terrain.transform.position.x;
zTerrainPos = terrain.transform.position.z;
prefabs = Resources.LoadAll("Prefabs", typeof(GameObject)).Cast<GameObject>().ToArray();
foreach (GameObject prefab in prefabs)
{
if (prefab.name == "Test")
{
go = prefab;
}
}
}
void generateObjectsOnTerrain(GameObject trans)
{
float randX = UnityEngine.Random.Range(xTerrainPos, xTerrainPos + terrainWidth);
float randZ = UnityEngine.Random.Range(zTerrainPos, zTerrainPos + terrainLength);
float yVal = Terrain.activeTerrain.SampleHeight(new Vector3(randX, 0, randZ));
yVal = yVal + yOffset;
GameObject objInstance = (GameObject)Instantiate(trans, new Vector3(randX, yVal, randZ), Quaternion.identity);
}
void Update()
{
if (Input.anyKey)
{
foreach (Transform child in go.transform)
{
if (Input.inputString == child.name)
{
generateObjectsOnTerrain(child.gameObject);
}
}
}
}
}
This will Instantiate a new gameobject each time i click on a key in a random position.
The problem is that it’s placing gameobjects also out of the terrain area and i want it to Instantiate them only inside the terrain area with gap/space of 50 between each one.
Then i want to add a bool variable if checked make them Instantiate random inside the terrain area with gap/space of 50. If unchecked make them Instantiate one by the other in same line for example:
And then to add another bool variable and if the first one is unchecked not random then consider the second bool variable effect if checked Instantiate the objects from left to right in gap/space of 50 when getting to the end of line drop to next line. If unchecked Instantiate them from right to left gap 50.