Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 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 Supremetor · Aug 10, 2019 at 12:23 AM · inheritanceaccessderived-class

Can I access a deriving class through a base/parent class?

I am working on a project that uses inheritance to make my life easier (or at least it will be soon). Let's say that i have a base class "Base Class" and I have two classes that drive from Base Class, let's call them "Class 1" and "Class 2". I don't know ahead of time which one of Class 1 or Class 2 it will be. I would like to have a reference to a singleton of Base Class and reference Class 1 or Class 2 (whichever it would be) through the singleton. I have not gotten to the point in the project that i need to do this yet but it is coming soon so i would like to know if this would work or if there is an alternative. I am not very experienced with inheritance so I might be asking a question with a super simple answer or a question with no answer. Any help is appreciated.

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 sacredgeometry · Aug 10, 2019 at 12:37 AM 0
Share

Im not sure I understand what you mean. Can you elaborate or provide some pseudo code?

So you have a singleton base class with a property that is polymorphic between two of its derived classes? Is that what you are trying to say?

Im not sure what it has to do with inheritance other than the fact you are deriving the base class twice.

avatar image sacredgeometry · Aug 10, 2019 at 12:44 AM 0
Share

Is this what you mean?

 public class Base
 {
     public Base derived { get; set; }
 }
 
 public class DerivedA : Base
 {
     
 }
 
 public class DerivedB : Base
 {
     
 }
 
 public class Example
 {
     public Example() {
         var test = new Base {
             derived = new DerivedA()
         };
 
         Debug.Log(typeof(DerivedA) == test.derived.GetType()); // TRUE
 
         test.derived = new DerivedB();
 
         Debug.Log(typeof(DerivedB) == test.derived.GetType()); // TRUE
     }
 }
avatar image Supremetor · Aug 10, 2019 at 04:10 PM 0
Share

Sorry, I'm new at posting questions here. I'll try to make more sense and be more clear.

The context of my question is that I'm trying to create a game with a bunch of different $$anonymous$$i-games. I want to use one base class for a general game manager with code for spawning, etc. and I want a separate class for each $$anonymous$$i-game containing the gameplay code.

I would like to use the same player script for all $$anonymous$$i-games but the player wouldn't know which $$anonymous$$i-game script it should look for, but it would be able to know the base class (since that would always be consistent). I am wondering what the best way to do this is.

Also, thanks for the super quick responses.

avatar image sacredgeometry Supremetor · Aug 10, 2019 at 07:04 PM 0
Share

Nothing to apologise for:

You could do it like that or you could use a design pattern like the one I pointed out which would solve some of the problems you may come up against if you just try to solve this problem with inheritance.

The strategy pattern I listed below is literally designed to solve this problem and is generally taught as one of the first OO design patterns so shouldn't be too hard to get your head around.

2 Replies

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

Answer by sacredgeometry · Aug 10, 2019 at 08:22 AM

Try the strategy pattern instead of inheritance

It will improve extensibility, readability and generally solve you a lot of headaches as your class variants grow more complex .

As said, inheritance is not a particularly good way to implement polymorphic traits. It's something that should generally be avoided unless you are trying to model a specific inheritance structure that, which is unlikely to ever change/ get more complex (and even then I would question the need to use it much).

Strategy Pattern Video

OO Design Patterns Bible

Comment
Add comment · Show 19 · 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 ownezx · Aug 10, 2019 at 04:25 PM 1
Share

Well, I think I'm going to watch all these videos, good references there.

avatar image Supremetor · Aug 10, 2019 at 06:09 PM 0
Share

Is there a video that explains strategy pattern in unity well?

avatar image sacredgeometry Supremetor · Aug 10, 2019 at 06:59 PM 0
Share

It's language and framework agnostic. It's an Object Oriented pattern.

avatar image ownezx sacredgeometry · Aug 10, 2019 at 07:04 PM 0
Share

It does come into play when you want to modify things from the editor no? Let's say I made an IDamagable interface with an instance of it being DamagableShipBehaviour with a value called hitPoints.

I would not be able to modify the DamagableSubsystemBehaviour hitPoints if I have a mono behaviour that has an IDamagable object in it.

Show more comments
avatar image Supremetor Supremetor · Aug 10, 2019 at 07:17 PM 1
Share

I found a good tutorial that taught interfaces and strategy pattern really well (for me). I think it will have the desired effect. Thanks for all the help, both of you. Tutorial

avatar image
0

Answer by ownezx · Aug 10, 2019 at 03:10 AM

What you want to do is called upcasting or downcasting.

Let's say you have a WeaponProjectile and a MissileProjectile, child of WeaponProjectile.

You can do something of the sort :

 public void myFunction(WeaponProjectile wp)
 {
     MissileProjectile mp = (MissileProjectile)wp;
     mp.range = 400f; // Public variable of type MissileProjectile
     mp.damage = 100f; // Public variable of type WeaponProjectile
 }

You can also use typof to get the lowest class the object is.

Read more about upcasting and downcasting here : https://www.c-sharpcorner.com/article/polymorphism-up-casting-and-down-casting/

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 sacredgeometry · Aug 10, 2019 at 08:11 AM 0
Share

You probably dont want to direct cast in this case as theres a chance it would throw an exception as you are expecting that cast to fail sometimes. Either you would need to wrap it in a try catch, which could get convoluted depending on the amount of variants or I would use "is" or "as" ie:

 if(mp is $$anonymous$$issileProjectile) 
 {
     var mp = wp as $$anonymous$$issileProjectile;
 }

or if C#7 is supported

 if(wp is $$anonymous$$issileProjectile mp)
 {
     // Code goes here and has been null checked on failure of conversion
 }

avatar image sacredgeometry · Aug 10, 2019 at 08:13 AM 0
Share

Also there are better ways to achieve polymorphism than by using inheritance.

Inheritance is a particularly bad way given the alternatives. It locks you into an inheritance structure, it's cumbersome, hard to modify, prone to introduction of passing around larger objects than you need, having to write special case code and generally forces you to break SOLID principals a whole bunch.

Simply using interfaces (and if you need implementations on those interfaces: extension methods) is a much better solution to this problem.

Thats before going into patterns like the strategy pattern (potentially relevant here).

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

112 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 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 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 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 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

C# How to derives A from B, where B in different .cs file 1 Answer

An OS design issue: File types associated with their appropriate programs 1 Answer

Why the null reference? 2 Answers

Making a static class derive from MonoBehaviour in C# 3 Answers

Is it possible to change value on base class when the same field gets changed on it's derived class 0 Answers


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