How to change value of a null element in an array?
So i had a custom class and an array of that class in my script. I want to change a value of a null element but unity keep having nullreferenceexception error. How to fix this?
Answer by streeetwalker · Apr 03, 2020 at 07:06 AM
Hi @Long2904, show us the relevant code. In my understanding, you will not get a null reference error on setting a null array element a value, or even setting it to null, only on if you to read one as some expected value type.
// say you define class MyObject with a string ID and constructor
MyObject[] myObjects = new MyObject[]; // all are null from start
myObjects[0] = new MyObject( "BabaYaga"); // will not throw null error
myObjects[0] = null; // will not throw null error
Debug.Log( myObjects[0].ID ); // *** will throw null error
myObjects[0].ID = "BabaYaga" // *** will throw null error
if( myObjects[0] == null ) // will not throw null error
if( myObjects[0].ID != "BabaYaga" || myObjects[0] == null ) // *** will throw null error
if( myObjects[0] == null || myObjects[0].ID != "BabaYaga" ) // will not throw null error
Yeah my code is like: myObjects[0].ID = something so it will throw null error. I have just fixed this by initialized the element first: myObjects[0] = new myObjects(). Thank you for your reply.
Your answer
Follow this Question
Related Questions
NullReferenceException Help please :> 1 Answer
ObjectPool for Class Instances using Built-In Array 1 Answer
Object reference not set to an instance of an object + array of positions 1 Answer
C# Multidimensional arrays 0 Answers
Getting the element that has the same element number on another list ? 2 Answers