- Home /
Question by
haimmoshe · Oct 06, 2017 at 01:22 PM ·
c#scripting problemscript.
How can i Instantiate on the terrain from left to right ?
Now when i Instantiate objects it's placing them on the terrain but from right to left.
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
public class ClickOnKeys : MonoBehaviour
{
public GameObject[] prefabs;
public int gap = 10;
private GameObject go;
void Start()
{
prefabs = Resources.LoadAll("Prefabs", typeof(GameObject)).Cast<GameObject>().ToArray();
foreach (GameObject prefab in prefabs)
{
if (prefab.name == "Test")
{
go = prefab;
}
}
}
void Update()
{
if (Input.anyKey)
{
foreach (Transform child in go.transform)
{
if (Input.inputString == child.name)
{
Transform clone = Instantiate(child, new Vector3(gap += 50,0,0), Quaternion.identity);
clone.parent = transform;
}
}
}
}
}
I want that when i click on the keys it will place the child from left to right.
Update:
I can make them Instantiate random but some of them not on the terrain area but out of the terrain. How can i make sure they will Instantiate only inside the terrain area and to keep gap/space between each one of 50 ?
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()
{
terrainWidth = terrain.terrainData.size.x;
terrainLength = terrain.terrainData.size.z;
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);
}
}
}
}
}
Comment