• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by PrimeDerektive · Nov 29, 2010 at 03:03 PM · arraygameobjectsiterate

Having trouble iterating through an array of GameObjects of a certain type

I'm working on an inventory system, and I want it to be an array of gameobjects of type Item (a script that I have in my project). I have a gameobject in the scene with script Item.js, that has an itemName var defined, and the collision code to call the AddItem function in the Inventory script on the player with itself as the parameter. Here is the inventory script so far:

var inventory : Item[]; var inventoryLength : int = 16;

function Awake () { inventory = new Item[inventoryLength]; }

function OnGUI(){ for( var i = 0; i < inventory.length; i++ ){ var currentItem = inventory[i]; if(currentItem != null){ GUI.Label (Rect (30, (30*i), 120, 30), currentItem.itemName); } } }

function AddItem( item : Item ) { for( var i = 0; i < inventory.length; i++ ) { if( inventory[i] == null ) { inventory[i] = item; print(inventory[i].itemName); return; } }
}

Notice in the AddItem function I am printing the itemName var of the item being added upon collision after I inserted into the inventory. THAT is working. However, in my OnGUI function where I am trying to iterate through the inventory and print all the itemNames as labels, it is not doing anything. No errors, nothing. What am I doing wrong?

Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Jesse Anders · Nov 29, 2010 at 03:27 PM 0
Share

I didn't spot any errors in your code (although maybe someone else will). If you're still stuck on this though, I'd recommend adding some debug output in OnGUI() as well to try to deter$$anonymous$$e more specifically what's going wrong. ($$anonymous$$g., are all of the items 'null' in OnGUI()? Are the labels being rendered but not ending up being visible for some reason? Etc.)

avatar image PrimeDerektive · Nov 29, 2010 at 03:45 PM 0
Share

Thanks Jesse. Inside my for loop in OnGUI(), I removed the null check and just drew the label. It works now! $$anonymous$$y only problem is that for every iteration through an index of the inventory array that is empty, it throws back a NullReferenceException :( Any suggestions?

1 Reply

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by skovacs1 · Nov 29, 2010 at 04:39 PM

EDIT: After re-reading the question and comments, I now believe that you were not properly passing the instances of the Item script to your array. Make sure to get them with GetComponent and that they actually have the script attached.

EDIT 2: As it seems the place wherein you are incorrectly passing the items to your inventory is in the collision code that you failed to provide, I will provide how that code and setup looks like for a working setup that I tested:

Item.js (attached to some object(s) in the scene)

var itemName : String;

function OnCollisionEnter(collision : Collision) { var script : Inventory = collision.gameObject.GetComponent(Inventory); if(script) script.AddItem(gameObject); else Debug.LogError(collision.gameObject.name + " has no inventory."); }

Inventory.js (attached to some other object(s) in the scene)

var size : int = 16; var items : Item[];

function Start() { items = new Item[size]; }

function OnGUI () { for(var i : int = 0; i < items.length; i++) { var item : Item = items[i]; if(item != null) GUI.Label(Rect(30, 30 * i, 120,30), item.itemName); } }

function AddItem(obj : GameObject) { if(obj == null) { Debug.LogError("Tried to add an invalid Item"); return; } var item : Item = obj.GetComponent(Item); if(item == null) { Debug.LogError("Tried to add an invalid Item"); return; } for(var i : int = 0; i < items.length; i++) { if(items[i] == null) { items[i] = item; Debug.Log("Added " + item.itemName); return; } } Debug.LogWarning("Inventory full."); }

Comment
Add comment · Show 24 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Mike 3 · Nov 29, 2010 at 04:58 PM 0
Share

Small note: Awake is only called once before Start - It doesn't get called when the script is enabled after being disabled (Unlike OnEnable)

avatar image skovacs1 · Nov 29, 2010 at 05:30 PM 0
Share

Fair enough. I mistakenly thought it had to do with collisions and sleep. I will revise the answer.

avatar image Eric5h5 · Nov 29, 2010 at 05:37 PM 0
Share

I'm sorry, but that's not correct. In Derek's code, "currentItem" is cast as Item because of type inference. In loops, "i" is cast as an int because of type inference. Explicitly adding the type will do nothing as far as the compiled code goes; it's exactly the same. This has nothing to do with strict/dynamic typing, which is a different matter entirely.

avatar image PrimeDerektive · Nov 29, 2010 at 05:53 PM 0
Share

One thing I noticed that you are doing differently is defining Item as a class inside Item.js... I was under the impression that because all scripts are technically classes in Unity, that I didn't need to do that (for instance, in my Item.js script itemName is just a public var). Is that my problem?

avatar image PrimeDerektive · Nov 29, 2010 at 06:16 PM 0
Share

Also, in your example with class Item being defined in Item.js, if I wanted to have Item.js on an object in my scene, and be able to edit its itemName from the inspector, how would I go about doing that?

Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

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

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

No one has followed this question yet.

Related Questions

Using a number array? 1 Answer

I'm new to Unity and attempting to create an infinite array of cubes. How would I go about doing this? 0 Answers

Displaying/getting elements of a list in a certain order 3 Answers

Deactivated Targets in Shooting Game Cause Score to Never Stop Adding One 1 Answer

Iterate an array 4 by 4 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges