我正在使用TextMeshPro的一個輸入欄位。我正在搜索一個輸入字符,然后用另一個字符替換它。我可以用Update()函式輕松地做到這一點,但呼叫的費用相當高。我如何創建一個事件來檢查一個文本欄位是否已被更改?
編輯:根據用戶的回答,我確實嘗試使用onValueChanged,但我收到了一個例外錯誤 - StackOverflowException。請求的操作引起了堆疊溢位。
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class TextChangeEvent : MonoBehaviour {
public TMP_InputField textInput_;
public void Start(){
textInput_.onValueChanged.AddListener(delegate { myTextChanged(); })。
}
public void myTextChanged() {
textInput_.text = textInput_.text.Replace("World"/span>, "Unity"/span>)。
}
}
uj5u.com熱心網友回復:
試試這個來自Unity檔案。OnValueChanged
編輯1。
我研究了一個問題,我確實讀了這個帖子。在Unity中移除只有一個引數的監聽器。
問題是,當你檢測到一個變化時,你正在改變這個值,但你所做的這個變化觸發了無限大的回圈...。因此,解決方案是在你改變值時洗掉監聽器,然后你需要再次添加監聽器。
uj5u.com熱心網友回復:
那么你在做什么呢
textInput_.text = textInput_.text.Replace("World"/span>, "Unity"/span>) 。
正在改變文本
→ 因此,再次呼叫事件onValueChanged。
→ 再次呼叫myTextChanged。
→ 它再次改變了文本
→ 因此,再次呼叫事件onValueChanged。
→ .......... 無休止的回圈
你可以嘗試做的是
public TMP_InputField textInput_;
public void Start()
{
//onValueChanged期望一個`void(string)`,所以不要添加一個匿名的。
//delegate,你永遠無法再次洗掉,而是要確保你的方法實作了。
//正確的簽名并直接添加它。
textInput_.onValueChanged.AddListener(myTextChanged)。
}
//我們需要這個簽名,以便直接添加和洗掉這個方法作為。
//一個onValueChanged事件的監聽器。
public void myTextChanged(span class="hljs-built_in">string newText)
{
//暫時洗掉你的回呼。
textInput_.onValueChanged.RemoveListener(myTextChanged)。
//改變文本而不被通知。
textInput_.text = newText.Replace("World"/span>, "Unity"/span>)。
//再次附加回呼。
textInput_.onValueChanged.AddListener(myTextChanged)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/312441.html
標籤:
上一篇:統一,安卓資料檔案夾為空
下一篇:Mouse.current.WarpCursorPosition似乎只在向左或向上移動(而不是向右或向下)時才能正常作業?
