Hello, I am trying to read an enum value from the class TileType that is a object in the class TileInfo. I just cant get this to work, I am getting an error saying “NullReferenceException: Object reference not set to an instance of an object.”
In TileInfo.Start(), you have a suspicious line “MapInfo _MapInfo = new MapInfo();”. If MapInfo inherits from MonoBehaviour, which it looks like it does because you’re using GetComponent<MapInfo>(), then this is invalid. You’re not supposed to new components; you must use AddComponent<>() on a GameObject. I can’t remember what Unity does when you try to new a component, but I wouldn’t be surprised if it throws an exception (check the console for earlier errors), and the rest of your Start() method never executes. You don’t even need that assignment anyway because you re-assign it two lines further down.
Regardless, you have more problems in that area, because _MapInfo in that method is just a local variable, which is temporarily hiding the class field with the same name. So when you assign it a couple lines below, you’re assigning the local variable, not the class field. The class field keeps its old value (either null, or whatever you assigned in the editor). If you did assign it in the editor, then you have no need to find it by name and assign it anyway; it already has a usable value. It’s not an immediately problem because it doesn’t look like you use that particular _MapInfo anywhere else, so the fact that the assignment is to a local variable doesn’t yet have any bad effects. But it will as soon as you start accessing TileInfo._MapInfo outside of Start().
Finally, although it might be legal C# syntax, it’s awkward to give a variable the same name as a class. In your case you have a local variable called “MapInfo” when there’s also a type called “MapInfo”. Common practice is to make the first letter of a parameter or local variable lowercase (such as “mapInfo”), to distinguish it from type names which usually start with an uppercase letter.
for (int i = 0; i < mapInfo.mapSide; i++)
{
for (int j = 0; j < mapInfo.mapSide; j++)
{
DataTile[i, j] = new TileType(); /////////////////////////////// This is the line were the code stops
DataTile[i, j].InitializeTileType();
}
}
Is that the correct way to make 2D array of objects?
Error is “NullReferenceException: A null value was found where an object instance was required”