如下:
void Start()
{
inputFloat.contentType = InputField.ContentType.DecimalNumber;
inputFloat.onValueChanged.AddListener(OnFloatChanged);
}
float _val = 0;
public float val { get { return _val; } }
string strPre = "";
void OnFloatChanged(string strVal)
{
int indexOfDot = strVal.IndexOf('.');
if (indexOfDot + 4 < strVal.Length)
{
strVal = strPre;
}
else
{
strPre = strVal;
}
inputFloat.SetTextWithoutNotify(strVal);
if (float.TryParse(strVal, out float v))
{
_val = Mathf.Clamp(v, min, max);
onSetFloat?.Invoke(_val);
}
}
下面是最近改良的写法,感觉效果更好一些,思路也更清晰一些。
void Start()
{
inputFloat.contentType = InputField.ContentType.DecimalNumber;
inputFloat.onValueChanged.AddListener(OnFloatChanged);
}
float _val = 0;
public float val { get { return _val; } }
void OnFloatChanged(string strVal)
{
if (float.TryParse(strVal, out float v))
{
if (v > max)
{
inputFloat.text = max.ToString();
return;
}
if (v < min)
{
inputFloat.text = min.ToString();
return;
}
_val = v;
onSetFloat?.Invoke(_val);
int dotIndex = strVal.IndexOf('.');
if (dotIndex >= 0)
{
int lenMax = dotIndex + 4;
if (strVal.Length > lenMax)
{
strVal = strVal.Substring(0, lenMax);
inputFloat.SetTextWithoutNotify(strVal);
}
}
}
}