[英]Why the compiler gives an error when I'm right-clicking NOT on the UI element
My compiler gives an error ArgumentOutOfRangeException in the file List.cs when I click on the empty space but if I click on the UI elements it's doesn't gives an error.当我单击空白区域时,我的编译器在文件 List.cs 中给出错误 ArgumentOutOfRangeException,但如果我单击 UI 元素,它不会给出错误。 But how it gives an error if I have a check但是,如果我有支票,它是如何出错的
if (results != null)
There is my code :有我的代码:
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);
}
}
}
}
My best guess is that you are checking that results != null, but you are not checking if results actually has any elements in it.我最好的猜测是您正在检查结果!= null,但您没有检查结果中是否确实包含任何元素。 So using results[0] on an empty array results in the ArgumentOutOfRangeException you are seeing.因此,在空数组上使用 results[0] 会导致您看到的 ArgumentOutOfRangeException。
Adding && results.Any()
to the if check should resolve it.将&& 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")
Line 1 initialises results
, so that check on line 3 will never be false.第 1 行初始化results
,因此第 3 行的检查永远不会为假。 Just because results is initialised, doesn't mean it has any entries in it, so line 3 will give an error if there are no results.仅仅因为结果被初始化,并不意味着它有任何条目,所以如果没有结果,第 3 行将给出错误。
As others have pointed out, line 2 should be:正如其他人所指出的,第 2 行应该是:
if(results.Any())
.Any()
is better that .Count > 0
because it implies the intent that 'something is in the list', rather than 'the count is greater than 0'. .Count > 0
.Any()
比.Count > 0
更好,因为它暗示了“某些东西在列表中”的意图,而不是“计数大于 0”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.