Why when using array of Renderer i'm getting null reference exception ?

In the top of the script i have:

[SerializeField] public Transform[] m_PropModel;
[SerializeField] public Transform[] m_PropBlur;
private Renderer[] m_PropellorModelRenderer;
private Renderer[] m_PropellorBlurRenderer;
private Renderer test;

Then in Awake()

private void Awake()
        {
            // Set up the reference to the aeroplane controller.
            m_Plane = GetComponent<AeroplaneController>();

            test = m_PropModel[0].GetComponent<Renderer>();
            m_PropellorModelRenderer[0] = m_PropModel[0].GetComponent<Renderer>();
            m_PropellorBlurRenderer[0] = m_PropBlur[0].GetComponent<Renderer>();
            m_PropellorModelRenderer[1] = m_PropModel[1].GetComponent<Renderer>();
            m_PropellorBlurRenderer[1] = m_PropBlur[1].GetComponent<Renderer>();

            m_PropBlur[0].parent = m_PropModel[0];
            m_PropBlur[1].parent = m_PropModel[1];
        }

When i’m using the test variable it will be fine.
But when i’m using the m_PropellorModelRenderer[[0] the m_PropellorModelRenderer[ will be null.
Why when it’s in Array it’s null but when it’s alone single Renderer it’s not null ?
How can i fix it ?

NullReferenceException: Object reference not set to an instance of an object
(wrapper stelemref) object:stelemref (object,intptr,object)

At line 34
Line 34 is:

m_PropellorModelRenderer[0] = m_PropModel[0].GetComponent<Renderer>();

test is not null but m_PropellorModelRenderer[0] is null.

I Attached to Unity and used breakpoint on this line.

You have not initialized the array before you started populating it.

m_PropModelRenderer = new Renderer[m_PropModel.Length];

And the same for any array that is not filled in the inspector.

One additional note: any reason you’re not using a for loop to process the array? Kind of pointless to use an array if you’re not going to loop through it.

2 Likes

If you’re referring to an actual index like you are here, I think you have to first size the array… something like this…

if you’re expecing an array of 2 rows…

private Renderer[] someRendererArray = new Renderer[2];

Edit: @StarManta beat me to it, and his answer is better and better explained.

1 Like