Answer the question
In order to leave comments, you need to log in
Why is the texture of the prefab created via Instantiate not displayed in the code?
I am writing a game 2048 to practice)))
Here is the cell code:
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class Cell : MonoBehaviour
{
public int X {get; private set;}
public int Y {get; private set;}
public int Value {get; private set;}
public int Points => IsEmpty ? 0 : (int)Mathf.Pow(2, Value);
public bool IsEmpty => Value == 0;
public const int MaxValue = 11;
[SerializeField]
private Image image;
[SerializeField]
private TextMeshProUGUI points;
public void SetValue(int x, int y, int value)
{
X = x;
Y = y;
Value = value;
UpdateCell();
}
public void UpdateCell()
{
points.text = IsEmpty ? string.Empty : Points.ToString();
points.color = Value <= 2 ? ImageManager.Instance.PointsDarkColor : ImageManager.Instance.PointsLightColor;
image.color = ImageManager.Instance.CellColors[Value];
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Board : MonoBehaviour
{
[Header("Переменные поля")]
public float CellSize;
public float Spacing;
public int BoardSize;
[Space(10)]
[SerializeField]
private Cell cellPref;
[SerializeField]
private RectTransform rt;
private Cell[,] board;
private void Start()
{
GenerateBoard();
}
private void CreateBoard()
{
board = new Cell[BoardSize, BoardSize];
float boardWidth = BoardSize * (CellSize + Spacing) + Spacing;
rt.sizeDelta = new Vector2(boardWidth, boardWidth);
float startX = -(boardWidth / 2) + (CellSize / 2) + Spacing;
float startY = (boardWidth / 2) - (CellSize / 2) - Spacing;
for (int x = 0; x < BoardSize; x++)
{
for(int y = 0; y < BoardSize; y++)
{
var cell = Instantiate(cellPref, transform, false);
var position = new Vector2(startX + (x * (CellSize + Spacing)), startY - (y * (CellSize + Spacing)));
cell.transform.localPosition = position;
board[x, y] = cell;
cell.SetValue(x, y, 0);
}
}
}
public void GenerateBoard()
{
if(board == null)
{
CreateBoard();
}
for(int x = 0; x < BoardSize; x++)
for(int y = 0; y < BoardSize; y++)
board[x, y].SetValue(x, y, 0);
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question