#🧰┃ui-toolkit
1 messages · Page 9 of 1
the things that always make me confused is, if my uss like this
* {
margin: 0;
padding: 0;
border-radius: 0;
border-width: 0;
border-color: transparent;
}
.side-bar {
padding: 5px;
background-color: rgb(47, 47, 47);
flex-direction: column;
}
.side-bar__element {
background-color: rgb(32, 32, 32);
border-width: 1px;
padding: 5px;
margin-top: 2px;
margin-bottom: 2px;
transition-property: border-color;
transition-duration: 0.2s;
transition-timing-function: linear;
}
.side-bar__element:hover {
border-color: rgb(168, 255, 243);
}
.side-bar__element-button {
width: 30px;
height: 30px;
}
``` why my side bar are taking all the available space???, what i i want the size of size bar came from size of its child + its padding, where did i do wrong??, thanks
do i really need to spesify size of size bar???,
so, my side bar for now should have width of 35, and heigth of 400
Hi, is there a way to render certain panels underneath canvas elements?
you should probably use percentages instead of pixels
but yea I guess you have to specify a max width/height
well i can definitely do that, it just seems, not "correct"
width: 30px;
height: 30px;
that's the only thing that applies size
everything else is irrelevant
use debugger to inspect why
Hi!! I am new to using the UI Toolkit... actually I am playing with it and trying to make a custom editor for a scriptable object. I am having trouble with saving the values after they are changed inside the inspector... so for instance if I have a float field with a default value of 0, I change it to 10 from the inspector. The next time I click on that asset, it goes back to 0. I got comfortable with the styling part of the system... but am yet to learn how to use it with C#
some suggestions would be really helpful
🙂
still working on it, just skip this for a while
you need to bind the property to it
@gusty estuary sorry to ping, here is the current update of my "side bar" visual Element custom Control https://pastebin.com/hHJg2pph
got the error abount override content container and i believe this part
VisualElement sideBarContentContainer;
public override VisualElement contentContainer => sideBarContentContainer;
and the error is, what i am do wrong here?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
error says you are trying to parent object to itself
so if i want visual element(in this case side bar element) when i drag to side bar custom control, its goes to side bar content container, what should i do?
will give it a go!! thanks buddy🙂
Thanks alot mate!! You are a life saver
glad its help
I'm using the UI Builder. ¿How can I fix this field that doesn't fit in the canvas?
I want it to shrink so it fits. But the label (or space between the label and the input, not sure) doesn't shrinks.
Setting a max width prevent it from getting outside the box, but the input vanishes...
How can you style the dropdown? Why is it even locked in the first place?
Hello, from script, I would like to set label text color to a vertical 2 colors gradient. Could you please tell me if it is possible and how ?
see from debugger, or ui Builder, click those dropdown, go to its child click one by one till whatever you looking for are blue(focus) then you know what class affecting its style, or you can use its name too
It is not possible to set a Vertical color gradient to label from script ?
Hey, I need to check is pointer over UI. Currently, I'm doing EventSystem.current.RaycastAll, which works fine, except it also raycasts on transparent VisualElemens with focusable property set to false. Is there any way to check if the pointer is over Visual Element that is marked as focusable / not transparent?
My UI check:
public static bool IsOverUI(this Touch touch)
{
RaycastResults.Clear();
var eventDataCurrentPosition = new PointerEventData(EventSystem.current)
{
position = new Vector2(touch.screenPosition.x, touch.screenPosition.y)
};
EventSystem.current.RaycastAll(eventDataCurrentPosition, RaycastResults);
return RaycastResults.Any();
}
If this is for UITK I would subscribe to eg the FocusIn & FocusOut events on the root. You can also get access to the root of the panel and call 'pick' - something like root.panel.Pick() and it will pick the item under the cursor.
instead of focusable you need to define picking mode
you can also use panel method
to get visual element at coordinates
how to make numberOfSteps more than 11 in Scrollbar?
the initial number of steps is definitely more than 11
is it even possible?
wrong chat
why? that's UI
wrong one
quick question"
var chatTab = w_TextChatWindow.Query(className: "chat-tab");
this searches fol all elemeents that have correct class.
var chatTab = u_Patterns.Query(name: "-pattern");
this finds all that have namer -pattern. How should I write if I want to find names that contains "-pattern"? Or only way is to assign class to visual element?
Do query foreach and compare names however you want
public override IEnumerable<UxmlChildElementDescription> uxmlChildElementsDescription
{
get
{
yield return new UxmlChildElementDescription(typeof(SideBarItem));
}
}
``` i search in doc override this to decide what can add to custom control, but as for now, why im still able to add anything??, what can i use so my custom control only able to add spesific thing?
I think Query can do Where clause too like in Linq
yes it does
@copper solar see that
you can see how it used here https://docs.unity3d.com/Manual/UIE-UQuery.html
Thank you. But what issue states was correct, as it does not have function "contains", so I need to check every string. So I could use where name contains specific string. I created more simple approach which works. But thank you for your help!
that's what Where clause is for too
var vis = root.Query().Where(x=> x.name.Contains("something"));
you can do early exit too, with .First as the tail
I don't think there's a built-in solution for this, tho you can filter it via GeometryChanged pretty easily
@gusty estuary proly knows
👴
in my process in designing a weapons upgrade (or more like a customization) menu i stumbled upon Unity UI toolkit and the standard UGUI
what i got from my studies is that the Unity UI toolkit doesn't react to things such as light sources or world space event interactions (whatever that means)
if I were to make a UI that needs to see the weapon/character you're buildling then it's best i use UGUI instead right?
ui toolkit is panel based UI
ugui is game object based
with uitk you can only have pure UI in screen space
with uGUI you literally create game objects which are observable by camera, but act as ui. And thus also have all capabilities of game objects
hm
in noob terms, what can I do w/ uGUI where uitk can't?
or are there things where ugui isn't necessary and i can do better with uitk?
unit overlays, 3d rotations
simple ui
when all you want is menu
settings and etc
uitk will do just fine
if you want some super specific style
or to use specific textures
you might want to go with ugui
uitk styling options are very limited compared to ugui
righto
in cases where I want the stuff in the background be visible (but not interactable), ie semi transparent, would uitk do well or it's less hassle to do it with ugui?
thabks
is it possible to use both systems and have a script handling the transition were I want to use functions limited to UGUI?
you can use ugui just as normal game objects with text mesh pro
for UI specifically you better choose one
mixing two will be painful
okay
for things such as "draw a "lookie here" tag" on top of a 3D object objective, i should use UGUI?
quoting : UI toolkit doesn't react to things such as light sources or world space event interactions
Yeah, bcos UIToolkit can't do custom materials ootb for now...
they're working on it
and for your worldspace question, uitk can't do z order for now, so yeah, no worldspace ufortunately @formal wyvern
thanks
i guess i'll fiddle with UGUI for most things except for the most simple ones
for your use cases, just use UGui, yeah...
hey guys!! I need some help with binding a ui element in c#... I am aware of the uxml way by using "binding-path" but I am trying to play with the C# style... am stuck😶... this is my code:
Editor:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
[CustomEditor(typeof(TestScript))]
public class TestEditor : Editor
{
public VisualElement root;
public VisualTreeAsset main_window_uxml;
public StyleSheet main_window_uss;
public TestScript _target;
public SerializedProperty serialised_FullName;
public void Initialise()
{
root = new VisualElement();
if (main_window_uxml == null || main_window_uss == null)
{
main_window_uxml =
AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(
"Assets/--DEBUG_AND_TESTING/TestUI.uxml");
main_window_uss =
AssetDatabase.LoadAssetAtPath<StyleSheet>(
"Assets/--DEBUG_AND_TESTING/TestUss.uss");
}
main_window_uxml.CloneTree(root);
_target = target as TestScript;
serialised_FullName = serializedObject.FindProperty(nameof(TestScript.mFullName));
}
public override VisualElement CreateInspectorGUI()
{
Initialise();
var fullnameTextField = root.Q<TextField>("f_fullName");
fullnameTextField.bindingPath = "m_Fullname";
fullnameTextField.Bind(serializedObject);
fullnameTextField.RegisterValueChangedCallback(OnNameChange);
return root;
}
private void OnNameChange(ChangeEvent<string> evt)
{
serialised_FullName.stringValue = evt.newValue;
_target.DebugFullName();
}
}
Monobehaviour Script:
public class TestScript : MonoBehaviour
{
public string mFullName;
public void DebugFullName()
{
Debug.Log("New Name: "+ mFullName);
}
}
the uxml:
<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/--DEBUG_AND_TESTING/TestUss.uss?fileID=7433441132597879392&guid=2df1d85562576e442a9bdbf169afe026&type=3#TestUss" />
<ui:VisualElement name="root" class="defaultLayout">
<ui:TextField name="f_fullName" picking-mode="Ignore" label="Full Name: " value="Name: " text="" />
</ui:VisualElement>
</ui:UXML>
Question: Do I have to use UI builder to create a custom Inspector? I just want to use the default inspector with just a few added fields based on whats in a list.
Like say the List has 2 items. for each item in items, Create a Header, and then display the variable x and y
No
you might just get away with custom property inspector for your specific item instead
no need to override whole script
Not really sure where to start though. Can you point me in the right direction
Hey, I need to send an event to all elements when the panel is hidden. I've tried creating my own event (inherited EventBase) and sent it though SendEvent, but it never gotten anywhere. Rn I'm doing query for interface, but maybe there's a better way of doing it, or I didn't get how custom events work
RootVisualElement.Query<VisualElement>().Where(element => element is IViewShownHandler).ForEach(
element => { ((IViewShownHandler)element).OnViewShown(this); });```
For events I did
using var viewHiddenEvent = ViewHiddenEvent.GetPooled();
RootVisualElement.SendEvent(viewHiddenEvent);```
I event tried cs using var viewHiddenEvent = ViewHiddenEvent.GetPooled(); RootVisualElement.RegisterCallback<ViewHiddenEvent>(_=>print("test")); RootVisualElement.SendEvent(viewHiddenEvent);
test never gets to console
so i have a visual element and i set its width and height to 50% yet it seems to span the entire screen height - what am i doing wrong
the width worked fine
You have flex grow
Why not let owner of hierarchy sub to events instead?
why would it grow full height when there are no children elements
It does not depend on children
Grow equals fill
oh
And value is it's part (if there multiple grows)
whats the simplest way to just center the element on screen based on a size then
so an empty parent and center its content
Kinda
im trying to create a ui of a fix width and height that appears in the middle of the screen
but this doesn't seem very simple compared to the old anchor setup
I know
Idk about anchors, but simply assigning 3 styles on parent is easy enough
I even have premade style class
That does it
im not sure i know how to setup the parent to do it either tbh
align and justify content i presume
Yeah, I think those
You also want to define size of element precisely
So center is true
Position absoulte, width height 100%
i think i have it working now
seems i just need to make more child elements to align things
is there a way to combine ui together
such as if i disable a component i want to disable elements in the tree
seems to me i can only make one full ui thing and i can't seperate them into parts
so still on my side bar custom control so as you see from uxml hierarcy, side bar has Register Callback when its click its will expand the side bar width, and the side bar item also has click event when its clicked its will invoke action, the problem is when i click on the side bar item instead of just invoke the action, the side bar click event also triggered, which lead to expand the side bar width, did try to use evt.StopPropagation() and evt.StopImmediatePropagation still the parent event triggered, what i am doing wrong?
private void OnClick_Button(ClickEvent evt)
{
if (sideBar == null)
{
Debug.LogError("Bind Side Bar to use");
return;
}
sideBar.ClickItem(this);
evt.StopPropagation();
}
It's terrible 🤣
i cannot figure out how that mess some how becomes a nice layout when you press play
its a complete joke
What? Is that game view outside of play?
thats the ui in the builder
Ahem
how does all that suddenly become laid out nicely when i press play
makes no sense
check other themes
wdym
At top right
top right has no theme option?
Only editor and default runtime?
oh
theres 3 others but they just swap out sprites
they dont change the mess hell that you see on the screen
doesn't really tell me much on how this suddenly becomes nicely laid out when i press play
when used themes
With code
im looking at the code
i can tell you they dont do anything in the code other than assign events
that's pretty much it
pressing play looks like this
But I find it terrible approach
Open ui builder
i am trying to figure out wtf this system is doing
Check their panel settings asset
This will tell resolution they used when making ui
what does it mean when an element is greyed out
?
Probably display style
It's a style
theres no style sheet
It disables drawing of element
Could be global style
Or inlined
You can check when selecting it
Matching selectors
i think i might just go back to old ui this is so overly complicated
Weak
its a mess theres no way to understand why something is disabled
Demo is terrible
theres no style sheet so where would the global style even be
Yeah
In theme assets
sure but youtube is terrible too they only cover absolutely basic stuff
Just read manual
It's most up to date source
No kappa
i read that first before going on to the demo
Out of everything
it doesn't cover everything not even close
Only manual gave me proper understanding of uitk
well the themes isn't causing the elements to be greyed out
they just change the sprites
Maybe, I am not aware how they manage it in this awful demo
how would you be even able to disable it in the builder
I closed it as soon as I realised it's bad 🤣
since its not a game object i see no setting for disable
By setting display style
From flex to None
display is also disabled
the display settings are greyed out i cant change the display style
it cant be im not even running the game
Uxnl has no access to it
Complex controls might create additional elements
Seems like they created screen as custom control
what
the whole tree is greyed out but the char screen parent has contents set to be visible
¯_(ツ)_/¯
check what class this uxml belongs to
And find it in code
It creates all elements in constructor
i honestly don't like this approach
But it's valid
all i can find is this:
// Toggle a UI on and off using the DisplayStyle.
public static void ShowVisualElement(VisualElement visualElement, bool state)
{
if (visualElement == null)
return;
visualElement.style.display = (state) ? DisplayStyle.Flex : DisplayStyle.None;
}
kinda useless though as that shouldnt mean its disabled in the builder
preventing me from doing ant kind've edits
when not even in play mode
i checked the flex settings and thats not set to none
It's not it
Display has nothing to do with it
Controls can create elements via code
And you can't modify those in uxml
wdym by controls
its just a uxml like the #HomeScreen is but that one is not disabled
even if by code - the game isn't running
right now no code is doing anything
i just want to know how its disabled in the builder
not during run time
By this not being just uxml
it is an uxml
https://pastebin.com/c0u0Cb1b this is the only C# script that mentions the char screen
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
but again this is for run time im not playing the game this code isn't running right now so its irrelevant
well what are you referring to then
uxml has code behind
Button is a class
With uxml factory
I think this screen is same aproach
Hierarchy has an option to show assoiciated class
Somewhere
🤔 what
i have no idea what you referring to
i searched the code for char screen and only one file seems to be related to it lol
you should read manusl 😅
the manual doesnt explain the demo
It explains uitk
yes but not to this level of complexity
ok but im trying to know how they disable a simple element in the builder
They don't
even you're struggling to explain which highlights how hard it is
Check class IntField
i literally cannot change any values on the elements - they clearly have them disabled
and they are all disabled
i cant change those element's values
i cant change their layout the text size or anything
yes
so you agree they are disabled
so how are they created
In code
because i already said the code is not running
so how come i can still see them in the builder
thats pretty vague
Everything inherits from it
which one
Dud
Read manual on custom controls
This exolains it in depth with examples
I also suggest exactly 2022.2+ one
i already told this is the only script that even mentions character screen
but you keep saying there is some other script that doesn't appear to exist
if it exists i have no idea where it is or what its called
That's why it's better to read manual before jumping into advanced framework usage
nevermind i'll ask on another server
im fully aware of what controls are and thats not relevant here
Then you should be aware that listview creates tons of elements
same ss intfield
Oe any other field
And you also can't modify thel via uxml
not relevant though the docs clearly say we should be able to modify control properties
but those are not controls
i can't do that second line because its all disabled
they are sub elements
you literally just said "Read manual on custom controls"
Of main control
the controls manual says we can apply properties in ui builder
but they are all disabled
you can't apply anything that is not defined by uxml
If your control crrates additional visualelement - it's read only
If you open uxml you won't see any of those
but theres no way to edit them because there is only one uxml file
As they are part of runtime code (which also runs in ui builder)
There's clearly a bunch of them
right but then they are not relative to the parent
so their layout is broken
eg if i open in isolation
the layout is all over the place
👴
which is of little use if i want to align it based on the parent
without the parent its all overlapping and broken
like all the other elements
so i cant adjust it whilst its a child element to make sure its right
which is silly
expand listview
but once its a child of another uxml i can't modify it and then i have no control over how to lay things out relative to the parent
try to modify content
Not listview itself
Ah
I get it now
You can't modify children
yeah
but then how do you make sure the child layout works under a parent
By parsing uxml
If you want to modify uxml - open actual one
Not the one that simply instantiated it
i see
Ui builder does not support overrides yet
But uxml does
Surely, tricky engine part is not explained in manual, but template instancing is
so I stand by my words - manual is best and seems like the only way to underdtand uitk
Atm
most of it makes sense though some parts become quite technical
Open it in context
Repost:
so still on my side bar custom control so as you see from uxml hierarcy, side bar has Register Callback when its click its will expand the side bar width, and the side bar item also has click event when its clicked its will invoke action, the problem is when i click on the side bar item instead of just invoke the action, the side bar click event also triggered, which lead to expand the side bar width, did try to use evt.StopPropagation() and evt.StopImmediatePropagation still the parent event triggered, what i am doing wrong?
private void OnClick_Button(ClickEvent evt)
{
if (sideBar == null)
{
Debug.LogError("Bind Side Bar to use");
return;
}
sideBar.ClickItem(this);
evt.StopPropagation();
}
``` sorry keep asking this, because this looks so basic but still cant figure out, and i guess many people also want to know
did you set the pickingMode ?
Is there any known bugs about the Tmp text changing it's positioning when played after a plastic scm import?
Hello. I have a label. I want to center it on screen, so I set:
- position = absolute
- left = 50%
- top = 50%
- align = center
- Transform.Translate (-50%, -50%).
Now the text is correctly centered.
Now I would like to have a transition effect: The text comes from the outside on top of the screen and scroll to the center of the screen.
To do that, from a script, I set the label Top = 0 and then I set the Transition Animation top duration = 3s, and then I set the label Top = 50%.
I can see the label move from 0 to center in 3s.
The problem is that, at 0, I can see the half of my label because of the Translate Y -50%.
Instead of 0, I need to init the Top to (0 - "Height of the Label" / 2).
Could you please tell me how to do that ?
just make a style class where you set top to - 50%
and when you remove it
transition animation will animate from this -50 to 50%
The top percent is "screen height percent" or "label height percent" ?
whatever animated container is
It is "percent of what" ? How to specify between 50% of the screen height and 50% of the current object height ?
top
If my label height is 30px and my screen height is 400px if I set top to 50% it if 200px. Right ?
I'm in absolute position
then 0% will mean at the top
it's still local to parent
Your solution works only if the label height is lower than the 50% container height. Right ?
height has nothing to do with it
top specifies distance to top point
so as long as you specify top bigger than your label
at the start
it'll appear out of nowhere
when aniamted
Ok I try
it will not, unless you set the overflow to hidden then it would appear out of nowhere
I mean
it will be outside of screen bounds
so it will be out of nowhere
no matter what
Ok I tried. The text correctly come from nowhere.
But there is a problem, the transition speed is not correct because the label comes from far away, not from the start of top screen.
then specify top accordingly
This is my first question
how to specify the top, as it is dependant of the label size
try specifying bottom isntead then
It doesn't work, I still dependant of the size of the label... I need to center it on screen. I don't see a way to position it outside of the screen and then make a transition to the middle of the screen without using the size of the label somewhere.
if you specify bottom 100% you don't care about label size
To center the text in the middle I set bottom to 50% and translate Y to 50% so If I put bottom to 100% I can see the bottom of my text because of the translate Y.
why not just use text style to center it?
How do you center text verticaly using only text style ?
there's literally style for that
I tried a lot of styles, did find one to center an element in the middle of it's parent.
open ui builder
and simply look at text section
Align ?
I don't remember names
It's to center the text in the label area, not in it's parent
The parent let the child processing it's transition from top to middle ? What property hsould I use for the transition ?
in parent element
align I think?
2 styles
1 to align vertically
and 1 to allign horizontally
is there a way to make the parent element expand horizontally or vertical based on the child elements
i want to add buttons dynamically and make sure the container grows to accomodate how many i add
right now it doesn't stretch horizontally
i got flex grow set to 1 thought that would solve it but evidently not
Auto size
no that just makes the visual element the entire width of the screen
or does auto constrain to the min/max
i was hoping it would auto choose the smallest
so i didnt have to set a min/max
Play with align style as well
for example constrained width but no constrained height
it defaults to full height which is weird
Parent style also affects layout
to affect how buttons size (with auto size) you set parent style
If parent is at root - you need to manually set size
oh it cant auto calculate the height from the children and padding/margins ?
Or create additional fullscreen pare t
It does by default
well no because it went full height by default
instead of stopping once it encapsulated all the buttons
yeh i have grow set to 1
because i want it to grow horizontally
i put direction to row
Horizontal fill can be controlled by parent
I believe it's copied from css? Could be wrong
Sadly there is no spacing in uss
i see so each button has to have its margins set
i guess i'll make them their own ui document and copy paste
Or you can make custom control which adds empty spacings inbetween
i had that idea for a while
But didn't get to use it
by the time i get around to doing it i would not be surprised if unity adds some kinda grid element
to do it for us
which is what typically happens after wasting my own time writing my own
Maybe it's already written, but not exposed to ui builder
This is a case for a bunch of elements
isnt picking mode like interactable in unity ui???, what i mean is equivalent to block raycast from unity ui in UI Toolkit
No. Picking mode is whether it blocks
kinda confused here, so picking mode is the thing that i looking for??, to block below element from receiving event?
yes
thanks
use flex-wrap on the parent then set the margin on the children
btw, that's a workaround, it shouldn't be like that in css even
or use justify + flex-wrap on the parent, and pick the space-between for the justify, I forgot what it's called you should check
you can set flex-grow to 1 but set the initial size + padding preferably (roughly)smaller than the child so it would expand. Then set flex-grow on the children as well with 100% width and whatever height value, then justify to center or flex-wrap should work
that's not how supposed to be done in css even, they're working on it (hopefully)
Jeez, I explained how to do it with just 2 styles
And here you suggest some monstrocity
Why
👴
🥳
below element still trigger its callback, here the scripts
public SideBar()
{
this.AddClasses(ussClassName, activeClassName);
StyleSheet styleSheet = AssetDatabase.LoadAssetAtPath<StyleSheet>(ussFilePath);
this.styleSheets.Add(styleSheet);
elementContainer = new VisualElement()
.SetName("side-bar__title-container")
.AddClasses(elementClassName, titleContainerClassName);
hierarchy.Add(elementContainer);
// button = new Button(On_ClickSideBar)
button = new Button(() => Debug.Log("Test"))
.SetPickingMode(PickingMode.Ignore)
.AddClasses(buttonClassName);
icon = new VisualElement()
.SetName("side-bar__icon")
.AddClasses(buttonIconClassName);
button.AddElement(icon);
titleLabel = new Label()
.AddClasses(labelClassName, titleClassName);
elementContainer.AddElement(button, titleLabel);
separator = new VisualElement()
.SetName("side-bar__separator")
.AddClasses("side-bar__separator");
hierarchy.Add(separator);
sideBarContentContainer = new VisualElement()
.SetName("side-bar__content-container")
.AddClasses(contentContainerClassName);
hierarchy.Add(sideBarContentContainer);
this.RegisterCallback<ClickEvent>(evt => On_ClickSideBar());
}
``` as you see button currently only do log when its click, and base element has Click Event when its click the width of side bar will expand, but when i clicked button, not just log test, its also expand the side bar, so clearly the event on base element still triggered, what am do wrong? thanks
set it the picking mode to position instead
hmm... that fluent extension you're using looks very familiar 😃
i have seen before from github of Dozzy UI, and create my own(which honestly mostly the same) anyway i did set picking mode to Position and Ignore just in case, still the below element still trigger its event
did you also stopimmediatepropagation?
button doesn't have evt came as parameter, unlike using RegisterCallback, so im not call evt.StopPropagation or Immediate Propagation
but i believe, did try before i change button as Button from just Visual Element, and still the event triggered
is there not any built in from unity, like when we use Unity UI, its has Block Raycast and if we tick, the below Ui will no interact
that's what basically pickingMode is for
as said bu the other guy before too
button.clicked already has stoppropagation, so it's mostly related to your setup
hmm, weird....currently
``` this removed from my side bar, and let side bar icon button, do the job for expanding or not the side bar, but i just think will be great if click anywhere inside the side bar just not any button or other child element has event callback, do the expanding side bar
anyway leave for now, i will came asking later on....
thanks
You guys, how do I expand/edit the dropdown choices here in the UI toolkit?
I can only edit the dropdown itself but not the choices(the part circled with blue)
Anyone?
iirc dropdowns are generated on runtime and it's very tricky to know which one when using debugger due to UIElements.DropDownMenu and it's container aren't derived from VisualElement class.
I heard they're planning to changed it to the generic version, and if so, you can peek all of them through debugger with no problem
Looks like extra work. For now I'll stick to uGUI.
it is yeah, that's the nature of uitk at lest for now... hope they would make it much easier in the future
did check, and i think currently you can't style that, custom control probably the best thing you could do atm
Why does the view of the UI in the UI builder view never match the size of the UI in the main editor's Game view? I have "Match Game View" option turned on, and everything is on the canvas in UI-Toolkit, so I don't know what could be happening.
Hi everyone, I wanted to ask about some help with the resolution / display used for UI toolkit. I'm building a simple app for android and testing it on a Galaxy Note S9, the resolution for this phone is listed online as 2960x1440 pixels. When putting this into the game view and testing it in Unity my screen looks like this:
However, when building it and running it on the phone, the screen is compressed and zoomed very far in.
I'm a bit confused for why the scale is so completly different on the build when the same resolution in the editor seems to work fine without an issue. Any help on solving this would be appriciated.
Maybe you set sizing to auto. Have you checked with the intended reso on the sim?
did you pick correct theme?
Theme?
- I am going to use ui toolkit for an inventory ui. Obviously i need a responsive item counters and stats. Should i bind my inventory cell objects to visual elemetns via unity's api, or do it manually with c# events? I heard that binding is heavy, and in my case there are going to be a lot of objects to bind
binding is editor only
- Ah, missed that. So custom event buses it is then. Thank you
I have a custom element with a label inside how do I update the label when the element is repainted using VisualElement.MarkDirtyRepaint?
I can't do it inside GenerateVisualContent, so is there another method/event?
I'm not sure what you mean by this, I do want this to be able to run on other android devices not just the Note 9 so I would need it its automatically update its resolution correctly.
I tried using Screen.SetResolution too where I got the resoltion from Display.main.Width, and Height but still the saem results.
font seems different
I think your theme is wrong
Hi! is there a way to Serializefield a value like a List of ScriptableObject in a custom EditorWindow? Thank you
What do you mean by this? The font should just be the default font built in to Unity since I havn't changed anything? Why would that also change the size of the text if the text size is the same?
also
for proper resolution you should use % based styles
and select matching scaling type in panel settings
for text
Yeah I can't do that in GenerateVisualContent
Is there something else called when it's bbeing redrawn?
why do you want to do it in this callback?
don't touch low level stuff
I have a custom element to show some custom value and I want to show the max amplitude
That doesn't explain why you can't just apply value to label
Ahh, good point. I'll move over to percentage based sizes. Do you know what axis the percantage is taken from? With my lacking knowledge of css you could do vw or vh, but it doesnt seem to let you do this in Unity
Where should I updated the text value?
axis?
Maybe I 'm just not in the right mind right now 😛
%'s are usually based on parent container
wherever you update graph
I know, but if you have a container that is 200px by 200px, but then shrink it to 50px by 200px then the container has shrunk to 25% its size vertically, but remained the same horiztontally
So for the text, I am unsure on what the percentage size really means in terms of relation to the parent
oh, it's always using matching axis
Does it take a percentage size from the height, or width. or does it combine both
matching axis?
Sorry I'm quite new with this stuff
for the text size though its a single field is it not?
for text you use px
panel supports text scaling
My panels all use percentage, but if its the text thats driving it then that could be why they are forced to expand
This is my panels settings, there using percentages for the size
by Panel I mean IPanel from uitk
inspect your UIDocument
and see panel settings asset yourself
there you will find scaling options
but keep in mind, so far it only works for text (maybe something else, but I haven't noticed)
Ah thank you, Scale Mode was on constant physical size
Ive set this to Scale with screen size now
Im going to do a quick build now and see, thank you for your help ^-^
Working perfectly now
Thank you
so I have a scrollview
I want to be able to click a button and it goes to a certain part of the scrollview...is there a way to do this?
aka when it opens it starts, say scroll midway, or scroll all the way down
you can use ScrollTo to scroll to the child element
am i dumb, but when i click a ui toolkit element its not blocking the raycasting in the actual game like old ui system does
is there some toggle to deal with that
Surely can be done but not sure how.
have u setup uitk properly in the scene hierarchy? You need to provide the root asset.
tbh im very confused with how the ui works
i made a container and saved it as a document then i imported it in another document
now i want to drag buttons into said container
but it wont adhere to the layout i had set
so it doesn't really work like a prefab
when i made iconswapper i told it to make the child elements align horizontally and wrap around
so now i add 2 slots in another document and it ignores the layout entirely
yeh i figured out how to solve the ray issue
just the ui system is confusing to setup
i dont think it works like prefabs in the rest of unity
either that or its bugged
is a template instance specific to the current document or will editing effect all documents that use that template
You can't edit instanced document
You can only implement overrides
So how do you make dynamic prefab ui components
what is Exact use scenario?
Item container to populate at run time but I want the item container in different documents for different menus
as per the image above it ignores all the settings of the alignment i had
the overrides seem to be a parent element in the template so it doesn't work properly
i made the document set icons to span horizontally and wrap around
then i put the document in as a template and added icons and it no longer spans horizontally
I'm not sure you did everything correctly, templatt instance is just same as any other control technically
no because when i drag it in it is a child of some other element for some reason
the settings i set was set in the child element with the red arrow
but because i cant add icons to it - i can only add it to the parent version it ignores what i set
the way i did it was made the container and saved as template - then i added it to my new document
then added the two icons as child elements and as you can see they stack vertically
but the icons need to align based on the settings i put in the template
how else are you suppose to do it
when you say instantiate do you mean drag it into the hierarchy ?
thats exactly what i did though
But not into another template
visual element¬
template 1 : icon swapper¬
template 2: icon
template 2: icon```
thats the layout but icons are ignoring the template 1 alignment data
if you swap your templates with other elements, does it behave the same?
If it acts the same
Then it's not template
It's your alignment
Template is no different to VisualElemnt
Same thing
let me show you images of it so you can see what i mean
ill post some images later i got work to do atm -_-
uxml would give more sense
Hey folks, I'm working on building a game for Android, but I'm running into some trouble. I've made a UI using Visual Elements , but it's not rendering properly with OpenGLES3. Anyone got any ideas on how to fix this?
You'd need to set the pickingMode..
Man, it's like the most asked question here 🤣 ...proly pin it or something...
sweet thx
- A quick question about uss: where do i define a variables so that they're visible everywhere, just like built-in ones?
add uss to theme asset
but don't think any intellisense will pick it up
- As far as i read, i have to create a new tss file, inherit it from the default theme asset and add my variables in there. In case it's right, how do i inherit? I don't see any tss files other than mine in the whole project
just create it and then you'll figure it out yourself
it's pretty straightforward
- Maybe it is for you, but not for me. How do i locate default themes? Importing the path specified in the documentation did not work, and the assets in the selection window are not found
@import url("Assets/UI Toolkit/UnityThemes/UnityDefaultTheme.tss");
default theme is globally accessible
and for some reason it also duplicates itself
-
So far i've been prototyping with borders and background colors, but now i want to replace it with textures. The problem comes with aspect ratio
If i set fixed size, it obviously doesn't scale with different screen sizes
If i make it scalable, the image is stretched, hence borders are below, not around the elements
I can't use 9-sliced etc., because the image is not optimized for this -
So how can i get around this? In a nutshell, i need to make a scalable image, preserve its aspect ratio while also making sure that all children elements are aligned properly inside of it
using textures slicing style barely works in uitk
I never managed to create a proper health bar
- So i should stick to either no textures or fixed size elements?
definitely not fixed size
but so far with uitk best achieved via vector graphics
(best relative to uitk)
it's not mature enough, so styling options are really lacking
Did youever do this?
Hello, nope I didn't had the time to do it. I made a small changes to the gist because I found something really annoying during a game jam but no optimisation yet
all good! figured I would check since its been awhile lol
modified your file anyway so it prints like this
not sure why the public variables were in it tbh 😄
Because I'm reading them from another script
ah that makes sense then
And also because the auto generated classes are overrided pretty often so I don't want to store anything custom inside
makes sense
I just plan to copypaste the stuff from generated classes into new class anyway
I see, I could also make partial classes so you can inherit from them but the names of the classes are a bit weird in that case
😄
I could barely figure out how to modify the other file to print it out like this lol
It's made to fit in a single file so yeah it's a bit compressed
I was only trying to change lines like 200 and down anyway lol
which was the easy stuff 😄
how hard would it be to just have the script not run if the file its trying to write to already exists?
I feel it would be fairly easy...but I barely understand how this works lmao
Could be simply storing the existing used IDs in a comment on the top of the file, and before overriding it parsing it to get the previous Ids list
It's probably the simplest solution without breaking anything with retro compatibility
The IDs are also inside the queries so might be doable even without writing anything extra 🤔
what if I just change this
that would make it so the script "ends" if the file exists already right?
Yes, but it will never update even if you add new auto-reference class
It will just work the first time
awesome
that would be a huge speed increase though right?
since almost all code wont execute if the file exists?
Depends the size of your UIDocument I guess, I didn't had much waiting time on the game jam I was talking about but I need to try with bigger files
But yeah the GenericScriptContent method is probably the most taxing one
Also I could try to make the writing of the file async, I don't remember if Unity support that
took 5s off of a 5s save 😄
normally takes 5s to save/generate file for one doc
now takes 0s if script already exists 👌
Mouse events still happen in the game so that didn't change much
@teal belfry it's updated, at the end I simply checked if the new content was the same as the previous, and I move the read/write file method to async so it doesn't impact the main thread: https://gist.github.com/Anthelmed/fc5040ca4e036024098ba6228601a40c
ah sweet thanks 🙂
ngl, thought unity only had 1 thread so you couldn't do async
You should read about DOTS and especially the jobs then
will do thanks
But in the gist case it's simply native c# async stuff
I still get the "repiling files"
guessing thats just cause unity is dumb and refreshes a bunch of stuff when something changes
Nothing should change at least in the script 🤔 it wasn't reloading on my side
Oh but you are changing the script after it's generating right?
ah, no I was saying the first time its made and any time its changed
good evening everyone. how can i add an input overlay of mouse and keyboard on screen while using my project.
oh
input (keyboard and mouse) overlay
so that when I press a key it highlights in the overlay
there are lots of 3rd parties that do that
yeah, honestly it's up to user to use those
otherwise I need to make an info menu to show the user which buttons to use within the project. So maybe it is more convenient. Then illustrate that we move with WSAD etc.
usually there are tutorials for that
how do you center the root visual element center of the entire window
i tried 50% top on the position settings
but thats not factoring the size of the actual element
i found how to center horizontally using align self but not vertically
create fullscreen root
and use both align styles in it
to make children elements appear in center
ah ok
Hello, anyone know how to fix this rich text problem?
some tags works some tags doesnt, seems pretty random
- When i set panel settings to scale with screen size, is it affected by the game's view resolution option?
yes
I have a label with rich text. I have an anchor tag with href set to "link-test". It display as a link, how do I intercept a click on actual anchor content instead of the whole label? And how do I extract data from the click, like the value of the href attribute?
if (App.User.IsAuthenticated)
{
var usrMsgLabel = RootElement.Q<Label>("user-msg");
usrMsgLabel.text = $"Hi, {App.User.Name}. <size=15><a href=\"test-link\">Not you?</a></size>";
usrMsgLabel.RegisterCallback<PointerDownLinkTagEvent>(ev =>
{
Debug.Log($"Event: Link Text: {ev.linkText} | Link ID: {ev.linkID}");
});
}
else
{
AppUI.Modal<UserAuthView>(false);
App.User.OnLogin += OnUserLogin;
}
And it does style the Not you? like a hyperlink. But the mouse cursor doesn't switch to pointer and the PointerDownLinkTagEvent isn't triggering either. Is there another way to achieve what I'm trying to do here?
is using monobehaviour the way to animate things like progress bars based on game code or does unity have some new setup for all that
i know there is transition stuff but that doesn't seem like its for actually relating to game code
you can use transitions to animate your uis.. it's a pain to use tho
the easiest is to interpolate the style values like you usually would via Upadate
keep in mind that both would mostly likely trigger the mesh bug, you'd notice that your verts count get multiplied to a massive amount
You definetly should use separate class to apply data binding to presentation
seperate how ?
Unless ofc your progress bar for example is self sufficent (like windows xp one which simply loops)
yeh this is what i do currently:
void Update()
{
_t += Time.deltaTime * _tSpeed;
_t = Mathf.Clamp01(_t);
_bar.style.width = Mathf.Lerp(_startVal, _target, _t);
float per = _bar.resolvedStyle.width / _bar.parent.resolvedStyle.width;
_percentLabel.text = (per * 100).ToString("F" + _decimalPlaces) + " % ";
if (_t >= 1)
enabled = false;
}
just wasnt sure if i should be using update or late update or what
or if there is an entirely different ui update function im not aware of
You can change data on elements at any points
yes but what is best practice
It's layout calc is asyn mostly
does ui update every update frame
because if not then i dont see the point in using update
It does, but heavy work only done on changes
Best practice is to have 1 way interaction with ui layer
You only send data when you want ui to change
well yeh why would you send data if its not changing 🤔
You check yourself whether new value is same as previous
To avoid wasteful calculation
Of layout
well sure - though that is a bit of a micro op for me right now
I'm just providing concept here
just was surprised we still have to use monobehaviours in the heirarchy when the ui has been seperated into ui documents
So you avoid doing bad practice later
You don't. You can use any class structure
But monob is just most convinient for unity
well theres no other kind've update loop provided by unity outside of a monobehaviour for ui documents
it's 0 overhead anyway compared to ui gui
There is schedule
schedule ?
It's property
Lets you make some element loops
but honestly, I find this a bit anti pattern
i see
its annoying that there is a style.width and a bounds.width and a resolvedStyle.width
why must there be so much bloat like that -_-
are we not suppose to use resolvedStyle.width?
what would you use to adjust a progress bar width
whats the alternative?
Is when I made square element, which made itself square
Fot progress bar I use style.width
But it's a bit of exception
Because built in progress bar is dogshit
it wouldn't let me use that for some reason
Whicj can't be properly styled
the only way i could even use a width like that is this stupid syntax :
_bar.style.width = _bar.parent.style.width.value.value * (percent / 100f);
for some reason i have to do .value.value just to be able to do any math to it
totally stupid
If I was to do it properly I'd make custom control with high level property for fill value
It's not float
so they could've overloaded the operator
You have to provide proper type
It can be % based or px based
It's runtime style
Which are created from uss
i would've preferred .percentageWidth and .pixelWidth personally
it also has shitload of other options
not this .value.value nonsense
That's high level sugar
yeh and is a lot easier
Style.width is direct style accesor
yeah but you can't do much with it
i dont want to be writing code for ui it should be there for me so i can make games -_-
You can do everything with it ?
But that's like 10 lines of code tops
Why would you extract value
This is anti pattern
Besides
For raw px
Go for resolved style
because this should just work: float ratio = _bar.style.width / _bar.parent.style.width;
this is anti pattern
instead it has to be like this:
float ratio = _bar.style.width.value.value / _bar.parent.style.width.value.value;
You rely on ui code
I would't do it at all
its not anti pattern is pretty understandable i want to divide the two widths to get a ratio
you literally just said you use style.width 2 minutes ago
I set up all ui ratios in uxml
🤔
And in code I only set % of width
the ratio changes every frame based on progress bar
i display the text by doing ratio*100+"%"
the only way to know the true % is divide the two widths
I don't get what kind of progress bar you want, but it sounds more complex than just simple box filling from left to right
it is just box filling left to right
so I suggest to just write a custom control for it
then all you need is style.width setter
works perfectly fine but your suggesting to use uxml for some reason
where you set % values
no you can't use style.width i just told you that
Then I guess my progress bar does not work 😅
it literally wont allow you do calculate the % with it
do you want me to show you the error
to prove it
see, you are trying to do some calculation of layout
yes
because the script doesn't know the % it only knows the progress bar's width
even if i set the width i need to know the % by calculating its relative width to the parent
private float _storedValue;
public float LoadingValue
{
get => _storedValue;
set
{
if (Math.Abs(_storedValue - value) > 0.1f)
{
_storedValue = value;
SetValue(value);
}
}
}
private void SetValue(float value)
{
_bar.style.width = new Length
{
value = value,
unit = LengthUnit.Percent
};
}
here all I do
mines a bit more compelx than that
<ui:VisualElement name="loading-bar" style="background-color: rgb(49, 255, 0); height: 100%; align-self: flex-start; width: 50%;" />
here all uxml required
my bar lerps to a new percentage based on its previous position at a normalised speed
why not calculate it from within code then?
/// <summary>
/// Animate to percentage
/// </summary>
/// <param name="percent">A value between 0 and 100</param>
public void AnimateTo(float percent)
{
percent = Mathf.Clamp(percent, 0, 100);
_target = _bar.parent.resolvedStyle.width * (percent / 100f);
float span = Mathf.Abs(_target - _startVal);
_tSpeed = _speed / (span / _bar.parent.resolvedStyle.width);
_t = 0;
_startVal = _bar.resolvedStyle.width;
enabled = true;
}
you are trying to rely on values calculated by layout
this is super fragile at least
if you set the width by applying the value how does it know you're giving it a % and not a pixel
oh i see
it actually gets implicitly converted
because original is StyleLenght
which also has a bunch of properties
but they are not relevant
so i might not need to care about the true pixel widths
i might try refactor it then
you don't care about anything inside UI elements
with proper pattern you only set values to it
1 way direction data flow
(only exception to it are callbacks)
if you get the value style.width will it automatically be percentage then
since thats what you set it to be
no
you'll get style applied to it
if it was set as %
it'll be percent
if it was set as px it'll be pixel
i see
and I advice against using getter of it
so then how do you get data from elements
because inventory slots you might want to know their positions for drag and drop etc
drag'n'drop is something that is better managed by some manipulators
or potentially other system integrated into whatever you use to manage your ui
That convo I talked about concepts more
because you don't really want your game logic code to reference UIElements namespace
i read the docs and dont recall them talking about manipulators
(what if you later would want to switch UI to ugui?)
thats literally impossible to do for progress bar though
I just did
you'd have to use that namespace to even query for elements
public class LoadingScreenPresentation : MonoBehaviour
{
private UIDocument _doc;
private VisualElement _bar;
private void Awake()
{
_doc = GetComponent<UIDocument>();
}
private void OnEnable()
{
_bar = _doc.rootVisualElement.Q<VisualElement>("loading-bar");
SetValue(LoadingValue);
}
private float _storedValue;
public float LoadingValue
{
get => _storedValue;
set
{
if (Math.Abs(_storedValue - value) > 0.1f)
{
_storedValue = value;
SetValue(value);
}
}
}
private void SetValue(float value)
{
_bar.style.width = new Length
{
value = value,
unit = LengthUnit.Percent
};
}
}
this is service class
my game logic knows nothing about UIElements
it just accesses this class
and sets LoadingValue
for even further abstraction, I can implement interface
private UIDocument _doc;
private VisualElement _bar;
these are part of UnityEngine.UiElements namespace
with float LoadingValue property
you can't not reference to it in order to use them
and this is not my game logic code
it's ui code
nothing stops you from doing all that in usual C# class
I did it for convinience
outside of my ui framework
because by the time I need to implement loading screen
sure i know that but if you need animation at some point you need the game update loop
my ui is not loaded yet (it has to load translations async)
its impossible to completely seperate them
i used the old ui for 5 years and animated it in a similar way
game update loop != ui update loop
void update is the game update loop
unless it's part of game logic at least
there is no other update loop except fixed and late
they have not provided a seperate ui update loop
well, you can use schedule if you really want UI specific loop (but it's same Update)
in Unity everything runs on main thread
ok but you would still be referencing UiElements namespace
its 100% impossible not to
otherwise you couldn't even query an element from root
that's not what I meant
I meant to use presentation (or VIewModel) layer inbetween
because ViewModel
can be tweaked to use different UI framework for example (or if you heavily refactor existing one)
while game logic can stay intact
there is nothing worse than a need to modify game logic because you modified ui
i do it slightly different
i make it a component of the gameobject that i am interested in to make a progress bar and get component for <IProgressBar>
yeah, this is pretty much service like structure
so what ever game script has that interface it'll hook to automatically
so IProgressBar here is your ViewModel
but still
reading layout values is ugly 😅
besides
yeh i didnt realise i could apply a % directly
it's all consts anyway
thought i had to apply pixel widths
oh, all right then
ill clean it up - it will make my code cleaner too thankfully
generally you want to avoid that too
(at least imo)
progress bar is exception
because you don't want to have 100 styles for each % fill
but in general I prefer to declare USS style
for each interaction
and then just apply them
layout engine will figure everything itself
this also allows to use transition animations fluently