Search Unity

  1. The 2022.1 beta is now available for testing. To find out what's new, have a look at our 2022.1 beta blog post.
    Dismiss Notice

Is there any way to make an extendable class like in java?

Discussion in 'Scripting' started by bananapizzuh, Jan 14, 2022 at 10:56 PM.

  1. bananapizzuh

    bananapizzuh

    Joined:
    Jan 2, 2021
    Posts:
    5
    Exactly what the title says, because it's the way I would ideally make weapons in my game.
     
  2. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    632
    When you define the class, you put the class it "extends" after it with a colon

    Code (CSharp):
    1. public class Child : Parent {
    2.     // stuff in class
    3. }
     
    bananapizzuh likes this.
  3. bananapizzuh

    bananapizzuh

    Joined:
    Jan 2, 2021
    Posts:
    5
    Is the class just any class, and is the parent Mono? And do they have to be child and parent in the hierarchy?
     
  4. Rin-Dev

    Rin-Dev

    Joined:
    Jun 24, 2014
    Posts:
    440
    Typed from my phone but the basic outline of how it works.

    Code (CSharp):
    1. Public class WeaponClass:Monobehaviour{
    2. Public Virtual void Use(){
    3. \\code
    4. }
    5. }
    Code (CSharp):
    1. Public class Submachine gun:WeaponClass{
    2. Public override void Use(){
    3. base.Use();
    4. //Other code
    5. }
    6. }
     
    bananapizzuh likes this.
  5. Stardog

    Stardog

    Joined:
    Jun 28, 2010
    Posts:
    1,714
    The parent can extend MonoBehaviour only if you want to attach it to a GameObject as a component. Attaching the component is the way to create an instance.

    If you don't want to attach it to a GameObject, the parent does not need to inherit from anything. The way to instantiate it is using the "new" keyword.
     
    bananapizzuh likes this.
unityunity