添加立方体预制件不成功。
gameBoardCreator和gameBoardView的位置是不是错了,是什么问题?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameBoardView : MonoBehaviour
{
[SerializeField] private GameObject _cubePrefab;
private GameBoard _gameBoard;
public void SetGameBoard(GameBoard gameBoard)
{
_gameBoard = gameBoard;
for (int col = 0; col < _gameBoard.Columns; col++)
{
for (int row = 0; row < _gameBoard.Rows; row++)
{
var position = new Vector3(col, 0, row);
var instance = Instantiate(_cubePrefab, position, Quaternion.identity, transform);
}
}
}
}
using UnityEngine;
public class GameBoardCreator : MonoBehaviour
{
public int columns = 2;
public int rows = 2;
private void onEnable()
{
GameBoard gameBoard = new GameBoard(columns, rows);
FindObjectOfType<GameBoardView>().SetGameBoard(gameBoard);
}
}
public class GameBoard
{
public int currentColumn;
public int currentRow;
public bool[,] _positions;
public readonly int Rows;
public readonly int Columns;
public GameBoard(int columns, int rows)
{
Columns = columns;
Rows = rows;
_positions = new bool[columns, rows];
}
}
你在"onEnable
",应该是"OnEnable
",才能被MonoBehaviour正确调用。因此,你的SetGameBoard函数永远不会被调用。你也可以考虑把这个逻辑移到 Start
. 该 文件 的MonoBehaviour提供了所有关于哪个函数在何时被调用的信息。