Question

Hey everyone i am trying to make an inventory list in C# for unity but i run into an array error when i pickup my item, I cant figure out why i wondered if someone could help. I have searched everywhere for some tips but not come across any the error is :-

ArgumentException: Destination array was not long enough. Check destIndex and length, and the array's lower bounds

As an edit iv attached the full code

code attached below :-

using UnityEngine;
using System.Collections;



[AddComponentMenu ("Inventory/Inventory")]
public class Inventory : MonoBehaviour {
//This is the central piece of the Inventory System.

public Transform[] Contents; //The content of the Inventory
public int MaxContent = 12; //The maximum number of items the Player can carry.

bool DebugMode = true; //If this is turned on the Inventory script will output the base of what it's doing to the Console window.

private InventoryDisplay playersInvDisplay; //Keep track of the InventoryDisplay script.

public Transform itemHolderObject; //The object the unactive items are going to be parented to. In most cases this is going to be the Inventory object itself.



//Handle components and assign the itemHolderObject.
void Awake (){
    itemHolderObject = gameObject.transform;

    playersInvDisplay = GetComponent<InventoryDisplay>();
    if (playersInvDisplay == null)
    {
        Debug.LogError("No Inventory Display script was found on " + transform.name + " but an Inventory script was.");
        Debug.LogError("Unless a Inventory Display script is added the Inventory won't show. Add it to the same gameobject as the Inventory for maximum performance");
    }
}

//Add an item to the inventory.
public void AddItem ( Transform Item  ){
    ArrayList newContents = new ArrayList();
    //FIXME_VAR_TYPE newContents= new Array(Contents);
    newContents.Add(Item);
    //Contents=newContents.ToBuiltin(Transform); //Array to unity builtin array
    newContents.CopyTo(Contents); //Array to unity builtin array
    System.Array.Resize(ref Contents, 1);
    if (DebugMode)
    {
        Debug.Log(Item.name+" has been added to inventroy");
    }

    //Tell the InventoryDisplay to update the list.
    if (playersInvDisplay != null)
    {
        playersInvDisplay.UpdateInventoryList();
    }
}

//Removed an item from the inventory (IT DOESN'T DROP IT).
public void RemoveItem ( Transform Item  ){
        ArrayList newContents = new ArrayList();
    //FIXME_VAR_TYPE newContents=new Array(Contents); //!!!!//
    int index = 0;
    bool shouldend = false;
    foreach(Transform i in newContents) //Loop through the Items in the Inventory:
    {
        if(i == Item) //When a match is found, remove the Item.
        {
            newContents.RemoveAt(index);
            shouldend=true;
            //No need to continue running through the loop since we found our item.
        }
        index++;

        if(shouldend) //Exit the loop
        {
            //Contents=newContents.ToBuiltin(Transform); //!!!!//
            Contents=newContents.ToArray(typeof (Transform)) as Transform[];
            if (DebugMode)
            {
                Debug.Log(Item.name+" has been removed from inventroy");
            }
            if (playersInvDisplay != null)
            {
                playersInvDisplay.UpdateInventoryList();
            }
            return;
        }
    }
}

//Dropping an Item from the Inventory
public void DropItem (Item item){
    gameObject.SendMessage ("PlayDropItemSound", SendMessageOptions.DontRequireReceiver); //Play sound

    bool makeDuplicate = false;
    if (item.stack == 1) //Drop item
    {
        RemoveItem(item.transform);
    }
    else //Drop from stack
    {
        item.stack -= 1;
        makeDuplicate = true;
    }

    item.DropMeFromThePlayer(makeDuplicate); //Calling the drop function + telling it if the object is stacked or not.

    if (DebugMode)
    {
        Debug.Log(item.name + " has been dropped");
    }
}

//This will tell you everything that is in the inventory.
void DebugInfo (){
        Debug.Log("Inventory Debug - Contents");
    int items=0;
    foreach(Transform i in Contents){
        items++;
        Debug.Log(i.name);
    }
    Debug.Log("Inventory contains "+items+" Item(s)");
}

//Drawing an 'S' in the scene view on top of the object the Inventory is attached to stay organized.
void OnDrawGizmos (){
    Gizmos.DrawIcon (new Vector3(transform.position.x, transform.position.y + 2.3f, transform.position.z), "InventoryGizmo.png", true);
}
}

