Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This is a 'stare button' for Google Cardboard apps where you just want to stare at a button over time to select it.
using System;
using System.Reflection;
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.UI;
public class StareButton : MonoBehaviour, IEventSystemHandler, IPointerExitHandler, IPointerEnterHandler, ISelectHandler {
//[RenamedSerializedData("onPress")]
[SerializeField]
private ButtonClickedEvent _OnClick = new ButtonClickedEvent();
public float fillSpeed = 2f;
Text _buttonLabel;
public Image radialFill;
bool _selected;
bool _staring;
void Awake() {
_buttonLabel = this.gameObject.GetComponentInChildren<Text>();
}
// Use this for initialization
void Start () {
Reset ();
}
// Update is called once per frame
void Update () {
if (_staring)
radialFill.fillAmount += (Time.deltaTime * fillSpeed);
else
radialFill.fillAmount -= (Time.deltaTime * fillSpeed);
if (radialFill.fillAmount >= 1f) {
radialFill.fillAmount = 1f;
if (!_selected) { //prevent multiple triggers
_selected = true;
_OnClick.Invoke();
Debug.Log("CLICK!");
}
}
else if (radialFill.fillAmount <= 0f) {
_selected = false;
radialFill.fillAmount = 0f;
}
}
public void StaringAt(bool on) {
_staring = on;
}
public void Reset() {
_staring = false;
_selected = false;
radialFill.fillAmount = 0;
}
public void OnPointerEnter(PointerEventData eventData) {
//do your stuff when highlighted
StaringAt(true);
}
public void OnPointerExit(PointerEventData eventData) {
//do your stuff when not highlighted
StaringAt(false);
}
public void OnSelect(BaseEventData eventData) {
//do your stuff when selected
_OnClick.Invoke();
radialFill.fillAmount = 1f;
_selected = true;
Debug.Log("SELECT?!?!?!!");
}
[Serializable]
public class ButtonClickedEvent : UnityEvent {}
}
@Enumio

This comment has been minimized.

Copy link

Enumio commented Jul 27, 2015

Man this code of yours is awesome. I am no coder and i was able to use your prefab in unity 5.1.
Can you tell me or show me how can i turn thit into a toggle? How to get instead of a OnValueChanged event instead OnClicked?

Cheers :)

@Enumio

This comment has been minimized.

Copy link

Enumio commented Jul 27, 2015

Man this code of yours is awesome. I am no coder and i was able to use your prefab in unity 5.1.
Can you tell me or show me how can i turn thit into a toggle? How to get a OnValueChanged event instead OnClicked?

Cheers :)

@ludo6577

This comment has been minimized.

Copy link

ludo6577 commented Nov 6, 2015

Nice code !
Thank you 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.