Skip to content

Instantly share code, notes, and snippets.

@codehoose
Created May 22, 2018 20:34
Show Gist options
  • Save codehoose/4bbf40464918269c11e77ad6019be386 to your computer and use it in GitHub Desktop.
Save codehoose/4bbf40464918269c11e77ad6019be386 to your computer and use it in GitHub Desktop.
Example class demonstrating how you can use the slider as a menu.
Add SliderMenu to the same game object as the Slider. Add an event handler (use dynamic) to the onIndexSelected property.
using System;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
[RequireComponent(typeof(Slider))]
public class SliderMenu : MonoBehaviour
{
Slider _slider;
int _index = 0;
Func<bool> _buttonActivated;
public bool reactOnButtonDown;
public string buttonName = "Fire1";
public SliderMenuEvent onIndexSelected;
void Awake()
{
_slider = GetComponent<Slider>();
EventSystem.current.SetSelectedGameObject(gameObject);
_slider.onValueChanged.AddListener(f => _index = (int)f);
_buttonActivated = () => reactOnButtonDown ? Input.GetButtonDown(buttonName) :
Input.GetButtonUp(buttonName);
}
void Update()
{
if (_buttonActivated())
{
onIndexSelected.Invoke(_index);
}
}
}
[Serializable]
public class SliderMenuEvent : UnityEvent<int>
{
}
using UnityEngine;
public class WriteToConsole : MonoBehaviour
{
public void WriteValueToConsole(int index)
{
print(index);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment