- Home /
Object is null when it shouldn't be.
So I'm working on something to create an array to store the data for locations you can interact with on a map, and I'm using an object called landmark which houses all relevant data needed when the game is saved and loaded.
The problem is that the object itself is recognized as null, which has made it impossible for me to store in an array (a NullReferenceException pops up every time).
Here's some example code, hopefully someone can figure out whatever mistake I'm making.
//an example of the landmark class
public class landmark : MonoBehaviour {
public int sectorNumber;
public int landmarkID;
public float positionX;
public float positionY;
}
//a test script showing the issue
public class landmarkTest : MonoBehaviour {
landmark[] testArray;
landmark landmarkTest;
void Start()
{
testArray = new landmark[1];
landmarkTest = new landmark();
testArray[0] = landmarkTest;
print(testArray[0]);
}
//when the print command runs, it prints "null" to the console.
//however, when I print testArray, it prints "landmark[]"
}
Note: In case you couldn't tell, I'm a beginner to both C# and Unity so the answer might be blindingly obvious.
I'm a beginner with both Unity and C#, so i'm not sure. But i think with the line "testArray = new landmark[1];" you only create an array, but it doesn't automatically fill it with landmark instances. Try adding "testArray[0] = new landmark();" after that line.
He actually does that. The problem is, like $$anonymous$$Watts said, you must not create a $$anonymous$$onoBehaviour with "new". $$anonymous$$onoBehaviours are "created" with AddComponent or by attaching them inside the editor to a gameobject.
Answer by DavidWatts · Aug 27, 2016 at 09:07 AM
landmark should derive from MonoBehaviour if you only need it to store data. If a class derives from MonoBehaviour it needs to be attached to a game object and created with AddComponent instead of new. so just take out the MonoBehaviour so it reads
public class landmark {