Instantiate GameObjects from editor via InitializeOnLoad
Web Technologies
Web Development
2 years ago
5
Star Rating
1
Rating
_x000D_
_x000D_
I have a programmatically generated board of a certain size. In order to see it, I would normally have to hit run, which is quite annoying and makes it hard to visualize.
Is it possible to make, and thus be able to visualize, the board via InitializeOnLoad?
I gave it a try:
Setup.cs
[InitializeOnLoad]
public class Setup : MonoBehaviour {
public static Map initialMap;
static Setup(){
initialMap = new Map ();
initialMap.createMap ();
}
}
Map.cs
public class Map {
private Tile[,] tiles= new Tile[5,5];
//I had Resources.Load here, but apparently thats not allowed either...
public GameObject defaultObj= new GameObject("MyCreatedGO");
public Map (){
Debug.Log("In Constructor");
}
public void createMap(){
for (int x = 0; x < tiles.GetLength(0); x += 1) {
for (int y = 0; y < tiles.GetLength(1); y += 1) {
// Tile Instantiates the defaultObj
tiles [x, y] = new Tile (defaultObj, new Vector3 (x, y, 0));
}
}
}
}
But unity responded by complaining that
UnityException: Internal_CreateGameObject is not allowed to be called
from a MonoBehaviour constructor (or instance field initializer), call
it in Awake or Start instead. Called from MonoBehaviour 'Setup' on
game object 'Map'.
Is the engine even in a state where it can make objects when the InitializeOnLoad-ed static constructor happens?
If this isn't possible, how are you supposed to visualize a procedurally generated map in Unity?
Posted on 16 Aug 2022, this text provides information on Web Development related to Web Technologies. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.
Take Quiz To Earn Credits!
Turn Your Knowledge into Earnings.