- Home /
NullReferenceException using Matrix4x4?
I'm having a error with Matrix4x4, I use this code for automatic GUI position correction on different aspect changes:
private var scale : Vector3;
function OnGUI (){
var scale : Vector3;
scale.x = Screen.width/originalWidth; // calculate hor scale
scale.y = Screen.height/originalHeight; // calculate vert scale
scale.z = 1;
var svMat = GUI.matrix; // save current matrix
GUI.matrix = Matrix4x4.TRS(Vector3(0,0,0), Quaternion.identity, scale); // substitute matrix - only scale is altered from standard
var BulletsGUI = Bullets;
var MagGUI = Clip;
var BulletsW : String = "Ammo:";
var BSlash : String = "/";
GUI.skin = guiSkin;
GUI.Label( Rect (25, 40, 800, 600), BulletsW.ToString());
GUI.Label( Rect (85, 40, 800, 600), BulletsGUI.ToString());
GUI.skin = guiSkinSmall;
GUI.Label( Rect (100, 40, 800, 600), BSlash.ToString());
GUI.Label( Rect (115, 40, 800, 600), MagGUI.ToString());
//GUI.Label( Rect (x, y, ?, ?), name.ToString());
GUI.matrix = svMat; // restore matrix
}
But then I get this error: NullReferenceException: Object reference not set to an instance of an object UnityEngine.GUI.set_matrix(Stuff)
The error points here:
GUI.matrix = Matrix4x4.TRS(Vector3(0,0,0), Quaternion.identity, scale); // substitute matrix - only scale is altered from standard
Any help?
Answer by Eric5h5 · Aug 27, 2012 at 04:05 AM
You're probably using integer division with scale.x and scale.y, which is not what you want, since those are probably becoming 0, which isn't a valid number to use for the scale in this function. (Also, just so you know, you don't need to use ToString with variables that are already strings.)
So how would I go about fixing that? $$anonymous$$inda stuck.
You mean the integer division? Just don't use integers for at least one of the variables involved in the division.
I fixed it, a real stupid coding mistake by me. used OnGUI(); in my update functions, caused the error. Forgot to take all those out.
Answer by DaveA · Aug 27, 2012 at 03:44 AM
try 'new'
Matrix4x4.TRS(new Vector3(0,0,0), Quater
or better yet
Matrix4x4.TRS(Vector3.zero, Quater
Unityscript doesn't need "new"; it's implicit. Even if it did, that's not the error message you'd get.
Your answer
![](https://koobas.hobune.stream/wayback/20220613080229im_/https://answers.unity.com/themes/thub/images/avi.jpg)