#🧰┃ui-toolkit

1 messages · Page 15 of 1

vagrant peak
#

this is a log from working buttons

rough scarab
#

In the dropdown in the top left I think you don't want GameView

#

You want the name of your panel

vagrant peak
vagrant peak
#

Using debug, it always shows visual element screen, which is top of my hireachy

#

Even when I do picking mode - ignore

rough scarab
gusty vapor
#

you can further debug this by adding a MouseDown event to the parent of those buttons then do var test (VisualElement)evt.target; Debug.Log(test.name);

#

@vagrant peak

#

see if it capture the correct button, if not, then the target element is overlaying on top of those buttons which why your click events wont work

#

either way, pickingMode should do the trick here i think

vagrant peak
vagrant peak
vagrant peak
#

Maybe it has something to do with me using InputSystem? but then why other buttons work, which do not have a screen parent...

vagrant peak
#

I am going crazy. Is here anyone who can save me 🙏

fast sonnet
#

hi, i am missing the NavMesh components, they don't exist at all, i don't even have an AI tab under "Window", but i have enabled AI under build-in packages Unity 2022.3 (Also no Navigation Tab)

zinc basalt
#

Hello, I hope you are doing well. I'm developing my Unity game using UI Toolkit, and I'm currently working on creating a friend list and other lists. So, I thought it would be a good idea to use the ready-made List View, and I have successfully managed to create individual tiles in the list. The friends are displayed, which is great, but now here comes the problem: I can't add a title to the list. I wanted to have a text label in the list, just like any other menu item, where it says, for example, 'Friends.' However, I can't seem to add things to the List View. I hope you understand the issue, and I would appreciate any response🙏

gusty estuary
#

keep list view as list container only

valid pilot
#

Hey! I want to make a game HUD, as i know the UI-toolkit is best for this. But i dont exacrtly know how to use it properly, does anyone got a good tutorial, or knowledge about it? I don't exactly know how to fx. add animations, based on triggers in game, and making whole UI size same as camera ;/

gusty estuary
#

tons of examples

#

many thigns explained in depth

#

it's pinned

valid pilot
#

thats tutorial?

gusty estuary
#

take a look

valid pilot
#

oh i see

#

and there i will find answers for my questions?

gusty estuary
#

there you will find the most information on ui toolkit in whole web

valid pilot
#

Okeyy thank u very much... if i will got some problems can i write to u?

wind gorge
#

Yes, but not before asking google

vagrant peak
#

I asked google and many youtube videos. Can someone help me, please?)

gusty estuary
#

OnDisable scraps all hierarchy

#

so when enable back, all Start callbacks are gone

vagrant peak
gusty estuary
gusty estuary
#

picking mode yeah

#

forgot what's it called

#

but seems ok

#

what about button when you click it

#

does it change style?

vagrant peak
#

no, it doesn't react to mu clicks

gusty estuary
#

is it full uxml hierarchy?

#

someone might be above your element

#

eating input

vagrant peak
gusty estuary
#

try to put your button at root and bottom of document

#

also

#

open debugger

#

and see if nothing is over your button

vagrant peak
vagrant peak
gusty estuary
#

above elements eat input

#

if they have picking mode set to position

vagrant peak
gusty estuary
#

open a debugger and literally take a look

#

it will tell all elements rendered

#

and you can easily find your button and see if anything is above it

#

and what picking mode those elements have

vagrant peak
gusty estuary
#

that's not it

vagrant peak
#

it shows the same as my UI document

valid pilot
#

why cant i set my own Width?

vagrant peak
#

oh god

#

wait

valid pilot
#

okey dokey'

vagrant peak
#

)

valid pilot
#

D:

vagrant peak
vagrant peak
# gusty estuary can you show?

I see what happened. I had two UI documents using the same "Panel Settings". The second UI document also had screen, but its picking mode was "position"

#

since buttons worked in the second UI document, I didn't thing it would be a source of the issue

#

Thank you very much

vagrant peak
#

for child and the parent

valid pilot
vagrant peak
vagrant peak
valid pilot
# vagrant peak

i got it, but still i dont exactly know what should I do ;/

vagrant peak
#

and see whether width changes

valid pilot
#

It worked!

#

@vagrant peak but i got 1 more question.

#

the size of a window i created in UItool, is diffrent than the game window

#

but in booth i got 320x180

vagrant peak
valid pilot
#

The square in UIbuilder isnt 320x180

vagrant peak
#

also, do this

valid pilot
#

but now it looks like this

#

okey

#

i changed to auto

#

in flex

#

now its better

vagrant peak
#

change your width and height in %

#

otherwise, the window will change based on the screen resolution

#

and I recommend you to watch some tutorials, otherwise it will be painful process

valid pilot
valid pilot
valid pilot
vagrant peak
#

