- Home /
How to add GameObject to List using a constructor method
I have this script attached to a GameObject prefab:
//Room.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Room : MonoBehaviour
{
public int sizeX;
public int sizeZ;
public Room(int minLength, int maxLength)
{
sizeX = Random.Range(minLength, maxLength);
sizeZ = Random.Range(minLength, maxLength);
}
}
And this script on another GameObject that is supposed to create a list, and populate it with the first GameObject class. I want each gameobject to be created using the constructor method on Room.cs, but it doesn't work. I find it difficult to work with classes and gameobjects at the same time.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HouseCreator : MonoBehaviour
{
public int roomCount;
public Room roomPrefab;
public List<Room> rooms = new List<Room>();
void Start()
{
for(int i = 0; i < roomCount; i++)
{
rooms.Add(roomPrefab(2, 6)); //I want to use the constructor here
//Debug.Log("Room " + i + ": " + rooms[i].GetSizeX() + " X " + rooms[i].GetSizeZ());
//rooms[i].CreateWalls(rooms[i].GetSizeX(), rooms[i].GetSizeZ(), i);
}
}
}
Answer by Bunny83 · Oct 29, 2019 at 11:25 PM
You can not use constructors with MonoBehaviour derived classes. Those class instances are created by the runtime when you use AddComponent or when you instantiate a prefab. You generally can not and should not use constructors with MonoBehaviour derived classes. Instead you may want to use your own initialization method which you simply call after you created an instance of your class. You can design that Init method in a way to allow chaining. For example:
public class Room : MonoBehaviour
{
public int sizeX;
public int sizeZ;
public Room Init(int minLength, int maxLength)
{
sizeX = Random.Range(minLength, maxLength);
sizeZ = Random.Range(minLength, maxLength);
return this;
}
}
By returning this we can directly use the return value somewhere else when we call it. To instantiate your prefab you would do
rooms.Add(Instantiate(roomPrefab).Init(2, 6));
Note that the Awake method of your Room class (or any other component which might be part of the prefab) will run before the Instantiate call returns and before your Init method is called. You can not really bypass this as the actual creation of the class instance happens in the engine core. Awake will be called once the deserialization of the prefab has completed. Note that the Start callback will be called after your Init method since Start is always delayed just before the next Update call.