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

Feature Request Make UxmlElement attribute of a derived class optional

Discussion in 'UI Toolkit' started by Hellfim, Sep 28, 2023.

  1. Hellfim

    Hellfim

    Joined:
    Sep 11, 2014
    Posts:
    91
    Suppose I have following classes:
    Code (CSharp):
    1. [UxmlElement]
    2. public partial class BaseClass : VisualElement
    3. {
    4. }
    5.  
    6. [UxmlElement]
    7. public partial class DerivedClass : BaseClass
    8. {
    9. }
    Now it's possible to omit UxmlElement on a derived class, though UI Toolkit will not be able to work with DerivedClass and will display 'Unknown class: <full class name>' error instead of the VisualElement.

    I would love if you make it possible to use following declaration:
    Code (CSharp):
    1. public class DerivedClass : BaseClass
    2. {
    3. }
     
  2. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    7,820
    We need the attribute for element creation, it takes the place of the UxmlFactory. Is there a reason you don't want to add it?
     
  3. Hellfim

    Hellfim

    Joined:
    Sep 11, 2014
    Posts:
    91
    Well, if there is no uxml-related code in DerivedClass (i.e. no UxmlAttributes), then it seems that it's possible to use a base factory to create class.

    Actually the only reason I brought up, is because I have a generic BaseClass which handles all uxml-related stuff, and it's DerivedClasses are only directly specifing generic parameter, and slightly customize their behaviour.
     
  4. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    7,820
    We cant use the base factory because its responsible for creating the instance and needs the actual type. It generates this method
    https://docs.unity3d.com/2023.3/Doc...ements.UxmlSerializedData.CreateInstance.html

    Which just creates a new instance of the type.
    E.G

    Code (csharp):
    1. public partial class DerivedClass : BaseClass
    2. {
    3.     public class UxmlSerializedData : BaseClass.UxmlSerializedData
    4.     {
    5.         public override object CreateInstance() => new DerivedClass();
    6.     }
    7. }
    So you do need to have the generated code if you want the element to be serialized from uxml.
    The BaseClass will just create a new BaseClass, it would not work with a derived type.
     
    Hellfim likes this.