So I was following this tutorial(https://catlikecoding.com/unity/tutorials/hex-map/part-1/). Eventually, I reached this part of the tutorial:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class HexMapEditor : MonoBehaviour
{
public Color[] colors;
public HexGrid hexGrid;
private Color activeColor;
public void selectColor (int index) {
activeColor = colors[index];
Debug.Log("**Color changed to : " + colors[index]);
}
void handleInput () {
Ray inputRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(inputRay, out hit)) {
hexGrid.colorCell(hit.point, activeColor);
}
}
void Awake(){
selectColor(0);
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0) &&
!EventSystem.current.IsPointerOverGameObject())
{
handleInput();
}
}
}
using UnityEngine;
using UnityEngine.UI;
using System;
public class HexGrid : MonoBehaviour
{
---
public void colorCell (Vector3 position, Color color) {
position = transform.InverseTransformPoint(position);
HexCoordinates coordinates = HexCoordinates.FromPosition(position);
int index = coordinates.X + coordinates.Z * width + coordinates.Z / 2;
HexCell cell = cells[index];
cell.color = color;
hexMesh.Triangulate(cells);
}
---
}
For some reason, this causes an "IndexOutOfRangeException: Index was outside the bounds of the array" error.
However, something like this works:
using UnityEngine;
using UnityEngine.UI;
using System;
public class HexGrid : MonoBehaviour
{
---
public void colorCell (Vector3 position) {
position = transform.InverseTransformPoint(position);
HexCoordinates coordinates = HexCoordinates.FromPosition(position);
int index = coordinates.X + coordinates.Z * width + coordinates.Z / 2;
HexCell cell = cells[index];
cell.color = touchedColor;
hexMesh.Triangulate(cells);
}
void handleInput () {
Ray inputRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(inputRay, out hit)) {
colorCell(hit.point);
}
}
---
}
Is there a way to solve this? Thanks in advance and also sorry if this problem is caused by a stupid oversight.