using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class StatReader : MonoBehaviour
{
public float modifier;
bool isIncrease = false;
void Update()
{
CheckInput();
Reading();
}
void CheckInput()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
Debug.Log("Input received.");
if (isIncrease == false)
{
Slider slider = gameObject.GetComponent<Slider>();
slider.value = modifier * Time.deltaTime;
isIncrease = true;
}
else
{
Slider slider = gameObject.GetComponent<Slider>();
slider.value -= modifier * Time.deltaTime;
isIncrease = false;
}
}
}
void Reading()
{
Slider slider = gameObject.GetComponent<Slider>();
float readingOutputs = slider.value;
if (readingOutputs <= 0f)
{
readingOutputs = 0f;
}
if (readingOutputs >= 100f)
{
readingOutputs = 100f;
}
Debug.Log(Mathf.RoundToInt(readingOutputs));
}
}
從上面的腳本中可以看出,我正在努力實作以下目標:
- 按下滑鼠左鍵后,滑塊開始填充,直到我再次單擊該按鈕。
- 再次單擊它后,滑塊開始耗盡,直到我再次單擊該按鈕。
問題是:
當我單擊滑鼠左鍵時,滑塊將填滿,但只是片刻通知。因此該值增加到 0.000438 或其他值。然后它會自動停止。當我再次單擊時,它會歸零。我自己除錯它已經有一段時間了。似乎 Update() 正在中斷自己。每一幀它都會停下來檢查輸入,這就是為什么增加/減少是這么小的值。
我實際上還有另一個問題:
最初,我使用 FixedUpdate() 而不是 Update()。奇怪的是,當我點擊 play 時,當我向滑鼠左鍵發送垃圾郵件時,程式無法接收所有輸入。一旦我將 FixedUpdate() 更改為 Update(),問題就消失了。問題解決了,但我想知道為什么會這樣。
請幫忙!非常感謝!
uj5u.com熱心網友回復:
Update被稱為每一幀。您Update不會被打斷,而只是在GetKeyDown回傳時做某事true。
那么GetKeyDown是true只在一個單一的框架,當你按下啟動鍵。
然后,您還可以在添加一次值后立即在增加和減少之間切換。
反正你也應該避免呼叫GetComponent中Update和,而存盤和重復使用參考
我寧愿簡單地做類似的事情
// already reference via the Inspector if possible
[SerializeField] private Slider _slider;
// a little helper method you can invoke via the context menu of your component
// allows you to a) already store the reference in the serialized field
// and b) you ca already see whether the reference is actually found as expected
[ContextMenu(nameof(FetchComponents))]
private void FetchComponents()
{
// as a FALLBACK get the reference ONCE
if(!_slider) _slider = GetComponent<Slider>();
}
private void Awake()
{
FetchComponents();
}
void CheckInput()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
// simply invert the direction ONCE on key press
isIncrease = !isIncrease;
}
// increase or decrease depending on the current flag state EVERY FRAME
// Clamp your result value between 0 and 100
var newValue = Mathf.Clamp(_slider.value modifier * Time.deltaTime * (isIncrease ? 1 : -1), 0f, 100f);
// apply the new value EVERY FRAME
// but only if it is actually different (-> hasn reached 0 or 100)
// to avoid unnecessary calls of onValueChanged
if(!Mathf.Approximately(_slider.value, newValue))
{
slider.value = newValue;
}
}
你的另一個問題是FixedUpdate:這是物理例程(通常只應用于與物理相關的事情)。它在固定時基上呼叫(默認情況下通常每 0.02 秒一次)=> 很明顯,GetKeyDown此方法會遺漏您的某些單次輸入,因為Update兩次FixedUpdate呼叫之間可能存在多個幀=>GetKeyDown是真的在沒有FixedUpdate電話的框架中。
=> Thumbrule:在Update. 然后,如果您正在處理物理學,則將此輸入應用于FixedUpdate(同時將其存盤在欄位中)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/403245.html
標籤:
