Hello Unity Engine community, recently, I’ve been doing multiple tests on the extent of what the unity GUI can do, and, I started doing experiments and searches as to how to set GUI elements to solid colors. During these, I found a glaring issue with script made Texture2D’s.
The current code I was using to create this error is quite simple:
Texture2D tex = new Texture2D(1,1);
void OnGUI()
{
Debug.Log(tex.width);
}
I, for the life of me, can not quite figure out why this code is failing. It’s such a simple quick snippet of code, that it’s almost amazing that it could fail like this. More than that, is that it actually produces errors both while the script attempts to run, and when execution is halted.
Errors produced by this snippet are as follows:
NullReferenceException
UnityEngine.Texture.get_width () (at C:/BuildAgent/work/7535de4ca26c26ac/Runtime/ExportGenerated/Editor/Graphics.cs:682)
Internal_Create can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
ArgumentException: Internal_Create can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
UnityEngine.Texture2D..ctor (Int32 width, Int32 height) (at C:/BuildAgent/work/7535de4ca26c26ac/Runtime/ExportGenerated/Editor/Graphics.cs:814)
I honestly don’t know what to say. Is this simply a bug in Unity 4.1, or am I making a simple mistake here? Any help is very appreciated.
Also, take note, moving this from the OnGUI function to the Start function as it tells you to do still produces the same error. Here is the code I used to create that error:
Texture2D tex = new Texture2D(1,1);
void Start()
{
Debug.Log(tex.width);
}