Search Unity

subclassing/prefab question

Discussion in 'Editor & General Support' started by stain2319, Mar 13, 2020.

  1. stain2319

    stain2319

    Joined:
    Mar 2, 2020
    Posts:
    417
    I am trying to create a prefab game object (a player avatar) and have what I suppose is a simple question. But for whatever reason I can't find a definitive answer...

    I have e.g.

    Code (csharp):
    1.  
    2. public class BaseClass : MonoBehaviour
    3.  
    4. { stuff }
    5.  
    And then I have another script to modify specifics

    Code (csharp):
    1.  
    2. public class SubClass: BaseClass
    3. { stuff }
    4.  
    If I create a GameObject with my SubClass script attached it seems to work fine but if I try to drag it down and create a Prefab out of it, I get an error that the SubClass does not derive from MonoBehaviour.

    Do I also need to attach the BaseClass script to the same object?
     
  2. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    That really should work, I can't see anything wrong with that. In my game I have these two classes, and I can make a prefab out of my SlimeEnemy just fine.
    Code (CSharp):
    1. public class BaseEnemy : MonoBehaviour
    2. {
    3.     stuff
    4. }
    Code (CSharp):
    1. public class SlimeEnemy : BaseEnemy
    2. {
    3.     stuff
    4. }
    This is a wild guess, but double check that both of your scripts are public and have "using UnityEngine" at the top.
     
  3. stain2319

    stain2319

    Joined:
    Mar 2, 2020
    Posts:
    417
    They are both public and have that at the top. Do I need to have my original script somewhere "in the game" as opposed to just in the assets for the project?
     
  4. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    My classes are both public. You only need to have them in the assets folder for them to work, you don't need to have an instance of the base class attached to a GameObject.

    One thing that's important for Monobehaviours is that the name of your script needs to be the same as your class. For example, your SubClass must be in a script called "SubClass.cs".

    If you still can't get it working, maybe you should delete your Library folder while your project is closed and reopen your project to have Unity rebuild your library folder.