- Home /
Can't add GameObjects to ArrayList
I am sending information from my item to my inventory. Telling the inventory to add the item. Gives me a null reference exception.
Item.js :
 inventory.AddItem(this as GameObject);    
Inventory.js :
 var items : ArrayList;
 
 function AddItem (item : GameObject) {
          
    items.Add(item.gameObject);  //Error happens here
      
 }
Why are you using an ArrayList if you're only putting one type in it?
the player may want more than 1 item in his/her inventory.
The error is occurring at the line in Inventory.js:
items.Add(item.gameObject);
Still got no idea why.
I'm not asking why you want a collection; I'm asking why you're using an ArrayList. You should only use that if you need to support multiple types.
Answer by Jessy · Feb 21, 2012 at 03:01 PM
this is not a GameObject; its class is derived from MonoBehaviour. You use the correct semantics later on:
 .gameObject
Using the shorthand for this.gameObject works fine:
 inventory.AddItem(gameObject);
However, you should use something other than an ArrayList; a List is probably what you want. Using .gameObject on item is useless; I don't even know why that compiles.
 import System.Collections.Generic;
 
 var items : List.<GameObject>;
 
 function AddItem(item:GameObject) {
    items.Add(item);
 }
i did not read:
import System.Collections.Generic;
you are absolutely correct. Thank you so much for the many and helpful replies!
Sorry, I tried to edit that line to be in the code, as I screwed up the initial answer, but QATO won't take the edit. If you get to the reputation level where you can edit the post, you can see that I actually committed the edit, but it won't display. I am not fond of QATO.
yeah no problem(its a problem I get all the time), thanks all the same.
Your answer
 
 
             Follow this Question
Related Questions
How To Get A Reference To All Nearby GameObjects? 1 Answer
A node in a childnode? 1 Answer
How to see what element is the current one 2 Answers
Storing complex GameObject structure 1 Answer
Scroll List Problem 1 Answer
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                