2012-03-06 56 views
0

我很新的编程/ Unity,并试图找出如何使用OnGUI水平滑块。 我有三个滑块范围0-100,当用户移动滑块时,想要一个名为pointsLeft的值增加/减少。另外三个滑块的总价值不能超过100.如果有人可以帮助新手,我会非常感激!查看代码以获取更多详细信Unity3D水平滑块的问题

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 

} 

}

回答

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); 
} 
+0

谢谢,这解决了我的问题!必须使用(int)Mathf.Round(newSliderA)对浮点数进行类型转换,因为移动多个滑块时我无法将pointsLeft降到零 – zirth 2012-03-09 17:23:22