Screen.width Not Working

Hey everyone,

I’m trying to make a slider bar along the bottom of my screen with a length equal to 1/2 the width of the screen. I have sliders on the left & right of my screen properly functioning as vertical sliders, however the horizontal slider appears in the center of my screen (telling me it is calculating screen.width properly), however, the slider itself is not the proper length (keeps appearing as approximately 1/10 screen.width) and I have no clue why!

Any help would be much appreciated. Here is my code:

using UnityEngine;

using System.Collections;

public class GUI : MonoBehaviour {
	#region Variables
	//Slider Control Values
	public float sliderMin = 0.0f;
	public float sliderMax = 360.0f;
	public float xSliderValue;

	//Slider Layout Variables
	public int horzSliderLength = (Screen.width / 2);
	public int horzSliderWidth = 15;

	//General GUI Layout
	public int screenMargin = 10;
	public int sliderLabelWidth = 40;
	public int sliderLabelHeight = 25; 

void OnGUI ()
	#region Sliders
		//X-axis Slider (bottom middle of screen)
		xSliderValue = GUI.HorizontalSlider(new Rect((Screen.width / 2) - (horzSliderLength / 2), (Screen.height - ((horzSliderWidth / 2) + screenMargin + sliderLabelHeight)), horzSliderLength, horzSliderWidth), xSliderValue, sliderMin, sliderMax);  


Your horzSliderLength is currently a public variable, which means that its value will be being set by whatever is assigned in the inspector, overwriting the (Screen.width / 2) you’ve initialised in code.

The solution is simple - make it a private variable.

private int horzSliderLength = (Screen.width / 2);

Change this to private:

private int horzSliderLength = (Screen.width / 2);

and see what you get.