Search Unity

Unable to cast from component to child class of monobehaviour.

Discussion in 'Scripting' started by ownezx, Jul 24, 2019.

  1. ownezx

    ownezx

    Joined:
    Mar 29, 2018
    Posts:
    6
    Hi all,

    I'm currently trying to create a subsystem parent class derived from monobehaviour and I can't seem to figure out my downcasting:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class SubSystem : MonoBehaviour
    5. {
    6.     //stuff
    7. }
    8.  
    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class Engine: SubSystem
    6. {
    7.     //Some stuff
    8. }
    9.  
    10.  
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PilotPlayerInterface : MonoBehaviour
    6. {
    7.     public GameObject shipGameObject;
    8.     public Engine shipEngine;
    9.  
    10.     void Start()
    11.     {
    12.         shipEngine = shipGameObject.GetComponent(typeof(Engine)) as Engine;
    13.     }
    14. }
    15.  
    In the class PilotPlayerInterface I Visual Studio tells me that it "Cannot convert type 'UnityEngine.Component' to 'Engine' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion". However, when replacing the class Engine by SubSystem (line 8 and 12), the code works. Can't I downcast a "SubSystem" class to an "Engine" class?

    Can you guys see the silly mistake that I cant see here?

    Thank you in advance,
    Elliot.
     
  2. Stardog

    Stardog

    Joined:
    Jun 28, 2010
    Posts:
    1,322
    Code (csharp):
    1. shipEngine = shipGameObject.GetComponent<Engine>();
     
  3. ownezx

    ownezx

    Joined:
    Mar 29, 2018
    Posts:
    6
    Worked like a charm ! I will try to read some more unity manuals.
    Thank you good sir, have a wonderful day.
     
  4. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    1,104
    Stardog's suggestion is the better way of doing this, although I'm surprised your first attempt threw an error...