Skip to content

Instantly share code, notes, and snippets.

@aberloni
Last active November 10, 2016 13:45
Show Gist options
  • Save aberloni/87bfa516aa4d28fb2d12 to your computer and use it in GitHub Desktop.
Save aberloni/87bfa516aa4d28fb2d12 to your computer and use it in GitHub Desktop.
Unity crosshair
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class MouseCrosshair : MonoBehaviour {
protected int cursorState = 0; // index of states[] to draw on screen
protected int cursorSizeX = 16;
protected int cursorSizeY = 16;
Rect cursorInfo;
public Texture2D[] states;
bool draw = true;
void Awake(){
//default loading
if(states.Length <= 0){
List<Texture2D> ts = new List<Texture2D>();
Texture2D t;
t = (Texture2D)Resources.Load("Textures/GUI/cursor_normal");
if(t != null) ts.Add(t);
t = (Texture2D)Resources.Load("Textures/GUI/cursor_action");
if(t != null) ts.Add(t);
states = ts.ToArray();
}
if(states.Length > 0){
cursorSizeX = states[0].width;
cursorSizeY = states[0].height;
}
cursorInfo = new Rect(0f,0f,cursorSizeX,cursorSizeY);
}
void Start(){
cursorState = 0;
event_resizeScreen();
}
public void toggle(bool flag){
draw = flag;
}
/* to call when screen switch size */
public void event_resizeScreen(){
int w = (Mathf.CeilToInt (Camera.main.pixelWidth * 0.5f) - Mathf.CeilToInt(cursorSizeX * 0.5f));
int h = (Mathf.CeilToInt (Camera.main.pixelHeight * 0.5f) - Mathf.CeilToInt(cursorSizeY * 0.5f));
cursorInfo.x = w;
cursorInfo.y = h;
//Debug.Log (cursorInfo);
}
/* draw crosshair on screen */
void OnGUI(){
if(!draw) return;
if(states.Length <= 0) return;
GUI.DrawTexture(cursorInfo,states[cursorState]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment