x


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

}
more ▼

asked Feb 21 '12 at 01:57 PM

MithosAnnar gravatar image

MithosAnnar
299 22 36 40

Why are you using an ArrayList if you're only putting one type in it?

Feb 21 '12 at 02:02 PM Jessy

the player may want more than 1 item in his/her inventory.

Feb 21 '12 at 02:10 PM MithosAnnar

The error is occurring at the line in Inventory.js:

items.Add(item.gameObject);

Still got no idea why.

Feb 21 '12 at 02:43 PM MithosAnnar

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.

Feb 21 '12 at 02:46 PM Jessy

Ok, im using it because it supports Add().

Feb 21 '12 at 02:56 PM MithosAnnar
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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);
}
more ▼

answered Feb 21 '12 at 03:01 PM

Jessy gravatar image

Jessy
15.6k 72 95 196

i tried this but it gave me the same error.

Feb 21 '12 at 04:26 PM MithosAnnar

i did not read:

import System.Collections.Generic;

you are absolutely correct. Thank you so much for the many and helpful replies!

Feb 21 '12 at 04:30 PM MithosAnnar

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.

Feb 21 '12 at 05:08 PM Jessy

yeah no problem(its a problem I get all the time), thanks all the same.

Feb 21 '12 at 05:10 PM MithosAnnar
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x2088
x1363
x356
x255
x67

asked: Feb 21 '12 at 01:57 PM

Seen: 1855 times

Last Updated: Feb 21 '12 at 05:10 PM