Extend basic UI Element and attach custom USS (no UXML)

Hello!

I’ve created a custom component which I use multiple times within my UI. It’s basically just a TextField with some additional style options. Here is some pseudo code so you get an idea (the code is a bit more complex but I want to spare you the details):

public class FancyTextField: TextField
{
    public void FancyTextField() {
        AddToClassList("textfields");
    }

    public void SetErrorState() {
        this.style.borderBottomColor = Color.red;
        this.style.borderLeftColor = Color.red;
        this.style.borderRightColor = Color.red;
        this.style.borderTopColor = Color.red;
    }
}

This is working fine so far and I can use this in other UXML files simple by using <LoginTextField />. Now I want to move the code where I change the actual style into a separate USS file. I’ve done this with more complex elements before which have their own UXML file. Since this one is just a plain TextField creating an UXML would feel silly. So I’d like to just add the USS. And this is where I’m currently struggling with.

I’ve enhanced my class in loading and applying a custom USS file:

    public void FancyTextField() {
        var textFieldStyleSheet = Resources.Load<StyleSheet>("path/to/stylesheet");
        this.styleSheets.Add(textFieldStyleSheet);

        AddToClassList("textfields");
    }

Then I try to change the text color just to see if this is working. Since I don’t know how to do this I tried different approahces. However none of them is working for me (the text color stays white):

.root {
    color: rgb(0, 255, 0);
}

TextInput {
    color: rgb(255, 0, 0);
}

.textfields {
    color: rgb(0, 0, 255);
}

Do you know what I’m doing wrong here? How can I address a native UI element’s ViewElements and change its style? is this even possible without creating a custom UXML. And if not how would said UXML look like if my class is already a TextView? Would I have to change it to VisualElement and include ther TextField into the UXML?

I found a solution for my issue:

The TextInput style did work, however it was overwritten by a more concrete default styling id #unity-text-input which is found on every TextField. So adjusting my selectors did the trick for me (making it more concrete):

FancyTextField > #unity-text-input {}

The UI Debugger helped me figure that out. Checking the Matching Selectors region let me see which styles were applied and their order(the lower the more weight). If you want to know more about selector hierarchy check the Unity Docs.

Since this is my first post in the Unity forum I’m not very familiar with the way this is handled. I won’t delete this post since others might face similar issues.