I'm working on my game, it's my first project on Unity. In short, it has 3d Grid and should have box in each grid cell. I need to instantiate Box prefab in each cell, but I'm getting this error: "Assets\BoxGrid.cs(26,67): error CS0165: Use of unassigned local variable 'BoxPrefab'". How do I assign GameObject BoxPrefab a Prefab using only script?
public class BoxGrid
{
private GameObject BoxPrefab = GameObject.Find("Box");
private int width;
private int height;
private int length;
private float CellSize;
private int[,,] BoxGridArray;
public BoxGrid(int width, int height, int length, float CellSize) {
this.width = width;
this.height = height;
this.length = length;
this.CellSize = CellSize;
BoxGridArray = new int[width, height, length];
for (int x = 0; x < BoxGridArray.GetLength(0); x ) {
for (int y = 0; y < BoxGridArray.GetLength(1); y ) {
for (int z = 0; z < BoxGridArray.GetLength(2); z ) {
GameObject BoxPrefab = GameObject.Instantiate(BoxPrefab, GetPosition(x, y, z) new Vector3(CellSize, CellSize, CellSize) * .5f, Quaternion.identity) as GameObject;
Debug.DrawLine(GetPosition(x, y, z), GetPosition(x, y, z 1), Color.white, 100f);
Debug.DrawLine(GetPosition(x, y, z), GetPosition(x, y 1, z), Color.white, 100f);
Debug.DrawLine(GetPosition(x, y, z), GetPosition(x 1, y, z), Color.white, 100f);
}
}
}
}
private Vector3 GetPosition(int x, int y, int z) {
return new Vector3(x, y, z) * CellSize;
}
}
Code below is other script with MonoBehaviour that defines Grid's parameters.
public class GridCreate : MonoBehaviour
{
public void Start() {
BoxGrid Grid = new BoxGrid(4, 4, 4, 25f);
}
}
How do I fix this error?
I'm trying to make Minesweeper game in 3d even though I'm newbie in programming. I tried to assign GameObject a Prefab like this "private GameObject BoxPrefab = GameObject.Find("Box"); " but it doesn't seem to work, is there any other way?
CodePudding user response:
By writing
GameObject BoxPrefab = GameObject.Instantiate(BoxPrefab, GetPosition(x, y, z) new Vector3(CellSize, CellSize, CellSize) * .5f, Quaternion.identity) as GameObject;
you "hide" your class field and basically overrule it with this local variable with the same name.
That local variable isn't initialized until Instantiate
returns something => you can't have the same variable as parameter.
you probably just want to use
Object.Instantiate(BoxPrefab, GetPosition(x, y, z) new Vector3(CellSize, CellSize, CellSize) * .5f, Quaternion.identity) as GameObject;
as I don't see where you ever use the local variable later anyway.
I would also avoid issues with static context etc. rather explicitly move this into the constructor
public BoxGrid(int width, int height, int length, float CellSize)
{
GameObject BoxPrefab = GameObject.Find("Box");
...