【问题标题】:Problems with Unity3D Horizontal SliderUnity3D 水平滑块的问题
【发布时间】:2012-03-07 10:05:55
【问题描述】:

我对编程/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

}

}

【问题讨论】:

    标签: slider unity3d


    【解决方案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);
    }
    

    【讨论】:

    • 谢谢,这解决了我的问题!必须使用 (int)Mathf.Round(newSliderA) 对浮点数进行类型转换,因为在移动多个滑块时我无法将 pointsLeft 降为零
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-27
    相关资源
    最近更新 更多