Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • 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 W1k3 · Jul 10, 2014 at 08:31 PM · c#objectarraylist

How to read properties from an arraylist of objects C#

I'm quit new to working with objects in c# and don't know how to properly read values. I have a script that adds a bow object to a static array list in another scrip, but when I try to pull values from that arraylist, I get error CS1061.

This is my bow script:

 using UnityEngine;
 using System.Collections;
 
 public class bow : MonoBehaviour {
 
     public float damage;
     public float firerate;
     public float accuracy;
     public string description;
     public string name;
 }
 

This is the script that assigns the bow to the arraylist:

 bow coolbow = new bow ();
 
         coolbow.damage = damage;
         coolbow.firerate = firerate;
         coolbow.accuracy = accuracy;
         coolbow.description = description;
         coolbow.name = name;
 
 
         inventory.items.Add (coolbow);

And this is the inventory script:

 using UnityEngine;
 using System.Collections;
 
 public class inventory : MonoBehaviour {
 
     public static ArrayList items  = new ArrayList();
 
     void Update () {
         if(items.Count > 0){
             Debug.Log("" + items[0].damage);
         }
     }
 }
 
Comment
Add comment · Show 4
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 NoseKills · Jul 10, 2014 at 08:42 PM 1
Share

Judging by the error you get, what ever is in cell 0 of the ArrayList, doesn't have a member called "damage".

What happens if you just do:

  Debug.Log("" + items[0]);

?

Reference

avatar image W1k3 · Jul 10, 2014 at 08:51 PM 0
Share

It just prints null

avatar image AndyMartin458 · Jul 10, 2014 at 11:10 PM 1
Share

@W1k3 Have you tried using List ins$$anonymous$$d of ArrayList?

avatar image Kiwasi · Jul 11, 2014 at 12:15 AM 0
Share

Unless you have something forcing you to use ArrayList you should use a List ins$$anonymous$$d. ArrayList is only included in C# for backwards compatibility.

3 Replies

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

Answer by Kiwasi · Jul 10, 2014 at 11:48 PM

You are using a non generic function. Therefore items[0] is an object. To get it to a bow you need to use casting as follows

 // If you are sure its a bow
 ((bow)item[0]).damage;
 
 // Safe casting is slower, but won't throw a runtime error if it is not a bow
 (item[0] as bow).damage;

I would suggest using the generic version List. Its faster and simpler to code.

Comment
Add comment · Show 1 · 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 Landern · Jul 11, 2014 at 12:40 PM 0
Share

To @Bored$$anonymous$$ormon point, ArrayLists as you can see from the example above require casting. There are inherit performance issues being introduced just from the point of casting, boxing and unboxing, particularly often can suck the life out of what your doing. Using generics introduces type safety(it is what it is) and better readability for the future.

avatar image
2

Answer by gjf · Jul 11, 2014 at 09:55 AM

you'll likely be adding other inventory types too. here's an example of how you might approach it:

 using UnityEngine;
 using System;
 using System.Collections.Generic;
 
 public class InventoryItem
 {
     public string Name;
     public string Description;
     public Type ItemType;
 }
 
 public class Arrow : InventoryItem
 {
     public float Speed;
 
     public Arrow()
     {
         ItemType = typeof (Arrow);
     }
 }
 
 public class Bow : InventoryItem
 {
     public float Damage;
     public float FireRate;
     public float Accuracy;
 
     public Bow()
     {
         ItemType = typeof (Bow);
     }
 }
 
 public class InventoryExample : MonoBehaviour
 {
     public List<InventoryItem> Inventory = new List<InventoryItem>();
 
     public void Awake()
     {
         var coolbow = new Bow { Name = "Dummy", Description = "Dummy item description", Damage = 2.0f, FireRate = 1.0f, Accuracy = 50.0f };
         Inventory.Add(coolbow);
 
         var arrow = new Arrow { Name = "Arrow", Speed = 10.0f };
         Inventory.Add(arrow);
     }
 
     public void Update()
     {
         foreach (var inventoryItem in Inventory)
         {
             if (inventoryItem.ItemType == typeof (Bow))
             {
                 var bow = (Bow) inventoryItem;
                 Debug.Log("Bow damage is " + bow.Damage);
             }
 
             if (inventoryItem.ItemType == typeof (Arrow))
             {
                 var arrow = (Arrow) inventoryItem;
                 Debug.Log("Arrow speed is " + arrow.Speed);
             }
         }
     }
 }

put everything that's common to all inventory items in the InventoryItem class, and specific things in each class (i've created Bow & Arrow to illustrate this) and how you'd access each (casting to the correct type as suggested by BoredMormon)

Comment
Add comment · Show 3 · 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 Kiwasi · Jul 11, 2014 at 12:02 PM 0
Share

I was going to suggest something like that, but it was a bit much to write out.

Never seen anyone cache the type of an object before, is it faster then just getting the runtime type using reflection?

avatar image gjf · Jul 11, 2014 at 12:25 PM 0
Share

i've used it to illustrate something before so wasn't a huge effort to cut&paste then tweak a little ;)

re: the caching - i don't imagine that doing it at runtime would be faster although ymmv

avatar image W1k3 · Jul 12, 2014 at 06:54 AM 0
Share

This is quite useful, thanks!

avatar image
0

Answer by Nick4 · Jul 10, 2014 at 08:45 PM

You can't create an instance of an object that inherits Monobehaviour using the "new" key. So your bow class simply can't inherit Monobehaviour.

Comment
Add comment · Show 2 · 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 W1k3 · Jul 10, 2014 at 08:53 PM 0
Share

I changed public class bow : $$anonymous$$onoBehaviour to public class bow and it didn't make a difference.

avatar image Kiwasi · Jul 11, 2014 at 12:10 AM 1
Share

This is true, but not the problem in this case.

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.

Follow this Question

Answers Answers and Comments

25 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Distribute terrain in zones 3 Answers

Casting objects in Unity using a local class of an object 2 Answers

Multiple Cars not working 1 Answer

Rotation to certain degrees while holding a button? C# 1 Answer

NullReferenceException - When destroying Object 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