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. Have a look at our Games Focus blog post series which will show what Unity is doing for all game developers – now, next year, and in the future.
    Dismiss Notice

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

Discussion in 'Scripting' started by bananapizzuh, Jan 14, 2022.

  1. bananapizzuh

    bananapizzuh

    Joined:
    Jan 2, 2021
    Posts:
    7
    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:
    1,380
    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:
    7
    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:
    516
    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,818
    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