我是编程/ Unity的新手,并试图弄清楚如何使用OnGUI水平滑块。 我有三个滑块范围0-100,并且当用户移动滑块时,想要一个名为pointsLeft的值增加/减少。此外,三个滑块的总价值不能超过100.如果有人可以帮助新手,我真的很感激!有关更多详细信息,请参阅代码。
using UnityEngine;
using System.Collections;
public class Slider : MonoBehaviour {
public float sliderA = 0.0f;
public float sliderB = 0.0f;
public float sliderC = 0.0f;
public float startingPoints = 100f;
public float pointsLeft;
void Start() {
pointsLeft = startingPoints;
}
void OnGUI () {
GUI.Label(new Rect(250, 10, 100, 25), "Points Left: " + pointsLeft.ToString());
GUI.Label (new Rect (25, 25, 100, 30), "Strength: " + sliderA.ToString());
sliderA = GUI.HorizontalSlider (new Rect (25, 50, 500, 30), (int)sliderA, 0.0f, 100.0f);
GUI.Label (new Rect (25, 75, 100, 30), "Agility: " + sliderB.ToString());
sliderB = GUI.HorizontalSlider (new Rect (25, 100, 500, 30), (int)sliderB, 0.0f, 100.0f);
GUI.Label (new Rect (25, 125, 100, 30), "Intelligence: " + sliderC.ToString());
sliderC = GUI.HorizontalSlider (new Rect (25, 150, 500, 30), (int)sliderC, 0.0f, 100.0f);
/*if(sliderA < pointsLeft) {
pointsLeft = (int)pointsLeft - sliderA; //this is not doing the magic
}
*/
//decrease pointsLeft when the slider increases or increase pointsLeft if slider decreases
//store the value from each slider when all points are spent and the user pressess a button
}
}
答案 0 :(得分:1)
在确定滑块移动有效之前,请勿更新滑块值。
下面,此代码将新的滑块值存储在临时变量中,如果该值低于允许的点,则允许更改:
public float pointsMax = 100.0f;
public float sliderMax = 100.0f;
public float pointsLeft;
void OnGUI () {
// allow sliders to update based on user interaction
float newSliderA = GUI.HorizontalSlider(... (int)sliderA, 0.0f, sliderMax);
float newSliderB = GUI.HorizontalSlider(... (int)sliderB, 0.0f, sliderMax);
float newSliderC = GUI.HorizontalSlider(... (int)sliderC, 0.0f, sliderMax);
// only change the sliders if we have points left
if ((newSliderA + newSliderB + newSliderC) < pointsMax) {
// Update the current values for the sliders to use next time
sliderA = newSliderA;
sliderB = newSliderB;
sliderC = newSliderC;
}
// record the new points count
pointsLeft = pointsMax - (sliderA + sliderB + sliderC);
}