if you are ready to spend money, this one goes discount to ~10$ often (i don't know this guy and not sponsored). I watched, and it was decent: https://www.udemy.com/course/modern-unity-ui-with-ui-toolkit/

For free, this one is okay: https://www.youtube.com/watch?v=0mYtI21Fmg4&t=735s

Udemy

A Complete Overview Of Unity's New UI System UI Toolkit

Hj

UI Toolkit is a Unity’s new UI creation and development tool. This tutorial introduces the UI toolkit through making a simple but working UI. For those who are still unfamiliar with it, especially UI artists in the field, it will be an opportunity to foresee the future changes in the production.

00:00 Introduction
00:22 UI Toolkit?
00:53 Setti...

▶ Play video
dusk geyser
#

Hey everyone! Are there any graph-based menu controllers for UI Toolkit, like Doozy or UI Graph?

gusty vapor
#

uitk integration with bolt is on the the roadmap, not sure if that's already done or not

dusk geyser
#

Ok. Then I have a question to people who tried Doozy or similar packages. What's your opinion on Doozy vs UI Toolkit?

soft quiver
#

anybody successfully overridden the uss built in variables?
https://docs.unity3d.com/Manual/UIE-uss-built-in-variable-reference.html

i'm trying to simply override the blue highlight color for all inputs in my :root but nothing seems to be taking effect

    --unity-colors-button-border-hover: var(--green);
    --unity-colors-button-border-focus: var(--green);

edit for posterity:

i ended up just adding element selectors to my global, pretty tedious but it works:

Button:focus {
    border-color: var(--green);
}

Button:hover {
    border-color: var(--green);
}
inner kayak
#

hello, i have a reorderable listview bind to an array of a serilized class,i am using uxml and visualTreeAsset.clonetree ,the uxml has some fields binding to the class (using bingdingPath)and a button,i want the button to do something based on the class.like api said,if i reg a callback to listview.bindItem,then assign button callback there,i will lost all fields binding,is there a easier way to assign the button callback without losing filed binding?
---by casting the visualelemnt to bindableElement

                    root.Q<ListView>("KeyMap").makeItem = vts.KeySet.CloneTree;
                    var keymap = root.Q<ListView>("KeyMap");
                    keymap.bindItem = (e, i) =>
                    {
                        var visualElement = e as BindableElement;
                        var p = settings.GetSerializedObject().FindProperty("KeyMap").GetArrayElementAtIndex(i);
                        visualElement.BindProperty(p);
                        // ((BindableElement)e).BindProperty(settings.GetSerializedObject().FindProperty("KeyMap").GetArrayElementAtIndex(i));
                        e.Q<Button>("Bind").clicked += () =>
                        {
                            WhichKeyManager.LogInfo(p.FindPropertyRelative("KeyLabel").stringValue);
                        };
                    };
wispy mango
#

Is there an easy way to do a weight based sizing? I keep setting weight for elements % values. :(

wispy mango
copper solar
#

Any ideas why on WebGL I am getting this error?
This code does not seem to use any indexes but only one that is related to error. In editor it works without problems. Unity version 2023.1.11f

copper solar
#

Seems I just stumble on same problem as before #🧰┃ui-toolkit message

Last time I gave up, now seems need to solve it again. The previous suggestion to run on main thread does not seems to help.

obtuse jay
#

How can I execute a callback in a VisualElement when it's repainted/redraw?

gusty vapor
#

repaint/redraw-ing in uitk isn't the same like in immediateMode, that said you only know when it's resolved or not

obtuse jay
#

I'm not sure what I actually need, I want to do something like root.PropagateCallback() and then all the hierarchy below run some registered callbacks for that event.
I thought that I could use root.MarkDirtyRepaint() for that

#

¿Maybe a custom event?

gusty vapor
#

you don't necessarily need to manually MarkDirtyRepaint in uitk unless there are changes to the mesh data, one good example is changing font-type of a TextElement would require you to do that

rough scarab
#

What do you actually want it for? Because there are all sorts of callbacks, GeometryChanged being one of them. Just look down the list and pick the one that makes sense for your usecase. I often find myself browsing the events that derive from EventBase

fiery mountain
#

Funny enough, i am looking for the same thing. I was having a custom element that draws some lines. When the state of one of the elements changes i wanted to set a specific segment of the line to redraw with the new colors. Since adding a style class to one element doesn't trigger a geometry changed event I would like for a way to trigger the regenerate mesh

inner kayak
#

hello guys, i am having trboule with struct has an arrary

    [System.Serializable]
    public struct WkKey
    {
        [SerializeField]
        private int[] _keySeq;

        public int[] KeySeq
        {
            get => _keySeq == null ? _keySeq = new int[0] : _keySeq;
            set => _keySeq = value;
        }

        [SerializeField]
        private string _keyLabel;
        public string KeyLabel
        {
            get => _keySeq == null ? "None" : _keyLabel;
            set => _keyLabel = value;
        }
        public WkKey(int[] keySeq)
        {
            _keySeq = keySeq;
            if (keySeq.Length == 0)
                _keyLabel = "None";
            else
                _keyLabel = keySeq.ToLabel();
        }
        public static implicit operator WkKey(int[] keySeq) => new(keySeq);
}
#
    [CustomPropertyDrawer(typeof(WkKey))]
    public class WkBinderDrawer : PropertyDrawer
    {
        public override VisualElement CreatePropertyGUI(SerializedProperty property)
        {
            var root = WhichKeyManager.mUILoader.WkBinder.Instantiate(property.propertyPath);
            var be = root.Q<VisualElement>() as BindableElement;
            be.BindProperty(property);
            var btn = root.Q<Button>("Bind");
            btn.clickable = new Clickable(() =>
            {
                BindingWindow.ShowWindow((int[] ks) =>
                {
                    WkKey wkKey = ks;
                    var array = property.FindPropertyRelative("_keySeq");
                    array.arraySize = wkKey.KeySeq.Length;
                    for (int i = 0; i < wkKey.KeySeq.Length; i++)
                    {
                        array.GetArrayElementAtIndex(i).intValue = wkKey.KeySeq[i];
                    }
                    property.FindPropertyRelative("_keyLabel").stringValue = wkKey.KeyLabel;
                }, -1, "WhichKey Binding");
            });
            return root;
        }
    }
#

is there a simple method to setup the array?

rough scarab
inner kayak
#

i am creating a custom control that user can bind shortcuts, so protyfiled is too simple

fiery mountain
#

anyone know of a way to detect or trigger some action on the main thread when a VisualElement is destroyed. I was setting something up in the deconstructor but it's calling something that down the chain checks Application.IsPlaying which can only be called from the main thread.

rough scarab
fiery mountain
#

Basically i am doing some cleanup of events but one of the unsubscribes (unity internal event) is checking application status

#

when i have a debugger attached, it's showing some exceptions that occur when entering/exiting play mode because when entering if your active scene has those elements it creates and destroys them at the same time as it is starting

fiery mountain
#

to give a little more details on it, it's basically using a localized string within a custom visualelement. setting table and entry triggers it when entering play mode

scarlet stag
#

Hello! Id like to make an editor tool. id like to make a node editor and connect nodes with each other. Is graph view still my only option or did UI Toolkit add something better for that purpose?

gusty vapor
knotty dock
#

Hello, I want to know if anyone knows how to disable the interaction of a VisualElement. This same thing I want can be achieved by changing the value of CanvasGroup.Interactabe of UnityUI, but I don't know how to do it with a VisualElement of UIToolkit.

versed timber
#

hi.. I've got a problem with nested EditorWindows and don't know how I should takle it..
I have few windows with their ucss and xmls, but I also want to make something like a dashboard - additional window with tabs where I can open those windows as a part of that dashboard.. I can just add their xml, but then I won't have whole logic done with my cs editor files. Is there any tutorial or somebody who knows how it should be added?

I tired to wrap those windows with custom VE and via attributes just call static method that creates that GUI (and that's also called in CreateGUI on each window), but it's problematic with OnGUI and it kinda feels hacky.

How such nested editor windows should be properly added?

inner kayak
latent shore
#

what is UI toolkit?
My friend says he heard it's very powerful and that i should look into it now that we're doing UI

#

right now we wanna make a circular cooldown that rotates/empties as the value lowers

thin coral
#

What has google revealed to you when you asked that very question?

latent shore
#

idk i didnt think much would pop up for that internet search

#

the pins here though ooh

cold bough
#

girdbackground style is not changing when i setup in this way, what did i miss?

cold bough
#

okay so i figured it out. it seems custom layout is not managed by uitoolkit. you have to manully add style sheet to graphview

#

like this

latent shore
#

oh ui toolkit does not look like something you get into unless its a very ui centric game

cold bough
#

not really, you can build whatever you want. but imho it's mainly for editorui

proven sluice
#

Question: PropertyField doesn't seem to work correctly for a field like:
[SerializeReference] object myArbitraryObject;

Is there a way to render a PropertyField (or something similar) for an object with only a runtime type?

cold bough
#

how do you add style to element that can not be added in UIbuiler? and how do i know which selector should i use? like the Node in GraphView

rough scarab
#

You add your USS StyleSheet file to the stylesheets property of an element, preferably the root of the window you're drawing your elements in.

cold bough
#

i know that, i just dont konw what style selector to use. the Node is completely hidden in UIBuilder. is there anyway i can make custom style for Node inside UIBuilder?

rough scarab
#

If you went through my resource you would find out how to find the style selector to use

gusty vapor
rough scarab
#

Most of these will get you to some details and at least answer the

what is UI toolkit?
question

proven sluice
fiery mountain
#

Anyone know why in 2022 the list view selection change isn't working in the editor game window? In the simulator and on device it works correctly.

unborn bluff
#

Why are progress bars not displaying negative lowvalues? How can I work around that? 2022.3.8

unborn bluff
#

Manipulated it using InverseLerp.

unborn bluff
#

Is it possible to add multiple draggers to a Slider element?

wind gorge
#

They might have added it in 2022 but I doubt it

gusty vapor
#

create your own custom control for this would not be that hard

latent badge
#

I've made two UI Editor Windows through ui-toolkit, one should act as a main window whereas the other should be inside the other window.

#

Each window has its own script

#

However, when I draw the uxml into the UI Builder, no code is being ru by the second window

#

The second window has buttons that I should be able to interact with, without coding it into the main .cs

#

Is this possible?

tall vortex
#

Hi ! When creating a ListView through code, you bind element to a single data, but is it possible to "hook" something on this same binding so that if you edit the element, other objects can update themselves too ?
For example, in multi selection, if i change the list displayed in inspector, i want other lists to get updated too. SerializedObject works fine for it, but for cases where Unity can't serialize the data, I can't pass a SerializedObject.

gusty vapor
#

just do event callback, no?

#

then manually wire them up

#

tho this way you must handle the undo/redo on your own

tall vortex
#

So just a classic callback on the "main" data which others listen to ?

fiery mountain
#

anyone know of a way to make a ListView behave with flex rows and wrapping?

#

I'd love a tile thing. I'd rather not use a scrollview

solid crag
#

is there anywhere where there's a list of the USS selector 'styles'? for example I've been working on a GraphView editor window, with some specific styling like --grid-background-color, --thick-line-color etc. I can't find these anywhere and only know about them from a video

wispy mango
#

Is there a way to call InspectorElement.FillDefaultInspector on a single property instead of an entire object?

knotty dock
inner kayak
inner kayak
solid crag
inner kayak
#

make sure you open the window first

#

the click slect a panel ,it should be in there

solid crag
#

it doesn't but pick element works, I didn't realize it took a second

inner kayak
#

emm, strange,anyway glad it works 🙂

solid crag
# inner kayak emm, strange,anyway glad it works 🙂

how does this help view the available USS styles though? this is helpful but I don't think this is quite what I'm looking for. I see some of the common ones like margin/padding/color etc but some like --spacing, --line-color etc are missing

#

nvm I found it, just looking at the wrong thing

#

very helpful, thanks a ton @inner kayak

versed timber
#

can someone explain to me how view-data-key works?
I'm creating dynamically list of foldouts and each of them has it's own key assigned, but when I close window and reopen it all foldouts have default (opened) state.. keys are still the same..
do I need to save that data persistence with some method? do I need to manually change foldout value while creating it from some ve attribute?

unborn bluff
#

Is it possible to overlap visual elements? What is the right way to do so?

unborn bluff
#

Sorry for the second question, but how can I overwrite an attribute of a sub element for example ListView/ScrollView's mouse-wheel-scroll value? 2022.3.8

unborn bluff
unborn bluff
wind gorge
#

It isn't

#

It's literally the same as positioning elements in ugui

unborn bluff
versed breach
#

Ops, wrong channel

viral token
#

hey so when i make a build of my game the ui wont show up on screen whats happening

tall vortex
#

Hi ! Is there a way for a ListView to differentiate when it resized through the add element button from when it is resized when modifying the size directly ?
Both trigger itemsSourceChanged and itemsAdded, so how can I get different behaviors ?

acoustic sparrow
#

Is it possible to make a grid of instantiated slots using UI Toolkit?

unborn bluff
unborn bluff
raven plover
#

Hello, I want to make a template for a window. The Problem is that I can't add things to the template. The template consists of labels, buttons and a visual Element for the content. I want to use this template and fill the content. Is this possible?

fiery mountain
#

anyone know why when you use a SVG it is showing me this warning and if so how can i resolve it so it isn't spitting out a warning?

Invalid value for image texture Enum
UnityEngine.UIElements.UIDocument:OnValidate ()
raven plover
# raven plover Hello, I want to make a template for a window. The Problem is that I can't add t...

I found this thread about this topic: https://forum.unity.com/threads/containeroverride-let-you-add-things-inside-templates-inside-specific-elements.960210/.
But I don't really understand it. Can anyone help?

trail oasis
#

i have this in my code:

            _cancelButton = m.Q<Button>("cancel-btn");
            _cancelButton.clicked += () =>
            {
                _editData = !_editData;
                _editButton.style.display = DisplayStyle.Flex;
                _cancelButton.style.display = DisplayStyle.None;
                Debug.Log("TEST");
                EditorUtility.SetDirty(target);
            };
            _editButton = m.Q<Button>("edit-btn");
            _editButton.clicked += () =>
            {
                _editData = !_editData;
                _editButton.style.display = DisplayStyle.None;
                _cancelButton.style.display = DisplayStyle.Flex;
                Debug.Log("TEST 2");
                EditorUtility.SetDirty(target);
            };

The debug log shows the correct output but for some reason the edit button doesn't swap to the cancel button... what am i doing wrong here?

fiery mountain
#

has anyone ever tried using ObjectPools with visual elements?

gusty vapor
#

c# one or Unity's?

#

I used pooling a lot for my custom editors, shouldn't be a issue

fiery mountain
#

@gusty vapor the unity specific one. I have pooled my own elements as well. I was going to do another one and realized i should just be using the unity one but wasn't sure if anyone else has tried it and had issues. I haven't noticed any issues with pooling have you had any?

flint bough
#

Hey, can anyone recommend a good tutorial? I now my basics around UI Toolkit and I've also done webdev before

#

But I'd like to mostly know the best practices for using ui toolkit for ingame UI

#

Should I be creating custom elements, how much should I do via code vs via uxml etc

gusty vapor
#

UI pooling is a very rare scenario for in-game stuff

trail oasis
#

god knows why we need to do it manually

gusty vapor
trail oasis
#

Why doesn't it just mark dirty auto for us though

gusty vapor
#

I honestly don't know, sorry 🥹

#

@gusty estuary proly knows 😂

sullen ledge
#

when is the "correct" time to perform a lookup query to find a visual element? I usually try both in Start and OnEnable, and sometimes thats successful, but other times it doesnt seem to find the visual element, where as if i put the exact same code in update (so it gets the reference every frame) it seems to always work. I would prefer not to recheck in update, but i struggle to figure out the correct timing to find these elements.

hard pewter
#

I set up all 3 TextFields to have flex-grow: 1 so each of them occupies exactly 1/3 of avaliable space, but as seen on the image, these TextFields grow when they get some input text and I dont know how to style them properly... any help? 🥹

gusty vapor
# hard pewter I set up all 3 TextFields to have ``flex-grow: 1`` so each of them occupies exac...

Do this:
1st

  1. Make a dummy container for Type, Name, Classes (each one of them)
  2. set flex to column to each and every dummy container

2nd

  1. parent your TextField to Type dummy container (then use percent for the width and set to 100)
  2. parent your MyText to Name dummy container (then use percent for the width and set to 100)
  3. and last input field to Classes dummy container(then use percent for the width and set to 100)
hard pewter
#

I guess that works, thanks man!

gusty vapor
#

aight, goodluck

teal belfry
#

so I can use a "textfield" to take in "input" from the player

#

is there a way to make it so I get the nice keyboard with only numbers and a negative sign?

#

when they click the box

fallow karma
#

Hi! is ui toolkit is more optimal to use in terms of performance? I'm working on a mobile game.

fallow karma
#

I also did a quick search just now and I saw this, what does this mean?

gusty estuary
#

not sure

#

I guess they mean something like blazor?

frank schooner
#

Is there an equivalent to OnInspectorUpdate method I can override in a custom inspector (Editor, not EditorWindow)?
I need some sort of tick to poll state, I've been susbcribing to the SceneManager.onSceneGui as a workaround but it's a little cumbersome, also what if there's no scenegui!
Using IMGUI obviously you could just use the OnGUI method as it was a tick.

gusty vapor
#

it may not what you're looking for (see the desc). Proly make your own longrunning loops in the background via async/await and do your own math

frank schooner
#

awesome thanks. I want the tick to be tied to the lifetime of the editor window so I'll put the subscribing/unsubscribing into the OnEnable/OnDisable instead.

gusty vapor
#

I really not sure what you mean by tick here. it's TimeSpan.Ticks property or ssomething else?
Just curious 🥹

merry mountain
#

Why dont nested property drawers work right with unity uxml / ui toolkit?

#

i just have a simple example and the moment i nest it inside a custom class it just explodes

#
public class TestNumbers : MonoBehaviour
{
    public List<NumberHolder> NumberHolder = new List<NumberHolder>();
}

[Serializable]
public class NumberHolder
{
    public List<JustANumber> Numbers = new List<JustANumber>();
}

[Serializable]
public struct JustANumber
{
    public float Number;
}

Edit: Removed some slight stuff that were messing up my render
Like we have a simple case like this (with a custom inspector that overrides and returns a simple property field that binds into NumberHolder)

#
[CustomEditor(typeof(TestNumbers))]
public class TestNumbersEditor : Editor
{
    public override VisualElement CreateInspectorGUI()
    {
        PropertyField field = new PropertyField();
        field.BindProperty(serializedObject.FindProperty("NumberHolder"));
        return field;
    }
}

Then we just define this

#

    [CustomPropertyDrawer(typeof(JustANumber))]
    public class JustANumberDrawer : PropertyDrawer
    {
        public override VisualElement CreatePropertyGUI(SerializedProperty property)
        {
            VisualElement root = new VisualElement();
            Slider slider = new Slider();
            
            slider.BindProperty(property.FindPropertyRelative("Number"));

            slider.highValue = 100;
            slider.lowValue = 0;
            slider.showInputField = true;
            slider.style.flexGrow = 1f;
            root.style.flexDirection = FlexDirection.Row;
            root.style.paddingLeft = 4;
            root.Add(slider);
            return root;
        }
    }```

The moment you draw this it just breaks apart
#

(the reason i have some extra styles is cause i am testing out different layouts)

#

Hmm i guess it does work if you dont use a List with a predefined array reference

#

but it does break on my case due to probably the fact i use SerializeReference on my side to handle polymorphism

#

anyone have had this problem?

#

(basically BindProperty stops working - values constantly snap to original - not allowing you to modify them, and getting SerializeReference errors due to it)

fiery mountain
#

anyone know of a way to do something like a radial fill with an image? Is there a way to use the vector API to generate a mesh with the image being cutoff at the specific points?

gusty vapor
#

@fiery mountain

#

you can achieve that with the Vector Api too, create your radial mask via vector api, export it as VectorImage and assign a background image to it.

fiery mountain
#

interesting

fervent swift
#

I've been struggling with this issue for a few hours. I have a ScrollRect that I use as an in-game message viewer. Messages are added to the bottom and there's a vertical scroll bar.
When a new message (a TtextMeshProUGUI) is added, it appears at the bottom but the view is not scrolled there. The player has to keep scrolling the view to see if there's new messages.
Every time an item is added, I would like the view to scroll so the bottom item is visible.

merry mountain
#

cause some people keep confusing it with scroll view

fervent swift
merry mountain
#

Good enough for me, give me a moment

#

check this out:

normalizedPosition```
fervent swift
#

I'm currently struggling to find the VisualElement of the object I added to the Content gameobject.

merry mountain
#

How are you adding it?

#

Just normally in the content i assume of this

#

Since this is UGUI, you cant add visual elements iirc (ill have to fact check if they can work together just in case as i may be wrong none the less)

#

Ensure you have both VerticalLayoutGroup also in the content (and contentsizefitter)

#

Albeit that depends on your use case

fervent swift
# merry mountain How are you adding it?

I instantiate a UGUI with the parent transform = the Content GameObject.
I was also looking at using ScrollView.ScrollTo(item), but I can't get hold of the objects needed.

merry mountain
#

ill explain there

hard pewter
#

I have a small problem with uss
I want this red selector to be more important than the blue one, so it doesnt override it. In my .uss file red selector appears later than blue one, but now I guess that the order is not dictating the priority, but I dont know what does

#

I guess simply names are more important than classes, so can somehow target an element that has a given name an given class, and then access its descendant?

#

oh I can...nvm I thought it doesnt work but apparently you cant use space when using multiple selectors XD

versed shard
#

[reposted here due to better fitting] Hey! could I ask for help on how to make a 9-sliced image resize its width depending on the length of a text that is positioned above it? (example picture included)

knotty coyote
#

Hi there. I'm using a two pane split view. One of the children is an inspector element. I want the inspector element to change OnSelectionChange. Atm, I remove the old InspectorElement from the Splitview, and add the new one (from the new selection). This breaks the split view. Is there another way to go about this?

#

This is how I update it atm:

                if(_currentNodeInspector != null)
                    _splitView.Remove(_currentNodeInspector);
                _currentNodeInspector = nodeInspector;
                _splitView.Insert(0, _currentNodeInspector);
gusty vapor
#

you need some sort of dummy container so it wont screw the layout when removing/adding @knotty coyote

knotty coyote
#

aha

gusty vapor
knotty coyote
#

For a container, is that just creating an empty visualElement? Or is there actually a type for that sorta stuff

#

I'm still new to the whole UI toolkit thing

knotty coyote
#

That works like a charm, thank you very much!

gusty vapor
#

np!

still lantern
gusty vapor
#

you'd need to set the default/initial size 1st then set flexGrow iirc. I made similar to that awhile back

still lantern
gusty vapor
#

yes. Also you'd need more than one uielement in the container

scenic orchid
#

I've been creating player UI in UI toolkit. I'm curious what someone else thinks about my approach.

My approach:

  • Create a theme USS
  • Think about how to split up a UI into modular "documents." Add classes from theme USS. ID key pieces of UI (e.g. buttons) in a way that's very unique. This is because...
  • For each modular "document", create a controller C#. The controller is responsible for exposing a editor UX for designers (e.g. expose UnityEvents that are triggered by buttons)
  • Assemble the modular "documents" into a page document. This page allows me to only have one UI document in a scene.
  • Add all relevant controllers to the page document.

The last few bullet points are where things don't feel quite right but I'm unsure how else to do it.

spark axle
#

then on the gameobject that has the UI document, I split logic into different components for each template

scenic orchid
scenic orchid
spark axle
#

the structure feels natural to me, but I just don't like the way unity editor handles it (e.g. having to open up the entire hierarchy each time) but I'm hoping that's just because it's still early development on that side

#

but it really depends on your project, I guess

#

I'm making a game entirely in UITK, so I want each element to be reacting to its neighbors and having everything in a single document is a lot less of a hassle

spark axle
#

on a different note... anyone has tips on how to do this..?
I need to display a floating text over a button when it gets clicked; the only solution I can think of is to load up and instantiate an uxml asset which only includes the float text element, hide it, wait a frame for resolvedStyles to compute, place it where it needs to go, display it, wait some time and finally delete it

#

and even then the positioning is still off especially when I resize the window and I cannot figure out why

#

there's gotta be a better way to create these sorts of fx, but I just can't see any..?

trail oasis
#

is it possible to add a context menu to an inspector to open the ui builder of the inspector?

#

its annoying navigating to find the ui document to edit all the time

#

they have a drop down for -> edit script but not for editing ui

#

referring to this context menu

#

would be nice if they had Edit UXML

olive totem
#

Alright, I know almost nothing about UI and frontend but I want to create a badass 'flatty' UI set in 2-3 weeks. Whats a good guide/resources I can reference to get started? I am using UI-toolkit. Does anyone have any reccommendations? Thank you!

trail oasis
#

does binding not work if we use generics?

lucid saddle
#

Hi, can someone help me pls ? I'm surfing on all forum but can't resolve my problem
I'm making a custom property drawer for my own struct, and unity throws that ⬇️ when I edit the property, in editor or in the code using the button

Unsupported type PositionRotation
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)```
**edit3**: I don't know why but recently it changed to something very similar

Unsupported type PositionRotation
UnityEngine.StackTraceUtility:ExtractStackTrace


edit: I'm on 2022.3.9f1, windows build
**edit2:** The drawer print the error but works well, and doesn't do the error when the play mode is on
my custom struct
```cs
using System;
using UnityEngine;

[Serializable]
public struct PositionRotation
{
    public Vector3 localPosition;
    public Quaternion localRotation;
    public PositionRotation(Transform tf)
    {
        localPosition = tf.localPosition;
        localRotation = tf.localRotation;
    }
 
}

just trying to use it like this

    [SerializeField]
    PositionRotation centerTransform3D;

and my drawer

#
using UnityEngine;
using UnityEngine.UIElements;
using System;

#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.UIElements;
#endif

#if UNITY_EDITOR
[Serializable]
[CustomPropertyDrawer(typeof(PositionRotation))]
public class PositionRotationDrawer : PropertyDrawer
{
    private Texture texture = EditorGUIUtility.IconContent("d_GizmosToggle").image;
    private SerializedProperty position;
    private SerializedProperty rotation;
    public override VisualElement CreatePropertyGUI(SerializedProperty property)
    {
        position = property.FindPropertyRelative("localPosition");
        rotation = property.FindPropertyRelative("localRotation");

        Foldout container = new();

        Debug.Log("here");
        Debug.Log(position.vector3Value);

        VisualElement horizontalBox = new VisualElement();

        PropertyField vector3Field = new();
        vector3Field.label = "Position";
        vector3Field.BindProperty(position);


        PropertyField rotationField = new();
        rotationField.label = "Rotation";
        rotationField.BindProperty(rotation);

        Button alignWithViewButton = new();
        alignWithViewButton.tooltip = "Align with view";
        alignWithViewButton.clicked += () =>
        {
            PositionRotation pos = new PositionRotation(SceneView.lastActiveSceneView.camera.transform);
            position.vector3Value = pos.localPosition;
            rotation.quaternionValue = pos.localRotation; 
            property.serializedObject.ApplyModifiedProperties();
            property.serializedObject.Update();

        };
        alignWithViewButton.Add(new Image { image = texture });
 
        horizontalBox.Add(vector3Field);
        horizontalBox.Add(alignWithViewButton);

        container.Add(horizontalBox);
        container.Add(rotationField);
        return container;
    }

}
#endif
lucid saddle
#

Finally fixed my problem, I moved SerializedProperty position (and rotation) from private field to in-method field and this was fixed (It also caused problem with PositionRotation in lists)
Apparently it was sort of synchronisation problem

dark blade
#
            tab_Setting = tabPageContainer.Q<VisualElement>(name: "tab-setting");
            tab_Setting.UnregisterCallback<ClickEvent>(ClickEvent_TabSetting);
            tab_Setting.RegisterCallback<ClickEvent>(ClickEvent_TabSetting);

i always told to unregister callback before register new callback, so is this rule also applied to UI Toolkit Register Callback???, especially now i am dealing with editor scripting, AFAIK unity is cleaning up everything when we enter and leave play mode, but that i guess didn't happens on editor scripts, since we never go into play mode, so what you guys think??, does always call Unregister before register?

onyx remnant
#

Hey, is it ok to create complex game UI using UI Toolkit. is it production-ready? Why should I use UI Toolkit instead of Unity UI

rough scarab
olive totem
#

Alright, Im stuck. Using Unity 2023.1. Trying to implement a custom event with UIElements but the event callback is failing. I know the event is sent however the registered callback does not receive it. I am pointing to the same VisualElement on the same UIDocument. Here is a sample script that explains my confusion. Anyones help to pinpoint my problem helps tremendously! Thank you in advance!

{
    public class MyEvent : EventBase<MyEvent>
    {
        public customStuct thing { get; set; }
    }
}
Script 1:
void Start() {
    ChildVisualElement = GetComponent<UIDocument>().rootVisualElement.Q<VisualElement>("targetElement");
        ChildVisualElement.RegisterCallback<MyEvent>(OnMyEvent);
}
void OnMyEvent(MyEvent evt) {
    Debug.Log("this function is never getting called despite it being previously registered for a callback on the same VisualElement")
}

Script 2:
Emitted thru:
IEnumerator function {
    ChildVisualElement = GetComponent<UIDocument>().rootVisualElement.Q<VisualElement>("targetElement");

    var myEvent = new MyEvent { thing = thing2 };
    ChildVisualElement.SendEvent(myEvent);
}```
#

After surfing the documentation, I am wondering if calling a middle child VisualElement is causing problems? Maybe the top-up phase is messing up the bottom-down phase because its in the middle? I do not understand it fully yet.

rough scarab
dark blade
olive totem
onyx remnant
rough scarab
onyx remnant
#

So should we use it on a big scale project or not? 2021 lts version

rough scarab
onyx remnant
#

Thank you very much

olive totem
#

This phrasing is horrible, triple negative.
Note: Don’t send events that don’t come from the operating system and can’t be found in the UnityEngine.Event types.

I think this is saying that events must be from UnityEngine.Event or an operating system event

olive totem
#

I am a little stuck. This is from the docs:

// Send user data along to the callback
myElement.RegisterCallback<MouseDownEvent, MyType>(MyCallbackWithData, myData);
The signature for the callback function looks like this:
void MyCallbackWithData(MouseDownEvent evt, MyType data) { /* ... */ }```
How would I send an event with MyType? I want to trigger an AttachToPanelEvent with my custom MyType. 

I got an event to trigger however not with MyType. Work in progress ![sakuTea](https://cdn.discordapp.com/emojis/930426171202629642.webp?size=128 "sakuTea")
spark axle
olive totem
#

This is how I am currently pooling the event. Not sure how to add in MyType when I send the event

using (AttachToPanelEvent panelEvent = AttachToPanelEvent.GetPooled())
{
    panelEvent.target = visualElement;
    visualElement.panel.visualTree.SendEvent(panelEvent);
}```
I have learned this sent the event successfully however the MyType on the other end is empty.
spark axle
#

for example

olive totem
#

Im very curious how you would encapsulate this, thank you for your help

spark axle
#

sorry, misunderstood the original code snippet

#

sounds like you should be able to do something like

using (AttachToPanelEvent panelEvent = AttachToPanelEvent.GetPooled())
{
    panelEvent.target = visualElement;
    panelEvent.RegisterCallback<AttachToPanelEvent, string>(MyCallbackWithData, "datastring");
    visualElement.panel.visualTree.SendEvent(panelEvent);
}
olive totem
#

I wanted to avoid directly referencing the script's method I want to call. It seems like customEvents are a bit wonky. Might as well have called the method directly. Maybe there is a better way to do this noted This is what worked.

script 1:
using (AttachToPanelEvent panelEvent = AttachToPanelEvent.GetPooled())
{
    panelEvent.target = visualElement;
    visualElement.RegisterCallback<AttachToPanelEvent, string>(scipt2.targetMethod, "datastring");
    visualElement.panel.visualTree.SendEvent(panelEvent);
}```
#

Script 2 doesnt need to registerCallback anymore since its done immediately b4 the event is sent.

knotty coyote
#

Hi there. I'm working with the experimental graph view to make a node editor. I'd like this to be a vertical editor, and have gotten it mostly working, except that the ports are not quite centered. Is there a way to do this?

#

I've tried setting the flexDirection directly on the port, but this doesn't seem to update the hover-over position for it

knotty coyote
#

Found a bit of a work-around by setting the label display style to none, and then setting the picking mode of the selector to position

gusty vapor
#

create your own custom Node and make your own template

wispy mango
#

hey, anyone has an idea how to rebuild a listview completely? I am changing the itemsSource and want to refresh the UI but nothing makes it work properly :(

vast maple
#

hi, is there a way to get better rounded corners than this?

#

for the inner box, not the outer one

#

if I put the border radius any higher than that, it turns into an oval, which is not what I want. I would like to only have rounded corners, but still have shape resemble a rectangle

#

nvm solved it by using px values instead of %

gusty vapor
dapper scarab
#

Beginner to UI Toolkit here, I have a very crude UI with a single button for debugging, and I would like to know how to actually get that button input into a script (with new input system)? I've looked all over online and I can't find a clear answer.

olive totem
#

Guys, I spent hours thinking my Unity client was bugged because I could not get the UI Toolkit coloring to show up. Turns out the opacity is 0% by default, everything was invisible

#

Time for bed, sleep well devs / artists / staff nemuComfPat

hard pewter
#

Can I bind EnumField to an integer property?
Cause I think this doesnt quite work...

var enumParam = new EnumField("", Enum.GetValues(parameterType).GetValue(0) as Enum);
enumParam.BindProperty(property.FindPropertyRelative("EnumValue")); //EnumValue property is an int
parameterContainer.Add(enumParam);
#

Or am I forced to manualy register value change callback and so on?

tough fractal
#

Anyone happen to know how to add a lock to a custom window, similar to the inspector and the timeline window? I'm not sure quite what it is called so as to look it up properly.

tough fractal
#

hrm. Seems I need to implement 'IHasCustomMenu' which sound fucking hilarious

rough scarab
tough fractal
#

Partially! I seem to have taken a wrong turn somewhere but made a bit of progress before closing for the night

tough fractal
#

Appreciated

tall vortex
#

Hi ! Is there a way to remove all manipulators on a VisualElement ? RemoveManipulator require to give a Manipulator reference, but that doesn't fit my purpose

#

Or is there at least a way to find which manipulators are on a visualElement ?

gusty vapor
tall vortex
#

Thanks 🙂

tall vortex
gusty vapor
#

just make a function with the required signatures

tall vortex
gusty vapor
#

does this ring a bell to you?

class DragManipulator : MouseManipulator
{}
...
private DragManipulator mouseEvent;
someElement.RemoveManipulator(mouseEvent);
tall vortex
#

Ok, so this is a custom Manipulator and you have a ref as a member, which is totally different from a signed method

#

Was it what you were talking about ?

gusty vapor
#

thats just an example

#

Just a very quick one, if you're still confused look up the examples from thhe source code on githb

gusty vapor
tall vortex
#

Oh ok, that makes sense

gusty vapor
#

whether it's cuustom or not, doesn't matter as long as it implements the interface

tall vortex
#

Thanks. Sorry for bothering you, the documentation is lacking example and the only looks wrong (element.RemoveManipulator<MyManipulator>();)

shy shore
#

Can somebody give me an overview about how Focus() is expected to work. I'm having a difficult time understanding how to do something simple, like have a menu with a list of buttons. However calling Focus() on this menu does not do anything, even if I set delegatesFocus to true on the entire hierarchy. What is the right way to do this?

olive totem
#

I got stumped again UnityChanHuh
On 2023.1, for some reason, visible is not working. SetEnabled works as intended. HomePage is the root VisualElement of the project.

HomePage.rootVisualElement.SetEnabled(false); //works
HomePage.rootVisualElement.visible = false; //does not work

Found it! New UI did not have a panel settings!

split swallow
hybrid flame
#

I am trying to do a PropertyDrawer for a custom struct. I want to flip bit of a ulong for each toggle. I have two issue. Firstly, the layout stay in min-width for some reason even after adding all the same CS class. Secondly, the value doesn't serialize even thought I changes the SerializedProperty. So everytime it redraws the property the value revert back to the previous one.
https://hatebin.com/rkmsipvifu

dark blade
hybrid flame
#

Just need to align the grid now

dark blade
#

glad to know, and UITK is easier to do layout than old IMGUI,

hybrid flame
#
    private void AlignLabel()
    {
      if (!this.ClassListContains(BaseField<TValueType>.alignedFieldUssClassName))
        return;
      float labelExtraPadding = this.m_LabelExtraPadding;
      Rect worldBound = this.worldBound;
      double x1 = (double) worldBound.x;
      worldBound = this.m_CachedInspectorElement.worldBound;
      double x2 = (double) worldBound.x;
      float num1 = (float) (x1 - x2) - this.m_CachedInspectorElement.resolvedStyle.paddingLeft;
      float num2 = labelExtraPadding + num1 + this.resolvedStyle.paddingLeft;
      float a = this.m_LabelBaseMinWidth - num1 - this.resolvedStyle.paddingLeft;
      VisualElement visualElement = this.m_CachedContextWidthElement ?? this.m_CachedInspectorElement;
      this.labelElement.style.minWidth = (StyleLength) Mathf.Max(a, 0.0f);
      float b = (visualElement.resolvedStyle.width + this.m_LabelExtraContextWidth) * this.m_LabelWidthRatio - num2;
      if ((double) Mathf.Abs(this.labelElement.resolvedStyle.width - b) <= 1.0000000031710769E-30)
        return;
      this.labelElement.style.width = (StyleLength) Mathf.Max(0.0f, b);
    }

Seems like they apply the width directly on BaseField. Which is kind of weird. Probably to stay compatible to IMGUI.

#

The note is interesting but I do already have unity-base-field__aligned on my VisualElement

/// A BaseField is a base class for field elements like TextField and IntegerField.
/// To align a BaseField element automatically with other fields in an Inspector window,
/// use the .unity-base-field__aligned USS class. This style class is designed for use with
/// Inspector elements like PropertyField, which has the style class by default.
/// However, if you manually add a child BaseField element to a PropertyField, you must add
/// the style class manually.
///
///
/// When the style class is present, the field automatically calculates the label width
/// to align with other fields in the Inspector window. If there are IMGUI fields present,
/// UI Toolkit fields are aligned with them for consistency and compatibility.

hybrid flame
#

Ok so it seems to only work if the root element is a basefield. So I did a small hack. I used the UnsignedLongField, removed the input field and added the grid and now it is aligned.

var rootElement = new UnsignedLongField(property.displayName, -1);
rootElement.AddToClassList(UnsignedLongField.alignedFieldUssClassName);
rootElement.Remove(rootElement.Q("unity-text-input"));
gentle raft
#

Hello there
Has anyone here used the UI Toolkit with screen size to match width or heith mode?
I'm on 2021.3 and when I try to use it in this mode it doesn't become responsive, I want to know if anyone has achieved a responsive screen on UIToolkit to know if it's a version bug, or if I'm doing something wrong

#

If anyone can help me with this, please send me an @

olive totem
#

@gentle raft I have only used 2023.1, however, when my UI refuses to render, my first thought is check the panel settings are attached to your UI Document and that your transparency is not the default 0. (I had to learn this the hard way) KaguyaSip Maybe that helps you

spark axle
#

not sure if this is related to UITK but since it's related I'll shoot anyways...

#

anybody has an idea why click events wouldn't register unless the mouse is moved..?

spark axle
#

hmm... turns out it's because the window I turn visible on top of my button doesn't get noticed by mouse events until I move it

#

using style.display instead of .visible fixed it shrugs

empty glen
#

Hello some question. UI toolkit support custom material or not?

#

Want to create visual effect for UI using shader graph

empty glen
#

I am using lts 2022

empty glen
#

Hmm is there no alternative?

#

I mean how another gamedev achieve same kind of thing like visual effect in their ui?

rough scarab
#

They don't use UITK

empty glen
#

Hmm I see... maybe I will combine ugui with ui toolkit.

#

Don't know if that will be a hastle or not

rough scarab
#

That is a fine workaround, though yeah, it can be annoying at times

empty glen
#

At least ugui still support custom material

#

For static UI without effect it easier to use ui toolkit

vast maple
#

hi, does anyone know how to increase the quality of textures? The icon top left is looking way choppier than it should be.

wind gorge
wind gorge
#

Try adding -unity-background-scale-mode: scale-to-fit

vast maple
#

scale mode is not the issue here, the image quality itself seems choppy no matter which one I use

spark axle
#

what's a simple way to have a temporary text appear and float up after a button click all in UITK?

#

current solution I have is to instantiate a new VirtualTree asset, start a coroutine to wait for its size to be set, manually position it on screen (with some error, somehow), give it a style class with some transition animation, wait for the duration of the transition then finally delete the object... seems a bit too much think

gusty vapor
#

what error? If it's NaNs related errors try to schedule it

spark axle
gusty vapor
#

dont use coroutine, there's no guarantee still, properly scheduling will guarantee the style to be resolved when you access it later

unborn bluff
#

How can i create control without removing its decorator?
I have a list and it has "Header()" attribute.
I created a Mask Field in UXML and set its binding path. It removed the Header()..

#

Its showing when i put it in propertyfield tho ._.

#

Also mask field's binding path not works on public List<string> ._.

errant harbor
#

So this code works in an editor window but not in a runtime UI Document script:

          IManipulator manipulator = new ContextualMenuManipulator((evt) =>
          {
              evt.menu.AppendAction(name, (x) => { action.TryInvoke(); }, status);
          });

          source.AddManipulator(manipulator);

is there a reason for that; was it not intended to work for runtime or is the reason it's not working on a Visual Element in the game view for me more of a styling issue?

digital ocean
olive totem
#

Is there a guide to using the UI Toolkit event system? I feel like I am doing it wrong. I have registerCallback b4 sending event, but then must unregister it when it lands or the events double trigger (unintended event triggers).

junior tundra
#

Uss How to select TemplateContainer

digital ocean
olive totem
#

To summarize, I think I need to use a different pre-built event even though its the same action? I am updating my UI when a thing happens, true is Method1, false is method2.

using (AttachToPanelEvent event = AttachToPanelEvent.GetPooled()) 
{
event.target = visualelement;
if(thing){
visualelement.RegisterCallback<AttachToPanelEvent>(Method1); }
else {
visualelement.RegisterCallback<AttachToPanelEvent>(Method2); }
visualelement.panel.visualTree.SendEvent(event);
}```
#

I believe the problem is that I am using the same event trigger on the same element so once both are registered, both get triggered. My quick fix was to unregister it in Method1 and in Method2. I do not think this is very efficient...I would appreciate a better approach to this.

ocean tinsel
#

Hi, I need some help, I'm currently working on UIToolkit and I want to create a DropDown menu. However I can't open it with my controller, so I decided to do a PopupField instead but it doesn't seem to work. Can I have a method to open a DropDown menu or a PopupField with a controller ?

digital ocean
#

Because yes, if you register the callback twice, it will be called twice

#
visualElement.UnregisterCallback<AttachToPanelEvent>(Method1);
visualElement.UnregisterCallback<AttachToPanelEvent>(Method2);
if (thing)
{
  visualElement.RegisterCallback<AttachToPanelEvent>(Method1);
  return;
}

using AttachToPanelEvent event = AttachToPanelEvent.GetPooled();
visualElement.RegisterCallback<AttachToPanelEvent>(Method2);
visualElement.panel.visualTree.SendEvent(event);
olive totem
unborn bluff
#

How can I update/change the item source of a ListView and update it (in runtime)

gusty vapor
spice lantern
#

I'm trying put foldout to Node in GraphView. but, when i open toggle, the shape is broke. how can i solve it?
To be precise, the size of the foldout becomes larger when opened, but the size of the node does not change accordingly.
But when i add new Choice, the node's size is flexible!

fickle comet
#

What's the status of ui toolkit / builder, is it fine to use it in production for runtime in 2022 lts? It looks interesting, especially coming from a web background, back there's still little resources. I wonder how to deal with multiple menus (there's some comment in one of the demo projects that it's recommended to have a single panel renderer?)

How do you deal with "first selected" and the navigation ordering to make sure menus work fine on consoles?

ocean tinsel
#

Hi , I need your help with UiToolkit and the popupField, I currently have generated a popupfield but it cannot get opened with click. I want to create a system which opens and changes screen resolution value with a controller but the click event by default not working. In the script, all information are correctly implemented. Do you have tips that would help me solve this problem ?

copper sundial
#

Need sóme help, im not finding the name of a color fade; I want to have an Ui image that is red on the left and beginning to get black to the right

rough scarab
tall vortex
#

Hi ! Is there a way to give tooltip for each action of a ContextualMenuManipulator's menu ?

unborn bluff
#

Does VisualElement.Q-VisualElement.Query starts from its content container or from the given element?

ocean tinsel
onyx remnant
#

is there any extension for vs-code / vs for UI toolkit to write USS better?

fluid spindle
#

Hello, I was wondering if there is a guide or something to change the sprites of the progress bar

delicate talon
#

So I found something odd and I don't know if it is a bug.

If you have a ListView and add bindings for VisualElements that are buttons or have children that are buttons. There is a weird thing where when clicking buttons everything works until you scroll and the ListView rebuilds and then if you click a button that had been removed from the list it will call the click function for said button multiple times.

gusty vapor
#
var unbind = Action<VisualElement, int> (vis, index)=>
{
    ///Clear all callbacks from element
}

myListview.unbindItem = unbind;
#

something along that code snippets. Not on my pc so cant test it, but you should get the idea

Note: If you're using binding property for serializedObject and not regular callbacks, you'd still need to release the binding from them

delicate talon
gusty vapor
#

unbinding callbacks on ListView can be a little hairy, the easiest is to cache your callbacks/events then pass it via userData so later on you can just get it from your unbind input parameter

unborn bluff
olive totem
#

I wish there was a list of what events get emitted by each method in the Unity Docs. I want to know if ToggleInClassList emits a TransitionEndEvent? I know it does usually however if theres already an animation playing from a previous event and thats ongoing, will it emit another one despite the classes toggle animation not being played since theres already another ongoing?

olive totem
#

I figured out that the 2nd Toggle gets cancelled while the first Toggle still plays sakuTea

copper sundial
#

Need some help the red thing is a panel and on the top right theres an image in the panel, Bcs i want the panel to have a little up thing idk how to say it, but i want it to look like that but that aint clean. How do i d0 that

#

And how can i move those buttons (back,save are not on the panel) above the panel so they can too be clicked

clear plinth
errant harbor
#

The DropdownField is no longer seperating items by slashes in unity 2023

#

Anyone else have this problem?

rough scarab
fierce dew
#

Hey everyone ...
I got probably a stupid question, but the way I currently use the UI Toolkit for my mobile game, I have no overlapping layers, everything seems to be in the same layer, so how can I add something which is like a pop up window, that is on top, in the same uxml hierarchy?

fierce dew
#

ex.
- visualElement (parent) |- visualElement (child 1) +- visualElement (child 2)

I want to add a visualElement that overlays child 1 and 2 ...

fierce dew
#

seems to work with position abosult, over releative ... not sure if that or using an additional canvas is the best practice or neither of both ^^

errant harbor
#

Also where would you guys recommend i report the issue to unity in a way that it is most likely to be seen and fixed for the next 2023 release?

errant harbor
#

Ok so a bit more information for anyone who might be curious about the dropdown issue in 2023, it still works in 2023.1 normal release and stops working in 2023.2 Beta and up so i imagine it'll be fixed by the time 2023 LTS is released

errant harbor
errant harbor
#

How do i access unity's internal images?

I'm making a cusom debug console window with additional functionality and rather than unessasarily bringing extra icons into the project i'd like to re-use the message, warning and error icons already used in the normal console.

sturdy lark
#

A panel, with some button children.
I want the panel to have a gridded layout for its children, such that there are 3 buttons per row. Additionally buttons will start a new row, with the 4th button appearing in the first slot of the second row.
Currently, as depicted, 4 buttons results in a 2x2 grid, but I actually want it to be a 3x2 grid, with 4 of 6 slots filled. Something like:
X X X
X - -
Additionally, I was expecting the ContentSizeFitter componenet to shrink wrap what's there, but I imagine the behaviour of the GridLayoutGroup is causing the panel to appear not shrink-wrapped.

Anyone know how I can easily achieve the desired result?

sturdy lark
#

ahh, start axis needed to be horizontal!

unborn bluff
#

UITK seems to have massive memory leaks in 2022.3.8 any known fixes for that?

unborn bluff
#

After further investigation of the problem I think it might be because I create visual elements dynamically and don't dispose of them properly

#

What is the correct way to destroy/dispose of a visual element? Is parent.clear not enough?

gusty vapor
#

unregistering callbacks is definitely no.1

#

Clear just detaching from the hierarchy and will dispose automatically as necessary but it will not clear all those callbacks

unborn bluff
#

Thanks in advance!

delicate talon
#

OK so I'm a bit confused on why this isn't working. I'm making a toolbar overlay panel for a level editor I'm working on. But I'm getting No GUI Implemented

But in my game object it shows my property drawer as intended

#

Not sure how to fix this.

#

This is the code I'm using for the ToolbarOverlay

rough scarab
delicate talon
#

Not sure if I'm missing something

rough scarab
delicate talon
scarlet stag
#

Is there yet a way to drag and move windows on the screen with UI toolkit?

#

I can only find events for editor purposes

scarlet stag
#

i got so far to address the .style.top , and style.left property but no attempt has worked so far

trail oasis
#

any one else find ui toolkit editor quite slow and a bit unresponsive when dragging elements in the document's hierarchy

#

trying to drag elements as child to another it some times just decides to instead put it at the bottom of the entire hierarchy

gusty vapor
#

my 1st impression of UIBuilder is similar to like when you buy cheap made-in chinese plastic toy. the experience is too clunky..
Hopefully that's not the case today

rough scarab
#

It's slowly getting better as time goes on. I do hope it'll end up more like Figma and become really easy to play around with layout

wet wigeon
#

I saw someone made a Figma-To-UIToolkit converter recently

merry mountain
#

reposting from editor-extensions

#

i have a property drawer with a custom delete button (calls property.DeleteCommand if said button is pressed).

This drawer then is used for my elements inside my listview (Through simple binding in this case), but after deleting a property im meant to rebuild the listview and im kinda confused as to how to achieve this since the button lies inside the property drawer and the SerializedPropertyChangedEvent isnt working (its invoked constantly & rebuilding causing recursion)
i wanted to use onItemsAdded / removed but those only work if i add and remove elements from the listview and not from adding to the item source (and usually my add logics are done inside classes instead of the editor for my use case)
any suggestions?

spark axle
#

anybody have suggestions about using pixelperfect camera with ui toolkit?

#

I'm probably setting something up wrong, but I can't seem to be able to show the camera view behind the ui document
it works using render texture as background, but then the pixels are all wonky because pixelperfect camera doesn't support render textures

#

but since it's all just a 2d game anyways, I'm wondering if I should just do everything in ui toolkit instead

fast jetty
#

Anybody tried to do splitscreen, with each side of the screen having its own Panel which only accepts navigation events from one controller?

#

Ive got a set up where navigation works but I cant figure out how to stop one panels FocusController from unfocusing an element when the other panel gets focus. The documentation says that each FocusController should only control focus for its panel, but that seems incorrect

vast maple
#

Hi, I'm having some issues where my UITK elements are blocking other UI, regardless of display and picking-mode values. Does anyone know why this is happening?

old gorge
#

Why is this not taking up the full width?

.unity-scroller--vertical > .unity-scroller__slider
{
    margin-top: 16px;
    margin-bottom: 16px;
    min-width: 16px;
    width: 16px;
}

.unity-scroller
{
    background-color:  rgba(44, 44, 44, 1);
}

.unity-base-slider__dragger
{
    margin-left: 3.5px;
    margin-right: 3.5px;
    border-width: 0px;
    border-radius: 4.5px;
    padding: 0;
    width: 9px;
    left: auto;
    background-color : rgba(209, 209, 209, 1);
}
rough scarab
old gorge
digital ocean
#

How do you return focus to a TextField with isDelayed on a ChangeEvent<string> callback? I've tried field.Focus(), and the UI debugger shows the element as having the Focus state, but there is no caret and the field is not editable. (also input is not captured by the field. Typing certain characters selects/focuses other elements)

old gorge
#

Weird, I nested the whole ScrollView inside two parent VisualElements and it fixed itself...

#

nvm issue came back when I reopened ui builder

#

I changed it to align-self: center removing the left and right margin, and the dragger is still not centered.

#

So I changed to even number of 8px for the width of the dragger and it fixed it

digital ocean
ancient shale
heady rune
#

Has anyone ever attempted either succesfully or not, to create a game with a mix of UI Toolkit and canvas ? Reason being is that certain screens require rendering 3d Objects ontop of UI, but others do not. I want to take advantage of the XML based benefits as much as possible and minimize use of Canvas to just the one or two screens I need to render 3D Objects on top of the UI, but I'm worried that mixing the two will cause problems, such as not getting the style to match up correctly

gusty estuary
#

so, just use it together with some camera

heady rune
gusty estuary
#

show only one render texture

#

oooor

heady rune
#

isn't real time render textures expensive on mobile?

gusty estuary
#

no idea

#

technically

#

you could also just not render anything at specific points where 3D object should be

#

and use overlay camera

#

but I feel like working with that is going to be awful

heady rune
#

yeah but in a CCG, you render the cards on top of a background

#

with UGUI you can render to 2 different cameras and layer them but I guess this isnt possible w/ UI Toolkit as it always renders on top, w/o using hack of using Render Texture

gusty estuary
#

so if you are really experiencing problems with multiple render textures - just have 1

#

for a specific layer

gusty estuary
#

it's a native feature

#

but anyway, I never heard anything about render texture being slow

#

so I suggest to just benchmark

#

setting up render textures with UITK is very simple

heady rune
#

multiple cameras/render textures is slow on mobile from what I understand

#

maybe with just doing it with 1 is possible

gusty estuary
#

Before attempting some premature optimization, best to actually see if it's really a problem

gusty vapor
terse stream
#

hey everyone

#

i need help with using ui toolkit on 3d materials

#

so i have this

#

but i want the interactions to be accessible by clicking on 3d materials instead, like on the cube

#

tried using render texture but it was not displayed properly and the button was not clickable. anyone can help?

rough scarab
terse stream
#

alright

orchid thorn
#

Question, how do I link my UIdocument with the new input system? Is there a page that explains it?

frank schooner
#

Hello, I'm having an issue when I VisualElement.TrackPropertyValue(SerializedProperty, callback) when the serializedProperty is an element within a list. If I remove the element/tracked-serialized-property from that list I get the following exception thrown:

ObjectDisposedException: SerializedProperty MyContainingType.myTypeWithACustomPropertyDrawer.Array.data[indexITriedToRemove].myCustomEnum has disappeared!. The visual element (controlled by the property drawer) is then no longer removed properly and the UI and serialized data becomes divergent.

I can't do a simple myVisualElement.Bind() as my UI Elements and the serializedProperty type I'm tracking are not compatible.

I can't catch the exception as it doesn't happen with a stackframe I can insert any code in.

I also would prefer to avoid creating and managing my own ListView by providing it with the various bind, makeItem, sourceItems [..] delegates. I would have more control over the binding and unbinding, but its a lot of boilerplate code to maintain when I don't need any custom functionality on the listview itself.

Any suggestions would be greatly appreciated :)

random perch
#

Hey, is there a way to move the UI? Can't move the canvas nor a empty gameobject as parent. It's just annoying, trying todo my first scene. And clicking the whole time accidentelly on the UI elements.
Any solution, or just disable UI during that time or via Script?

fickle perch
#

does anyone know how to make one of those large texture fields in UITK?

#

I tried to set the style size to, large, but it only expands width, not height

#

I wanna fit an assignable texture field here

#

but I can't find a TextureField type or similar

#

like I want this bad boy

#

but in UITK

fickle perch
#

eh nvm reverted back to IMGUI

rain wind
#

with UxmlFactory & UxmlTraits being deprecated in 2023.3, does anyone have an example how to replace them with UxmlElementAttribute?
I assume unity will document this soon~ but they haven't updated their own elements yet for me to use as a reference and I'd like to get a head start to remove the warnings spamming me now

rain wind
#

^ to answer my own question, just seems i need to put [UxmlElement] on the element... magic

gusty vapor
dreamy merlin
#

The UI Toolkit doesn't support % scale on fonts labels & textfields? or am I doing something wrong?

pastel portal
#

How to add for example a button as an inline element inside some text (like display: inline from css) ? I have 3 elements: 1 textElement, 1 button and 1 more textElement. My second text needs to begin right after button, but I don't know how to do it

digital ocean
#

Using an empty theme, there are still styles applied to the unity controls - where are they coming from? I can't find any relevant .uss files on my system, and there don't seem to be any references to styles in the control source files themselves.

unborn bluff
#

How can I add a sprite sequence animation to my UI?

frank schooner
#

When using the ListView control, in editor, with Show Add Remove Footer == false, no elements seem to be drawn under the unity-content-container when the serializedProperty array it's bound to contains a single element. is this expected behaviour? Is there a workaround (I would just enable Add/Remove Footer but then hide it in USS).

frank schooner
#

How to add for example a button as an

solar tangle
#

Does anyone know what _AEAManager is? I believe this is some middle thing between uitoolkit and the editor view.. Im doing some weird things, but also getting weird results:

solar tangle
#

Tag: EditorOnly is also not mine..

worthy fiber
#

So far i've tried every hack I found in forums to request Focus on a textfield from script but without success. I'm using UI Toolkit, did anyone face the same issue, how did you resolve it ?

solar tangle
#

@worthy fiber why not just focus on a button? thats what i do, then add styles\

worthy fiber
#

you use buttons as Textfields ?

solar tangle
#

if it needs focus/events yeah

worthy fiber
#

ok i'll try thanks

solid maple
#

Using buttons as textfields sounds kinda wild lol. Calling a normal textField.Focus() works for me. When and you calling focus?

solar tangle
#

You might need FocusInEvent..

solid maple
solar tangle
#

ive had a beer or two 🙂

#

wtf is _AEAManager?

worthy fiber
solid maple
solar tangle
#

it's auto generated by ui toolkit somewhere, my handling of the elements causes the wtf errors

#

if i knew what popped the GO, i would know where to go with it lol

#

double click the error gives me a gameobject i havent made =)..

solid maple
# worthy fiber It's something as simple as this

Yeah that looks straightforward, dunno why it isn't working. Are you sure you're not blurring after getting focus? You tried attaching a debugger or printing debug logs and everything? If so, I would also try to look at some of these values:

Debug.Log($"Is focusable: {testTextField.focusable} | {testTextField.canGrabFocus} | {testTextField.tabIndex}");
solid maple
worthy fiber
#

It sometimes randomly get focus after running the OpenChat() multiple times

#

What I found out is that once I get the focus once, I get the focus everysingle time I call the method, but once I clic anywhere else, I need to spam the OpenChat to get the focus again

#

I should probably .Blur() whatever is in focus before any .Focus()

solid maple
worthy fiber
solid maple
glacial badger
#

With the UI Toolkit, why do 100% size elements directly under the root node not resize when I resize the canvas in the builder? Can I not resize the root element in the builder or what is going on there?

dull onyx
#

guys, I've been trying to use the the new UIBuilder ListView to create a high scores list. I've created a new Visual Tree asset for the list entry

<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" xsi="http://www.w3.org/2001/XMLSchema-instance" engine="UnityEngine.UIElements" editor="UnityEditor.UIElements" noNamespaceSchemaLocation="../../../UIElementsSchema/UIElements.xsd" editor-extension-mode="False">
    <Style src="project://database/Assets/UI%20Toolkit/UGUI/listEntry.uss?fileID=7433441132597879392&amp;guid=6ba520f1250203b4d948fbbe4b670fa3&amp;type=3#listEntry" />
    <ui:VisualElement name="parent" style="flex-grow: 1; flex-direction: row; width: auto; height: auto;">
        <ui:Label tabindex="-1" text="Label" parse-escape-sequences="true" display-tooltip-when-elided="true" name="name" class="nameLabel" style="width: 30%; margin-top: 4px; margin-right: 0; margin-bottom: 4px; margin-left: 2px;" />
        <ui:Label tabindex="-1" text="Label" parse-escape-sequences="true" display-tooltip-when-elided="true" name="score" class="scoreLabel" style="flex-shrink: 1; flex-grow: 1; width: 70%; margin-top: 4px; margin-right: 2px; margin-bottom: 4px; margin-left: 0;" />
    </ui:VisualElement>
</ui:UXML>

and I created a list to be the info for the ListView. But I son't know how to correctly do the binding, for the labels on the ListEntry visual tree asset to change according to the list content. Any Ideas how can I make that happen?

dull onyx
#

Hey guys, I'm getting some problems with the list view components. As I said before I managed to add my custom List Entry object to the ListView. However the borders are no matching and everytime I change the borders of the ListView they get distorted, any tips?

errant harbor
#

Anyone know how to get around this issue. I register a change event on a foldout like this:
_inputNameFoldout.RegisterCallback<ChangeEvent<bool>>(changeEvent => FoldoutClicked(changeEvent));

and then on another foldout that is a child of the first foldout like this:
_inputSourcesFoldout.RegisterCallback<ChangeEvent<bool>>(InputSourceFoldoutClicked);

Now the problem i'm having is that when i click the child foldout the event for the parent foldout fires as well

gusty vapor
#

set the PickingMode, tons of people asked about it if you scroll way up there you'll find the answer too

snow frost
#

Hey folks, if I have an array of objects, and I want to bind it into a list, how do I get the list item as the binding path? I can get a property of the object (like in this tutorial's step 4 it binds to name: https://docs.unity3d.com/Manual/UIE-bind-to-list.html), but I'd like to bind a PropertyField to the whole object

I would need something like <PropertyField binding-path="."/> but I can't get it to bind properly... Thanks!

solid maple
# snow frost Hey folks, if I have an array of objects, and I want to bind it into a list, how...

I may be wrong, but I think by setting the binding-path of the ListView (step 3 under "Create a custom Editor..."), UI toolkit will automatically bind any elements within the list. You wouldn't normally set the list items individual binding path since it'll be something like "switches[2]" for the third element and which needs to be dynamic rather than hardcoded if that makes sense. So if you set the binding path of the list, you can just make a custom property drawer (as in the example you gave) for your item and it should work fine

snow frost
dull onyx
#

hey guys, how can I add a new List Entry to a list view in runtime?

dull onyx
tiny mountain
#

im using OnGUI and making sliders (look at the gif below for my problem)

strong sparrow
#

I added picking up wood into my game and it stores the amount of wood in an int variable and it works but I just have no clue how to put that into the UI cause ive barely worked with it

#

If anyone could just point me in a direction cause i have no clue what to do or search up, I will appreaciate it

fathom steppe
#

In a custom control, how do you specify where children will be placed? Similar to how ScrollView puts them into the "unity-content-container", when dragged onto the ScrollView.

I feel I must be missing something, been pouring over ScrollView source and custom control docs - but can't seem to find the magic.

old burrow
#

Hi All... I am trying to implement a UI in my Quest 2 VR app. Followed the instructions here:

https://docs.unity3d.com/Packages/com.unity.xr.interaction.toolkit@2.0/manual/ui-setup.html

My event system and canvas are set up just like the docs, and the menu I wrote displays in the game. When I point the red ray from the right hand controller at it, the ray turns white but I can't get the sliders or button to respond. I feel I need to also add interactors somewhere, and I was able to get the entire menu to change its placement based on the right controller being moved, so I'm close.

I have watched many tutorials, but many are out of date (prior to the XR UI toolkit) or just don't cover this well. Here is my setup:

I have killed too many hours on this, and any help will be greatly appreciated, thanks!

old burrow
solid maple
fathom steppe
#

Oh wow, my first attempt at that blew up Unity hard with thousands of-

InvalidOperationException: You can't add directly to this VisualElement. Use hierarchy.Add() if you know what you're doing.

But, I think you might be on the right track. I'm investigating a bit deeper to see if I can pinpoint it more.

solid maple
fathom steppe
#

I found that UIToolkit doesn't yet support 9-slice, so I rolled my own "good enough" that automatically generates the 9 slices based on a Sprite's border. So, I needed the 'content container' to be the center VE. Turned out decent, I think; if a little clunky.

fathom steppe
#

Notably another issue, unrelated to my original question.

UxmlAssetAttributeDescription<Sprite> - I'm using this, with a Texture2D as a sprite-sheet (lots of sprites).

Dragging one of the sprites into that field, works... temporarily. Until "refresh" then the data is semi-lost... it sets it to the 'first sprite' in the sheet.
The .uxml file has the correct sprite named. But the property just doesn't seem to load correctly in the UIToolkit editor.

Any suggestions?

solid maple
fathom steppe
#

I have a clunky workaround, but it'd be nice to clean it up if I could figure out why it's happening.
It almost seems like a bug to me. It's easily reproducible with a simple custom-component.

What's recommended code-pasting tool again? I've forgotten for here.

fathom steppe
solid maple
#

I usually just paste code with markdown:
```cs
// code here
```

fathom steppe
#
using UnityEngine;
using UnityEngine.UIElements;
class SpriteElement : VisualElement {
    public new class UxmlFactory : UxmlFactory<SpriteElement, UxmlTraits> { }
    public Sprite mySprite { get; set; }
    public new class UxmlTraits : VisualElement.UxmlTraits {
        UxmlAssetAttributeDescription<Sprite> m_Sprite = new UxmlAssetAttributeDescription<Sprite>{ name="my-sprite" };
        public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) {
            base.Init(ve, bag, cc);
            ((SpriteElement) ve).mySprite = m_Sprite.GetValueFromBag(bag, cc);
        }
    }
}
#

Oh that's neat. I've never done that before.

#

Anyway, that will make a custom control you can use in UIToolkit.
Just drag a Sprite into the sprite field, then save the uxml file.
Your sprite will 'refresh' to show the wrong sprite.

Notably, to reproduce, you must drag a sprite from a sprite-sheet that has more than 1 sprite, and you must not drag the 1st sprite in the list.

solid maple
fathom steppe
#

Yeah, looking at the uxml file, I see the correct reference.

<SpriteElement my-sprite="project://database/Assets/...spritesheet.psd?fileID=...&amp;guid=...&amp;type=3#actual_correct_sprite_name" />
#

But the UIToolkit UI shows the wrong sprite. Also the custom controller's value is wrong, when accessing the sprite (ie: If I tried to do any processing/logic with 'mySprite', it'd be the wrong one)

solid maple
#

Yeah I'm out of ideas then. If it ends up turning out to be just a bug, I'd just report it to Unity. Maybe you can work around by creating a custom scriptable object that can reference the sprite or even spritesheet/index and manually set the correct sprite in code. I haven't worked with spritesheets or anything so maybe this doesn't work

fathom steppe
#

I made a workaround, yeah.

Unfortunately I wasn't able to find any way to get a list of sprites in a spritesheet, directly. If anyone does know a way, I'd love to know.

So I resorted to basically, adding an additional string-field for the 'correct_sprite_name', then...

Resources.LoadAll<Sprite>(wrongsprite.texture)

And just iterate all of the sprites in the texture, to find the right sprite, and replace mySprite with the correct one. It's hacky "do this every refresh" call, but it "works".

vernal fulcrum
#

FIGMA Users:
Am I correct in saying there is a new Figma to Unity tool and if you have used it, how functional is it in comparision to manually converting layers to PNG for customisation?

fathom steppe
# fathom steppe ```cs using UnityEngine; using UnityEngine.UIElements; class SpriteElement : Vis...

Potentially related to this Sprite issue.

Make a VisualElement (any type), set its Background Image to an atlas/sprite-sheet Sprite that is not the first/only sprite in the sheet. (just like the previous example)

Note that the VE should correctly display the correct sprite.

Now, move the spritesheet into a Resources folder and repeat the steps (drag any non-first sprite as the Background Image).
Note that the VE should incorrectly display the first sprite in the sheet, and not the one you selected.

Is this a bug? Or am I missing something?

scenic orchid
#

Does anyone else use vanilla C# classes to act as controllers for UI?

fathom steppe
fathom steppe
scenic orchid
scenic orchid
#

When I say "controller" I mean in the sense of MVC (model view controller)

fathom steppe
#

Oh, I think I know what you mean; working on a lot of those lately. What's the question?

scenic orchid
#

I guess none really.

#

Just curious if others are using the technique

fathom steppe
#

Ah, yeah. I think it lends itself well to the MVC pattern, in my opinion.
I'm absolutely loving the UI-Toolkit because it keeps things nicely separated like that. Sans some... issues, that I keep finding. But still, in my opinion, way better than previous UI approaches (and I've been using Unity long enough to have experienced most of them > ; P)

scenic orchid
#

@fathom steppe Have you found a good way of pushing data into the UXML? In HTML there are data- attributes which affords the ability to write out info onto the html. UXML doesn't have data attributes but maybe there's another way?

Right now I have a list in my UI that has buttons for each list item. Right now I'm maintaining state in C# but it'd simplify code if I could push items like IDs into the UXML.

fathom steppe
# scenic orchid <@200416434776440832> Have you found a good way of pushing data into the UXML? I...

If the buttons are set ahead of time, look into custom controls (that I originally referenced).

If the buttons are generated dynamically at runtime, I think you could make a C# class that extends VisualElement (or even Button), and have a field for your ID. Then, when instantiating the button, do so through a factory.

I think you also could use that C# class approach even if the buttons are set ahead of time, and when you Q<Button>() just run the result through your custom class factory to build a wrapper.

If I'm understanding your question correctly.

scenic orchid
#

That helps. Cool cool

#

@fathom steppe One more Q... Do you know how to simulate a button click on a UXML button? I'm trying to write tests for my controller and I can generate UXML from C# and pass it into the controller C# class... However, I'm not able to "click" the button in a test. Any ideas?

#

I was advised to just call the OnButtonClicked style method directly since maybe Unity doesn't expose an API to programatically click buttons, maybe. But maybe I'm wrong and there is an API, I just can't find it since testing isn't really something game devs do..?

fathom steppe
#

I do not know, sorry; hopefully someone else here will be able to answer, sorry.

vast raptor
#

I've updated unity to 2023.2.0b17 - but ever since then I've been having issues, specifically UI toolkit isn't working.
Code that worked before is no longer working, such as simply setting the display mode of an element in the visual tree no longer works.

Weirdly with a blank installation on another machine, I don't get this issue. None of the other devs on the project get this issue. Any ideas?

vast raptor
#

I've re-installed unity, deleted every single editor, Unity hub, deleted all folders under appdata, and still, I get the same issue on this PC

vast raptor
#

Really weird. After all of that, the thing that fixed it was resetting my layout... That somehow fixed all my in-game UI.......

scenic orchid
# solid maple You could try this: https://docs.unity3d.com/2023.2/Documentation/Manual/UIE-Eve...

I tried a few iterations of sending an event using this technique in the context of a test.

I think I’m missing something to get it working. The thing I think I’m missing is something to “run” the UXML. I’m getting the UXML from the asset database and cloning a new tree. However I realize when I use UXML in an editor window or UI I either have to bind to the editor window’s root vis element or a ui document component. …hmm, actually I wonder if I can just attach the UXML to a ui document and get it working inside the context of a test

solid maple
# scenic orchid I tried a few iterations of sending an event using this technique in the context...

I see what you mean. My guess is that attaching to a panel/ui document is the best or only approach. I also was trying to simulate UXML but not in the context of running a test. However I could not get it to work at all. At the bottom of the link I sent they mention that there are some internal events that must not be sent but the don't specify which ones. Anyway, I ended up giving up on event synthesizing but if you end up finding something that works I'd be glad to know how you did it.

errant harbor
#

How can i get a dropdown where i can select multiple options (like a flags field) without using the EnumFiled control?

Because my items will change so i can't use an enum with set items

#

Also on a sidenote i just saw that in 2023 there are controls for tabs, really wish that was there sooner i had to make my own over a year ago and it does the same thing 😭 😂

But anyways i'll continue using mine for the next 6 months or until the 2023 LTS comes out then i'll use unitys built-in tab controls

errant harbor
#

I'll just go with this solution of using a custom UI element for now unless someone knows of a better, already build in way that looks more like a flags dropdown?

scenic orchid
scenic orchid
# solid maple I see what you mean. My guess is that attaching to a panel/ui document is the be...
[UnityTest]
public IEnumerator TodoAppControllerSimplePasses()
{
    var view = FakeTodoAppView();
    var panelSettings = AssetDatabase.LoadAssetAtPath<PanelSettings>("Assets/Editor/Demo/Views/Settings/PanelSettings.asset");
    var gameObject = new GameObject();
    var uiDocument = gameObject.AddComponent<UIDocument>();
    uiDocument.rootVisualElement.Add(view);
    uiDocument.panelSettings = panelSettings;
    var sut = new TodoAppController(uiDocument.rootVisualElement);
    var todoAdded = false;
    sut.TodoAdded += _ => todoAdded = true;
    yield return new WaitForEndOfFrame();

    var button = uiDocument.rootVisualElement.Q<Button>("user-action_add-new-todo");
    using (var clickEvent = ClickEvent.GetPooled(new Event
           {
               type = EventType.MouseDown, clickCount = 1, button = 0, modifiers = EventModifiers.None,
           }))
        button.SendEvent(clickEvent);
    yield return new WaitForEndOfFrame();
    Assert.IsTrue(todoAdded);
}
=

I tried the ui document experiment but I haven't gotten it working quite yet. The code inside the editor window works perfectly when I manually test. I'm hoping I can get a test working and think I'm on the right track...

scenic orchid
#
[UnityTest]
public IEnumerator SampleButtonClickTest()
{
    // Arrange
    var containerVisElem = new VisualElement();
    containerVisElem.Add(new Button
    {
        name = "user-action_click-me-button"
    });
    var panelSettings = ScriptableObject.CreateInstance<PanelSettings>();
    var gameObject = new GameObject();
    var uiDocument = gameObject.AddComponent<UIDocument>();
    uiDocument.panelSettings = panelSettings;
    uiDocument.rootVisualElement.Add(containerVisElem);
    yield return new WaitForEndOfFrame();

    var button = uiDocument.rootVisualElement.Q<Button>("user-action_click-me-button");
    var buttonClicked = false;
    button.clickable.clicked += () => buttonClicked = true;
    
    // Act (I've also tried variations e.g. clickEvent = new ClickEvent() or ClickEvent.GetPooled(new Event { /* ... */ })
    using (var pointerDownEvent = new PointerDownEvent())
        button.SendEvent(pointerDownEvent);
    yield return new WaitForEndOfFrame();
    using (var pointerUpEvent = new PointerUpEvent())
        button.SendEvent(pointerUpEvent);
    yield return new WaitForEndOfFrame();
    
    // Assert
    Assert.IsTrue(buttonClicked);
    
    // Cleanup
    Object.DestroyImmediate(gameObject);
    Object.DestroyImmediate(panelSettings);
}

Here is a simplified version of the test; if anyone can get this to work I would be greatly appreciative:

rough scarab
scenic orchid
rough scarab
#

Button calls RegisterCallback<NavigationSubmitEvent>(OnNavigationSubmit); internally, which does:

private void OnNavigationSubmit(NavigationSubmitEvent evt)
{
     clickable?.SimulateSingleClick(evt);
     evt.StopPropagation();
}```
#

As submit is much simpler, I'd go with that

#

I would not use ClickEvent

scenic orchid
#

Sounds good. I'll send a "submit" event instead.

rough scarab
#

Also, to be clear, SendEvent sends an event to the Panel, not to the element the method is called on

#

Which imo is very unclear, and not what you'd expect

scenic orchid
#

What the fuck it works?!?

#

@rough scarab Can you elaborate on your explanation? I'd like to understand why this works.

rough scarab
#

Focus is required, because NavigationSubmitEvent is basically a fancy remapping from what's typically "pressing Enter/Return", if the target wasn't focused pressing Enter would do nothing, or send the event to whatever else was focused.
element.SendEvent does nothing with the element, and just sends the event to the panel it's attached to https://github.com/Unity-Technologies/UnityCsReference/blob/master/Modules/UIElements/Core/VisualElement.cs#L1665 so there's no "send an event directly to an element", only sending it via the whole panel's event system

scenic orchid
# rough scarab `Focus` is required, because `NavigationSubmitEvent` is basically a fancy remapp...

Vocabulary clarification: "panel" is referring to the thing that is running the UXML, like the ui document component or an editor window's rootVisualElement? Each panel has its own event system...

Speculation: so by Focus()ing the element, the event gets assigned a target (the button) so that even the event is sent to the panel the panel can send the event down to all elements but the button will "catch" the event... Any corrections to offer up?

rough scarab
#

Yeah, the panel is the parent of the visual tree that handles focus (it has a FocusController of its own), event dispatching (it has a EventDispatcher), scheduling, everything...

#

I'm not totally across the details of how it all comes together, as there's a lot of complex logic making it flexible and whatever else, but that's the gist of it

scenic orchid
#

Wow... I don't think I could have figured this out. This solution feels like a hack but I suppose that's okay. Thanks a ton @rough scarab I'm already plugging this technique into my more complex tests

hot tusk
#

Nothing to add, just +1 that I enjoyed this thread. TIL (although whether or not I remember or use this tidbit is entirely something else).

rough scarab
#

I'm sure you can also do it with the ClickEvent, but sadly I think you'd have to actually properly populate the event so it sends the mouse position correctly so it reaches the button. It's sadly not as easy as just sending it direct. I spent a whole heap of today figuring out why my navigation events weren't being sent correctly to my runtime ListViews, so I've recently been poking around all this 😄

hot tusk
#

Oh come on, vertx, why deflate the magic. We assumed you had internalized this, not had a recency-effect thing going on. 😉

rough scarab
#

I had the first part down, but the detailed part was recent 😄

scenic orchid
#

If others are using the technique described above, make sure to update your button.RegisterCallback<ClickEvent>(onBtnClick); with button.clickable.clickedWithEventInfo += onBtnClick

solid maple
rough scarab
#

At that point I'd probably just create an Assembly Defintion Reference that referenced something that has InternalsVisibleTo access, to get internal access to UITK, and then just directly call the clickable's functions

#

I'm tired of hunting around internal code to figure out how to do things, or using reflection, at the end of the day I often just access the internals and call it directly so I don't have to think about it all

#

I found out the runtime FocusRing was screwing up my ListView navigation, so I just replace it myself with the one the Editor uses directly 😄

solid maple
rough scarab
#

An asmref just puts the code in the assembly you reference; the assemblies in this list have access to the UIElements assembly, so choose one to reference in the asmref, and then reference that assembly's asmdef in your own asmdef and call into whatever helper methods you've made

solid maple
#

Okay, it's sort of injecting some code in another assembly, it's a bit confusing but I'll try this out. This is very helpful by the way, I appreciate it

rough scarab
#

Yeah, those assemblies already have a bridge declared from UIElements so they can get internal access. So you just pop your code in their assembly using an asmref, and then access it as you would normally

scenic orchid
#

@solid maple @rough scarab I’ll try the internals assemble def trick too. If I can call clickable “click” elements directly to simulate interactions that’d be great

solid maple
#

The asmref internals ended up working out for me. So much of the UITK api is internal and thus hard to work with through code. In my case I wanted to open a dropdown field through code but no function exists for that. So I'll probably be using this technique a lot more. Thanks again @rough scarab

scenic orchid
solid maple
# scenic orchid I’m about to hop back in. You don’t mind sharing what the code looks like in you...

Sure, but I don't know if it'll really help since I just pretty much copied what I found in Unity source references:

public class DropdownMenuState
{
    public GenericDropdownMenu menu;

    public void Hide()
    {
        menu.menuContainer.RemoveFromHierarchy();
    }
}

public static class UITK
{
    public static DropdownMenuState CreateMenu(this DropdownField field)
    {
        DropdownMenuState dropdownMenu = new DropdownMenuState();

        IGenericMenu menu;
        if (field.createMenuCallback != null)
        {
            menu = field.createMenuCallback.Invoke();
        }
        else
        {
            menu = field.elementPanel?.contextType == ContextType.Player ? new GenericDropdownMenu() : DropdownUtility.CreateDropdown();
        }

        if (menu is GenericDropdownMenu genericDropdownMenu)
        {
            field.AddMenuItems(menu);
            menu.DropDown(field.visualInput.worldBound, field, true);
            dropdownMenu.menu = genericDropdownMenu;
        }

        return dropdownMenu;
    }
}
#

Basically with asmref I am able to access internals like IGenericMenu, menu.menuContainer, field.AddMenuItems, etc. CreateMenu is pretty much a copy of DropdownField.ShowMenu (which is private)

scenic orchid
#

@solid maple thanks for sharing..!

scenic orchid
#

@rough scarab I'm confused on the assembly def instructions. I want to use UITK. Based on the messages, it seems like I should add a UIElements assembly def to my Controllers.Runtime.Tests assembly definition?

UnityEngine.UI is an accessible assembly def I can add but my button.clickable doesn't have access to the internals (e.g. Click isn't accessible). I can't find any other plausible ones from the file you shared https://github.com/Unity-Technologies/UnityCsReference/blob/master/Modules/UIElements/AssemblyInfo.cs

Can you re-explain the assembly definition bits of your technique? Sorry for being a bit slow on this part 😦

rough scarab
#
  1. Create an assembly definition reference in a new folder that adds to UnityEngine.UI
  2. Add scripts to that assembly that expose relevant UIToolkit internals, making a public wrapper of some sort.
  3. Reference the UnityEngine.UI assembly in your relevant assembly definition.
  4. Call your wrapper
#

The wrapper could be an extension method, an addition to a partial class, a static method, whatever works best for your scenario

scenic orchid
#

Add scripts to that assembly that expose relevant UIToolkit internals, making a public wrapper of some sort.
How does a script expose UITK internals?

#

I created a wrapper assembly definition that includes UnityEngine.UI. What might a script look like that exposes an internal? I'm going to go hunt down the relevant one for a clickable element like a button

solid maple
#

Assembly Definition Reference is different than an Assembly Definitinon. That's where you're getting confused. They should be right next to each other in the context menu when you're trying to create it

scenic orchid
#

So... Create an assembly reference in the same folder as Controllers.Runtime.Tests?

#

And then reference UIElements...?

solid maple
#

Should be in a different folder. The way vertx explained it is that anything in the asmref is injected into the other assembly. It's like you're extending UnityEngine.UI. You should then just be able to use it normally (I guess since UnityEngine.UI is accessible to all scripts)

scenic orchid
#

@solid maple @rough scarab Sorry I'm really confused now. Okay so I created a new assembly definition reference that references the UnityEngine.UI assembly def. I created a new C# script. How would I expose the clickable Invoke method for a button through this wrapper class? https://github.com/Unity-Technologies/UnityCsReference/blob/master/Modules/UIElements/Core/Clickable.cs#L247

Am I supposed to reference the assembly definition reference in my Controllers.Runtime.Tests assembly definition?

rough scarab
#

Reference the UnityEngine.UI assembly in your relevant assembly definition.
You reference the assembly you are extending, because the asmref does nothing but add code to that assembly, it's got no functional purpose beyond that

#

How would I expose the clickable Invoke method for a button through this wrapper class?

The wrapper could be an extension method, an addition to a partial class, a static method, whatever works best for your scenario
I would just go with an extension method on Button

scenic orchid
#

I would just go with an extension method on Button
I think I get that.

scenic orchid
rough scarab
#

You create an extension method that calls into the Button's clickable, calling SimulateSingleClick

scenic orchid
#

Okay I was able to get the technique working. Wow, I haven't ever used an assembly definition reference before today.

#

Thanks @rough scarab & @solid maple

fathom steppe
#

"Foldout > Toggle" is not the same structure as a regular "Toggle".
Specifically, the Label is inside .unity-toggle__input

Is this a bug, or some sort of necessary deviation? (that makes no sense to me)

Usage Problem: Foldout as a checkbox-style Toggle.
ie: "Auto-Save" checkbox, that when enabled expands out to show additional auto-save options.

I have a standard Toggle uss theme setup for 'checkboxes', where that VE.unity-toggle__input has a background styled 'box' image.
If the two toggles were the same, I could be done already with just that.

Because they are different, this suddenly seems like a non-trivial task.

old gorge
#

Has anyone had an issue of UI Toolkit elements displaying as completely white in a Windows build?

Tabbing out and back into the game fixes it for some reason

scenic orchid
#

@rough scarab @solid maple I'm going to try to get the events working in a test context. I'm okay limiting API usage for the sake of tests but being able to use the RegisterCallback API is desirable.

I'll report back when/if I discover anything interesting or have questions.

real elbow
gusty estuary
rough scarab
#

Modern UI Development
Tutorial series is ~10yrs old

real elbow
rough scarab
tall vortex
#

Hi ! I'm encountering an issue with UIToolkit and some element whose label's width is ignored. The hierarchy is quite simple : a container with a flex-direction row, which contains a field and second container. The second container has a header and a content which is a simple visual element with a flex-direction column.
Problem is, as you can see on image, PropertyFields contained in the content have their label's width kind of ignored. I don't have USS attached to it, only Unity native classes. When I check with the debugger, the label have a width equal to 0 when it should be 'auto' and it's marked as inline (which is a sign that unity is forcing something if i understood correctly). Any thoughts on how how I could bypass this ?

sharp agate
#

Greetings all,

I'm currently facing an issue where UITK fails to load/use font assigned via the panel text settings asset(see attached imgs.). I have done everything as stated from the docs regarding it to no avail. Please, does anyone have a workaround for this or could it be a possible bug?
Meanwhile it loads when referenced in USS file, that I'm aware of.

PS: I'm sorry if this question may have been asked before, kindly tag the answer assuming so.. Thanks.

queen flint
#

Has anyone had the No GUI Implemented when trying to create propertydrawers for custom timline clips? Works for even=rything else in my project but not custom clip.

scenic orchid
#

@rough scarab @solid maple

[UnityTest]
public IEnumerator ButtonReceivesClickEvent()
{
    bool wasClicked = false;
    Button btn = new Button { name = "foobar" };
    btn.RegisterCallback<ClickEvent>(_ => wasClicked = true);
    GameObject hostGameObject = new GameObject();
    UIDocument uiDoc = hostGameObject.AddComponent<UIDocument>();
    uiDoc.panelSettings = ScriptableObject.CreateInstance<PanelSettings>();
    uiDoc.rootVisualElement.Add(btn);
    yield return null;

    using (ClickEvent clkEvt = ClickEvent.GetPooled())
    {
        clkEvt.target = btn;
        btn.SendEvent(clkEvt);
    }

    Assert.IsTrue(wasClicked);
}

I was able to get a click event sending through "normal" means in the context of a play mode [UnityTest]. Notable things: GetPooled calls some setup functions on the ClickEvent, panelSettings has to be set, the UIDocument.rootVisualElement is the UITK (ui toolkit) panel, and the ClickEvent.target has to be set to the button one wants to click. Sharing just to share.

maiden otter
#

Anyone know how to set the default scrollbar height for a scrollview element?

glacial verge
#

Is there a way to tie the button name set in the UI Builder to a const string file? I don't want to have magic strings that leave room for error when calling _testButton = m_Root.Q<Button>("myTestButton");

glacial verge
#

I made a custom button that allows you to assign an enum to the button.

using System;
using System.Collections.Generic;
using UnityEngine.UIElements;

[Serializable]
public enum ButtonId 
{
    START = 1,
    DEMO = 2,
    TEST = 3,
}


public class CustomButton : Button
{
    public ButtonId ButtonId;

    public new class UxmlTraits : TextElement.UxmlTraits
    {
        UxmlEnumAttributeDescription<ButtonId> _buttonId = new UxmlEnumAttributeDescription<ButtonId> { name = "ButtonId" };

        public override IEnumerable<UxmlChildElementDescription> uxmlChildElementsDescription
        {
            get { yield break; }
        }

        public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
        {
            base.Init(ve, bag, cc);
            ((CustomButton)ve).ButtonId = _buttonId.GetValueFromBag(bag, cc);
        }
    }


    [UnityEngine.Scripting.Preserve]
    public new class UxmlFactory : UxmlFactory<CustomButton, UxmlTraits> { }
    public CustomButton()
    {

    }
}
glacial verge
#
/// <summary>
/// This is an extension of the UIElement Button
/// </summary>
public class CustomButton : Button

I extended a button for a custom UI element, but it's undefined in another script and I have no idea why

If I perform a standard query for the type "Button" named "MyCustomButton" it will return at runtime the CustomButton instance. However at pre-runtime it doesn't even know the type CustomButton

#

Think I figured out the issue -- unity has funky extra assemblies in the small scale multiplayer template

glacial verge
#

I got it working completely without the need to create an additional type for every new button. You create duplicate buttons all of the same type and simply assign different Enums in the inspector instead of magic strings.
On the "view" side, you simply query for type and filter by ButtonId enum to assign. No magic strings anywhere to be found!

_testButton = root.Query<CustomButton>().Where(elem => elem.ButtonId == ButtonId.START);
scenic orchid
# glacial verge I got it working completely without the need to create an additional type for ev...

I like where your solution ended up. You've created a custom element to afford a design time interface.

Sharing just to share: I usually define a class string field and assign the query expression to it at programmer time For example private string startButtonQuery = $"{ButtonId.START}"; meaning where the name attribute is set to ButtonId.START; I think in more complex queries (e.g. class selections) thus have a habit of thinking of query expressions. Usage looks like view.Q<Button>(startButtonQuery);.

So far I haven't wanted/needed a design time interface but if I do I'm going to pocket how you approached this. 🎉

fathom steppe
# glacial verge I got it working completely without the need to create an additional type for ev...

I also like this idea, and may adopt something similar; I too highly dislike the string-constant matching game, and always avoid it when possible.

However, I might make consider alterations (untested, just a passing thought as I'm waking up to this) - Instead of a straight enum, I'd consider coupling it to an SO, that maybe has an enum, or a custom UI itself.

My reasoning being that, eventually, your enum list will become unmanageable. Where if instead you have something like SO's for categories/grouping/etc, each only having a subset of options - then drag-drop those 'option containers' and select the option you need, even reuse standard ones between projects. ie: One SO for "Main Menu", another for "Settings UI", or "Merchant UI", etc.

glacial verge
#

I'd think if dealing with 20+ buttons as enums maybe start looking into implementing an SO approach

glacial verge
#

Yeah scriptable objects that would contain an enum like badger mentioned. Though myself I'd just live with having a huge enum file until it hit like 100 haha

cunning obsidian
#

how would i disable this ugly blur effect on my text

#

i disabled bilinear filtering but i want to get rid of those ugly grey streaks

formal badge
#

cause if you have an enum that you just keep adding more things to, you're just hardcoding data when writing conditions for it that would normally belong in a scriptable object and end up mapped to those scenarios

gusty estuary
formal badge
fathom steppe
#

I'm also still having an issue, unrelated to that.

I posted the question in the webgl channel, since it only happens when playing a webgl build; however, I am thinking it may be better moved here, since it is UIToolkit that seems to be breaking.

Not sure if I should move it here or just leave it there.

flint bough
#

does anyone know if one can use the "shapes" or "aline" plugins to draw graphs in UI Toolkit? Or in general, if I want a relatively simulation-heavy/scientific UI with function graphs etc, whats the best way to go?

median sphinx
#

what's the proper way to load a uxml document to create a custom control? for now I'm loading from resources but I don't like this idea

#

this is what I have now

solid maple
# median sphinx what's the proper way to load a uxml document to create a custom control? for no...

Not sure if there is a proper way but that looks fine to me. Aside from using Addressables.LoadAsset or AssetDatabase(for editor UI), maybe you could define the VisualTreeAsset as a public serializable field. For custom editors you can then set the visual tree asset on the script itself, or if monobehavior, you can set it on the component probably. Also if editor script and using AssetDatabase, you can reference by guid instead.

median sphinx
#

yeah, I found the documentation that says exactly that

#

I guess my only options are the addressables or resources

lost agate
#

may I know why I don't have a button component?

rough scarab
lost agate
upper dirge
#

Hi. Im starting a new project and its been a while since I did Unity stuff. So is UI Toolkit finally in usable state? I tried it out a year ago, and my conclusion was that it is still work in progress. At least world space UI:s were not possible back then, and this seems to be the case still, but are there other limitations? The project I am starting is mobile game, with a lot of menus etc.

#

I have used Unity UI in the past, but it has its limitations (like the lack of global styles). So if UI Toolkit is finally mature, I could move on...but is it?

rough scarab
#

the feature list has expanded and so has the stability/workflows, but the two major world-space/shaders features are still missing

upper dirge
#

So no major improvements during the past year..?

#

UI Toolkit and Unity UI can be used in paraller, right? So if I need world space UI:s, i can implement those with Unity UI?

rough scarab
#

Yes

upper dirge
#

ok thanks

hidden nova
#

is it normal i cannt find the normal test ui

mental cave
#

Hi guys. Why my SVG looks like this?
(Not like in UI builder)kekwait

info:
Unity 2023.2.3f1
Def. 2D template

tame vessel
#

Anyone managed to do sortable tables?

ornate obsidian
#

i want to add arrows selection on button hover, just started and think im getting the tag stuff wrong, i thought i could just set them to visible on the tag .menu-button:hover#Arrows
am i wrong?

rough scarab
#

If they're a direct child you separate the queries with >, if they're a descendant you separate with a space

#

#Arrows is a direct child of .menu-button, so that's .menu-button:hover > #Arrows

#

@ornate obsidian

ornate obsidian
#

I mean i tested with colour instead of visibility and it worked

#

so im a bit confused

#

But ill try that

#

Yeah it just doesnt work if i wanna set the visibility to true, is that how it works? can i only change the visual colours and so on?

rough scarab
#

Toggle the display visible setting to false and then true so it's actually marked as a change

#

because there is no white bar/bold text, it's not actually a listed value in the USS

ornate obsidian
#

You mean just pressing this right?

#

Well i do

#

but i dont know i can do a work around so its not big deal but dont know what im doing wrong haha

ornate obsidian
#

is there smthg similar to figma with text auto-width so the container fits the widht of the text and not a fixed width?

median sphinx
#

Hi, I have a problem with ui toolkit input field and webgl full screen on mobile

#

the input doesn't show the keyboard when I click it, but it works normally if it's not full screen

median sphinx
#

confirming that using the old ui "uGUI" the keyboard shows on full screen, but not on ui toolkit

#

I hope there's a setting I can use the fix this issue

#

rebuild the whole UI now would be painful

median sphinx
#

the ui input field appears behind the canvas when on full screen

mental cave
#

How i can change this default control widget?

quick sable
#

Is there a way to set a toggle to this "in-between" state?

rough scarab
tame vessel
#

Is there a performance consideration to consider like with canvases when updating text continuously, if I have a top bar in my game that displays resources that need to be constantly updated. Think RTS resources, building buildings, units etc.

rough scarab
plucky glacier
#

hey, how can I disable/clear the sorting indicator on a multi column tree view? Clicking on a column header makes the sorting indicator arrow appear but I'd like to make it disappear with kind of a "clear sorting" button

median sphinx
#

I might be blind, but how do I change the toggle background color?

#

If I change the background color on this guy I don't get the result I'm expecting

#

nevermind, I have to change background color on the checkmark, weird

#

background color changes the background and tint color changes the flag

rough scarab
maiden otter
#

Is there a way to reverse the direction of scrollview?

gusty vapor
#

define reverse

#

the scrolling or ?

wooden delta
#

Is toolkit good enough yet to be used in production? I wouldn't wanna lose time switching back to regular UI mid-project.

ancient shale
wooden delta
#

I'll stick to regular UI

solid maple
# wooden delta I'll stick to regular UI

I haven't done much in-game UI but, IMO, UITK is really great for creating editor extensions / UI. I actually can't go back to the old way of creating UI. I am also using it to create in-game world-space XR UI and it works great for me. Also easy to use especially if for those that have a web dev background. Just my take

maiden otter
maiden otter
#

nvm solved it by reversing the transform of the scrollview and then reversing all the elements inside. Probably not the greatest way of doing it but I'm limited since I'm using a react native-esque plugin

#
    <div class=" w-72 h-96 bg-orange-900 rounded-lg border-2 border-white mr-4 mb-16 flex flex-col text-white p-4 ml-auto mt-12">
      <span className="bold text-xl mb-2 text-center">{data.npc.npcName}</span>
      <scrollview
        ref={scrollViewRef}
        class="max-h-full pb-4 transcript-scrollview"
        style={{ scale: [1, -1] }}
      >
        {data.Dialogue.reverse().map((object) => {
          return (
            <div class="mr-4" style={{ scale: [1, -1] }}>
              <div class="mt-4">
                <div class="bg-white w-full min-h-8 rounded-lg border border-black text-black p-2">
                  {object.Message}
                </div>
                <div
                  class={`text-orange-300 bold ${object.isAI ? 'ml-auto' : ''}`}
                >
                  {object.isAI ? data.npc.npcName : 'You'}
                </div>
              </div>
            </div>
          );
        })}
      </scrollview>

      <textfield
        ref={textFieldRef}
        onNavigationSubmit={() => {
          data.npc.SubmitChat(textFieldRef.current.ve.Children()[0].text);
          textFieldRef.current.ve.Children()[0].text = '';
        }}
        class="bg-white text-black bold mr-10 mt-auto"
      />
    </div>
warm bluff
#

this should look like that? unity 2022

#

ahh yes default unity runtime theme

fathom steppe
#

How do I set 'disabled' via css? I see :enabled :disabled selectors, but can't find a style to set. Does one even exist?

Scenario: I want to disable all inputs in a panel while processing.

ie: Add a '.processing' class to the parent, with css rules like: .processing Button { enabled = false; }

Only thing I can think of is a callback to manually Q<Button>() and toggle, but this feels cumbersome. But may be the only way?
Using parentPanel.SetEnabled(false) - is hierarchical, so its children are also disabled. This is an easier workaround, but still would be nice to be purely style controlled.

cobalt nimbus
#

Hello! Is it possible to use ui toolkit with shader graph?

rough scarab
tranquil sigil
#

How to create a visual element that's not affected by the layouts?

#

So it should just be a like a floating image on screen that I can animate programatically

rough scarab
hushed nexus
#

I have an issue with the UI builder, I parented 5 visual elements to another visual element
Each of child elements are displayed next to each other, yet they don't occupy the entire height of the parent

how could I resolve this?

cinder narwhal
# wooden delta Is toolkit good enough yet to be used in production? I wouldn't wanna lose time ...

In my opinion UI toolkit is much better than UGUI was years ago… but in that time nested prefabs and prefab in context improvements, plus the UGUI package being Source code so you can step through and debug all your LayoutGroup nonsense mean that unless you have a large pile of web developers you need to be feel happy, just stick with UGUI for everything. Otherwise you will end up using UGUI for some of your UI anyway and then you have 2 systems.

hushed nexus
tranquil sigil
#

How to get top root of the UI Document?

gusty vapor
rough scarab
#

Both are coming, it's just sad it's taking so long ):

gusty vapor
#

yeah, lets hope it will happen when 2023 lts released

rough scarab
#

Unity 6? Maybe

gusty vapor
#

I'm hoping as soon as possible, the issues have existing more than 2 years at this point and lots of people are starting to doubting uitk due to how slow they're fixing these two most glaring issues

tranquil sigil
#

Where even is aspect ratio lock button

#

That comes before fancy custom material pls

rough scarab
#

I have been using it for ~5 years

gusty vapor
#

We almost used uitk in production last year, but bailed out due to it failed passing our prototyping phase

gusty vapor
# tranquil sigil Where even is aspect ratio lock button

if we're talking about flexbox convention, this feature should be in their flex api. Sadly there's nothing like this at all in there.
But it's easy to make. Here's taken from my Maui code which you can adapt it to any type of layout you're using in uitk

        (double width, double height) CalcAspectRatio(double srcWidth, double srcHeight, double maxWidth, double maxHeight)
        {
            var ratio = Math.Min(maxWidth / srcWidth, maxHeight / srcHeight);
            return (srcWidth * ratio, srcHeight * ratio);
        }

trigger it after attaching or after the size has been allocated/resolved

#

iirc if it's runtime stuff, there's one available in the Panel iirc

#

just make sure your child elements can be dynamically sized, well, or just use flexbox

#

Note : with flexbox you can use it on the parent, without it, you must manually resize each of the child element

gusty estuary
#

Is there a way to have a custom window holding built in window?

#

I want to have a custom window

#

With hierarchy + inspector of custom prefab

#

Without affecting currently open prefab

#

so I just need a hierarchy window + inspector window in split pane window

fathom steppe
#

Building a chat-window, and can't think of any way to get a desired UX: [Time] [Username] [Message] - Where Time can be toggled on/off, Username may change to a new color, and Message wraps beneath the entire line (under Time and Username) to maximize space-efficiency.

My first thought was 3 labels, easily toggle-Time and color-Username; however, it would not wrap as desired.

Second thought was 1 label, so it wraps properly; however, then I can't easily toggle-Time and update-color.

Unless there's some magic I don't know of, to make either of those two routes work as desired. (?)
Any suggestions?

gusty vapor
gusty vapor
#

I don't know how they did it tbh, wasn't me who made it. it looks basically the exact copy of the hierarchy

cobalt nimbus
gusty vapor
#

let alone VFX support, uitk still cant do custom shader ootb

#

kinda sucks tbh

wraith mist
#

How can i change the background color of the Text field in the ui builder?

solid maple
wraith mist
solid maple
#

Well the example I gave targets the field box, if you want to change the background color of the label and the field, you should be able to just change the background color under the "Background" section in UI builder. What are you trying to do?

wraith mist
solid maple
#

Something should've changed for sure, are you sure the alpha value is not set to 0?

wraith mist
solid maple
#

How does it look? TextField is changing for me:

wraith mist
#

wait it changed something

#

i try unsetting everything ig

solid maple
#

Oh, well that seems to be your issue lol. I don't know what's going on though, is there another element on top? Where is the white coming from? Maybe try changing border color or something else idk?

wraith mist
#

I tried some things but it doesnt work i only need to change the white part (behind "filler text")

solid maple
#

The link I referenced might help. And if you want to understand uss maybe learning a bit about css syntax could also help. (I know css so I'm used to styling with sheets)

rough scarab
#

I also have a guide "styling elements" that is pinned that goes over my workflow

wicked totem
#

How do I get a UIDocument to obey the canvas size I set for it? I set it to 1920x180 but it still fills the screen. Why does it do that?

solid maple
wicked totem
#

Ok thanks. That was so simple. A bit confusing that the canvas size is meaningless though.

solid maple
wicked totem
#

Is there a way to make a listView that has 2 columns of X items? I looked at multiColumnListView but that seems to be for each individual item having multiple columns, rather than the listView itself "wrapping" into a 2nd column if the first one is full.

ie. In this picture it would be 2 columns of 16

wraith mist
#

How can i scale the UI Element which i build with the builder to support diufferent aspect ratios?

#

I tried to use the canvas scaler but it doesnt work

mortal anvil
#

Anyone have examples of drag and drop inventories using UI Toolkit? Specifically when dragging across different UI Documents? Or at least a child element to a different parent element?

Having trouble figuring out a good way to do it and will likely just switch to uGUI for this kind of stuff if too much of a work around is needed for UI Toolkit.

wraith mist
spark oxide
#

why cant i see the outline of my label? if i put a bigger value, the text gets slimmer

spark oxide
austere geode
#

Whats the best way of animating UI? Does anyone have a good video or article about it? or just person take

fathom steppe
stark jacinth
#

Got this Unity inventory UI with slots and backgrounds to hide images. I made a button to open it up, but when I set everything to 'not active,' they go unresponsive in the game. And when I try to reference them in another script, it's like they've vanished from the scene. Any ideas to handle this better?

tidal fable
#

How do you make a UIElements (UI Toolkit) PropertyField readonly?
there's an option for it in the ui builder but I can't figure out how to do it through a script
SetEnabled(false) works partially, in the sense that it disables editing the property, but doesn't allow selecting the values
Can someone please help me on this?

ornate obsidian
#

is it possible to have a particle system using UI Builder?

hoary marsh
#

@gusty vapor I actually tried using the UIToolkit to replicate something doable out of the box by Odin, didn't go well xD
This is the behaviour I want to replicate: https://gdl.space/uhemetapeb.cpp

#

so typing [SerializeField] WeightedSelection<TileType> middleTile; gives me this:

#

The issue (without UIElements) is that as soon as the serialization tree gets a little more complex it freaks out and straight up doesn't render it (with errors)

#

This was my attempt with UIElements but it's clear I don't know what I'm doing -- it rendered only the %s rect but not the list property, lol:

public override VisualElement CreatePropertyGUI(SerializedProperty property) {
    var container = new VisualElement();
    var weightObjsProperty = property.FindPropertyRelative("weightObjects");
    DrawWeightBars(container, weightObjsProperty);
    container.Add(new PropertyField(weightObjsProperty));

    return container;
}

void DrawWeightBars(VisualElement container, SerializedProperty weightObjsProperty) {
    container.Add(new PropertyField(weightObjsProperty));
    container.style.flexDirection = new() { value = FlexDirection.Row };

    float totalWeight = Enumerable.Range(0, weightObjsProperty.arraySize)
                .Sum(i => weightObjsProperty.GetArrayElementAtIndex(i)
                .FindPropertyRelative("weight").intValue);

    int i = 0;
    foreach (SerializedProperty item in weightObjsProperty) {
        var weightProperty = item.FindPropertyRelative("weight");
        var widthPercentage = weightProperty.intValue / totalWeight;

        var bar = new VisualElement();
        bar.style.flexGrow = 0;
        bar.style.flexShrink = 0;
        bar.style.flexBasis = Length.Percent(widthPercentage * 100);
        bar.style.backgroundColor = niceColors[i % niceColors.Length];
        bar.style.height = 12;
        container.Add(bar);

        bar.Add(new Label(i.ToString()));
        i++;
    }
}
#

had bit of trouble getting anything non-UnityEngine.Object so gave up on ListView after not finding a valid target item source lol

indigo hound
#

is there any way to override these? I'm trying to increase the height of the slider and these values make it very hard to keep everything centered

unborn bluff
#

Blur for UITK ?

tall vortex
#

Is there an equivalent to GUI.Color for UI Toolkit or do we have to modify each individual color of elements ?

solid maple
tall vortex
#

OK, so there's no such thing as a tint that would work the same way GUI.Color does. It's background-color and I need to do the multiplication myself. Thanks for the answer

solid maple
ebon lark
#

Why does unity seemingly insist on not letting me modify the UI styles?

#

like the style is there but it's combining it with the defaults and then I need to reference the default style sheet or else the UI doesn't work, don't recall having this issue before

gusty estuary
#

not via uxml

ebon lark
gusty estuary
#

just make a style that targets those classes

#

and... that's it

ebon lark
#

This doesn't seem to work

gusty estuary
#

what doesn't work for you?

ebon lark
#

making a selector for the text field element

#

What would be the method of doing the TextField as an example

#

I understand what's happing now,

rough scarab
charred zephyr
#

I think I'm missing something basic.. when adding a TabView and Tab to my UI Document this is the default styling that I get. Is this as intended?

#

(orange text my captions added to the screenshots)

analog bronze
#

how do i get my ui to have a custom size

#

i want black to be a specific size

#

i can only drag it up and down, it wont let me drag left or right

#

Both of the widths are displayed as 957 in the debugger

#

oof unity just OOM'd

analog bronze
#

i tried

#

but the children still stretch to the width of the item

fallow badger
#

something fundamental changed between unity's 2022 -> 2023 versions?
after migration to 2023 some of my ui got broken
in this picture my element has selector but it's values not respected

analog bronze
#

im on 2023 too

gusty vapor
#

set Grow to 0 on the children

analog bronze
#

oof

#

isnt there a way to set it on the parent and have children automatically respect such

#

tho why is grow set to 1 by default

fallow badger
#

if element have styles with "inline" it means this styles was set manually for it?
this elements was created by new VisualElement() and apply nothing after, so why they have overrides for all possible styles?
It was not like this back in 2022

analog bronze
#

Dunno

tranquil sigil
#

How to move UI elements around programatically?

#

I'm trying to make an image slowly move towards another visual element

#
_icon.schedule.Execute(() =>
    {
        _icon.transform.position = Vector3.MoveTowards(_icon.transform.position, _targetElement.transform.position, 2f);
    }
).Every(50);
#

But this doesn't work

tranquil sigil
#
long executionTime = 50;
float speed = 1.2f;

_icon.schedule.Execute(() =>
    {
        Vector2 direction = new Vector2(rootContainer.resolvedStyle.left - _icon.resolvedStyle.left, rootContainer.resolvedStyle.top - _icon.resolvedStyle.top).normalized;
        Vector2 newPosition = new Vector2(rootContainer.resolvedStyle.left, rootContainer.resolvedStyle.top) * direction * speed * (executionTime * 0.001f);

        _icon.style.left = newPosition.x;
        _icon.style.top = newPosition.y;
    }
).Every(executionTime);
#

This still doesn't work

vale charm
#

How can I fix the text showing behind the other image?

tranquil sigil
#

Anyone?

solid maple
# tranquil sigil Anyone?

Find out what's not working about it. If you simply set only _icon.style.left = 200 or some arbitrary value without scheduling, does the icon position change at all? Is the _icon absolutely positioned? Is the _icon just not moving? Or is the rootContainer values not what you expect it to be?

The only advice I can give you is that your first attempt doesn't look like the right way to do it but the second attempt seems to be going in the right direction

tranquil sigil
#

I guess the better question would be how to get the target VisualElement's absolute top/left values

#

When they aren't using absolute position

solid maple
#

Yeah exactly, that's probably the problem. You can try .layout and .worldBound. Idk maybe one of those would work

tranquil sigil
#

It seems like .worldBound is the absolute position, .layout returns 0 0 as well.

#

Ok that is very confusing

#

All these layout and worldBound and how to even set them

solid maple
#

I think layout returns the position relative to the parent. You can probably recursively get the position by adding all layout's left/top positions to the root element. Or maybe you can use ChangeCoordinatesTo which was referenced in the link I sent. Idk if those could work

thorny vigil
#

Hey, guys.
I'm going to change the UI from UGUI to Toolkit for the corporate project.

#

First I wanted to know if the clicker was optimized in the toolkit?
How about the limitations of uguI
I've never worked yet. I wanted to ask a few questions first.

thorny vigil
#

Do you know how I can check the performance of the mans click on the profile I can get results

quick sable
#

the performance better than ugui

thorny vigil
quick sable
# thorny vigil Tkanks, I'm just sorry. I'm taking your time. Have you read an article or have y...
  • UI toolkit doesn't have to redraw the whole canvas when one element changes.
  • UI toolkit has a much faster layout engine. In uGUI the recommendation is to avoid layout groups when possible, while in UI toolkit everything is placed using the layout.
  • UI toolkit doesn't have the overhead of game objects and components.

There are a bunch of other sources that say the same thing if you just google "ui toolkit performance".

analog bronze
#

nice

#

should i use Unity 2022 or Unity 2023 for UI Toolkit ?

#

im currently on 20223 but apparently it is still (beta)

analog bronze
#

tbh UI Toolkit is very different from what im used to working with :3

analog bronze
#

hmmm```
Some Android devices and WebGL can’t partially patch index buffers.

If your audience uses such devices or if you target WebGL, UI Toolkit rendering is still functional but performance may be degraded.

To avoid performance degradation, don’t animate too many elements at the same time and profile on device.

median sphinx
#

hi, does anyone know a library to create charts?

gusty vapor
#

You can make your own pretty easily with Vector api

tall vortex
#

Quick question: I'm trying to update a custom inspector from IMGUI to UIToolkit and I was wondering if CreateInspectorGUI also work with HasPreviewGUI or if it was only a IMGUI thing

cinder pier
#

I can't seem to find how to have a button detect being held down in UI Toolkit, anyone know how it might be done?

manic plover
#

do we absolutely need to use third-party solutions for animation timelines in toolkit? or will there be an official solution coming within the next few months

cinder pier
#

Sounds like until the thing they announced is ready to be launched, 3rd party is best party.

manic plover
#

I just really dont wanna migrate after

#

imagine i spend 6 hours on UI timelines only to have the official soltion require remaking them

#

I like toolkit so much more than canvas just cause of how easy it's been to make dynamic UI like a list of character skills (its also especially more cooperative with controller support - less buggy)