我如何才能在unity2d中消除这个讨厌的错误?

问题描述

您好,我正在用统一C#编写代码,并且我的库存广告位脚本一直收到此错误,而且我不知道如何解决它!如果可以的话,谢谢您!

错误在这里

ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of 
the collection.
Parameter name: index
System.ThrowHelper.ThrowArgumentOutOfRangeException (System.ExceptionArgument argument,System.ExceptionResource resource) (at <fb001e01371b4adca20013e0ac763896>:0)
System.ThrowHelper.ThrowArgumentOutOfRangeException () (at <fb001e01371b4adca20013e0ac763896>:0)
System.Collections.Generic.List`1[T].get_Item (system.int32 index) (at 
<fb001e01371b4adca20013e0ac763896>:0)
InventorySlotHandeler.Update () (at Assets/Scripts/InventorySlotHandeler.cs:24)

以及此错误针对的脚本

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;

public class InventorySlotHandeler : MonoBehavIoUr
{
public SpriteRenderer SlotSprite;
public string SlotName;
public int slotnumber;
public GameObject player;
public TextMeshProUGUI SlotNameText;
// Start is called before the first frame update
void Start()
{
   
}

// Update is called once per frame
   void Update()
  {
    SlotSprite.sprite = player.GetComponent<PlayerScript>().Inventory[slotnumber].ItemSprite;

    SlotName = player.GetComponent<PlayerScript>().Inventory[slotnumber].ItemName;

    SlotNameText.text = SlotName;

    
  }
}

解决方法

您必须在脚本中执行一些错误检查:

void Update()
{
    if(slotNumber < 0)
        return;
    var inventory = player.GetComponent<PlayerScript>().Inventory;
    // I'm assuming inventory.Count gives you the number of item in your collection.
    // If it's an array you have to use inventory.Length here.
    if(inventory == null || slotNumber >= inventory.Count)
        return;

    SlotSprite.sprite = player.GetComponent<PlayerScript().Inventory[slotnumber].ItemSprite;

    SlotName = player.GetComponent<PlayerScript>().Inventory[slotnumber].ItemName;

    SlotNameText.text = SlotName;
}

尽管有趣的问题是无效索引来自何处。您应该先进行一些验证,然后再进行设置以及广告资源尺寸的更改。

此外,您不应该在每一帧都调用GetComponent<T>()。只需为库存添加一个成员变量,然后将其存储在void Awake()方法中即可。

,

首先,您没有在Int插槽号中分配任何数字。您正在Update中运行此程序,因此它会立即运行,从而出现数组边界错误。