- Home /
2D array initialized but send Null
Hello !
Here's the issue: I got a simple class named Room
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Room : MonoBehaviour {
public int PosX;
public int PosY;
//don't mind the next variables
public bool HasBeenAdded = false;
public List<Room> listeRoomsLinked = new List<Room>();
public bool IsEntree = false;
public bool IsSortie = false;
public int NUMERO = 99;
public Room(int _x, int _y)
{
PosX = _x;
PosY = _y;
}
...
and a 2nd class Named GenerateFloor
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class GenerateFloor : MonoBehaviour {
int WidthMap;
int HeightMap;
Room[,] TableauRooms;
void Awake()
{
GenerateTheFloor ();
DrawMap ();
}
public void GenerateTheFloor()
{
WidthMap = 4;
HeightMap = 3;
//Initialize Array[,]
TableauRooms = new Room[WidthMap , HeightMap];
//Fill the table with Room Objects
for (int i = 0; i < WidthMap ; i++)
for (int j = 0; j < HeightMap ; j++) {
TableauRooms[i, j] = new Room (i,j);
}
Room _room = TableauRooms [2, 2];
...
And now
you can see I get null value
But the array[,] has objects in it
What am I doing wrong ? Thanks for reading
Answer by Bunny83 · Aug 24, 2017 at 03:11 AM
You have derived your Room class from MonoBehaviour. MonoBehaviour classes are component which can not be created with new. When you create them with new what you get is a fake null object.
For more information see this Unity blog post.
If your room class is a plain data class, you shouldn't derive it from MonoBehaviour. If you want to derive it from MonoBehaviour you have to use AddComponent to create an instance.
You are the best. replace this "public class Room : $$anonymous$$onoBehaviour { by public class Room { Thanks a lot! Smooth and clean
Your answer
![](https://koobas.hobune.stream/wayback/20220612133419im_/https://answers.unity.com/themes/thub/images/avi.jpg)