• 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 pauldoody25 · Jan 19, 2016 at 07:32 PM · parentchildclassinheritanceparent-child

Putting a Child Class into a List of Parent Type and then casting it back to a Child

I'm trying to set up an inventory system with a List of Inventory_Items to store them. However I want to use weapon or armor classes that inherit from Inventory_Items so they don't have worthless variables like ammo type on a sword or something. I have it set up, however, upon casting the Inventory_Items object in the list back into its original child class, all of the variables belonging to the child class are set to their default values. Is there a way for those variables to be recovered after being converted to a parent class?

         //parent class
         [System.Serializable]
         public class Inventory_Item: MonoBehaviour
         { //data types
       public Inventory_Item()
     {
              //constructor
     }
        }
         //Child Class

           [System.Serializable]
           public class Player_Usable_Item : Inventory_Item 
          {
          Player_Usable_Item() : base
          }
          //database class
          public class Item_Database : MonoBehaviour {

    [SerializeField]
    public List<Inventory_Item> allItems = new List<Inventory_Item>();

    void Awake () 
 {
     allItems.Add (new Inventory_Item());
     allItems.Add ((Inventory_Item)new Player_Usable_Item());
 }

   }
         //trying to access child variables
        Player_Usable_Item test = (Player_Usable_Item)itemDatabase.allItems[3];
        Debug.Log (childVariable + ""); //returns default values
Comment
Add comment · Show 9
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 Bonfire-Boy · Jan 19, 2016 at 09:13 PM 1
Share

Yes you could do that like this...

 Inventory_Item i = itemDatabase.allItems[3];
 Player_Usable_Item p = i as Player_Usable_Item;
 if (p != null)
 {
    // do stuff with p
 }
 else
 {
   // it's not a Player_Usable_Item
 }

However...

You don't need to cast a Player_Usable_Item to the parent class when adding it to the list. A Player_Usable_Item IS an Inventory_Item.

You've made Inventory_Item a $$anonymous$$onoBehaviour, so neither that nor the derived class can have a constructor (and hence can't be created in the way you're doing it in the Awake function).

avatar image pauldoody25 Bonfire-Boy · Jan 19, 2016 at 10:35 PM 0
Share

I see. However, once converted all of the new variables belonging only to the child are still all set to their defaults. Is there no way to prevent this as the data is simply lost when it's first put in the parent list?

avatar image Bonfire-Boy pauldoody25 · Jan 19, 2016 at 11:21 PM 0
Share

Not sure what you mean, the classes don't appear to have any member variables in the code you've shown. How are you changing the defaults?

You won't be losing data just by putting the references into a List.

Show more comments
avatar image cjdev pauldoody25 · Jan 20, 2016 at 12:17 AM 0
Share

I think what's happening is that if you're casting the derived class to the base class it won't have the variables that are unique to the derived class anymore. So when you cast it back those variables are basically reinstantiated to their default values. Ins$$anonymous$$d of using a base class to organize the inventory items try using an interface ins$$anonymous$$d.

avatar image Bonfire-Boy pauldoody25 · Jan 20, 2016 at 12:38 AM 0
Share

@cjdev That is totally wrong. Putting a derived class reference into a list of base class references does not change the derived class object in any way. You can get it from the list, cast it back, and it will retain its values. This is how one uses polymorphism.

Simple example...

     public class A
     {
         public A( ) { }
     }
 
     public class B : A
     {
         public float b = 0f;
         public B(float bt) : base()
         {
             b = bt;
         }
     }
 
         // then put this block into a function
         {
                         List<A> AList = new List<A>( );
         AList.Add( new A( ) );
         AList.Add( new B( 1f ) );
 
         for (int i = 0; i < AList.Count; i++)
         {
             A a = AList[i];
             B b = a as B;
             if (b != null)
             {
                 Debug.Log( "A #" + i + " is a B with b = " + b.b );
             }
             else
             {
                 Debug.Log( "A #" + i + " is not a B ");
             }
         }
         }

This prints

         A #0 is not a B 
         A #1 is a B with b = 1

(ie, the B retains its non-default value of the variable b)

Of course, you can't quite do this with the OP's classes because they are $$anonymous$$onoBehaviours, so the setting of the variable values can't be done using constructors, but the principle holds.

avatar image cjdev pauldoody25 · Jan 20, 2016 at 01:12 AM 0
Share

Ah, you're right, my mistake. Not sure what I was thinking there, I think the cast on the new operator got me all mixed up.

avatar image Bonfire-Boy pauldoody25 · Jan 20, 2016 at 08:40 AM 0
Share

@cjdev I do see what you mean. Sorry if the tone of my reply was a bit blunt, given the misunderstandings evident in the code in the question I was just concerned about the OP being led in the wrong direction when it comes to how inheritance works, so I jumped on you a bit quick :)

0 Replies

· Add your reply
  • Sort: 

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

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

Make a simple tree 1 Answer

Trying to get my sub class to do the update function of my parent class 1 Answer

Adressing a Child Object after it´s unparented 0 Answers

Child cant apply variables from parent 2 Answers

Parent object is getting generated why ?? 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