Hi im attempting to move the cube up and down at the same position as the slider so when the slider is at the bottom of the screen so is the cube and so on
here is what ive tried currently but it does not move enough id like to be able to times the value but as its a transform i cant seem to do it does anyone have any sugestions?
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class CharacterMovement : MonoBehaviour {
public Slider slider;
float sliderValue;
void Update()
{
sliderValue = slider.value;
Vector3 temp = transform.position;
temp.y = sliderValue;
transform.position = temp;
}
// Update is called once per frame
public void OnhSliderChanged()
{
Debug.Log (slider.value);
}
}
The slider value only goes from 0 to 1, while the position of a transform can vary a bit more than that. It’s also not guarantied how many units will be within the cameras viewport. I guess you could do something like this:
float distance = Vector3.Distance(Camera.main.transform.position, transform.position);
Vector3 point = Camera.main.ViewportToWorldPoint(new Vector3(0, sliderValue, distance));
Vector3 temp = transform.position;
temp.y = point.y;
transform.position = temp;
Anyways, I haven’t tested the code, so do let me know if it doesn’t work or compile. You can also check the documentation on turning a viewport point into a world point Unity - Scripting API: Camera.ViewportToWorldPoint
You can have the slider to have the int values that you need by checking the property “Whole numbers”, that way your slider can manage int values as slider value. Once you set this, you may also want to set the Slider min value and Slider Max Value according to the desired range. Those values are also dynamic, in case you want to change the range in run time, you can also do that.
So, having your slider already managing whole number, you don’t need any extra operation so it may be:
public class CharacterMovement : MonoBehaviour {
public Slider slider;
float sliderValue;
void Update()
{
sliderValue = slider.value;
Vector3 temp = transform.position;
temp.y = sliderValue;
transform.localPosition = temp; //usually I use this instead of transform.Position, since I have nested objects
}
// Update is called once per frame
public void OnhSliderChanged()
{
Debug.Log (slider.value);
}
}
Here’s the whole Slider class Reference for further details: Redirect to... title of new-page
Hope this helps