#🧰┃ui-toolkit
1 messages · Page 14 of 1
no
you'll need custom implementation with code
Thanks
I have a project that does that, I could send you some source & how I did it if you want.
Please, if anyone can help me fix this, I am at a complete loss on what to do. Whenever I try to assign a value to any newly created 'object field', the value is immediately reset the moment I start the game or click off of the object. I only noticed this when trying to use a previously completely functional script (that hasn't been modifed) and realising that the value kept resetting.
I have tried creating a new editor script, new uxml file, etc., but the only thing that seems to "work" is duplicating an existing object property and not changing anything on it. (Which isn't helpful since I need to re-add the missing variable reference)
If it is too high res (it definitely is) when it gets shrunk with point filtering it will look terrible. Try make it close to the size it's going to be used at (128x128?)
I started off with 32x32 and it ended up kinda shoddy which is why I upscaled
I'm mostly just going off how the icon looks in my taskbar
I'll try going back to 32x32
i'd prefer it anyways, this 1 sprite is larger than my entire library of them so far lmao
I'm not sure how unity maps sprites to icons, but maybe try 64x64 and/or change point filtering to linear
I don't have linear as an option
not related to uitk though so probably better to ask elsewhere
where should I ask, i got directed here earlier from someone else
is there currently no way in UI Toolkit to set the anchor of the image of an element?
Id like the image to be anchored to the bottom, not centered
then make the element the same size as the image
The image is being scaled
It seems like the flex content doesnt count the image as "content", Im not sure how I go about making an element "fit" to its image
Im using scale-to-fit for the images, but Im not sure how I make the elements match the aspect ratio of the images
theoretically each of the 5 elements should have a height equal to 97.3% of their width
use pixel size instead? or just use the same ratio as your image
ah actually wait, I want a % padding top dont I
hmm, I think that is close to the answer, but Im not sure how to make the padding be the correct value because it cares about the width
Green represents the sprites, effectively I want em anchored bottom left, hug bottom of screen (though ideally with some padding of course), and then they will spread out and maintain aspect ratio with the parent container having a max width of 2000 px
normally in CSS with flexbox, IIRC, the image itself is content, so you can just align-items or whatever it to the bottom or something, I dont quite recall how but I believe you can just like, do that
They added object-fit/object-position in 2022 iirc
Im having trouble finding anything concrete on this tbh
Im digging into making a custom element that automatically fits to its sprite using padding, however Im having trouble finding info on UxmlTypeRestriction, the docs just have this to say, and its an abstract class:
https://docs.unity3d.com/ScriptReference/UIElements.UxmlTypeRestriction.html
Which is pretty much useless
Is UxmlAssetAttributeDescription just broken at the moment?
Heres all my code at the moment, I cant figure out why line 49 is straight up getting the wrong value entirely.
If I try and switch to instead setting the Sprite manually via normal backgroundImage, if I do something like
var sprite = this.style.backgroundImage.value.sprite;
It returns null and backgroundImage is "", even though in the UI I 100% definitely have a sprite picked in Background.Image UI
https://hatebin.com/aqfrbqdcnc
Also is Init supposed to be getting hit repeatedly, over and over, when I modify values in the UI for Attributes? I thought its supposed to just fire once when I add the element, and no more after that, instead it fires a whole bunch of times
Is it easy to make progress bar with this tool?
I think you want resolvedStyle
Hi. my UI renders to an Rendertexture but it seems that it does not properly clip overflow? It works when I set the panel to render to the gameview, is there a setting I am missing?
hmm, potentially it can be controlled by root visual element
I'm not sure what style though
Do you mean the way overflow is handled? The two pictures did not have any different styling only removed the rendertexture from the panel settings
maybe stencil or z buffer aren't set up correctly?
Is there a way to have a parent element focused, but have a child reciving input?
I have a TextField nested inside a custom VisualElement, when clicking on the custom element I want it to have the focused pseudo state, but for the TextField to act like it is focused (so you can type and such)
Not that I know of, proly just make your own custom manipulator to capture all inputs on the parent while it's focused then do SetValueWithoutNotify to the textfield
proly @gusty estuary knows
I second this
does the rendertexture support stencil?
That as the issue, I solved it by changing it 🙂
Would manually sending the events down to the text field make sense?
Also will need to figure out how to show the caret I guess.
uuugh, maybe?
I feel like it would just overcomplicate things
Well, without it things like moving the caret position wouldn't work. Guess I could manually hook it up though. Guess I will play around with it. Good to know there isn't a better way though
you can use cursorIndex/cursorPosition to move the carret around, I think. Right after you set the value of the textfield
Another thing you could try tf.RegisterCallback<FocusInEvent>() -> tf.focusController.focusedElement = parent etc - I could be wrong but I don't think that disturbs input capture.
Whats the best way to have content inside a background image and it being always responsive, meaning the content doesnt get out of the background image that is scale to fit
Example, a background image with form of a bubble and text inside
Hello, I am trying to make a debug console using UI toolkit. I am using a listview with labels for each entry into the console log. However, as not all of the messages are the same length, it has difficulty rendering anything with different numbers of lines, is there something I should be setting/using to resolve this or is it an issue with using list view?
For anyone in the future reading this, the solution is to set the virtualization method to dynamic height on the listview
setting the maxWidth of an element inside a UnityEditor.Experimental.GraphView.Node seems to set the minWidth to the same value, even if it is something drastically smaller(and unsetting the maxWidth causes the element to shrink/expand as expected with the content). dont suppose theres any known issues with this?
also a good chance Im misunderstanding something but heres what im talking about
Hello i wanna ask
Can i make the layout from this
To this ?
With UI element in editor
Its somewhere in the docs but I dont remember where, it might be somewhere under listview with how to make a double wide thingy?
Hello, I'm asking my question here because I'm a beginner and I can't figure it out. I'm on unity 2021.3.15f1 and I'm doing an inventory with ToolKit. To display my inventory I use this script :
public void ShowInventory(ScrollView DisplayContainerInventory)
{
// Vérifiez si le ScrollView a des éléments enfants
if (DisplayContainerInventory.childCount > 0)
{
// Supprimez les éléments enfants un par un
for (int i = DisplayContainerInventory.childCount - 1; i >= 0; i--)
{
DisplayContainerInventory.RemoveAt(i);
}
}
InventaireMenu inventaireMenu = gameObject.GetComponent<InventaireMenu>();
Player player = inventaireMenu.Player.GetComponent<Player>();
// On vérifie si l'inventaire est vide
if (player.inventory.items.Count == 0)
{
// On créer le labels
Label label_name = new Label();
// On met les informations récuperées dans le label
label_name.text = "Inventaire vide" ;
label_name.AddToClassList("LabelSave");
// On ajoute les labels et le Visual Element créés dans leur visual element respectives.
DisplayContainerInventory.Add(label_name);
}
else
{
foreach (ItemData Item in player.inventory.items)
{
// On les stocks dans des variables
string name = Item.itemName;
if (Item is WeaponData weaponData)
{
if (weaponData.strengthSlash > 0)
{
damage = weaponData.strengthSlash;
}else if(weaponData.strengthThrust > 0)
{
damage = weaponData.strengthThrust;
}
else if(weaponData.power > 0)
{
damage = weaponData.power;
}
else{
damage = 0;
}
}
else if (Item is ArmorData armorData)
{
resistance = armorData.resistance;
}
// On créer la Visual Element et on l'intègre dans le visual Element
VisualElement SlotItem = new VisualElement();
// On ajoute l'évenement de clique sur le Visual Element
SlotItem.RegisterCallback<ClickEvent>(evt => OnClick(Item));
// On créer le labels
Label label_name = new Label();
Label label_info = new Label();
// On met les informations récuperées dans le label
label_name.text = name;
if (damage != null)
{
label_info.text = damage.ToString();
}
else if (resistance != null)
{
label_info.text = resistance.ToString();
}
// On rajoute les classes de style aux labels et au Visual Element (Assets/UI/Template/SaveList.uss)
SlotItem.AddToClassList("StyleVisualSave");
label_name.AddToClassList("LabelSave");
label_info.AddToClassList("LabelSave");
// On ajoute les labels et le Visual Element créés dans leur visual element respectives.
DisplayContainerInventory.Add(SlotItem);
SlotItem.Add(label_name);
SlotItem.Add(label_info);
}
}
}
Unfortunately, at first it works but then the display becomes all black (see screen) and I don't understand. Can anyone help me?
how come u cant drag elements into the scrollview content bit etc? its just grayed out..
drag your element onto the ScrollView and it should throw it into the content container appropriately
Hey folk, I'm somewhat new to the ui toolkit. I'm trying to figure out how to assign textures to a ui element. I have some plain VisualElements for the texture container, however I'm not sure how to set a texture. Changing the style seems to be overbloated..?
Google seems to suggest that I can use Image from the ui toolkit namespace, however I'm not sure what element it corresponds to in the elements library? I can't seem to find an Image element there.
Is it just an interface for the background texture of any visual element?
Or is it an actual separate element that's only available via code..?
Oh I see... It is indeed not available in the builder. Good job Unity.😅
I wonder how long they're going to "figure it out"...
https://forum.unity.com/threads/is-there-a-way-to-add-an-image-to-my-ui-from-the-editor-and-not-via-uielements-image.1120009/
Aight, I think I can get it done with changing styles
Uh
all of those say the same thing
Also is there a way to load a document with a relative path?
why doesn't myVisualElement.style.backgroundImage = new StyleBackground(mySprite); work for your case?
Yep. I ended up doing that. I didn't realize we're supposed to assign a new struct. Was trying to copy the existing one and assign a new texture to it, then assign the struct back.
i'm having a small issue. i made a simple layout in the UI builder and it looks like this
But when i load it in the editor as an EditorWindow it looks like this
Any idea what could be the problem?
here is 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">
<ui:VisualElement style="flex-direction: column; flex-grow: 1;">
<ui:ScrollView scroll-deceleration-rate="0,135" elasticity="0,1" style="flex-grow: 1; height: auto; flex-shrink: 0;" />
<ui:VisualElement style="flex-grow: 0; flex-direction: row;">
<ui:TextField picking-mode="Ignore" style="flex-grow: 1; flex-shrink: 1;" />
</ui:VisualElement>
</ui:VisualElement>
</ui:UXML>
Why can I not edit anything in the slider?
Is it the ScrollView not having height: 100% ?
Built in Unity component. You can still style it by targetting each of the styles associated with each child element
Wouldn't that make it take all space regardless of the other children ? Or will it just take all available space?
If it takes up too much space, maybe you could be explicit and say the scroll area is height: 450px and then your child VisualElement has height: 40px or something of that nature
Can you change the order of the child elements?
Not in a built in element that I'm aware of
I'm trying to put one of these text fields after the label, but before the slider
So whatever TemplateContainer is is the thing causing me issues
It works if i change its height to 100% but when i open the window it is set to auto
Oh nvm i forgot to do something in my EditorWindow script
Fixed with treeAsset.style.height = new StyleLength(new Length() { value = 100,unit = LengthUnit.Percent});
You will have to make your own template for that
- Label
- Input
- MinMaxSlider (with blank label)
- Input
I have a webGL build with Input fields (UI Toolkit input fields) but the problem is that when i run the build on mobile i can't type, the mobile keypad does not pop up, what can i do about this?
Is there like some kind of internal unity code i can call to have the mobile keypad pop up?
Got a weird bug with UI Toolkit and addressables. It works fine running without addressables in editor but when I run with built addressable in editor or when I build the game: UI Document Sort Order doesnt work so my loading screen doesnt block other ui stuff. Any idea?
https://cdn.discordapp.com/attachments/847323228003237948/1135629142805717142/image.png
@past ermine TemplateContainer is root of any instantiated uxml. If you want custom root - just use Clone instead, so TemplateContainer is not even created.
Other than that - you have full control over TemplateContainer without ever writing any code and it can be previewed inside UI Builder outside of PlayMode.
@gusty estuary which method are you referring to? there's only CloneTree for VTA. the Clone you are describing is doing exactly the same thing then which the CloneTreeSingle does which i posted and started this discussion.
my annoyance for TemplateContainers don't just come from a design perspective but that they actively destroy layouting and scaling because they don't have any styles by default. also, it's backwards when you define scaling in the element when it should be in the parent (container) where the elements will be added to. i don't know, browsers do some pretty f'ed up stuff but i've never seen anything like that. no browser will ever add some nodes just because it thinks it's a cool idea.
i mostly understand the problem and usage of TemplateContainers because they were designed for editor where you not always have control where you are adding to which is quite different for any runtime UI where devs have full control over everything. another reason is that it's bad for performance when you have usesless nodes.
Hmm, pretty sure there was a method to instantiate into existing root... Can't find it though
They don't have any styles by default so that you can define thtm
I don't get the point about scaling
you can't have a fullscreen root and add another full screen element to it because of the TemplateContainer. now you need to add the same style of root to the TemplateContainer for it to work otherwise the width/height is wrong
You can
just use absolute position
With 100% hw
Define it in your theme and never care about TemplateContainer again
this won't work because it will scale up to the TemplateContainer width/height. which is wrong
I don't get what is it you want
you asked a question about scaling, i answered. your suggestion doesn't work because it was exactly what i was doing in the beginning.
a full screen element centered to the screen with like 70% width, 80% height for example.
so you make fullscreen root, center it's children and put ve in it
Don't see how TC breaks anything here
see if you put the element i want in the root.uxml that's all fine because no TC is created. but if you instantiate the element there will be one
Yeah, but how is it breaking anything?
the TC won't have the width/height from root
by root you mean uxml node in ui builder?
UIDocument root
it will if you define global style for it
for TC?
Yes
Or you can also define style that targets tc that are specifically children of uidoc root
i don't want to define a global style nor an individual one for TC. i think i've made that pretty clear by now ^^
So all other are unaffected
But what's the difference between other element as root? You define style for those anyway
And that's more effort, because it's code based
i also think that's dangerous because it makes the behaviour unclear when you instantiate or if you put the element directly into UXML. suddenly you have 2 possible outcomes
I use custom classes for roots, which help specify exact cases for styles
So no collisions with other behaviours happe
what? no. container styles, flex grow, etc... can be defined in UI builder and can automatically go from inline to class
But you have to swap your instantiated tc with custom root
That's what I mean
Instead of just modifying
i just use CloneTreeSingle instead of Instantiate. the former skips the TC
i want UITK code to not deal with any uss. it's so error prone and hard to figure out otherwise what's happening and CSS in general is already pretty difficult to figure out when things go wrong.
Uss is the best thing in uitk wdym 😅
I practically forbid myself from using inlined styles
Only use classes directly
So that everything is resolved by stylesheets
yeah that's how it should be. i'm just saying it gets weird when code does complex stuff with adding/removing classes. even worse when code adds inlined styles
can I generate a 2D grid in UITK based on data stored in a scriptable object directly? Im trying to pass in a reference to the data but there doesnt appear to be a descriptor for SO's/custom types
or should I generat that on Awake from a MB controller script?
you can do grids quite easily with Vector api. Also depends what kind of grid you're talking about
basically a 2D grid of squares that are part of a top-down clickable surface
like a bool[5, 5] as a grid of equal tile sizes
based on the state of that array on a MB
for highly scalable and dynamic grids, I recommend vector api
if it's just static grid and not that big, just regular bordered visualElements would do the trick
not particularly big, but it needs to be dynamic
the size of that grid is not static, since it will depend on parameters in an upgradable system
I will need to look into the vector api as I have never used it tho
@gusty vapor what is the point of using this API for this? with that I mean, why would I use this API rather than draw squares by giving an border to each element of the grid?
is there that much benefit in the scalability of a simple shape like this?
efficiency basically, with vector api you can generate a single mesh
while with multiple visualElements... well, you know it already
so then logically speaking, I want to create a Tile : VisualElement and use the vector api to draw one tile
then populate my grid with those elements
and you even do hex-grid with it
if that's the easiest route for you, go for it 👍
I mean with the mulktiple visualelements
mostly because each of them needs to be clickable separately
which would be rather difficult if I draw the entire thing from one component I would imagine
with vector api you can do that too 🫡 ... just setup bounds for each grid cell then check your mouse position, thats all 🤪
again, it's a matter of efficiency
hmm, interesting
given that, I should then be able to draw a 5x5 grid by drawing 6 horizontal and 6 vertical lines.
or is that going to be a problem to generate the mesh from it?
does it handle overlapping lines to generate a geometry with thickness?
you can draw anything you want 😃 , the api is for 2d drawing basically
if you used Skia/SkiaSharp before then it's similar to that
I see
im going to mess about with that api for a bit
see what I can make it do rather than speculate
there's another simple trick (probaby). By installing vectorGraphic package, you can make your grid cell in image editor such as Inkscape/Illlustrator, export it as SVG, then import it to your project then change the import settings to uitookit format.
So you can skip the vector api and only need to make layer of bounds for the grid cells so later you can do your mouse events
but yeah, that's for static grid only unfortunately
so making a context menu for right click is pretty simple, but anyone know how i could build a context menu that i can just invoke to display via code?
in my case i am wanting one to display after a DragPerformEvent
this is for editor not runtime, and is within a graphview
I';m not sure if manipulators can work with SendEvent. proly worth a try.
Make a dummy ellemet assign a contextualmenu then do SendEvent
Proly @gusty estuary knows
huh?
😂
found a other way around for now
was able to do a panel.contextualMenuManager.DisplayMenu(evt, this);
that is good to know, thanks for sharing that 👍
then in my function for building the context menu, i just check triggerEvents type
and build it differently based on it
does it take the default position of your visualelement OR your current mouse position instead? @autumn dagger
its still on the mouse
nice! 👍 and thaks
though that might be because the event i triggered it from also has position
panel.contextualMenuManager.DisplayMenu(evt, this) being called in my DragPerformedEvent handler
and evt i pass in is the DragPerformEvent
in my BuildContext menu all i do is if (evt.triggerEvent is DragPerformEvent dragEvt) { ...
and draw differnet items and return early, otherwise do my regular context menu
why does a relatively sized container not work at all?
the Grid element is 1000x1000px
the underlying visualelement is 100x100
yet its filling the entire width
appearantly, its just doing a % based fill based on its childcount even though I specifically told it the boxes should be 100px
try align-items: flex-start on the grid
doesnt rly do anything sadly, sorry, I was out makign food
setting the maxwidth on each item does appear to work 🤔
You can also try flex-grow 0 on the items
any reason why the shop png isn't showing up in the editor?
it shows up in the game
but for some reason I can't see it
I wanted to add more interactions but I need the image as a reference to know where the board and black border for options
ping me if replies
thx in advance
This channel is not for UGUI, you are looking for #📲┃ui-ux
ah mb
Is there a way to synthesize NavigationSubmitEvents? in the docs it seems to imply that only synthesizing OS events are supported (eg mouse events) and events found in the UnityEngine.Event types. I cannot find the navigationSubmitEvent as a valid EventType enum. Any work around? I'm trying to avoid using Unity's event system while still supporting keyboard/gamepad navigation.
why this is not main feature of unity UI toolkit?
I imagine the #763499475641172029 devs will add some nodes when UITK becomes recommended for runtime use
Is border style possible in UI Toolkit? I added it to my uss file but it didn't change anything.
https://developer.mozilla.org/en-US/docs/Web/CSS/border-style
you could probably make it with the vector API honestly
Definitely yes, but sadly people would not prefer vector api bcos they thought it's hard and overcomplicated 
anyone here?
the dropdown is too small, how do I make it bigger
Like the text in the dropdown
check the styles in https://docs.unity3d.com/Manual/UIE-uxml-element-DropdownField.html or in the uitk debugger
Hello, I want to create a friend list with the Unity UI toolkit list view. So, I wrote a script that clone a visualThreeAsset, but it works weird... I will send the files and screenshots, script
script: ```using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class FriendListManager : MonoBehaviour
{
public VisualTreeAsset friendItemTemplate;
public List<string> friendNames;
private ListView friendListView;
private void Start()
{
friendListView = GetComponent<UIDocument>().rootVisualElement.Q<ListView>("FriendList");
friendListView.makeItem = MakeFriendItem;
friendListView.bindItem = BindFriendItem;
friendListView.itemsSource = friendNames;
friendListView.selectionType = SelectionType.Single;
}
private VisualElement MakeFriendItem()
{
return friendItemTemplate.CloneTree();
}
private void BindFriendItem(VisualElement friendItem, int index)
{
Debug.Log("ID of the item: " + index + " content: " + friendNames[index]);
var butt = friendItem.Q<Button>();
butt.text = friendNames[index];
}
}```
11 elements you can see
List View UI Document
the template for each player
Sorry, I forgot to mention. As seen in the screenshot, there is no spacing between the elements. They are even overlapping. Additionally, the List View is not scrolling.
Hi ! I'm trying to make a simple search bar for a list view using UI Elements, but despite having the right results when filtering my data, my listview display the N first non-filtered elements (N being the amount of result). I suppose I'm not doing the listview update properly 😅 Could anyone have a look pls ? https://hastebin.com/share/fuvitobulo.kotlin
Is there a way to set text of a label with char[] to avoid string allocations in hot paths like Update()?
I think it's time to call it a day... BindListItem was pulling the wrong list, my bad.
Hi.
I find it very annoying that when i create an uxml template it creates a parent object to it. I dont want that when i need to create a template from a container. Is it possible to deny that?
My workaround right now would be deleting the Parent in the template and create a stylesheet from it. But then I'd need to add the stylesheet to every Template object because I cannot set it in the Template for some reason.
@gusty vapor do you know any easy way to create a multiline label that automatically splits between lines? Something like this.
I want to make a visually pleasant tooltip
oh
turns out they just have HelpBox
which almost same as imgui one
any TextElements should support multiline tho? you just need to set the style
give me a sec
couldn't figure style
but dw
HelpBox does it
and I don't need more

either way, this
public static T TextArea<T>(this T textField, float height) where T : TextElement
{
textField.style.flexDirection = FlexDirection.Column;
textField.style.overflow = Overflow.Visible;
textField.style.whiteSpace = WhiteSpace.Normal;
textField.style.unityOverflowClipBox = OverflowClipBox.ContentBox;
textField.style.height = height;
return textField;
}
thats inline, you just need convert it to uss 😄
nah, I use pure C#
default editor styles are good enough
Man, this is really fun
I made such a good inspector
which auto shows, hides fields
automatically estimates values and etc
holy shit I love it
I see so you already been toxicated by CustomEditor 😃
becareful, customEditor is very addictive, no joke
project idea, Odin-like serializer but uitoolkit and sell it on assets store for quick bucks 🥹
uh, what?
Asset store does not pay to my country
not even sure if they allow publishing at all
ffs dude, we're in the year 2023, many ways to do international transactions nowadays
you can open your virtual bank accont via Skrill iirc(I did this mmyself many years ago)
google up
need to visit other countries for that (I already made a huge research on what is possible and what not), but anyway it's offtop for this channel
aight last, if you have relatives that live in another country, ask them. It's somewhat a common practice btw
or just like I said, virtual bank account 🥹
hmmm, do you know if there's a way to track other component in inspector?
I have inspector for X
I want to track changes on component Y
Hello guys, i wanted to make a cutscene maker costume editor tools that consist of nodes that could be connected. Is there any tips on getting started? Tutorials or stuff like that?
Yes, there are couple of apis to do this, give me a sec lemme see what I did
on top of that component is optional
there is no graph api in unity, except obsolete ones
I'd look into 3rd party solutions for now
and where do I get it
that'\s just enum
kekw
public override VisualElement CreateInspectorGUI()
I'm inside of this method
case ObjectChangeKind.ChangeGameObjectOrComponentProperties:
stream.GetChangeGameObjectOrComponentPropertiesEvent(i, out var changeGameObjectOrComponent);
var goOrComponent = EditorUtility.InstanceIDToObject(changeGameObjectOrComponent.instanceId);
/*
if (goOrComponent is GameObject go)
{
Debug.Log($"{type}: GameObject {go} change properties in scene {changeGameObjectOrComponent.scene}.");
}
else if (goOrComponent is Component component)
{
Debug.Log($"{type}: Component {component} change properties in scene {changeGameObjectOrComponent.scene}.");
}
*/
if(!PortsUtils.PlayMode)
{
bool wasRenamed = false;
if(goOrComponent is Component com && (com is VStageComponent vstage || com is VelvieDialogue))
{
RevalidateAllComponents();
}
}
break;
I only have SerializedObject
put that in your editor initializer
huh?
this sounds like overkill
it is not, it's very common
you'd definitely want to do things while initializing, so thats that
I still don't get entry point
what you pasted is a switch for enum
which I don't have
😅
ffs 😄
you just need to subscribe it
ObjectChangeEvents.changesPublished -= ChangesPublished;
ObjectChangeEvents.changesPublished += ChangesPublished;
thus initializer is a must here
@gusty estuary
[InitializeOnLoad]
public class ObjectChangeEventsVR
{
static ObjectChangeEventsVR()
{
ObjectChangeEvents.changesPublished -= ChangesPublished;
ObjectChangeEvents.changesPublished += ChangesPublished;
...
}
and put that class in Editor folder as usual
that's your entry pretty much
this is totally an overkill
I'd rather make an imgui container which will constantly check value
rather then process all project modifications stream
wdym, they're made pure for convenience 😄 ...
You'll understand this as you dive deeper into customEditor
I'm not going to process all modifications events
It's only relevant to one little inspector
I wouldn't degrade whole editor performance just for that
lol
if it's mono your can just vallidate things in Reset(). Tho mind you this is ugly as poop
you wont 😄 , they're not llike you're imagine really
otherwise people would throw rocks at Unity
fr
ofc I will
editor code runs on main thread
tracking whole stream is a lot of work
doing same thing with IMGUI container - much less work
and it works
so I'm good
with local imgui checking I only do it when inspector is visible
and only for one object
vs all
aight, proly next time hop on to #↕️┃editor-extensions and let either Mech or Navi answer your doubts. They're very good at these and I learned alot from them
would this be the place to ask TMPro questions?
For future reference this channel is for UI Toolkit, TMPro is UGUI and world-space, so #📲┃ui-ux or a general channel is suitable
Hey, I'm running into a problem I cannot decipher.
I have created this page which seems to work perfectly inside the UIBuilder and also in editor mode the elements of the scroll-view are still visible. However, whenever I enter game mode all elements turn invisible.
The elements are still there, as shown by the scroll-bar and by the debugger. But I have not seen any property that is being modified in runtime that should make this happen.
I don't know if it is worth mentioning but the scroll does not work properly, it needs hundreds of mouse-wheel rotations to get to the bottom of the view
Hey guys, I have a quick layout question. I'm just getting used to UI Toolkit but I do have a background in web development and using frameworks such as WPF/XAML. It is my understanding that UI Toolkit is based on a library called "Yoga" where everything uses flex boxes, I'm wondering if it is possible to design a layout similar to the one in this image and if so how I would go about it? The main layout I am trying to achieve here is a banner/header with two panes for left and right. Usually I would use a grid layout or some sort of table but am having a bit of difficulty laying out the things I want using just flex boxes. Any help would be much appreciated
Make sure your ui builder theme is set to runtime and the theme in panelsettings is also set to runtime
If it is set correctly then I suggest looking in the styles panel of uidebugger to see why they might be invisible
Dont see what's so hard about this? To position the l/r panes on either sides of the screen you need to put them in a container with flex-dir: row;justify-content: space-between
I think the thing I'm struggling with is when I have a layout like this:
#Wrapper
-#Top
-#Left
-#Right
Where you want the "#Top" to become the banner/menu and then you need to position two panels either side, they tend to look rather odd as the left and right panes aren't often in alignment
#Wrapper .col
#Top
#Bottom .row .justify-space-between
#Left
#Right
Why would they not be in alignment?
Whoops fixed the alignment
For example, this is what I keep coming up with, this could be down to the lack of styles?
You need to put them in a container first
Like this
Are you sure you have background in webdev 😅?
Well, I'm more of a backend web developer but have messed around a little with the front-end 😛
Ah, I see
hi ppl. Is there a way to detect whenever a blackboard property field is deleted from its blackboard? It also would be useful to know how to delete elements user-side too since delete button does not work/exist, lol
to be clearer, i want to remove this property field and fire an event whever that happens
those ContextualmenuManipulator menu.append action has DropdownMenuAction.Status enum, and has enum value Normal, Disabled, Hidden, None, Checked, which from the name you can guess what will happens, the thing is that menu.AppendAction is return a void, so how i can change DropdownMenuAction.Status later on??, when i has something that become Normal, when didnt have then Disabled
When I go fullscreen, my Buttons (horizontal layout group) work properly
but my images (grid layout group) break and shift to the right too much, anyone knows?
nvm fixed
I was getting annoyed by the inspector having wrong alignment with custom fields when not using PropertyField binding. this script will fix it and does the same as a PropertyField (BaseField) usage is: ```var root = new PropertyField();
Label lbl = new Label(property.displayName);
root.Add(lbl);
root.Add(popupField);
root.UpdateLabelWidth(lbl);```
So the slider element will display it's value but, how would you do that for the min-max slider?
I can't find any option to enable that
when I import this 52x52 asset into unity it blurs really bad
hmm for some reason unity converts it to 64x64
i got thiws message while adding sliders on the ui
this is my code
and i have put the slider gameobject on the unity editor
and the error message doesnt say much after
that all it say
Have you got the references from the UXML using the root UIDocument?
Since UIToolkit requires something like this to reference:
slider = root.Q<Slider>("health-bar");
i fixed it
thx for helping
Is there a vid or something I can watch to get the basis of learning ui like menus, inventorys, ability timers and stuff like that ik how to do hp bard but not the other nesacary things
is there a way to call a method whenever any children buttons of a visual element are clicked
If i hate canvases but like the buttons and event system would this version of ui be better for me?
Hey all, I'm working on a dialogue system with UI Toolkit and want to keep characters from shifting around by rendering them as invisible, and then revealing them, instead of just setting the characters (detailed in this article: https://medium.com/red-blue-games-blog/texttyper-component-a-solution-for-autotext-in-unity-5a60225f5822). I attempted to try this method of shifting along a <color=#00000000> or <alpha=#00> tag, which works, but it appears to have no affect on <sprite> tags at all, seen in the screenshot below. Unity 2022.3.0f1.
Is this a bug, or intentional behaviour with the rich text tags? If it's intentional, any suggestions for a potential work around? Some USS I might be needing to set?
Just a quick question:
Is there a way to move UI components from UI builder using scripts?
Like for example a button element that moves around the screen whenever the player presses it?
You probably could get a similar effect by using absolute positioning and just randomising the position in code using Random.Rage in an onclick event, you could try getting the visual element and using that as a bounds to make sure the button stays within that bounds.
I think in order to affect sprite color you need to have the color attr inside the sprite tag
you can also use reflection to modify character color, the api is mostly the same as tmpro
except it's all internal and hidden away from you
If I have something like an inspector window where I display some stats (of the building clicked).
Should I have the node of this always in my tree and just enable/disable it, or should I remove and add?
Or does this not make a huge difference anyways?
Ah yes, that did it! It didn't occur to me that you could use a color attribute on the sprite itself, but yeah that makes sense. Thank you!
How can I view the event log debugger in newer 2023 version? I can't find it anywhere.
Seems they got rid of it. Its just not there anymore.
this.AddManipulator(new ContextualMenuManipulator((evt) =>
{
evt.menu.AppendAction("Copy", (x) => Debug.Log("Copy"), DropdownMenuAction.Status.Normal);
evt.menu.AppendAction("Paste", (x) => Debug.Log("Paste"), DropdownMenuAction.Status.Normal);
evt.menu.AppendSeparator();
evt.menu.AppendAction("Clear", (x) => Debug.Log("Clear"), DropdownMenuAction.Status.Disabled);
}));
``` still struggling on this, so for DropdownMenuAction.Status i want that not fix Normal or Disabled, but base on condition, if there any data then the Status is Normal, but if there no data the status be Disabled, how i can achieve that?
Hi! I'm just wondering if there's filters in UI toolkit as there's in CSS?
Like:
filter: contrast(200%);
Also, is there a solution for having two overlapping ui documents still be interactable?
Nope, not possible to implement yourself either
Okey, thank you!
Is there a way to instantiate a button asset and change the text of that button before it's loaded into the tree?
Because the TemplateContainer removes all the buttons properties. Maybe it's because it's a clone, but is there any work around? Clone the whole button and change it?
Hey, is there a way to create different radio buttons groups without using Unity's default Radio Button Groups?
I want to create these filter chips and I believe being able to use radio buttons for that could save me some lines of code by not having to handle the stylesheets of the chips. I could simply use the ":checked" pseudo-class to automatically change the color of the chips and since they are radio buttons the logic of only having one of them checked would also be handled by Unity.
That being said, the different chips have different shapes in my app and I cannot specify which shape corresponds with each chip inside a radio button group. So, I have to use multiple single radio button but I do not want these chips to interfere with other possible radio buttons in the document.
Why when i style a scroll the height gets overrided for some reason? _itemsView.Q<VisualElement>("unity-dragger").style.height =
new StyleLength(new Length(30, LengthUnit.Pixel)); (items view is a ScrollView)
its always set to 7px when i debug it for some reason
In case anyone was stuck in a similar problem. The way to create custom radio button groups is to enclose the desired radio buttons inside a "GroupBox"
I noticed a small bug i want help validating
If i use a Float Field (just an example, this occurs with multiple fields in UXML), and i use BindProperty on it, the field becomes impossible to edit in the editor then
(using it on a custom inspector)
Is there any way to have these toggles outside of the 'user' area of a TreeView? I want them fully left aligned so they are on the left side of the foldout toggle. Much like the visibility toggle in the hierarchy window.
There are several ways to go about this
a simple way would be to add a negative offset / padding
What i like to do in general though is to use more Visual Elements (as panels) to handle positioning
Yeah I thought about adding negative margin or something. But then means that they would have to go outside of the element bounds so would not get the selected over hover background behind them
What do you mean?
A simple example is something like this
Its in between my other elements
(or before in some other use cases of mine)
then you add your actual element inside to handle positioning
Sorry if I am not understanding, but I don't really get how that helps with this?
second im drawing something
So explain to me which is which please?
(drawing an example for your use case)
Like this basically. Where the eye icon would be my toggle. It is on the left, and the foldout is to the right of it
Ah that is tough to handle cause you are trying to do it outside the content container
2 ways i would go about this
A) Margin offset like i mentioned
B) Several visual elements to organize the order of the elements
ill explain (B) in a bit
Yeah exactly haha, that is why I am asking here 😛
tell me something
Would you need the Toggle here to be outside?
so first that then the dropdown?
pretty much asking this
Basically
So yea for this one okay
So a simple solution would be to split this into 2 part entries
where the blue outline is the First Visual Element Panel
And the green is the second
for each entry on the blue, you would have to add one on the green (just make sure they are both vertical and they would add automatically in order of appereance)
Albeit there are certainly more refined ways to do this, this is just a simple example
a different way would be to do:
To make each entry a single element (Red is a main visual element, holding 2 visual element holders, shown by the green split)
Hmmm. not sure I understand this one
Visualise it just like this for simplicity
With "Entry" having horizontal direction
@still lantern
thats all from me i have to go
hope it helps
the rest (as far as how to handle entry insertion) is just code
Oh I think I get what you are saying. Interesting. I had another idea I am going to try as well. Thanks for the help!
Well @merry mountain I got it working, though a bit ugly. In the BindItem callback of the treeview, I walk up the tree to get the item visual element that contains the foldout and indent, then unregister and reregister a callback to the GeometryChangedEvent on the indent element, and set my toggle's margin to be -(32 + indent.resolvedStyle.width). And I add a 15 margin to the foldout to make room for the toggle (also set the toggle's positioning to absolute.)
So... not pretty... but it works. Surprised Unity doesn't have a nicer way to handle this. Oh well. Next I gotta use reflection to get internal events so I can prevent a drag and drop from happening on some items 😅
Well, thanks again for the help!
Hey guys, I have a question regarding UI Toolkit that I would like other people's input on and that is how people go about handling/switching between multiple UIDocuments? I have read that people often show/hide multiple UI documents within a single UI Document but I cannot seem to find any information about best practices for UI navigation and I was wondering how others solve this issue
there are many ways to approach navigation
I'd say it really depends on what kind of app you're building
and what architecture you have in general
for game states (if it's even relevant)
is it possible to creatre a sprite object field?
i am trying but it doesn't work
but it also doesn't give an error why
For now I don't really have an architecture in place but I was looking at a general MVVM/WPF approach which seem to use service locators and data template bindings. This may work but the data-binding for UIToolkit doesn't seem as versatile as WPF. So I was wondering for a general architecture that may work for a relatively larger project with a lot of menus/sub-menus?
I actually made MVVM framework for UITK 😅
except no data templates
couldn't manage them
but still
even with it, there is no one solution to navigation problem
in manual on github, I have an example how to approach it with message bus
but it's not silver bullet
Nice, I came across this the other day. It looks very good. Good to know you are the author of the framework 🙂
I'll definitely check out the framework. Do you have any experience using UIToolkit for world space/in-game UI?
UI toolkit is not meant for world space
and using it for it's purposes will require hacks
Any idea why?
Do you have any code to show?
private VisualElement BuildProperties(SerializedProperty property)
{
var serObj = new SerializedObject(property.objectReferenceValue);
var container = new VisualElement();
container.name = CONTAINER_NAME;
container.Add(BuildObjectField<Sprite>(serObj.FindProperty("crossHair"), "CrossHair"));
container.Add(BuildObjectField<Material>(serObj.FindProperty("hitEffect"), "Hit effect material"));
container.Add(BuildObjectField<AudioClip>(serObj.FindProperty("attackSound"), "Attack sound effect"));
container.Add(BuildVec3Field(serObj.FindProperty("originPosition"), "Origin position"));
container.Add(BuildVec3Field(serObj.FindProperty("originRotation"), "Origin rotation"));
return container;
}
private ObjectField BuildObjectField<T>(SerializedProperty property,string label)
{
var objField = new ObjectField(label);
objField.objectType = typeof(T);
objField.BindProperty(property);
return objField;
}
when i remove the crosshair field,it seems to work fine,but when i add it,it suddenly stops like there is an error but it doesn't show anything
and yes the field name is correct
i literally copied it from the source file
@thorn summit Does it work with <Image> or <Texture2D>?
let me see
so i managed to find another way that lead to rewriting,thx anyways
Has anyone gotten UI Toolkit to work with multiple displays? I cannot get anything to show up on the second screen
I have two different UI Documents, each with their own PanelSettings asset that’s pointing to a different display
Black screen on the second
It’s activated using Display.Activate
Nevermind, fixed it
How do I find which versions of unity supports UI toolkit?
I think any version that is 2021 or later has UI Toolkit built into it
Thats good news :D Is there any way I can get it confirmed?
just take a look at UI Toolkit page in manual
it's not available in all versions but only recent
since 2020 I think
I tried but I cannot find it :P
take a look at pinned messages
So if I were to send my window editor to a friend while he's on Unity 2021.1 would it give errors?
I'm trying to understand which version I should send imgui to rather than UI Toolkit
Yo Pls help me
Yesterday I installed the ReadyPlayerme module in Unity but the setup guide didn't bring it up and so I couldn't add my subdomain
How can I add my subdomain at this time?
are we still expected with UITK to create different canvases (documents) and overlay them to limit redraws or is this not as much a problem with this compared to the GameObject based UI system
this is a non-issue in uitk
awesome
I was a bit concerned since I dont exactly know what triggers the events in UITK @wind gorge
mostly relating to the GeometryChangedEvent
all geometry changes are batched and evaluated once per frame iirc
im more about when this gets fired and what kind of overhead that causes
does it actually just execute once per frame?
to give some context ```cs
public void PopulateGrid(bool[,] data)
{
Clear();
var rows = data.GetLength(0);
var cols = data.GetLength(1);
tiles = new VisualElement[rows, cols];
for (int i = 0; i < rows; i++)
{
for (int c = 0; c < cols; c++)
{
var tile = new VisualElement();
tile.AddToClassList(TOP_LEFT);
if (c == cols - 1) tile.AddToClassList(RIGHT);
if (i == rows - 1) tile.AddToClassList(BOTTOM);
tile.RegisterCallback<GeometryChangedEvent>(x =>
{
var tileWidth = resolvedStyle.width / cols;
var tileHeight = resolvedStyle.height / rows;
tile.style.width = tileWidth;
tile.style.height = tileHeight;
});
Add(tile);
tiles[c, i] = tile;
//store indiices to prevent event firing at wrong one
var x = c;
var y = i;
tile.RegisterCallback<PointerUpEvent>(evt =>
{
Clicked?.Invoke(new Vector2Int(x, y));
});
}
}
}
I don't see what your concerns are about?
I have a geometrychangedevent that is firing for close to 300 objects
and I worry about the scalablity
oh ok, thats is perfect then
it depends on unity version, they've improved geometrychangedevent perf in 2022 and up i think
you should test it yourself
Aight, I ll profile it. tbh I could wrap the code block in the event in a function, call it and then remove it from the event
I ll do some profiling and see what's necesarry
Working in 16:9, I’m having a hard time getting text to scale correctly with screen size. Had no issues when working in 1920x1080 canvas but can’t get it to work in 16:9. Any ideas?
Hey, how can I change color of input field?
This only affects corners somehow
I also added this class but it does not work I think? How I can make this inputfield use stylesheet instead of inline?
You should use the UI Toolkit debugger to inspect the field in the wild and see how it's constructed, and which parts of it have the background color. Because it's a control made up of multiple pieces, you have to target the right part.
look this is locked somehow and Label's background color was changed
I cannot modify this #unity-text-input
how can I add styles or modify?
Yes, you can't, but you can target its styles via uss
Yes, or if you want to target only that one, add a class to the root of it and use an appropriate selector to then apply to the nested elements
in Rider, yes
extension or something in big VS
Ah. I have it too okay
if I select one of that
and override will it work?
You can try it out and look at what's doing the work using the UI Toolkit Debugger
where is it can you tell me?
(don't try to test it out in the UI Builder, as that's not a real setup)
in Ui builder?
don't try to test it out in the UI Builder, as that's not a real setup
Please listen to what I say
Nah, I did not meant to modify anything
Then why are you showing me this
only in Uss
Because I see some class-names and I thought you told me about this to find proper class names
to select it in uss. am I wrong?
The UI Builder's representation of the Input Field is not a real setup, it's complicated, don't inspect it, don't look at it, modify it, it's irrelevant.
You should use the UI Toolkit debugger to inspect the field in the wild
don't try to test it out in the UI Builder, as that's not a real setup
Nope, I doubt any exist
I have provided all the info you need. I don't have Unity open, and it's midnight, so I'll be going to bed 👋 If you need more help, show what USS you've tried to write and maybe someone can help you figure it out the rest of the way
Aha, no problem. Thank you for your time!
GoodNight
Here is midday
private IEnumerator LoadSceneCoroutine(int sceneIndex)
{
AsyncOperation operation = SceneManager.LoadSceneAsync(sceneIndex);
_loadingMenu.gameObject.SetActive(true);
ProgressBar progressBar = _loadingMenu.rootVisualElement.Q<ProgressBar>();
while (!operation.isDone)
{
float progress = Mathf.Clamp01(operation.progress / 0.9f);
Debug.Log(progress);
progressBar.value = progress;
progressBar.title = $"Loading:{progress * 100}%";
yield return null;
}
_loadingMenu.gameObject.SetActive(false);
}
so for anyone here,i assume the following code would work,and it kinda does but also not the way i expect,there is a huge delay when it begins loading and the loading menu shows up at the last second and the text always shots it begin at 100% and the debug log only logs 1 twice
any idea what the issue is?
Does anyone here have experience with ListViews?
I'm trying use RefreshItems after updating an item source and it's not working
And Debug.Log isn't working inside so I can't get any info as to why
Hello guys. Can someone please provide me some tutorial or documentation on how to drag visualElements? i want to drag visual elements outside a scrollview to a certain window. having issues with that, thanks!
Hello, is there a way to hide the "List is empty" when there are no items in a ListView ?
Soooo, this thing (I'm trying to display an icon) doesn't seem to work with SVG sprites. But it also has a "Vector Image" type, for which I can't even create an asset.
How do you display SVG sprites in UI Toolkit?
also, is there no specific "image" or "icon" visualelement? Feels wrong to be going via background.
Ok, vectorimage seems to be a sprite subtype.
But I still have no idea how to make it show up.
Ok, some sort of layout issue.
But...
Don't tell me this doesn't have an option for MSAA?
Holy cow this is >>> WITH <<< pipeline render scale = 200%
(and MSAA 4x, but already said that doesn't seem to be respected by UI Toolkit)
I think translate/transform should:
- allow z coordinate
- accept normalized device coordinates
- accept viewport coordinates
But yeah without AA, this is quite the showstopper anyhow.
svg assets are not antialiased
their only use is to mask elements
you can try using the new vector drawing api, which does aa
Yeah but I don't want to draw my icon set 😄
rasterize it then
you can probably somehow convert your icons into a font asset
like how they do it in the browser
Thanks.
Not really feasible for my use case, was trying to prototype adapting my UGUI icon HUD to UI Elements.
A little shocked about the AA thing. Text does seem to respect MSAA settings, which is weird, too.
I wonder what I would want to Mask, though, and not have the mask anti-aliased, either.
Like, smooth screen, and then a jagged line cuts through it like it's the PS1? 😄
svg's aren't antialiased in ugui either
you just have to deal with it, yeah
and hope msaa smoothes it up a bit
It doesn't. Neither does render scaling.
Do you know whether that's at least a planned feature?
I don't ship the game today, after all.
I highly advise you to never wait for unity to ship anything
even if they promise it done tomorrow
Not true, only if you use overlay canvas. I always use camera screen space.
Heh yeah you're right.
really? are you sure they aren't just rasterized?
I assume msaa doesn't work because uitk outputs to overlay and not to camera
that's with msaa enabled on the ugui camera?
Yeah, so how do you render 3D over UITK?
MSAA, no render scale.
Not on the camera, on the render pipeline asset.
Camera AA is bah-bah.
try removing msaa, I'm assuming it will have the same aliasing artifacts as ugui
render your 3d stuff to a texture and then display in uitk
How do I AA that? (I guess on the RT, but... feels off)
enable msaa on the rt asset
Yes, if you turn off Anti-Aliasing, aliasing does tend to occur. 😛
that's the price you pay for using utik for world space 🙂
well then it seems uitk and ugui both use the same svg renderer
Uhh... not sure what you mean. But doesnt matter.
that's just the general price of using uitk
It's actually UI space, that's the annoying part.
The font is nicely anti-aliased at least.
It's shocking that it doesn't respect render scale though.
then why do you need 3d over
3D icon.
same idea
VisualElement supports rendering images and... RenderTexture
the uitk demo project does it that way
I'll look into it, thanks guys.
and you can render anything to texture
does it blit the stencil attachment from the RT?
no idea
I would guess no, so, no, I can't render "anything".
but I'll test that.
Today is test day.
But I can already see Ugui still in the lead.
I'll wait, sure.
ugui will still be in the lead 5 years into the future
As ontrigger said, don't bank on anything unity hasn't shipped yet.
If you set the panel settings to render to texture with AA, results are passable but still not great and it’s a pretty rough performance hit so you likely want to compromise at eg 2x. There are also asset specific settings you can play with but for now I would recommend going eg png instead- in most cases svgs are just not worth it esp for icons.
@gusty estuary someone had the same idea as you https://github.com/LibraStack/UnityMvvmToolkit
his uxml generator repo is very interesting
didn't like his implementation because of way too much boilerplate
also forced to create all elements from scratch
Hi all, got (hopefully) a quick question:
I'm making some custom elements and it appears that I cannot add any child visual elements to my window-handler's content container
the window-handler is a custom control, in this instance its being created via the ItemWorkspace's constructor
Is there a way to add allow me to children to these sub-controls?
I think the issue might be this - elements are added to ItemWorkspace instead of the child controls
The ItemWorkspace can only have one contentContainer so I assume this is not possible if I have multiple constructed child controls
i have to say it's pretty baffling to go through all the uitk docs, use the awesome vector api to draw stuff, have all your fonts be beautifully scaled, use something like flexbox and css to layout your ui and then try to use an svg be told it's pointless and
rasterise it
major shame, why bother making a responsive UI if you have fixed size icons?
You can still use font icons
you mean like these?
https://matthewminer.com/2021/12/23/scalable-icons-in-unity-with-icon-fonts
Need scalable icons in your Unity GUI? Icon fonts might be for you.
that's pretty slick actually
sry i went to dinner, ty for the tip
Hi, I just created an element which support the box-shadow spec from W3C and wanted to control it through the "classic" way by utilizing uss properties, and I have two questions:
- is it possible to have a
CustomStylePropertywhich support format like the one used in the spec<color>? && [<length>{2} <length [0,∞]>? <length>?] && inset?or do I have to define all properties separately? - how can I manage to show theses properties in the
Inlined Stylessection of the UITK inspector?
- it is not, 2) do you mean the ui builder or the debugger?
- sad, 2) ui builder
ok thanks
It seems to works with some ugly tricks internally, all custom style come from a ICustomStyle interface which is propably here to permit bind between c++ code and C# scripts, it would be cool to have more way to customize the parser
Agreed, would also love a way to animate custom properties without tons of pain
So I have this container that it supposed to hold an icon, and when I add a background image texture through the UI builder, everything looks fine. But I'm creating runtime UI and when I instantiate this uxml file and set the background image through code, it stretches out. I'm probably missing something very simple but if someone could point me in the right direction I would appreciate it!
this is how I'm setting the image if it helps
Make sure the image has -unity-background-scale-mode: scale-and-crop set in the ui debugger
How do I make it so a parent element will receive the key down events from children? I have element that contains a list of other elements and when I press the delete key I want to delete the selected child element. But I can't figure out how to get the key event to trigger. I tried registering to each child (propertyField) but that didn't work. Ideas?
you can just do evt.keyCode == KeyCode.Delete, no? or proly I misunderstood?
I mean the event on the parent or on the child is not getting raised
proly focus issue?
Maybe? What would I need to focus/set ya think?
the element that you're registering the keydown event
Ahh yeah that was it! Thank you!
🥳
Now... what do ya do if a child element has focus? For example a text field.
🥹
Hello !
Is there a "content" equivalent in USS ? I can't find it !
The idea is to put an icon before a text label (with .myclass:before)
There is none
Okay thanks
How can I update style.display ?
I don't understand (the error says: unable to convert explicitly the type "string" to "...")
Oh, thanks 🙂
Is it possible to add vfx like snow or rain to my main menu if I use ui-toolkit as opposed to ugui?
There is currently less compatibility with world-space effects, or particle effects, or shaders in UI than UGUI.
Hey, I have this bug in LTS 2022.3.7f1 and I don't know if this is just a me thing.
Whenever I work with RenderTextures, the inline background style of the Element I'm working with is automatically set to none and unsetting the property does not work.
As can be seen, even when I unset the property and the symbol indicates that the property is being modified by a selector, the white vertical line expressing that the property has been modified in inline persists
Hi, I am using UI builder to make my custom inspector and an editor script with this function 'CreateInspectorGUI()' and I made a few buttons that need to change which Visual Tree asset is being rendered, but the change only happens when i deselect and select the object that has the scirpt with my custom inspector.
i just need to refresh the inspector window somehow
when working with a button in the toolkit, how can I make it so that the .clicked is called with a button press instead of mouse?
this is my solution
thanks
I'm struggling a little trying to build a very simple encyclopedia style browser using UGUI, and I wonder...
That's possibly the one thing where UIElements is actually ahead (maybe not, but I think it also does tables?)
||And could I put a UIDocument's RT into a RawImage and just... show UIElements in UGUI?||
(spoiler because this may make some heads spin or stomachs turn)
But how would I make links clickable then?
you can, but it will be 1 frame behind, unless your ugui is using overlays and is above uitk
Is there a preferred way of scaling text in a UI document to aid with accessibility? I would like to use a slider UI element to set the scale.
That's generally fine, this is for static "offline" content, like explanations of game mechanics, etc.
first attempt to "solve" box-shadow in UITK
unfortunately I can't do exactly what I want regarding the "styling" part due to the lack of tools to customize USS rules and the parser, we can't modify a CustomStyleProperty property like an inlined style and it's tricky to apply animations/transitions on it, ATM I use both UxmlAttributes and CustomStyleProperties to modify the style and I give the priority to the UxmAttribute, UITK really needs tools to customize this part with more ease
Are you doing this with a custom shader?
yes I use a compute shader and the MeshGenerationContext to do that, I need to recalculate the mask of the shape of the rounded rectangle to exclude it from the shadow
When using Textfields, Floatfields etc. for some reason the "label" is taking priority in growing over the inputfield, why is that? How do I make sure the "inputfield" parts are at least always the same size without needing to completely "drop" the standard controls and implement my own? It seems so rudementary?
it will do the trick
TextField .unity-base-text-field__input {
flex-shrink: 0;
flex-grow: 1;
}
TextField .unity-label {
flex-basis: 100px;
flex-grow: 0;
text-overflow: ellipsis;
overflow: hidden;
}
by default the field input is in flex-shrink: 1 so when the label take more space the field shrink
you can put this kind of changes in a TSS file which will be used across all your documents
Thanks, this somewhat puts me at ease!
.TSS seems interesting but it seems to only be for runtime UI, correct? Atm I'm only looking at UIToolkit & UIBuilder for editor UI ^^
IDK if it will works for Editor, but in this case you can simply reimport a common uss file to all your components/documents
np
anyone familar with the UIElements ListView, trying to figure out how i can override the Add and Remove buttons in its footer to have custom logic
Hello! Help me please - I have a background image and want to assign transparent buttons on top of some background elements. I give them absolute position, but the don't move with the background when it scales. How can I make them follow the background size changes? All the buttons are now children of the background.
Try forcing the background element in position: relative
Hello, I have a basic template with a text and an icon, is it possible to implement the template to another UI, and make the icon dynamic with classes ?
I tried something like this:
But the background texture is not applied to my IMGUIContainer
You mean to set the background position as absolute? It won't scale to screen then, which is not expected behavior
I mean, if you scale an element to position: absolute, it will be absolute INSIDE the first position: relative it will find in the parents element
I don't know if it's clear
What do you mean by scale to position: absolute?
Sorry, set to absolute* 😉
Hello, does anyone know if it's possible to drag and drop outside a custom script window to the unity editor?
Like from a UnityEngine.UIElements.ListView to a field in the inspector?
is it easy to play around and work with imported images in UI Toolkit ?
or is uGUI better at it ?
it's a trivial task, both should equally easy enough depends on your impl
Is there some part of this question that relates to UI Toolkit?
Oh my bad I missclicked unity tips sorry
I'll delete it
actually unitytips doesn't seem like the right channel either. Can I ask that question in Unity talk?
If there's no channel in #🔎┃find-a-channel covering topic specifically you can use #💻┃unity-talk
But it's already so, if I understood you correctly. My bg is the only root element in the document. It has relative position. And transparent buttons are the children of the bg element and all have absolute position. When I change the screen sitze, bg size also changes, but all the buttons remain in their places, while I expect them to scale and move too.
Your buttons must be set to relative
But I don't know exactly how to do what you are trying to do in CSS/USS
I don't know how to position them correctly in their positions with relative position, but will try) It seems like there is no other option 😦
Put the BG image inside a container. You will be resizing this container and not the image
Set the image as absolute and width height 100%
The container will have position: relative
Then just add buttons inside the container in whatever position you like
You mean, buttons and bg will be on the same layers - all are the children of the single container? I'll try, thank you. But theoretically I think that buttons still won't scale depending on screen size
They won't, but you can try setting the button size in percent
But it's kind of a pain
Yes, I think the same) Maybe I'm trying to do something wrong? I just have a location image and want to make some of its elements clickable
Not really, this is the easiest solution
It's just that scaling anything in percent means you have to find a magic number that looks good on all resolutions
I personally don't use percent size at all
What range of resolutions do you have?
All mobile devices
Then you don't need any scaling at all lmao
Question:
When making a template (an inventory slot(Size does not matter here)) and duplicated this template into the List view, do I fix the inventory slot template canvas size or match it to the game screen?
My logic is , if I fix the template size, it will remain the same size even if the List view canvas resolution changes, but If I set the inventory template to match the game View and add it to the inventory list then it will be distorted and look all messed up
Why?
All mobile phones have basically the same resolution
The only exception to that is tablets
If a fixed size button looks bad on a tablet but good on a phone then you can just create a separate button style for the tablet
No need to dynamically scale anything
But they differ on resolutions, so scaling on different screens exists
Hi ! Is there a way to access the TextElement of a FloatField for example ? Like if I wanted to force the input to be — if multiple elements are selected.
the easiest should be just registering valuechange callback then do your validation in it
floatField.RegisterValueChangeCallback(x=>
{
if(someThing == someThang)
/// do something
else
{
floatField = someCachedValueOrDefault; //Or *return*
}
});
or just return if false there
I'm unsure that answers my question. I don't want to detect/react to the value being changed. Say you make a custom inspector with a FloatField and you select multiple object that holds the script. The basic behaviour, if script holds different value, is the FloatField displaying — until you edit the value. I want to know how this is done by the inspector since you can't do floatField.text = "—" because it only accepts float value.
But I think I've found my answer. Since FloatField is a UI element, I should be able to use Q<TextElement>() to access the TextElement underneath
I don't understand the relation of text here tbh
yeah you can just query
but still I dont get the question 😆
I just want to know how Unity can enforce numerical fields to display a non numerical value when multiple object are selected xD
you cant with FloatField it's being constrained
That's why I want to access its TextElement (which is contained in its hierarchy), to bypass the validation step
what you can do :
- get the
TextElement<T>then get it's parent, lets say the parent here callledfParent - Make a TextField then parent it to
fParent - Add your logic in your TextField then pass it to FloatField if it's valid inputs otherwise do what you want with it
as said its being constrained, as in TextElement<T>
you can't force it to accept plain text/string to it
just make your own custom FloatField, much easier and quicker
OK. Too bad.
I suppose there's some job done under the hood by Unity for them to be able to do it.
It's not clean, but for the purpose of testing it does the job. So I found a way ton enforce non-numeric value in numeric UIElement.TextField like so
FloatField floatField = new FloatField("My First Float");
TextElement textElement = floatField.hierarchy[1].hierarchy[0] as TextElement;
textElement.text = "SuperTest";
Thanks for the help @gusty vapor, even if it was not what I was looking for, it was nice intel to have
Does it display the text at all? 😄
Look at my capture #🧰┃ui-toolkit message
The inspector in a simple FloatField, and it properly displays the text I passed as string
I kinda surprised it worked tbfh 😅
xD
I kinda knew it was possible since I played with the UIElement debugger first and the TextElement that holds the value doesn't have any validation if you modify it directly, that's why I was looking for a way to accesss it
It may be useless on the long run, but I needed to know if it was achievable
it does, you should see the source code for this kind of stuff, not debugger
The FloatInput does surely, but does the TextElement contained inside validate it ?
TextElement is only here for display if i'm not mistaken
It's not the actual value of the field
Up, if you have time to look at my issue 🙂
look in the ui debugger to see if the class is being applied
it kind of looks like the class is added but no style is applied
meaning you should change the selector
You mean this ?
In fact, in the icon itself, the selector is matching !
But I don't know why, background-image is empty, even if its set in the stylesheet
which class has the bg image property?
.resource-food .resource-icon
is the bg image property actually set in the styles file inside this selector?
well idk then, I'm not a ui builder expert
Thanks for tryin
what do you mean by impl
anyone have insights about why the MeshGenerationContextUtils class isn't public ?
because fuck you that's why
everything is either private or internal to make sure that you can't do anything
they copied the entirety of tmpro's text engine, renamed it to TextCore and made every single field, class, struct and method private/internal
oh, and they also made it part of the editor to make sure you can't override it with a local package
[assembly: IgnoresAccessChecksTo("UnityEngine")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UIElementsModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.TextCoreTextEngineModule")]
#pragma warning disable CS0618
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
use this to access their shit
Yes, honestly, the more I work with UITK, the more disappointed I am with the way it's been designed...
I start to think about making my own UI system at the end, I know how to write lexer/parser etc. so why not. ATM it doesn't exists any UI system which fulfill all my requirements regarding such system in Unity, in one hand we have a system with a lack of features and flexibility and in the other we have an old system which isn't relieable regarding the performances + the lack of way to truly design modular intefaces through code
just like anything made by unity in the last 5 years, uitk lacks vision
they could have implemented razor templates, copied the design tools from figma and it would have turned out great
instead we get this half assed uxml system that takes the worst parts of wpf and web
I am thinking of creating a razor template system similar to what s&box did
But it's going to be a lot of work, and I have too many projects in queue 😭
Does 2023 support rendering UIGUI in Screen Space - Camera ontop of UI Toolkit?
Hello, does anyone knows why my text is not aligned to the icon ?
They are correctly aligned in the UI Builder preview !
no
Unfortunate. I want to have playing cards that flip with perspective. UI toolkit doesn't offer this, so the flipping effect looks pretty cheap.
why dont i see the little orange square on my inspector? (my inspector is black, his is white)
nvm i fixed it sorry
i'm trying to create a function that adds/removes a specific class from a visualelement, how can I reference that class in my script?
by strings? Or if the class is declared as a constant somewhere, use that
I'm sorry to necro your answer, but how do you get this pop-up ? Is this built-in Unity or did you make a custom tool ?
By using the latest Alpha/Beta versions of Unity
Ok, so it's not available/in release yet. Thanks 🙂
I have a simple question. How can I do a vertical progress bar and scale it? For some reason, it just doesn't want to scale... Horizontal bars scaled fined by increasing size
Yes
anyone played much with the GraphView blackboards much? I got it working and displaying what i want but am stuck on how to drag into the graphview from the blackboard now
or really being able to use DragAndDrop.StartDrag with any VisualElement would do
it always reports Drags can only be started from MouseDown or MouseDrag events
i tried implemenating as per
https://docs.unity3d.com/2022.2/Documentation/Manual/UIE-Drag-Events.html
i know the receiving side works since it already handles other drop events
I need some opinions 🙏
I'm making a scifi game.
The game is UI heavy.
Currently, I'm using the old UI system, mostly because UI Toolkit does not support glowing UI elements (which is kind of important for a scifi game).
But since the game is so UI-heavy, I'm considering switching to UI Toolkit, and compromise on the looks.
What are your thoughts?
What makes you think you can't have glowing elements in uitk?
I tried a few months ago for quite a while, but it would never work.
If it is possible, do you maybe know a tutorial that actually works?
Well, for starters, you can just create a PNG glow effect and overlay it on top of your elements
Or you could use a custom shader
UI Toolkit is good when you need lightweight simple vector based UI with css based styling.
If you plan on UI heavy - make sure uitk fits all your technical needs first.
https://docs.unity3d.com/Manual/UI-system-compare.html
Does anyone know how to create a cooldown indicator for my button, similar to League of Legends?
found the code, if someone else need it
https://gist.github.com/Okay-Roman/8ba84316968cd3aac72f3984ad5a6251
Is there a way to fix semi-transparent visual elements from showing up as opaque in-game?
Inspect it in the ui debugger to see if the opacity is actually being applied
It is
er well its the alpha of the background color. Lemme guess I'm not supposed to touch alpha and only use opacity
I am not no
Oh well I guess technically I'm rendering it to a texture on a seperate game object for when VR players are used, that's probably doing it
since yeah even opacity didn't work
What are the settings for your rt
Nope none of the formats are using semi-transprency
Maybe it's something to do with the material you're blitting with?
material is just standard unlit
and also transparency is both not working for the rendertexture and the screenspace version
so its probably something closer to the UXML itself if its affecting both
Check the rt preview, I think your ui should have correct transparency there
damn
that's what I was using to test the formats
And youre saying it still looks like that in overlay mode?
yes
hooray
Is your colorspace linear?
Oh yeah that might be a super long-standing issue
I think I had to make a custom shader to fix this exact issue but on a texture
Not too familiar with that setting, is it for HDR support or smth?
But I'm assuming the alpha will be correct
It's the industry standard I guess
Just easier to work with
you might be able to get away with a custom blit material that does color.a = pow(color.a, 2.2)
oh wow yea the colors look awful
nah didn't change the opacity
absolutely very strange
There are a shitload of posts about it
Basically, If you want to design ui's in linear colorspace, you should stop using ui builder
Hi o/ noob question, how would I go about styling a visual element so it behaves like the IMGUI layout group in the screenshot? Margins on all 4 sides, a px amount of spacing between childs, force child width to expand to cover the entire area, same for height.
simply put them in a row, add flex-grow: 1, margin: 1px, border: 1px solid red
If you don't want borders to double then add border-right on all elements except the last one
And a border around the container
I have a simple question. I have a button, and I added a visual element as child of the button. How to make the visual element to be sized as the button? For some reason, it just doesn't want to increase further in height
Hi! I'm trying to make these buttons on the left opaque, even though their parent has an opacity less than 1. My first thought was to use the !important keyword like CSS, but that's apparently not supported in USS. Colors are also temporary, of course, I just have them so I can see all of the divs
also just so that im not only coming here for help y'all can check out how i'm generating the UI from script instead of UXML (markup languages are ugly!!!!)
i'm making a few extension methods to make it more fluent
i honestly really like this workflow lol, that tarodev video opened my eyes
Just don't make the parent transparent if you don't want its children to be transparent?
The child opacity is 1, the important keyword would not change anything. You should create a different hierarchy setup (an additional parent) if you want to make a certain section of the children transparent.
yeah you're right about that, i ended up just using the alpha of the background color in the end tho
im not very good at CSS lmao
Just wanna note I finally cleared this up, I'm running a multiplayer game and didn't consider the fact all players in the match were displaying their UIs at the same time
What are some reasons for using UGUI over UI Toolkit for a main menu? I know UI Toolkit has some limitations such as no world space support which is important for nameplates or health bars for example. However, what are the limitations of UI Toolkit for a main menu? I'm thinking I may use UI Toolkit for my main menu and UGUI in game for anything world space related such as in-game labels for objects
unsure of any reason to use UGUI for anything screen-space
like there might be some weird little quirks and im not exactly a huge fan of UI Toolkit's normal workflow but ugui is like
not very good LMAO
the main advantage would be that you aren't encouraged to use string queries for everything but you can get around that by building your UI toolkit UI through script instead of with UXML/UI builder
UI toolkit is also a little less familiar for general unity development since it relies on stuff like style sheets and markup but i'd still reccomend using it over UGUI unless you absolutely have to use UGUI (for stuff like world space UI)
Creation of ui by script is destroying all advantages of uitk over ugui
It's totally fine for editor because you don't care about styling, but it makes 0 sense for runtime
i find it a lot easier to work with personally
not sure where styling becomes an issue? using extension methods you can make adding style classes to very fluid
using UI toolkit's stock methods for everything would certainly be a lot worse but implementing a fluent interface makes it much nicer to work with
I was all about fluent api, once. It was a terrible mistake 
if you're working solo or just for customEditors, yeah fluent api is fine. Runtime stuff or if you're working in a team, definitely uss/uxml
i can see it being a problem for working on a team actually, yeah
you can't do dynamic templating with inlinestyles like uss/uxml would
i am generally not very comfortable with markup languages and not very good at CSS so i'm probably a little biased LOL
and inline styles are def a problem for this approach because i dont think there's a clean way to make extension methods for that because of how many different styles there are
that being said type safety makes me happy so im probably gonna continue down this route and keep building on it and see what kind of roadblocks i hit, i've honestly not had this much fun programming in a while lol
it is still nice tho for customEditors, I still use mine just for that
Sadly, the inlinestyle is internal
internal InlineStyleAccess inlineStyleAccess;
/// <summary>
/// Reference to the style object of this element.
/// </summary>
/// <remarks>
/// Contains data computed from USS files or inline styles written to this object in C#.
/// </remarks>
public IStyle style
{
get
{
if (inlineStyleAccess == null)
inlineStyleAccess = new InlineStyleAccess(this);
return inlineStyleAccess;
}
}
We cant have access to this without some hackery
and here some words from the staff
yeh, it sucks big time!
How do I reference content?
VisualElement root = rootVisualElement;
VisualElement content = root.Q<VisualElement>("content");
I tried this, but I can't access anything inside content so I assume its not referenced right
What are some good steps to follow on diagnosing why a :hover is not working? It used to work but I had to do some refactoring and broke it ._.
Perhaps an element in front of your :hover one is blocking it?
I was thinking that and been trying to figure out what it could be and just 1 second ago, I found the culprit. Now I need to find if there is a way to make it not block it with a style attribute or something. Like picking mode ignore >.>
Exactly that - use picking mode
Hello guys I am using UITK 2022.3.8. I have a custom control and I want to use a trait attribute to set it's label's name. I can't seem to get it to work. I have UIBuilder displaying the property but idk how to connect it to the label.name. How can I do that?
_rootElement = GetComponent<UIDocument>().rootVisualElement;
_label = _rootElement.Q("name of the label");
_label.name = ...
It is a custom control that needs to get its name from the user in UIBuilder
It's dynamically made querying the label and changing the name doesn't work for me
Can't you just in the same way query the label and take its name?
I can but it's inconvenient
why?
When you have 100s of labels for example and you want a unique name for them
Both ways are inconvenient
I guess I am going down a rabbit hole
you just do for each loop
and change label for all of them
Can someone help me out, please? I have a weird button bug. For some reason, I can't get it to respond to a click event.
Here is my UXML: https://gdl.space/wocahopahe.xml
I checked all these steps. In fact, I have other buttons working...
Then you probably have overlapping elements
Use the event debugger to find out, as listed in the troubleshooting steps
can you please help me to understand how to use it?
This is what it shows when I click on the button, but focused areas is some random container?
It seems like your button was never considered in the propagation path, which would indicate it's not pickable afaik. Do the working buttons appear clicked correctly in the debugger?
I also forget whether you need to change the debugger's focus to the correct panel for your game, I'm on phone and can't check. If it doesn't show the working buttons there's probably something you need to change in the debugger