Fields not populated during OnValidate on Editor startup

So my question and script is pretty simple. I get null reference exception. I have some components I need to assign, and before I do that I need to check if there’s particle systems in the array.

public ParticleSystem[] particles;

#if UNITY_EDITOR 
void OnValidate() 
{
	AssignParticleTurrets();
}
#endif

void AssignParticleTurrets()
{
	if(particles.Length < 1) //error on this line
		return;
//the rest of the code
}

Its as simple as that. As you can see I’m running this piece of code only inside editor. Could be why this weird nullexception is happening?

I want to check exactly what it says. Is there anything in the array, and if so, keep going, if not, do nothing. Because after the check, if its not empty, I’m using whats in the array, but it never gets that far, the error is at the very checking line.

Also tried (particles.Length == 0) and other variations doesn’t work. I tried putting #endif down after the method as well, but nothing new. Even tried changing “particles” to something else in case its a keyword.

Does particles actually exist at this point? Checking the length of an array that doesn’t exist / hasn’t been initialised may give this behaviour.

Dunno, works for me, but I didn’t restart the editor. I just slapped this on a game object and it had no problems.

What you could do is check references to the particles field, in case some other script it setting it to null. Also you can return early if it is null (or create a default array).

using UnityEngine;

public class Example : MonoBehaviour
{
    public ParticleSystem[] particles;

    #if UNITY_EDITOR
    void OnValidate()
    {
        AssignParticleTurrets();
    }
    #endif

    void AssignParticleTurrets()
    {
        if (particles == null)
        {
            Debug.LogWarning("particles is null", this);
            return;
        }

        if (particles.Length < 1) //error on this line
            return;
    }
}