Currently I am making a chess game, and I have an issue where I want to call Highlight() in BoardController, but it is empty when I call it, even though I have instantiated it in the Start() method.
This is my BoardController class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoardController : MonoBehaviour
{
[SerializeField] private Piece[] positions;
[SerializeField] private GameObject[] blueHighlight;
[SerializeField] private GameObject highlightSquare;
void Start()
{
InstantiatePieces();
}
private void InstantiatePieces()
{
blueHighlight = new GameObject[64];
for (int i = 0; i < 64; i++)
{
int x = i % 8;
int y = i / 8;
blueHighlight[i] = Instantiate(highlightSquare, new Vector3(x, y, 0), Quaternion.identity);
if (positions[i] != null)
{
Instantiate(positions[i], new Vector3(x, y, 0), Quaternion.identity);
}
}
}
private void Update()
{
}
public bool IsLegalMove(int x, int y)
{
int pos = y * 8 + x;
if (positions[pos] != null || !IsInBounds(x, y))
{
// change based on black or white;
return false;
}
return true;
}
public bool IsInBounds(int x, int y)
{
if (x < 0 || x > 7 || y < 0 || y > 7)
{
return false;
}
return true;
}
public void Highlight(int x, int y)
{
Debug.Log("Highlight");
int pos = ConvertToPos(x, y);
blueHighlight[pos].SetActive(true);
Debug.Log("Completed");
}
// Converts (x, y) coords to 0 - 63
public int ConvertToPos(int x, int y)
{
return y * 8 + x;
}
public int[] ConvertToXY(int pos)
{
return new int[] { pos % 8, pos / 8 };
}
}
And this is the Rook class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rook : Piece
{
public int[,] delta = new int[1, 2] {{0, 1}};
private void Start()
{
base.Start();
}
public override void GetAvailableMoves()
{
for (int i = 0; i < delta.Length - 1; i++)
{
int x = delta[i, 0];
int y = delta[i, 1];
if (boardController.IsLegalMove(x, y))
{
Debug.Log("Legal");
boardController.Highlight(x, y);
}
}
}
}
What I wanted to do is that when I click on the Rook piece, it will highlight the square it is sitting on, but I get an IndexOutOfBounds error since the blueHighlight array has length of 0 for some reason, even though I initialized it at the start