Unity3D – Tutorials – UI – Responsive Slider

The Event System check the user input over the Canvas elements.

This feature is avaiable for Unity3D 4.6 or above.

Create Objects

1. Open Unity3D and create:

– MAIN TOP MENU> GameObject> Camera, name it ‘Main Camera’
– MAIN TOP MENU> GameObject> UI> Slider

NOTICE: Canvas will be created inside Layer UI

NOTICE: In the Hierarchy there is:

– Canvas
-> Slider
->> Background
-> Fill Area
->> Fill
-> Handle Slide Area
->> Handle

– EventSystem

Setup Viewports and Tools

2. 3D Viewport select orthographic X View
3. TOP LEFT> TOOLS> Canvas Manipulation icon
4. Game Viewport> 4:3

Canvas Setup

Hierarchy> Canvas> Inspector>

>Canvas
– Render Mode> Screen Space – Overlay
– Pixel Perfect: check

>Canvas Scaler
– Ui Scale Mode: Scale With Screen Size
– Reference Resolution: 800×600
– Screen Match Mode: Match Width or Height

Slider Setup

Hierarchy> Slider> Inspector>

>Rect Transform>
– Pos X=0 Y=0 Z=0
– Width=800 Height=20 (The same of Canvas Scaler> Reference Resolution)
– Anchor Preset Button (the square icon on top left with a target): middle center

Play and try resize the Game Viewport

Event Listener

1. Hierarchy> select Slider> Inspector> Slider (Script)> +>
– Interactible> check (true)
– DRAG AND DROP into empty slot> Main Camera
– ON THE RIGHT rollout> Camera> fieldOfView

2. Slider (Script)> Min Value=1 Max Value=179

Eligible Functions

Functions that return a FLOAT value

Slider as Energy Bar – Graphic Setup

Hierarchy> Canvas> Slider> Background> uncheck, it removes the background OR simple change color to green

Hierarchy> Canvas> Slider> Fill Area> Fill> change color to red

Hierarchy> Canvas> Slider> Handle Slide Area> Handle> uncheck, it removes the handle

Slider as Energy Bar – JS

Slider (Script)> Interactable> uncheck (false)

1. Hierarchy> Slider> Add Component> New Script> EnergyBar.js


#pragma strict

var theSliderComponent : UI.Slider; // ASSIGN IN INSPECTOR!!!

function Awake () {
}

function Start () {
}

function Update () {
theSliderComponent.value = Mathf.MoveTowards (theSliderComponent.value, 100.0f,0.15f);
}

2. Hierarchy DRAG AND DROP Slider over Inspector> EnergyBar.js> var theSliderComponent

3. Play :)