Ah the most annoying thing about Unity coming from a traditional OOP developer.
C# has constructors, but Unity uses them as part of its GameObject creation system, so overriding it is not-recommended.
Here’s what I recommend. We will have two types of GameObject: Blocks and a GridManager. Create GridManager, stick it on a GameObject
public class GridManager : MonoBehaviour {
private int x = 5; // rows
private int y = 4; // columns
private float separation = 1.2f;
private void Awake(){
for(int x = 0; x < this.x; x++){
for(int x = 0; x < this.x; x++){
Block block = (Instantiate(Resources.Load("Prefabs/Block")
as GameObject).getComponent<Block>();
block.init(x,y);
block.transform.SetParent(this.transform);
block.transform.rotation = Quaternion.identity;
block.transform.localposition = new Vector3(x * separation, y* separation);
}
}
Then you set up your block like this
public class Block : Monobehaviour {
internal init(int x, int y){
Debug.Log("X: "+ x + ", Y: "+y)
}
}
The execution pattern will be that this init is executed ALMOST immediately. There will be a race condition between init and Awake, so do not have either method rely on work done by the other.
Okay, so now you have your scripts.
Now lets set up your prefabs folder… create this path in your project: “Assets/Resources/Prefabs”
(Assets/Resources is the base path for the Resources.Load functionality used above)
Now create a block
Make a cube object, ( GameObject > 3D Object > Cube ), stick the Block script on it, and rename it to “Block”. Then drag it from the Hierarchy view to the Prefabs folder. This will prefab it. You will know that it worked if the name in the Hierarchy turned blue. Now you can safely delete it from the hierarchy.
If we did everything right here, when you press play you should get a grid of 5x4 blocks 1.2f spaces apart, each of which has had its init called, and has spammed its coordinates to your Console.
Let me know if this didn’t work.