Question by
SalmonXerxes · Feb 24, 2019 at 11:08 PM ·
c#terraindatamodifyarray-out-of-range-except
IndexOutOfRangeException: Array index is out of range??
I've been trying to make a script that makes it possible for the player to edit terrain in real time. However, i keep getting "IndexOutOfRangeException: Array index is out of range." in my code. I'm new to c# so there is quite a big possibility that this is just some noob mistake.
The error is in line 56, where i have commented "//This is the error"
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ModifyTerrain : MonoBehaviour {
public Terrain terrain;
public float strength = 0.01f;
private int hightmapWidth;
private int hightmapHight;
private float[,] hights;
private TerrainData terrainData;
// Use this for initialization
void Start () {
terrainData = terrain.terrainData;
hightmapWidth = terrainData.heightmapWidth;
hightmapWidth = terrainData.heightmapHeight;
hights = terrainData.GetHeights(0, 0, hightmapWidth, hightmapHight);
}
// Update is called once per frame
void Update () {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//Raise terrain
if (Input.GetMouseButtonDown(0)){
if(Physics.Raycast(ray, out hit)){
RaiseTerrain(hit.point);
}
}
//Lower terrain
if (Input.GetMouseButtonDown(1)){
if(Physics.Raycast(ray, out hit)){
LowerTerrain(hit.point);
}
}
}
private void RaiseTerrain(Vector3 point){
int mouseX = (int)((point.x/terrainData.size.x) * hightmapWidth);
int mouseZ = (int)((point.z/terrainData.size.z) * hightmapHight);
Debug.Log(mouseX);
float y = hights [mouseX, mouseZ]; //This is the error
float[,] modifiedHights = new float [1, 1];
y += strength * Time.deltaTime;
if(y > terrainData.size.y){
y = terrainData.size.y;
}
modifiedHights[0,0] = y;
hights[mouseX, mouseZ] = y;
terrainData.SetHeights(mouseX, mouseZ, modifiedHights);
}
private void LowerTerrain(Vector3 point){
int mouseX = (int)((point.x/terrainData.size.x) * hightmapWidth);
int mouseZ = (int)((point.z/terrainData.size.z) * hightmapHight);
float[,] modifiedHights = new float [1, 1];
float y = hights[mouseX,mouseZ];
y -= strength * Time.deltaTime;
if(y < 0){
y = 0;
}
modifiedHights[0,0] = y;
hights[mouseX,mouseZ] = y;
terrainData.SetHeights(mouseX,mouseZ,modifiedHights);
}
}
Comment
Your answer
Follow this Question
Related Questions
[C#] Error in script [IndexOutOfRangeException] 1 Answer
Array out of index, but shouldn't be 2 Answers
Camera Modification Help 0 Answers