- Home /
InitializeOnLoad = System.NullReferenceException
using UnityEngine;
using UnityEditor;
[InitializeOnLoad]
public class VersionUpdater
{
static VersionUpdater()
{
GameObject.FindGameObjectWithTag("Version").GetComponent<TextMesh>().text = "v"+PlayerSettings.bundleVersion;
}
}
Gives this ugly error:
System.NullReferenceException: at (wrapper managed-to-native) UnityEngine.GameObject:GetComponent (System.Type) at UnityEngine.GameObject.GetComponent[TextMesh] () [0x00000] in :0 at VersionUpdater..cctor () [0x0000b] in /Users/Luke/Desktop/Unity/Unity Projects/Now You're Dead/Now You're Dead/Assets/Editor/VersionUpdater.cs:11 UnityEditor.EditorAssemblies:SetLoadedEditorAssemblies(Assembly[])
I think it's cause I'm trying to code in C# and I never have tried that before >_<
Answer by Aberro · Jan 06, 2014 at 06:23 AM
It's because you are trying to get an object which doesn't exists at that moment. [InitializeOnLoad] invokes static cctor as soon as possible, i.e. in most cases when Unity starts and no game objects created.
Yeah, you're right. I had to do it on editor play ins$$anonymous$$d… slight shame but I don't know if there was a way around it.