- Home /
Question by
jishansiddiquenuran · Aug 01, 2019 at 05:59 PM ·
instantiatepositionindexoutofrangeexceptionterain
Two Objects Instatiate Same Position??
issue is , i am instantiate a two prefab randomely but both prefab instantiate at the same position??
Code:
public class ObjectSpawner : MonoBehaviour
{
public Terrain terrain;
public int numberOfObjects; //15
private int currentObjects;
public GameObject[] objectToPlace; // GameObject to place //store two prefab cube and sphere
private int terrainWidth; // 500
private int terrainLength; // 500
private int terrainPosX;
private int terrainPosZ;
void Start()
{
terrainWidth = (int)terrain.terrainData.size.x;
Debug.Log("terrainwidth" + terrainWidth); //500
terrainLength = (int)terrain.terrainData.size.z;
Debug.Log("terrainlength" + terrainLength); //500
terrainPosX = (int)terrain.transform.position.x;
Debug.Log("terrainposx" + terrainPosX); //0
terrainPosZ = (int)terrain.transform.position.z;
Debug.Log("terrainposz" + terrainPosZ); //0
}
// Update is called once per frame
void Update()
{
// generate objects
if (currentObjects <= numberOfObjects)
{
// generate random x position
int posx = Random.Range(terrainPosX, terrainPosX + terrainWidth);
// generate random z position
int posz = Random.Range(terrainPosZ, terrainPosZ + terrainLength);
// get the terrain height at the random position
float posy = Terrain.activeTerrain.SampleHeight(new Vector3(posx, 0, posz));
for(int i=0;i<Random.Range(posx,posy);i++) //problem is both(two) object instantiate at a same position
{
GameObject newObject = Instantiate(objectToPlace[i], new Vector3(posx, posy, posz), Quaternion.identity);
currentObjects += 1;
}
}
}
}
what do i wrong and it is given an error array index out of range??
Referance:
Cube position:
Sphere Position:
Error:
sphere.png
(104.2 kB)
cube-position.png
(72.4 kB)
Comment
Best Answer
Answer by Vega4Life · Aug 01, 2019 at 06:09 PM
Probably need it to be more like this:
void Update()
{
// generate objects
if (currentObjects <= numberOfObjects)
{
for (int i = 0; i < objectToPlace.Length; i++) //problem is both(two) object instantiate at a same position
{
// generate random x position
int posx = Random.Range(terrainPosX, terrainPosX + terrainWidth);
// generate random z position
int posz = Random.Range(terrainPosZ, terrainPosZ + terrainLength);
// get the terrain height at the random position
float posy = Terrain.activeTerrain.SampleHeight(new Vector3(posx, 0, posz));
GameObject newObject = Instantiate(objectToPlace[i], new Vector3(posx, posy, posz), Quaternion.identity);
currentObjects += 1;
}
}
}
@Vega4Life can u give referance for this ,i want player should be able to feel the low gravity?? how can i do this??