I made a prefab and drag drop it to the Tile Prefab slot as shown in the picture
In my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameGrid :MonoBehaviour
{
private int width;
private int height;
private int[,] gridArray;
private float cellSize;
[SerializeField]
GameObject tilePrefab;// = default;
public GameGrid(int width, int height, float cellSize)
{
this.width = width;
this.height = height;
this.cellSize = cellSize;
gridArray = new int[width, height];
Debug.Log(width + " " + height);
for(int x = 0; x < gridArray.GetLength(0); x++)
{
for(int z = 0; z < gridArray.GetLength(1); z++)
{
GameObject tile =Instantiate(tilePrefab);
tile.transform.SetParent(transform, false);
tile.transform.localPosition = GetWorldPosition(x,z);
}
}
}
private Vector3 GetWorldPosition(int x, int z, int y = 0)
{
return new Vector3(x, 0, z) * cellSize;
}
}
1.It throw out error, ArgumentException: The Object you want to instantiate is null, it is very strange because I have the Prefab assigned in the inspector, what could ran wrong, and it is strange that the console did not tell me which line is wrong.
2.Another error is "You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed", it confused me because I did not new anything.
3.This line of code "tile.transform.SetParent(transform, false);" I copied from other resource which I do not fully understand, I looked to the Unity menu still did not get any idea of what it does, it setParent but what parent property this function tries to setup, is it trying to set its parent's transform or what?
Thanks very much I'm still new to Unity.
EDIT: Here is my testing.cs
public class Testing : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
GameGrid grid = new GameGrid(20, 10, 1);
}
}
1.Remove the default assignment is not working either. 2.Regarding to the setParent, I do not have a parent, then what parent this child is attached to, if this function will instantiate a parent, then no information is provided to the creation of the parent, still confused.
GameGrid grid = new GameGrid(20, 10, 1);
as far as I remember you shouldn't make objects like that, rather have it be a new GameObject and do gameObject.AddComponent(GameGrid) or something like that. Instead of your constructor you'd put the code in Awake() or Start(). (correct me if I'm wrong please.) \$\endgroup\$