Search code examples
c#nullreferenceexceptiontexture2dmouse-cursor

Can't load mouse cursor texture on C#/Unity


public class Cursor : MonoBehaviour 
{ 
     public Texture2D cursor; 
     public int cursorSizeX = 16; // default 
     public int cursorSizeY = 16; // default 

// Use this for initialization 
void Start () 
{ 
     Object temp = Resources.Load("Textures/CR_Cursor (Custom)"); 

     if (temp == null) 
     Debug.Log("Load Object Fail"); 

     cursor = (Texture2D)Resources.Load("Textures/CR_Cursor (Custom)"); 

     if (cursor == null) 
     Debug.Log("Load Cursor Fail"); 

     Screen.showCursor = false; 
} 

// Update is called once per frame 
void Update () 
{ 
     GUI.DrawTexture(new Rect(Event.current.mousePosition.x - cursorSizeX / 2,      Event.current.mousePosition.y - cursorSizeY / 2, cursorSizeX, cursorSizeY), cursor); 
} 

no matter where I instantiate the cursor im sill getting NullReferenceException: Object reference not set to an instance of an object Cursor.Update (), what I am missing?


Solution

  • you should put this line

    GUI.DrawTexture(new Rect(Event.current.mousePosition.x - cursorSizeX / 2,      Event.current.mousePosition.y - cursorSizeY / 2, cursorSizeX, cursorSizeY), cursor); 
    

    inside of OnGUI() and not in Update

    void OnGUI(){
    
    GUI.DrawTexture(new Rect(Event.current.mousePosition.x - cursorSizeX / 2,      Event.current.mousePosition.y - cursorSizeY / 2, cursorSizeX, cursorSizeY), cursor); 
    
    }
    

    here is a chart concerning the lifecycle of script

    Scripting Lifecycle