Unity Slider to Object Rotation Script Tutorial



In this blog post I will share a handy and yet very simple script to help you using Unity Slider UI to rotate an object, such as camera or any object, by changing the value of your slider in Unity Canvas.

This script also has clamping and limiting feature of how much angle the object (for example a camera) should rotate when you change the slider value.

Here is the script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class SliderToRotation : MonoBehaviour
{
	
	public Slider mySlider;
	
	public float xLimit = 45f;
	public float yLimit = 45f;
	public float zLimit = 45f;
	
	public bool xRot;
	public bool yRot;
	public bool zRot;
	
    // Start is called before the first frame update
    void Start()
    {
        mySlider.onValueChanged.AddListener(delegate{
			RotateMe();
		});
    }
	
	public void RotateMe(){
		if(xRot)
			transform.localEulerAngles = new Vector3(mySlider.value * xLimit, transform.localEulerAngles.y, transform.localEulerAngles.z);
		if(yRot)
			transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, mySlider.value * yLimit, transform.localEulerAngles.z);
		if(zRot)
			transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, transform.localEulerAngles.y, mySlider.value * zLimit);
	}
	
}

And how to use it? Here is the way: First, make a Unity slider on your UI canvas, then make an object, or just use your default Unity camera on your scene as the rotate-able object. Make the script exactly named “SliderToRotation.cs”, open it, copy the code above, paste it on your file (delete default code on your file and replace with this new one), then save it.

Take a look at your scene, drag your slider and drop it on slider slot in the script on the object that this script was attached.

Next step is check what kind of rotation do you need, x, y or z. You can also set the limit of rotation angle of the object as you desire.

If you’re not really sure how, watch this video:

loading...

Leave a Reply

Your email address will not be published.