Search Unity

Custom element not working, "has no registered factory method."

Discussion in 'UI Toolkit' started by TheGabelle, Feb 14, 2021.

  1. TheGabelle

    TheGabelle

    Joined:
    Aug 23, 2013
    Posts:
    229
    Not sure what I'm doing wrong.

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UIElements;
    3.  
    4. public class CustomElement : VisualElement
    5. {
    6.     // this doesn't work either
    7.     //public new class UxmlFactory : UxmlFactory<CustomElement, UxmlTraits> { }
    8.     public new class UxmlFactory : UxmlFactory<CustomElement> { }
    9.     public CustomElement()
    10.     {
    11.         Debug.Log(this);
    12.     }
    13. }
    14.  
    <?xml version="1.0" encoding="utf-8"?>
    <UXML
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="UnityEngine.UIElements"
    xsi:noNamespaceSchemaLocation="../UIElementsSchema/UIElements.xsd"
    xsi:schemaLocation="UnityEngine.UIElements ../UIElementsSchema/UnityEngine.UIElements.xsd">

    <Style src="MainMenu.uss" />
    <CustomElement>
    <Label text="Custom Element Label" />
    </CustomElement>
    </UXML>


    the error:

    Element 'UnityEngine.UIElements.CustomElement' has no registered factory method.
    UnityEngine.UIElements.UIDocument:OnEnable () (at Library/PackageCache/com.unity.ui@1.0.0-preview.14/GameObjects/UIDocument.cs:315)
     
  2. antoine-unity

    antoine-unity

    Unity Technologies

    Joined:
    Sep 10, 2015
    Posts:
    378
    Hello, you'll need to put your element into a namespace.

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UIElements;
    3.  
    4. namespace Test
    5. {
    6.     public class CustomElement : VisualElement
    7.     {
    8.         public new class UxmlFactory : UxmlFactory<CustomElement, VisualElement.UxmlTraits> {}
    9.  
    10.         public CustomElement()
    11.         {
    12.             Debug.Log(this);
    13.         }
    14.     }
    15. }
    16.  
    And then make sure to import this namespace in your UXML:

    Code (CSharp):
    1. <?xml version="1.0" encoding="utf-8"?>
    2.  
    3. <UXML
    4.  
    5.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    6.  
    7.     xmlns="UnityEngine.UIElements"
    8.     xmlns:test="Test"
    9.     xsi:noNamespaceSchemaLocation="../UIElementsSchema/UIElements.xsd"
    10.  
    11.     xsi:schemaLocation="UnityEngine.UIElements ../UIElementsSchema/UnityEngine.UIElements.xsd">
    12.  
    13.  
    14.  
    15.     <Style src="MainMenu.uss" />
    16.  
    17.     <test:CustomElement>
    18.  
    19.         <Label text="Custom Element Label" />
    20.  
    21.     </test:CustomElement>
    22.  
    23. </UXML>
     
    TheGabelle likes this.
unityunity