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

Question Override Base UnityEngine Class (Button)

Discussion in 'Scripting' started by Tornament2007, Jul 1, 2023.

  1. Tornament2007

    Tornament2007

    Joined:
    Feb 1, 2020
    Posts:
    2
    The code is:
    Code (CSharp):
    1. public new class Button : Selectable, IPointerClickHandler, ISubmitHandler
    Unity gives an error:
    Assets\Game\Scripts\NewOverride\Button.cs(10,22): error CS0106: The modifier 'new' is not valid for this item


    The goal is to expand base button functionality, while keeping same class. Because class Button is used in many other things which i can not replace;

    Writing new Button class derided from Button, and write many other components for new button is not an option.
     
  2. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,043
    That's not a legal class declaration in C#, keyword new is not allowed in a non-nested class declaration.

    The syntax is
    Code (csharp):
    1. class_declaration
    2.      : attributes? class_modifier* 'partial'? 'class' identifier
    3.          type_parameter_list? class_base? type_parameter_constraints_clause*
    4.          class_body ';'?     ;
    new
    is considered a class_modifier
     
    Kurt-Dekker and Tornament2007 like this.
  3. Tornament2007

    Tornament2007

    Joined:
    Feb 1, 2020
    Posts:
    2
    Ok, i see. Thanks.

    is there in C# methods to override(replace) Button class with my variant?
     
  4. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,043
    What do you hope to achieve with it? What you described isn't a good practice.
    In C# you either override a class with a specific
    using
    clause
    Code (csharp):
    1. using Button = MyButtons.Button;
    or you can perhaps create a locally nested
    Button
    override.
     
  5. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,560
    Even if you are successful, your Button absolutely WILL NOT be the same class to those other Buttons already in your project. That's not how objects work.

    Don't use this approach. Make a Component that interoperates with the Button to add the functionality. You might use other Components (such as EventTrigger) to bridge between your code and the button.
     
    spiney199 and orionsyndrome like this.