Hope someone could help thank you in advance :)

Was it helpful?

Solution

Arrays have a fixed size when they are allocated only complex types that mimic array interaction have auto grow functionality.

Check the capacity of the target array you are copying your original array contents too.

I am not sure what ToBuiltIn method does but it must be creating a new array as a copy of the origin (your data might already be in the array by the way, check it by debugging it) with the capacity set to the total number of items in the array which could be 1 or 0.

Check your variables and debug the code to see the lengths and capacities of you arrays.

UPDATE (From the updated code)

Your Contents array is not initialized when calling the Add Item method.

To make it clear I have rewritten the code you pasted I dont have all the classes you are using so I have not tested or checks it it builds however it will give you an idea of what you can do. Your array management can be simplified if you use generic list.

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



[AddComponentMenu ("Inventory/Inventory")]
public class Inventory : MonoBehaviour {
    //This is the central piece of the Inventory System.

    public List<Transform> Contents; //The content of the Inventory
    public int MaxContent = 12; //The maximum number of items the Player can carry.

    bool DebugMode = true; //If this is turned on the Inventory script will output the base of what it's doing to the Console window.

    private InventoryDisplay playersInvDisplay; //Keep track of the InventoryDisplay script.

    public Transform itemHolderObject; //The object the unactive items are going to be parented to. In most cases this is going to be the Inventory object itself.

    public Inventory()
    {
        this.Contents = new List<Transform> (MaxContent);
    }

    //Handle components and assign the itemHolderObject.
    void Awake (){
        itemHolderObject = gameObject.transform;

        playersInvDisplay = GetComponent<InventoryDisplay>();
        if (playersInvDisplay == null)
        {
            Debug.LogError("No Inventory Display script was found on " + transform.name + " but an Inventory script was.");
            Debug.LogError("Unless a Inventory Display script is added the Inventory won't show. Add it to the same gameobject as the Inventory for maximum performance");
        }
    }

    //Add an item to the inventory.
    public void AddItem ( Transform Item  ){

        if (this.Contents.Count < this.MaxContent) {
                        Contents.Add (Item);

                        if (DebugMode) {
                                Debug.Log (Item.name + " has been added to inventroy");
                        }

                        //Tell the InventoryDisplay to update the list.
                        if (playersInvDisplay != null) {
                                playersInvDisplay.UpdateInventoryList ();
                        }
                } else {
                    // show message that inventory is full
                }
    }

    //Removed an item from the inventory (IT DOESN'T DROP IT).
    public void RemoveItem ( Transform Item  ){
        if (this.Contents.Remove (Item)) {
                        if (DebugMode) {
                                Debug.Log (Item.name + " has been removed from inventroy");
                        }
                        if (playersInvDisplay != null) {
                                playersInvDisplay.UpdateInventoryList ();
                        }
                        return;
                } else {
                    // Item is not in inventory
                }
    }

    //Dropping an Item from the Inventory
    public void DropItem (Item item){
        gameObject.SendMessage ("PlayDropItemSound", SendMessageOptions.DontRequireReceiver); //Play sound

        bool makeDuplicate = false;
        if (item.stack == 1) //Drop item
        {
            RemoveItem(item.transform);
        }
        else //Drop from stack
        {
            item.stack -= 1;
            makeDuplicate = true;
        }

        item.DropMeFromThePlayer(makeDuplicate); //Calling the drop function + telling it if the object is stacked or not.

        if (DebugMode)
        {
            Debug.Log(item.name + " has been dropped");
        }
    }

    //This will tell you everything that is in the inventory.
    void DebugInfo (){
        Debug.Log("Inventory Debug - Contents");
        int items=0;
        foreach(Transform i in Contents){
            items++;
            Debug.Log(i.name);
        }
        Debug.Log("Inventory contains "+items+" Item(s)");
    }

    //Drawing an 'S' in the scene view on top of the object the Inventory is attached to stay organized.
    void OnDrawGizmos (){
        Gizmos.DrawIcon (new Vector3(transform.position.x, transform.position.y + 2.3f, transform.position.z), "InventoryGizmo.png", true);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top