#🧰┃ui-toolkit
1 messages · Page 15 of 1
In the dropdown in the top left I think you don't want GameView
You want the name of your panel
thanks, it works now
Using debug, it always shows visual element screen, which is top of my hireachy
Even when I do picking mode - ignore
Weird... I have no more advice. If you do find the issue do let me know so I can't help others in future
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
How would I do that? (adding a MouseDown event to the parent)
I tried to change it, but it dosen't do anything. Should I set on all parent visiual elements "ignore"?
I tried that and debug.log doesn't trigger
Maybe it has something to do with me using InputSystem? but then why other buttons work, which do not have a screen parent...
I am going crazy. Is here anyone who can save me 🙏
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)
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🙏
add them outside of list view
keep list view as list container only
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 ;/
unity manual is pretty good
tons of examples
many thigns explained in depth
it's pinned
thats tutorial?
there you will find the most information on ui toolkit in whole web
Okeyy thank u very much... if i will got some problems can i write to u?
Yes, but not before asking google
I asked google and many youtube videos. Can someone help me, please?)
I detailed my problem here
https://forum.unity.com/threads/button-does-not-work.1487289/
all elements registration better happen inside OnEnable
OnDisable scraps all hierarchy
so when enable back, all Start callbacks are gone
thanks, good to know.
However, I moved it on OnEnable, and it didn't solve the problem
can you show button inspector in ui builder?
picking mode yeah
forgot what's it called
but seems ok
what about button when you click it
does it change style?
no, it doesn't react to mu clicks
yes
try to put your button at root and bottom of document
also
open debugger
and see if nothing is over your button
I have two visiual element above it: screen and left
debugger shows screen
I put them on ignore, and the problem is still there
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
it shows the same as my UI document
why cant i set my own Width?
okey dokey'
D:
I found a hidden screen visual element, which is not in my UI Doc
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
try to play with with Flex "shrink" and "grow"
for child and the parent
where exactly is that?
i got it, but still i dont exactly know what should I do ;/
try putting parent or child at 0
and see whether width changes
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
use % instead of pixels
The square in UIbuilder isnt 320x180
i did it
but now it looks like this
okey
i changed to auto
in flex
now its better
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
omg
it is already, but i cant find a good one, and webs where sth is not exactly showed in video are hard to understand for me
...IT worked
good
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
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...
Hey everyone! Are there any graph-based menu controllers for UI Toolkit, like Doozy or UI Graph?
uitk integration with bolt is on the the roadmap, not sure if that's already done or not
Ok. Then I have a question to people who tried Doozy or similar packages. What's your opinion on Doozy vs UI Toolkit?
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);
}
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);
};
};
Is there an easy way to do a weight based sizing? I keep setting weight for elements % values. :(
flex grow
Tyvm!
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
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.
How can I execute a callback in a VisualElement when it's repainted/redraw?
repaint/redraw-ing in uitk isn't the same like in immediateMode, that said you only know when it's resolved or not
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?
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
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
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
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?
Just draw a PropertyField?
i am creating a custom control that user can bind shortcuts, so protyfiled is too simple
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.
Generally DetachFromPanelEvent is what you want to clean up depending on what you're using it for
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
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
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?
graphview is rock solid still 👍
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.
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?
here you have some snippets: https://discussions.unity.com/t/ui-toolkit-disable-button-in-uxml-template/252079/3
🍷 thanks, I will try that
have you tried change pick-mode to ignore?
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
What has google revealed to you when you asked that very question?
idk i didnt think much would pop up for that internet search
the pins here though ooh
girdbackground style is not changing when i setup in this way, what did i miss?
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
oh ui toolkit does not look like something you get into unless its a very ui centric game
not really, you can build whatever you want. but imho it's mainly for editorui
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?
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
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.
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?
If you went through my resource you would find out how to find the style selector to use
One or two may come up and those are barely in-depth and currently it's still flooded with Unity's legacy UI systems. New curious users will have a hard time googling for it I'd say
It absolutely is not difficult to find in the documentation, if you know UI Toolkit is the search term plenty also appears.
Most of these will get you to some details and at least answer the
what is UI toolkit?
question
Thanks I'll try that!
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.
Why are progress bars not displaying negative lowvalues? How can I work around that? 2022.3.8
Manipulated it using InverseLerp.
Is it possible to add multiple draggers to a Slider element?
Not in 2021
They might have added it in 2022 but I doubt it
create your own custom control for this would not be that hard
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?
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.
just do event callback, no?
then manually wire them up
tho this way you must handle the undo/redo on your own
So just a classic callback on the "main" data which others listen to ?
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
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
Is there a way to call InspectorElement.FillDefaultInspector on a single property instead of an entire object?
I really don't know. it looks like SetEnable is what I was looking for, thanks anyway.
window/UI toolkit/debugger, serlect a panel and pick elment
create a new propertyfield and set bindingpath to the property name
it's a custom editor window, it doesn't show up in the debugger dropdown, is it supposed to?
it doesn't but pick element works, I didn't realize it took a second
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
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?
Is it possible to overlap visual elements? What is the right way to do so?
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
position: absolute
I queried ListView's ScrollView and changed the attribute
Isn't there another way? That is what I am using currently but I thought it is a bad way.
Thank you
Ops, wrong channel
hey so when i make a build of my game the ui wont show up on screen whats happening
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 ?
Is it possible to make a grid of instantiated slots using UI Toolkit?
You can with 2 for loops, just like you would make a normal grid.
And make sure you have Wrap set to wrap for the container of the slots inside UIBuilder
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?
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 ()
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?
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?
Did you try this on both your buttons ? https://docs.unity3d.com/ScriptReference/UIElements.VisualElement.MarkDirtyRepaint.html
has anyone ever tried using ObjectPools with visual elements?
@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?
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
not much as it's just pooling. What is your use case? if they're not a lot pooling is useless tho
UI pooling is a very rare scenario for in-game stuff
you would think if you change something on the element it would auto mark dirty for the next frame for you
god knows why we need to do it manually
Changing DisplayStyle is a bit peculiar as it's actually reconstructing the whole geometry, so MarkDirtyRepaint makes sense
Why doesn't it just mark dirty auto for us though
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.
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? 🥹
Do this:
1st
- Make a dummy container for Type, Name, Classes (each one of them)
- set flex to column to each and every dummy container
2nd
- parent your
TextFieldto Type dummy container (then use percent for the width and set to 100) - parent your
MyTextto Name dummy container (then use percent for the width and set to 100) - and last input field to Classes dummy container(then use percent for the width and set to 100)
aight, goodluck
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
Hi! is ui toolkit is more optimal to use in terms of performance? I'm working on a mobile game.
yes
Thank you!
I also did a quick search just now and I saw this, what does this mean?
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.
use EditorApplication.update + initializer
[InitializeOnLoad]
class Foo
{
static Foo ()
{
EditorApplication.update += Update;
}
}
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
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.
I really not sure what you mean by tick here. it's TimeSpan.Ticks property or ssomething else?
Just curious 🥹
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)
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?
with SVG you can
@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.
interesting
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.
UGUI Scroll Rect component right?
cause some people keep confusing it with scroll view
It does say Scroll Rect in the inspector.
I'm currently struggling to find the VisualElement of the object I added to the Content gameobject.
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
this is more of a #📲┃ui-ux though
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.
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
[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)
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);
you need some sort of dummy container so it wont screw the layout when removing/adding @knotty coyote
aha
so you just need to clear/remove the children and the layout will stay intact
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
yes, just empty viselement
That works like a charm, thank you very much!
np!
How do you have a multiline textfield in a scrollview expand to take up max room, but still allow scrolling. It is the same as this person
https://forum.unity.com/threads/how-to-make-textfield-fit-scroll-view-and-also-expand.1371714/
Or is this like wanting to have your cake and eat it too?
you'd need to set the default/initial size 1st then set flexGrow iirc. I made similar to that awhile back
What do you mean? Like the min-height or something?
yes. Also you'd need more than one uielement in the container
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.
I'm no expert in UITK by far, but I've been nesting template instance inside a single UI document for my whole project
then on the gameobject that has the UI document, I split logic into different components for each template
How does it feel for you? I get a sense I’m kinda doing something wrong
Yea this is exactly how I do it too 😄
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
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..?
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
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!
does binding not work if we use generics?
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
I don't find any real difference with the tutorial https://docs.unity3d.com/ScriptReference/PropertyDrawer.html
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
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?
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
There is a feature comparison and recommendations doc in the pins
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.
Oh w8, this is in artist tools. Maybe I should pop this in #archived-code-advanced instead?
The issue may just be that you are not setting up your event correctly. I am unsure if there's requirements in the usual way of doing it https://docs.unity3d.com/Manual/UIE-Events-Synthesizing.html that you are missing out on by going the route of a plain constructor
name selector #element has more priority over class selector .foldout-error
I appreciate your response vertx. I will look into it more tomorrow.
Your comment / link has set me on a new path to resolution!
Thank you!
So, it is not ok to use UI Toolkit for game UI, only editor?
It is not yet completely recommended
So should we use it on a big scale project or not? 2021 lts version
If you're asking this question, then no, I would say don't
Thank you very much
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
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 
you can get the type by doing typeof(data) using that example
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.
I'm not sure how it works, but you could try encapsulating it in another event
for example
Im very curious how you would encapsulate this, thank you for your help
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);
}
Yaaaaaay! This worked! Thank you Platypus!
Changed panelEvent to the method in the 2nd script's method.
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
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.
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
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
create your own custom Node and make your own template
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 :(
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 %
Last time I tried round corners with px it was janky on different resolutions, % actually fixed that
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.
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 
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?
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.
hrm. Seems I need to implement 'IHasCustomMenu' which sound fucking hilarious
This is a #↕️┃editor-extensions question btw, no UITK involved. Did you figure it out?
Partially! I seem to have taken a wrong turn somewhere but made a bit of progress before closing for the night
I pinged you the solution in #↕️┃editor-extensions
Appreciated
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 ?
Don't use anonymous method, instead define a function with the required signatures and assign that to the manipulator so later on you can just remove it by just pointing to that function
OK. Too bad there's nothing that doesn't require the function.
Thanks 🙂
Actually, even if I don't use an anonymous function, what RemoveManipulator desires is a IManipulator, so I suppose a ref to a Clickable for example. It is what you meant ?
just make a function with the required signatures
That doesn't help me. Could you provide an example of using RemoveManipulator pls ? If I have void MyFunction(), which has the right signature, I can't make element.RemoveManipulator(MyFunction); as MyFunction isn't a IManipulator... https://docs.unity3d.com/ScriptReference/UIElements.VisualElementExtensions.RemoveManipulator.html
does this ring a bell to you?
class DragManipulator : MouseManipulator
{}
...
private DragManipulator mouseEvent;
someElement.RemoveManipulator(mouseEvent);
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 ?
thats just an example
Just a very quick one, if you're still confused look up the examples from thhe source code on githb
you can define a function that returns something that implements IManipulator
Oh ok, that makes sense
whether it's cuustom or not, doesn't matter as long as it implements the interface
Thanks. Sorry for bothering you, the documentation is lacking example and the only looks wrong (element.RemoveManipulator<MyManipulator>();)
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?
Explained in slightly more detail here on the forum https://forum.unity.com/threads/please-explain-and-document-focus.1504406/
I got stumped again 
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!
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
try to use property.SerializeObject.ApplyModifiedProperties after you change the value, but i guess that's not the problem, afaik UITK handle that automatically, maybe its because you use ulong, that didnt serialize
I was actually going to say property.SerializeObject.ApplyModifiedProperties fix the issue but as you mention I feel like it should handle it automatically.
Just need to align the grid now
glad to know, and UITK is easier to do layout than old IMGUI,
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.
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"));
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 @
@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)
Maybe that helps you
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..?
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 
Hello some question. UI toolkit support custom material or not?
Want to create visual effect for UI using shader graph
I am using lts 2022
Hmm is there no alternative?
I mean how another gamedev achieve same kind of thing like visual effect in their ui?
They don't use UITK
https://forum.unity.com/threads/when-will-ui-toolkit-have-feature-and-performance-parity-with-ugui.1327947/#post-8392725
2024 is when they'll hopefully have this stuff
Hmm I see... maybe I will combine ugui with ui toolkit.
Don't know if that will be a hastle or not
That is a fine workaround, though yeah, it can be annoying at times
At least ugui still support custom material
For static UI without effect it easier to use ui toolkit
hi, does anyone know how to increase the quality of textures? The icon top left is looking way choppier than it should be.
It does, but requires a bit of reflection
It looks like it is being cut off
Try adding -unity-background-scale-mode: scale-to-fit
scale mode is not the issue here, the image quality itself seems choppy no matter which one I use
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 
what error? If it's NaNs related errors try to schedule it
I was getting NaN issues before I set it in a coroutine- I haven't used scheduling yet though 🤔
the errors are related to position, though... it's slightly off and gets worse as the screen gets resized
dont use coroutine, there's no guarantee still, properly scheduling will guarantee the style to be resolved when you access it later
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> ._.
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?
I wanted to confirm a task on the UI roadmap: https://portal.productboard.com/rcczqdfvurr8zuws3eth2ift/c/522-addressable-asset-system-support?utm_medium=social&utm_source=portal_share
What are the implications of this? Is it simply not possible to include UIToolkit assets within addressable bundles?
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).
Uss How to select TemplateContainer
You shouldn't need to unregister the event. What exactly are you doing?
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.
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 ?
Does this code run multiple times on the same element?
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);
Yes, runs frequently on the same element.
How can I update/change the item source of a ListView and update it (in runtime)
myListview.itemSource = List<T>;
myListview.Rebuild();
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!
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?
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 ?
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
is it fine to use it in production for runtime in 2022 lts
You can see the comparison of UI systems pinned to this channel
Hi ! Is there a way to give tooltip for each action of a ContextualMenuManipulator's menu ?
Does VisualElement.Q-VisualElement.Query starts from its content container or from the given element?
On your VisualElement.Q-VisualElement.Query your search a VisualElement on your VisualElement. Like MyElemWithMyOtherElem.Q-ElemSearched.Query
is there any extension for vs-code / vs for UI toolkit to write USS better?
Hello, I was wondering if there is a guide or something to change the sprites of the progress bar
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.
This is due to the pooling system in ListView, so the templates will be reused along with your registered callbacks when you 1st bind them and those calllbacks will keep piling up, so you'd need to clear them
That said, you'd need to unbind/clear all registered callbacks on them via unbindItem property
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
Oh didn't realize that was something I missed 😅
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
Why does the content container not getting applied?
After when i save the UXML Document, everything goes off.
I appreciate if you test this out.
https://gist.github.com/YunusYld/112491143b8f23395b98704fc93cc04b
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?
I figured out that the 2nd Toggle gets cancelled while the first Toggle still plays 
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
The buttons need to be lower than the panel in the hierarchy
Thanks🫡
The DropdownField is no longer seperating items by slashes in unity 2023
Anyone else have this problem?
The code certainly reads like that's disabled; though I can't see where it previously allowed it in earlier versions; and I also can't see a way to enable it without a lot of hacking
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?
ex.
- visualElement (parent) |- visualElement (child 1) +- visualElement (child 2)
I want to add a visualElement that overlays child 1 and 2 ...
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 ^^
Well that's unfortunate, what do you mean it reads as if it has been disabled; did you use something like IlSpy to take a look at the code for dropdownField?
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?
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
The C# source is pinned to #↕️┃editor-extensions
Oh i see, thank you that's very useful
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.
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?
ahh, start axis needed to be horizontal!
UITK seems to have massive memory leaks in 2022.3.8 any known fixes for that?
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?
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
How can I unregister the callbacks? And do I need to do it for the whole hierarchy? Is there a faster way?
Thanks in advance!
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
Presumably your property drawer uses UIToolkit
You're using an IMGUI container to draw the default editor here, when you should just use an InspectorElement:
https://docs.unity3d.com/ScriptReference/UIElements.InspectorElement.FillDefaultInspector.html is helpful to do this
I tried this but nothing gets added to the container.
Not sure if I'm missing something
I'm busy rn so I can't check, but try calling Bind on v with your serialized object
Oh yeah that worked 👍 Thanks
Is there yet a way to drag and move windows on the screen with UI toolkit?
I can only find events for editor purposes
i got so far to address the .style.top , and style.left property but no attempt has worked so far
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
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
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
I saw someone made a Figma-To-UIToolkit converter recently
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?
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
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
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?
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);
}
Presumably because you've set a fixed width on the dragger
Why would that cause this issue though?
The parent has a width of 16px, the dragger has a width of 9px with 3.5px margin-left and 3.5px margin-right which should add up to the 16px width.
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)
Supposedly this was a bug https://issuetracker.unity3d.com/issues/uielements-textfield-is-not-focused-and-you-are-not-able-to-type-in-characters-when-using-focus-method, but it's supposed to have been fixed a long time ago. I'm using 2022.3.12f1
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
Figured this out... It's still absolutely bugged (classic Unity. Regression or didn't fix in the first place I wonder)
Had to attach a listener to NavigationSubmitEvent and then do inputField[0][0].Focus()
TextField cusor and selection do not behave as expected on andriod phone
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
UITK supports render texture
so, just use it together with some camera
thanks for the reply. The concern is using Render Textures on mobile. For example on a CCG, you might show 6-9 cards at a time in a collection manager. Now you need a lot of render textures. This could be expensive
isn't real time render textures expensive on mobile?
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
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
so if you are really experiencing problems with multiple render textures - just have 1
for a specific layer
it's not a hack
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
multiple cameras/render textures is slow on mobile from what I understand
maybe with just doing it with 1 is possible
Before attempting some premature optimization, best to actually see if it's really a problem
it may on some platforms due to swizzling in memory
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?
This is not supported, so everything would have to be custom
alright
Question, how do I link my UIdocument with the new input system? Is there a page that explains it?
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 :)
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?
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
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
^ to answer my own question, just seems i need to put [UxmlElement] on the element... magic
You can set style to be percent based, combined with Image class uitk you can lock the aspect ratio to to fit so it will be adjusted according to the parent container .
Doing this kind of stuff is much easier in uitk imho
The UI Toolkit doesn't support % scale on fonts labels & textfields? or am I doing something wrong?
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
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.
How can I add a sprite sequence animation to my UI?
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).
How to add for example a button as an
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:
Tag: EditorOnly is also not mine..
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 ?
@worthy fiber why not just focus on a button? thats what i do, then add styles\
you use buttons as Textfields ?
if it needs focus/events yeah
ok i'll try thanks
Using buttons as textfields sounds kinda wild lol. Calling a normal textField.Focus() works for me. When and you calling focus?
You might need FocusInEvent..
Also I don't know if this matters but what value is tabIndex on the text field?
It's something as simple as this
Never seen that before, was this GO just generated in your scene or something? Could you just delete it?
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 =)..
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}");
Also, is the blur functionality working? Like if you have focus and press escape, does it lose focus?
yes it's working
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()
Not a bad idea. I was thinking that some other element is trying to grab focus around the same time for some reason, so that would make sense. Another idea is maybe trying to grab focus on some key event like root.RegisterCallback<KeyDownEvent>. Other than that, I'm out of ideas
ok i'll check into that thanks for the help 👍
How do you know this was auto generated by ui toolkit? Was there more to the error messages?
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?
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&guid=6ba520f1250203b4d948fbbe4b670fa3&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?
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?
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
set the PickingMode, tons of people asked about it if you scroll way up there you'll find the answer too
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!
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
Thanks for the response! Maybe it's a problem with my object then? I do get some warnings on the editor about the type...
What do the warnings say?
hey guys, how can I add a new List Entry to a list view in runtime?
nvm I already solved It
im using OnGUI and making sliders (look at the gif below for my problem)
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
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.
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!
Haven't tried this, but maybe this is what you're looking for: https://forum.unity.com/threads/how-do-i-set-a-visualelements-content-container-in-c-code.1429207/
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.
Probably should ask this under "augmented-reality" or "virtual-reality" channel. UI Toolkit is different from XR interaction toolkit
That was it.
I got lots of errors because I missed replacing an this.Add() with the hierarchy.Add(). So, to anyone doing that... yeah, don't miss one of those. It gets real ugly real fast.
But this worked. Perfect. Much thanks!
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.
Nice, glad it worked
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?
I am not too familiar with 9-slicing or working with sprites. But I'm guessing this is somewhat of a bug, is it only in UI Builder the issue happens or what?
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.
I suspect it's a UIToolkit only thing... I've not worked with this anywhere else, if it even is applicable elsewhere. But it specifically is UxmlAssetAttributeDescription<Sprite>.
I usually just paste code with markdown:
```cs
// code here
```
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.
I was gonna try this out but apparently setting UxmlAssetAttributeDescription is only available on Unity 2023, and I'm still using 2022. Do the UXML files reference the correct sprite? Like if you have sprite #0 and sprite #1 in UXML, you'll see the corresponding guid and fileid (I'm guessing this is how it works, idk)
Yeah, looking at the uxml file, I see the correct reference.
<SpriteElement my-sprite="project://database/Assets/...spritesheet.psd?fileID=...&guid=...&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)
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
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".
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?
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?
Does anyone else use vanilla C# classes to act as controllers for UI?
You mean creating a custom controller?
Like this? If so, what's the question about it?
Yes exactly; a vanilla C# class (not a subclass of anything) that accepts a UXML tree and will find labels, buttons, or whatever UI elements and handle all the UI logic.
Not like this. That code looks like it's creating a new UI element.
When I say "controller" I mean in the sense of MVC (model view controller)
Oh, I think I know what you mean; working on a lot of those lately. What's the question?
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)
@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.
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.
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..?
I do not know, sorry; hopefully someone else here will be able to answer, sorry.
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?
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
Really weird. After all of that, the thing that fixed it was resetting my layout... That somehow fixed all my in-game UI.......
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
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.
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
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?
Just FYI most UI elements have a userData property that's of object type that you can put anything into (you'll just have to typecast the data when reading). This fit my data- needs.
[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...
[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:
It'd be easier if you did something like:
private static void SynthesizeAndSendSubmitEvent(Focusable element)
{
using NavigationSubmitEvent evt = NavigationSubmitEvent.GetPooled();
element.Focus();
element.SendEvent(evt);
}
Easy or hard, if I can simulate a click event I would be extremely happy.
Let me try to plug in what I understand from what you're saying. Instead of NavigationSubmitEvent.GetPooled() I'm going to use ClickEvent.GetPooled(). I don't know if Focus()ing the button is required but let me try an iteration with that method call too.
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
Sounds good. I'll send a "submit" event instead.
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
What the fuck it works?!?
@rough scarab Can you elaborate on your explanation? I'd like to understand why this works.
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
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?
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...
And yeah, the speculation is about correct https://docs.unity3d.com/Manual/UIE-Events-Dispatching.html it propagates and in the case of the NavigationSubmitEvent it sends it to what's focused https://github.com/Unity-Technologies/UnityCsReference/blob/master/Modules/UIElements/Core/Events/NavigationEvents.cs#L222
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
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
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).
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 😄
Oh come on, vertx, why deflate the magic. We assumed you had internalized this, not had a recency-effect thing going on. 😉
I had the first part down, but the detailed part was recent 😄
If others are using the technique described above, make sure to update your button.RegisterCallback<ClickEvent>(onBtnClick); with button.clickable.clickedWithEventInfo += onBtnClick
I had issues with synthesizing events because I could not get focus on elements with DisplayStyle = None, apparently it's not possible to focus non visible elements. Do you know of any possible way around this? The only thoughts I have is trying to set opactity=0 to try to achieve the same thing
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 😄
So basically if I make an asmdef , I can add InternalAccess.asmref and I should be able to use internals? Would I have to create something in their namespace or something? How does it work
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
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
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
@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
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
I’m about to hop back in. You don’t mind sharing what the code looks like in your use case, would 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)
@solid maple thanks for sharing..!
@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 😦
- Create an assembly definition reference in a new folder that adds to UnityEngine.UI
- Add scripts to that assembly that expose relevant UIToolkit internals, making a public wrapper of some sort.
- Reference the UnityEngine.UI assembly in your relevant assembly definition.
- 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
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
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
So... Create an assembly reference in the same folder as Controllers.Runtime.Tests?
And then reference UIElements...?
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)
@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?
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
I would just go with an extension method on Button
I think I get that.
I would just go with an extension method on Button
Sorry actually I don't get it.
How would I apply this technique to allow someone to Click() a button in a unity play mode test?
You create an extension method that calls into the Button's clickable, calling SimulateSingleClick
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
"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.
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
@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.
Hello. I bought this course for UI Dev on udemy: https://www.udemy.com/course/modern-ui-development-in-unity-46-or-50/
I noticed it hasn't been updated since 2015 I was just wanting to see if there any any better options or if this covers enough basics even for how old it is.
Pretty sure it's just a scam at this point
Modern UI Development
Tutorial series is ~10yrs old
Does that mean totally useless or would some of what's in the course still carry over? I've followed a bit of the course already and if there is any difference in the UI it hasn't been enough for me to not complete a project.
It's fine. There's just no reason not to find a more recent tutorial instead
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 ?
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.
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.
@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.
Anyone know how to set the default scrollbar height for a scrollview element?
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");
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()
{
}
}
/// <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
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);
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. 🎉
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.
I'd think if dealing with 20+ buttons as enums maybe start looking into implementing an SO approach
Scriptable objects?
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
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
while you certainly shouldn't do stringmatching on hardcoded strings, i also wouldn't use an enum for cases where you don't know for sure what the possible values are going to be
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
oh yeah, I can imagine enum with thousands of options
yea that's a clear indicator the data should come from a different source, like a scriptable object or database
Yeah, I'd try to avoid enums in cases like that, too. More likely I'd just have collections of SO's.
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.
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?
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
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.
yeah, I found the documentation that says exactly that
I guess my only options are the addressables or resources
may I know why I don't have a button component?
Because UI Toolkit doesn't have a button Component.
You're probably looking for UGUI, which is #📲┃ui-ux, not this channel.
You're also probably just missing the Unity UI package (ie. UGUI) in the package manager.
got it. problem solved. thank you.
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?
The comparison/recommendations remain the same, see the pinned message
the feature list has expanded and so has the stability/workflows, but the two major world-space/shaders features are still missing
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?
Yes
ok thanks
is it normal i cannt find the normal test ui
Hi guys. Why my SVG looks like this?
(Not like in UI builder)
info:
Unity 2023.2.3f1
Def. 2D template
Anyone managed to do sortable tables?
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?
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
oh okay
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?
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
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
is there smthg similar to figma with text auto-width so the container fits the widht of the text and not a fixed width?
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
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
the ui input field appears behind the canvas when on full screen
How i can change this default control widget?
Is there a way to set a toggle to this "in-between" state?
By targeting it with USS selectors
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.
You can mark visual elements to be optimised for certain types of changes https://docs.unity3d.com/ScriptReference/UIElements.UsageHints.html
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
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
I have a page that goes over my workflow for styling elements that may help you out in future. https://unity.huh.how/ui/ui-toolkit/styling
Basically, heavily leaning on the UI Toolkit Debugger
Thank you
Is there a way to reverse the direction of scrollview?
Is toolkit good enough yet to be used in production? I wouldn't wanna lose time switching back to regular UI mid-project.
It does not support z-index, world space UI.
The status for z-index support is Planned. Even people requested this feature 5 years ago.
So usual Unity abandonware then, tnx
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
Have the elements load bottom up rather than top down, and have the scroll position start from the bottom
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>
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.
Hello! Is it possible to use ui toolkit with shader graph?
If you're asking whether it's possible to create shaders for UI Toolkit, the answer is currently no
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
Absolute position means it doesn't use layout and instead is just positioned relative to its parent
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?
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.
Solution: Set Flex of parent to "left to right"
How to get top root of the UI Document?
if only they're managed to get the custom material and zOrder to work ootb in uitk, it will be much better than ugui. Also, flexbox in uitk is a powerful beast for doing multi resolutions stuff with pretty much ease
Both are coming, it's just sad it's taking so long ):
yeah, lets hope it will happen when 2023 lts released
Unity 6? Maybe
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
Where even is aspect ratio lock button
That comes before fancy custom material pls
I have been using it for ~5 years
We almost used uitk in production last year, but bailed out due to it failed passing our prototyping phase
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
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
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?
We have similar like this for our internal tool, I think the way my colleague did it is by making a copy of the hierarchy window and have a predefined built-in filter to it to only show certain gameobjects
Copy code wise you mean?
I don't know how they did it tbh, wasn't me who made it. it looks basically the exact copy of the hierarchy
pretty sure Mech or Navi would know if you ask it in #↕️┃editor-extensions
I want to implement a card like cards in hearthstone. I see that VFX stuff is compatible with regular canvas only. But UI Toolkit for me as a developer is better in terms of programming, because to get something I would use queries rather than try to fit all variations of card layout to some interface.
How can i change the background color of the Text field in the ui builder?
I use this USS selector:
TextField > .unity-base-field__input
{
background-color: rgba(13, 52, 54, 0.5);
}
I never worked with ui before, how can i do it xD
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?
And you can follow this for styling UI with USS: https://docs.unity3d.com/2022.3/Documentation/Manual/UIB-styling-ui-using-uss-selectors.html
I tried changing the background but it doesnt changes anything. I try following your link
Something should've changed for sure, are you sure the alpha value is not set to 0?
its at 255 and its white. if i change it in the color wheel the color field gets the new color but not the text field
How does it look? TextField is changing for me:
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?
I tried some things but it doesnt work i only need to change the white part (behind "filler text")
Yeah, so the selector I mentioned above should handle it. Create a USS stylesheet asset with the style I mentioned above and then add it here
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)
I also have a guide "styling elements" that is pinned that goes over my workflow
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?
Do you mean it feels the screen in game? If so, that canvas size is just for the inspector preview. You can set size with width/height properties
Ok thanks. That was so simple. A bit confusing that the canvas size is meaningless though.
Np, and yeah I had a feeling that's what you were talking about because I thought in the same way
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
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
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.
I have a solution but idk if its the best .-. i set the relative position in % so keeps the position with a different aspect ratio but it gets janky with the text size on some ratios
why cant i see the outline of my label? if i put a bigger value, the text gets slimmer
i found the issue!! the alpha component of the color was set to 0
Whats the best way of animating UI? Does anyone have a good video or article about it? or just person take
Not sure on 'best' way (still new, myself) - but for basic translation animations, I've been using classes with transition effects. There's a good bit you can do by just adding/removing classes.
If I need to loop/pingpong/etc, then I RegisterCallback<TransitionEndEvent>(...) and modify the classes there.
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?
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?
is it possible to have a particle system using UI Builder?
@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
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
Blur for UITK ?
Is there an equivalent to GUI.Color for UI Toolkit or do we have to modify each individual color of elements ?
If you wanted multiple elements to have the same color, you would add some class selector to the elements you want to have the same color and then add a style to the stylesheet
.myGroup {
background-color: red;
}
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
Np, for tinting I don't know if there is already a method to do this, so I would do what you mentioned. For tinting background images, there is -unity-background-image-tint-color selector, but it'll only work if your background is an image/texture
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
they are added via code
not via uxml
What is the solution for not having hard to work with elements? Now looking at text field, it's impossible to customize and looks horrible out of the box
it's totally possible to customize
just make a style that targets those classes
and... that's it
This doesn't seem to work
what doesn't work for you?
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,
Great talk: https://youtu.be/HQ0TmO8ZA4o
We’re constantly evolving the UI Toolkit to put the best UI tools in the hands of our users. Watch this video for expert guidance and valuable techniques to level up your UI skills. We show you how UI Toolkit can elevate and speed up teamwork with the new data-binding system, innovative UXML objects, and tailored inspectors in UI Builder. Don’t ...
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)
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
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
im on 2023 too
set Grow to 0 on the children
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
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
Dunno
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
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
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
Arbitary number on absolute position works, but it seems like resolvedStyle.left/top is returning 0, even though they're definitely not positioned at 0
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
Yeah exactly, that's probably the problem. You can try .layout and .worldBound. Idk maybe one of those would work
Maybe something here might help: https://docs.unity3d.com/Manual/UIE-coordinate-and-position-system.html
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
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
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.
Thank you very much، but I have already seen Unity Documentation and I just want to know the performance of it.
Do you know how I can check the performance of the mans click on the profile I can get results
the performance better than ugui
Tkanks, I'm just sorry. I'm taking your time. Have you read an article or have you read from experience?
- 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".
nice
should i use Unity 2022 or Unity 2023 for UI Toolkit ?
im currently on 20223 but apparently it is still (beta)
tbh UI Toolkit is very different from what im used to working with :3
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.
hi, does anyone know a library to create charts?
You can make your own pretty easily with Vector api
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
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?
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
Sounds like until the thing they announced is ready to be launched, 3rd party is best party.
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)
