/*

* Created December 2013 by Chris Ellis.

* Free for use and modification in all projects.

* No guarantees are made for this script.

*/

using UnityEngine ;

using System.Collections ;

public class Slider : MonoBehaviour {

//Used to save the slider value to PlayerPrefs.

//If this is not unique it will cause problems.

public string sliderValueName ;

//The slider thumb object.

public Transform target ;

//Set this to the position of the lowest point the slider can move.

public float min ;

//Set this to the position of the highest point the slider can move.

public float max ;

//Is your slider going left/right, or up/down.

public bool isHorizontal = true ;

//The camera that looks at the slider.

Camera UICamera ;

//Used to see if you're still trying to drag the slider.

bool mouseDown = false ;

//This is the normalized value of the slider bar. Returns between a 0-1.

public float value = 0 ;

void Awake ( ) {

//By default the target it set to the GameObject holding the script, if you haven't set it.

if ( target == null )

target = transform ;

//If you havet set a camera, the Main Camera is used.

if ( UICamera == null )

UICamera = Camera . main ;

//Load saved value.

if ( PlayerPrefs . HasKey ( sliderValueName ) )

{

value = PlayerPrefs . GetFloat ( sliderValueName ) ;

Vector3 pos = target . position ;

if ( isHorizontal )

{

pos . x = value ;

}

else

{

pos . y = value ;

}

target . position = pos ;

}

//Or set the value, if we don't have a save yet.

else

{

if ( isHorizontal )

value = Mathf . InverseLerp ( min, max, target . position . x ) ;

else

value = Mathf . InverseLerp ( min, max, target . position . y ) ;

}

}

void OnMouseDown ( ) {

mouseDown = true ;

StartCoroutine ( MoveSlider ( ) ) ;

}

void OnMouseUp ( ) {

mouseDown = false ;

}

IEnumerator MoveSlider ( ) {

while ( mouseDown )

{

float sliderPos = 0 ;

//We have to convert from the mouse position to the world's position.

if ( isHorizontal )

sliderPos = UICamera . ScreenToWorldPoint ( Input . mousePosition ) . x ;

else

sliderPos = sliderPos = UICamera . ScreenToWorldPoint ( Input . mousePosition ) . y ;

//Never let it go beyond min/max.

if ( sliderPos > max )

sliderPos = max ;

else if ( sliderPos < min )

sliderPos = min ;

Vector3 pos = target . position ;

//This is where the position is set.

if ( isHorizontal )

pos . x = sliderPos ;

else

pos . y = sliderPos ;

target . position = pos ;

//Get the normalized value.

if ( isHorizontal )

value = Mathf . InverseLerp ( min, max, target . position . x ) ;

else

value = Mathf . InverseLerp ( min, max, target . position . y ) ;

//Save

PlayerPrefs . SetFloat ( sliderValueName, value ) ;

yield return null ;

}

}