I am making chess in unity2D and am trying to set the pieces as children of the squares as shown in the function below, however it is not creating new game objects with no errors being output.
private void DrawPiece(int piece, Transform parentSquare)
{
if (!pieceSprites.ContainsKey(piece))
{
Debug.LogError($"Piece sprite not found for piece code: {piece}");
return;
}
string pieceBinary = Convert.ToString(piece, 2).PadLeft(5, '0');
GameObject pieceObj = new GameObject($"Piece_{pieceBinary}@{parentSquare.position.x * 8 + parentSquare.position.y}");
pieceObj.transform.position = parentSquare.position;
pieceObj.transform.parent = parentSquare;
SpriteRenderer sr = pieceObj.AddComponent<SpriteRenderer>();
sr.sortingOrder = 1;
sr.sprite = pieceSprites[piece];
pieceObj.transform.localScale = new Vector3(pieceSize, pieceSize, 1);
}
void DrawAllPieces()
{
// Clear old pieces
foreach (Transform child in transform)
{
if (child.name.StartsWith("Piece_"))
Destroy(child.gameObject);
}
for (int i = 0; i < 64; i++)
{
int piece = Board.Square[i];
if (piece != Piece.None)
{
int x = i % 8;
int y = i / 8;
Vector2 position = new Vector2(x - 3.5f, y - 3.5f);
// Find the square corresponding to the piece's position
GameObject square = FindSquare(position);
if (square == null)
{
Debug.LogError($"Square not found at position: {position}");
continue;
}
DrawPiece(piece, square.transform);
}
}
}
private GameObject FindSquare(Vector2 position) {
string squareName = $"Square_{position.x + 3.5f}_{position.y + 3.5f}"; return GameObject.Find(squareName);
}
I tried setting the pieceObj parent to transform and it generates the piece fine.
Output with pieceObj.transform.parent = parentSquare;
Output with pieceObj.transform.parent = transform;
Any help would be much appreciated :)
This was an issue with float
not being precise as @derHugo mentioned I just needed to use Mathf.RoundToInt