Search code examples
c#unity-game-enginepositionnullreferenceexceptionguitexture

NullReferenceException on GUITexture


I want to add GUITexture from script but it's error, then i try insert GUITexture (from GameObject > create other > GUI Texture) then link it to the script but then as i try move the guitexture using pixelInset, there is error said

NullReferenceException UnityEngine.GUITexture.get_pixelInset () (at C:/BuildAgent/work/d3d49558e4d408f4/artifacts/EditorGenerated/Graphics.cs:3254)

Here's the script

public GUITexture temp;

void Start () {
    temp = new GUITexture ();
    temp.pixelInset.Set (100,100,100,100);
}

Solution

  • Problem

    When you call new GUITexture() Unity will just make your temp object null. Then when you try to use it you get a NullReference Exception. Why? Because GUITexture inherits from Behaviour, it is just the way Unity is built.

    Solution

    You are already dragging your reference to the GUItexture via the editor, so all you need is to remove this line.

    // Remove this line
    temp = new GUITexture ();