Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 910
Ajna Avatar asked Sep 19 '26 15:09

Ajna


1 Answers

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

like image 141
JRowan Avatar answered Sep 22 '26 08:09

JRowan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!