[英]Why the compiler gives an error when I'm right-clicking NOT on the UI element
當我單擊空白區域時,我的編譯器在文件 List.cs 中給出錯誤 ArgumentOutOfRangeException,但如果我單擊 UI 元素,它不會給出錯誤。 但是,如果我有支票,它是如何出錯的
if (results != null)
有我的代碼:
public void Update()
{
if (Input.GetKey(KeyCode.Mouse1))
{
eventData = new PointerEventData(eventSystem);
eventData.position = Input.mousePosition;
List<RaycastResult> results = new List<RaycastResult>();
_raycaster.Raycast(eventData, results);
if (results != null)
{
if (results[0].gameObject.tag == "ItemIcon")
{
if(currentMenu != null)
{
Destroy(currentMenu);
}
currentMenu = Instantiate(SplitMenu, transform);
}
}
}
}
我最好的猜測是您正在檢查結果!= null,但您沒有檢查結果中是否確實包含任何元素。 因此,在空數組上使用 results[0] 會導致您看到的 ArgumentOutOfRangeException。
將&& results.Any()
添加到 if 檢查應該可以解決它。
最好的選擇:我們需要使用results.Count != 0
而不是null
。
1. List<RaycastResult> results = new List<RaycastResult>();
_raycaster.Raycast(eventData, results);
2. if (results != null)
{
3. if (results[0].gameObject.tag == "ItemIcon")
第 1 行初始化results
,因此第 3 行的檢查永遠不會為假。 僅僅因為結果被初始化,並不意味着它有任何條目,所以如果沒有結果,第 3 行將給出錯誤。
正如其他人所指出的,第 2 行應該是:
if(results.Any())
.Count > 0
.Any()
比.Count > 0
更好,因為它暗示了“某些東西在列表中”的意圖,而不是“計數大於 0”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.