Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Resolved Access a class as the class it's derived from

Discussion in 'Scripting' started by Sooly123, Oct 8, 2023.

  1. Sooly123

    Sooly123

    Joined:
    Aug 24, 2022
    Posts:
    90
    EDIT: I have thought of a better way

    title, I have 2 classes:
    class Add
    and
    class NodeStructure

    I need to do something like this:
    Code (CSharp):
    1. Add add = new Add();
    2. NodeStructure nodeStructure = add;
    but of course that isn't going to work, so what's the most efficient way of getting all the derived variables from
    class Add
    ?

    Thanks in advance!
     
    Last edited: Oct 8, 2023
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,843
    I think you misunderstand inheritance here, and this posting his lacking information. Is
    Add
    inherited from
    NodeStructure
    ? Assigning a derived type to a base type doesn't actually change the type assigned. It's still, in memory, the derived type.

    Note that the main point of inheritance is substitution. You should be able to use a derived type as a base type without caring about it's specific implementation. There are exceptions, such as component structures (like Unity's), but with node structures you should always be treating everything as its base type, and derived types just do their own thing on a "Tell, Don't Ask" basis.

    To actually answer the question, the most simple way if just pattern matching, eg:
    if (node is Add add) { }
    . But you probably ought to think about what you're doing, and perhaps explain your problem better.
     
    Bunny83 likes this.
  3. Sooly123

    Sooly123

    Joined:
    Aug 24, 2022
    Posts:
    90
    Thank you for reply. Yes, by the looks of it I think I do misunderstand inheritance. I haven't really explained it very well, and I can think of a much, much better way of achieving what I need now.