#🧰┃ui-toolkit
1 messages · Page 18 of 1
Just redoing all the UI for this game:
https://store.steampowered.com/app/1969810/Enter_the_Chronosphere/
A roguelike tactics game like no other—flow seamlessly between real-time action and turn based tactics.Play at your own pace, alternating between bold action and careful planning.Assemble a crew of misfit alien action heroes. Breach ancient alien juggernauts and have time-bending shootouts. Unlock characters, abilities, missions, new chronospher...
To be announced
I can't remember exactly what i needed events for now, we were looking at pushing a LocaleChanged event down the hierarchy but have since realized that's not the best pattern
I'm pretty sure you noticed already that UItk isn't production ready
It's come up a few times though
Nor is UGUI
Have you used it?
but uh,., uitk is like way worse than ugui
the layout works though
at least in 2022
which is what I wanted
I'm really enjoying it so far.
on 2022
I've only built out one modal so far
but it's a bunch of different elements
uitk cant do z-order, custom shader, vector support and the list goes on
It does have vector support
z-order doesn't matter
custom shader might matter, but we can always hack it in with a render texture
also someone in this room suggested it was possible to swap out the shader using an internal API
(per element)
I'm happy to take the limitations in exchange for the maintanability
UGUI is so bad it's insane
The constant scene thrashing is so awful
and the layouts not working at all
it's unacceptable
all I want for uitk is to have a propery inline apis
UGUI is really only bad in the layout department
But there are tons of flex layout plugins so this is a non issue
Uitk is not runtime ready and probably never will be
It was created with an editor only philosophy, it can never be fully runtime adapted unless they rewrite it entirely
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
nice, they introduced a new regression where elements with an overflow hidden and border radius now turn completely white
They're working hard on UItoolkit, dare to say it's the best UI system they can come up with in Unity to date
You can see this yourself on release notes, like most of fixes were mostly for UIToolkit on all recent versions 😄
Like anything else new, there will be tons of bugs, less features and whatnot
give the team more time to work on them, that said, I've high hopes for this ui system 🥹
(choose other 2022.3x versions too and see what they've been working on)
https://i.gyazo.com/cfe968d51eb4fa498289539c87029ccb.mp4
Why is all my UI lagging behind so much? Both with UI tool kit ( the circle ) and the legacy one (white square).
I've tried tying it to the transform (red wire sphere) and also to the rigid body that is updated every frame (yellow box).
yet they all overshoot and behave weirdly.
I've edited the Script Execution Order didn't do anything either. both ui-toolkit and legacy are the last script in the hierachy.
I'm having issues using fonts with UI toolkit, no matter what I do they just render as white boxes (both in editor and in game) 🫠 I've been searching around and in this channel but haven't seen anything similar. Anyone have any ideas?
^ it looks like I needed to be using ui:Label rather than ui:TextField 🫠 Not sure why TextField causes big white blocks tho...
Presumably the background color is white and the text color is also white
you should check using the UI Toolkit Debugger
thank you, you're probably on the right track with that. I've been using the debugger and tried modifying colors but there were a lot of possible places to change it, so I probably didn't change the right one 😅 Regardless, the label is what I actually wanted, so I'll solve TextFields if/when I need to cross that bridge 👍
My buttons work in the editor, but not in my build. In the build the button restart and main menu do not call the GameManager.SwitchScene Method, they do in the editor
Also for UI an overlay canvas should be used, right?
getting a nullref in the build
Does anyone understand this?
NullReferenceException
SceneManagement.LoadSceneWithLoadingScreen (System.Int32 sceneIndex) (at <996138dbc1aa4c169489560b7303c71e>:0)
GameManager.SwitchScene (System.Int32 index) (at <996138dbc1aa4c169489560b7303c71e>:0)
UnityEngine.Events.InvokableCall`1[T1].Invoke (T1 args0) (at <00d5b91f2c49467b95ced8aa41db73be>:0)
UnityEngine.Events.CachedInvokableCall`1[T].Invoke (System.Object[] args) (at <00d5b91f2c49467b95ced8aa41db73be>:0)
UnityEngine.Events.UnityEvent.Invoke () (at <00d5b91f2c49467b95ced8aa41db73be>:0)
UnityEngine.UI.Button.Press () (at <e4524f3390944067aab85bb302e4cc1d>:0)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at <e4524f3390944067aab85bb302e4cc1d>:0)
UnityEngine.EventSystems.ExecuteEvents.Execute (UnityEngine.EventSystems.IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at <e4524f3390944067aab85bb302e4cc1d>:0)
UnityEngine.EventSystems.ExecuteEvents.Execute[T] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.ExecuteEvents+EventFunction`1[T1] functor) (at <e4524f3390944067aab85bb302e4cc1d>:0)
UnityEngine.EventSystems.EventSystem:Update()
Guess I do a workaround with an event action
oml it finally works
Turns out my pause system is probably at fault by pausing what ever would happen when clicking the button, while in a (paused) menu
it's been almost 4 years and there is still no way to set line-height, maxVisibleCharacters or any of the rich text tags that are ALREADY SUPPORTED via css. There is no way to autosize text. The scrollview is locked to 30 fps. Input field is so unbelievably bad on mobile that it's more efficient to overlay a ugui input over it. Initialization performance is atrocious even on 2023. And that's just the tip of the iceberg. They had more than enough time to get this shit done.
Presumably flex grow is 1, so it's growing to fill the height of the parent
I made it initial
is there any way to bind button click actions without having to query the button?
I mean, visual binding
does anyone know how to make a dropdown submenu?
like i want categories in the dropdown
which extend another dropdown
next to it
Wdym "query the button"?
You have to get a reference to the button in order to subscribe to events
I mean, there's the new data binding system which looks great, the only thing that still need manual query is when you interact with buttons
You can't reference elements through the inspector as they are non serializable
I didn't mean this way
I meant in the ui builder add a unity event that should be called when the button is pressed
No, you can't do that
This wouldn't work even if the elements were serializable
As the template you create is just a normal asset and can't send events to anything because it's not tied to a scene or prefab
you can do data binding, so it should also be possible to bind the click action to a function in a scriptable object or other data source
but I guess there's no such option yet
you can bind an slider, input field, etc, but not the button click
Oh yeah I forgot about this abomination
Not seeing anything that would allow you to call a method
Even if they do add event binding it would be extremely limited
As it can only access methods inside this scriptable object and not the entire scene/prefab
I don't see why this is abomination
I think it's an abomination when you have to query the ui element with the exact name to then modify it
You need a separate asset and a lot of uxml just to bind a property
How about just bind-(propName)="fieldName" like literally every single js framework has been doing it since the dawn of time
Literally all they had to do was implement Razor
You still have to create the asset and pass it to your ui controller. Why not just bind to your ui controller instead of adding this indirection bullshit
I saved my .uxml and now it cant be used or opened anymore saying its causing a 'stackoverflow'. This a common issue?
No? Open the uxml file and try to remove stuff until it works
I can't open it at all, I'm unsure it must have been something to do with a custom class inheriting from VisualElement.
Open it via a text editor
Are you trying to open it with Ui Builder?
It's a text file
Yeah opening via UIbuilder breaks, or loading it via a UIDocument. Is there a guide on how to extend the VisualElement for custom data?
I can't be certain but i think its because of the constructor I had in the class it broke something.
Open this instead it will open the .uxml file in plain text for you to edit.
Instead of trying to open the Ui Document which will try and open Ui Builder
I have already re-made the class and uxml from scratch, but its good to know.
Just to be sure are there any docs on how to extend the Visual Element class for the future?
You can Extend it by making any class you have inherit from VisualElement
Then you can make your own custom VisualElements
And you can also inherit from any of the built in controls that also inherit from VisualElement
But then having .Q<Label>(); in the constructor seems to have caused it the corruption, because thats the only change I've made so far. I could only find tutorials that have a constructor and 2 uxml classes a factory and traits inside it. So im unsure.
instead of using .Q<Label>(); try .Query<Label>():
I tend to use the latter since from my undjerstanding they are technically the same thing.
But I could be wrong.
Ah alright, I'll keep that in mind for the future, thanks :)
So that worked for you?
I have not managed to cause the bug again so far, so we'll see.
Ah ok
Quick question how do I handle ICancelHandler events with Ui Toolkit? it seems that sicne the PanelSettings is what grabs focus in the event system there isn't a way to hook that stuff up anymore.
Nevermind I found out how to do it.
There's a weird discrepancy going on between my Scene window with my BattleUI prefab, and my Game window. The creature portraits in the top right are showing in the Scene window but not in the Game window. On the far left you can see my Hierarchy, it's the OpponentDetails > TeamImages which contains a GridLayoutGroup that contains 4 panels, each with an Image (titled CreatureXImage).
They also don't show up if I run the game. Any ideas what could cause this kind of discrepancy?
Are you using UI Toolkit or UGUI?
I ask because this looks like UGUI
And iirc UI Toolkit doesn't show up in the Scene view because of how it is rendered it only shows in game View
I have also noticed the top banner where you have some other GUI isn't showing either and everything is shifted up to where that info should be.
hello guys, about webGL and mobile support...
i notice that on some moment between 2021.3.0 and 2022.3.x TextFields now have a little support on mobile devices in WebGL...
but just a little detail persist to a full support... does not work on full-screen 😆
any one here has a confirmation if tihs was solved on a version after 2022.3.24?
Why my theme / styles don't always work when using a render texture ?
both configurations are nearly identical , the only difference is the targetTexture on Panel Settings
Make sure your texture has depth stencil support
yaeh that was it , thanks trigger
np
qq: Is it possible for TextMeshPro compenents to drop shadows?
- based on lighting. in world space.
is unity able to bind with Editor Binding system (https://docs.unity3d.com/2023.2/Documentation/Manual/UIE-editor-binding.html) to custom properties with [CreateProperty] attributes?
How can I make the space on the right shrink away when wrapping? https://imgur.com/a/hio4lRT
how to set ui builder theme to editor style and not runtime?
probably configure padding/margins or something
Hello, does any one know how to accept Dimension with CustomStyleProperties ?
Im getting the following exception when try to set pixel or percentage values
Trying to read custom property --tip-width value as Float while parsed type is Dimension
is it better to use textures or sprites with uitoolkit?
Is it possible to turn of those purple squares when using sprite shape?
go to the gizmos dropdown and look for the sprite shape gizmo
Thanks
Do you mean ReadOnly?
how are you accessing those settings?
i am only aware of being able to do it through script
ah i havent touched that at all
https://youtu.be/r3nwTGLHygI here is a great short tutorial on how to do this through code, if all else fails
I was asked by a viewer yesterday how I would go about displaying a field inside the inspector but no allow for it to be edited! We'll Frank. I hope this is what you we're looking for!
I created a custom attribute to allow just what you're after!
Find the code here:
https://github.com/Comp3interactive/Unity-CodeSnippets/tree/master/Code/Read%2...
is there any way to make a label in UIToolkit property drawer match the width of controls rendered via IMGUI and Odin?
cause I am about to lose it anytime now ^^
Thanks! I'll check that a bit later!
I'm trying to register mouse callbacks with a visual element but can not get any events to fire, Do i need to do anything else other then this? it was a multiple UI sort order issue
Why isnt the gameobjects showing on the camera
public LocalizedButton() {
// Listen to locale changes
RegisterCallback<AttachToPanelEvent>(e => {
LocalizationSettings.Instance.OnSelectedLocaleChanged += HandleLocaleChanged;
});
RegisterCallback<DetachFromPanelEvent>(e => {
LocalizationSettings.Instance.OnSelectedLocaleChanged -= HandleLocaleChanged;
});
}
Any reason why I might prefer to bundle this logic into a manipulator instead of handling these events in the constructor?
I could do something like this, for example:
class LocalizeManipulator : Manipulator {
protected override void RegisterCallbacksOnTarget() =>
LocalizationSettings.Instance.OnSelectedLocaleChanged += HandleLocaleChanged;
protected override void UnregisterCallbacksFromTarget() =>
LocalizationSettings.Instance.OnSelectedLocaleChanged += HandleLocaleChanged;
void HandleLocaleChanged(Locale locale) =>
((ILocalized) target).SetLocale(locale);
}
interface ILocalized {
void SetLocale(Locale locale);
}
class MyThing : VisualElement, ILocalized {
public MyThing() {
AddManipulator(new LocalizeManipulator());
}
public void SetLocale() {
text = T(key);
}
}
just not sure if there's any benefit other than sharing the manipulator code between elements.
I guess I'm wondering if attach/detach are equivalent for the register/unregister methods in the manipulator.
"UI Toolkit is not yet ready for in 3D world UI" Is that correct?
I just bought a course, and those were like the first words out of his mouth.
it's barely even ready for runtime, let alone 3d
The feature comparison table is pinned to this channel
Lol, of course! Thanks 🙂 I literally did not even think about checking :/ (I grew Way too accustomed to the utter lack of information in the 'other engine')
Hi, I'm having some trouble instantiating UI over above a gameobject.
When a tree is chopped down, I want a UI popup to display above it with an image of wood.
I can get this popup to display on the screen, but the position is never correct. I just need the initial position to be correct, I'm not worrying about updating the position if the camera is moved right now.
My Canvas is set to Screen Space - Overlay, if that matters
Hi! Where can I learn about updating my UIDocument labels information with ECS (DOTS)? I'm triying to display some information in the UIDocument. Everything is in place but I don't know if I can update the labels from a System. I don't know how to access to the UIDocument from the system.
Any guide or maybe advice to modify Shader Graph or UI in general with white theme?
Like going in changing every param color that has dark to white doesn't work well for me
do you mean the editor gui or the in-game ui?
editor gui
It is somewhat working but well... I guess 😂
heya ! 👋🏻
i have a small question, i got an "item db" which is just a list with items and info of them, and i made a shop screen in UIToolkit. In here im using a ScrollView, but how can i "dynamically" add items to the shop by code? i dont want to manually make every item card etc
thanks ❤️
get a reference of your UI document, query the scrollview and use the add function to add elements
Elements by code? 👀
Hmm okay I haven't really found anything about adding it by code yet 🙃
Holy shit how did I miss this yesterday 
I guess after searching too long you'll overlook things
Uh i think i misread hehe, this is only going to work for the editor windows? I need it for UI runtime hehe
oh gotcha 
I'm trying to "refresh" my inspector when the enum value changes, the debug shows up in the console but I can't seem to get the inspector to actually redraw.
https://gdl.space/nulizixixe.cs <-- code for dash
Hello, i am making a dash script and i need help with the dash charge i want 2 charges and each charge have a 3 or 5 sec cooldown. i tried making my own script but it dose not really work can anyone guide me to make it work
Do you have an example of this?
Yes
The runtime material thing seems to be unused
Awesome. And it works?
Out of curiosity how many people here prefer to type their CSS in things like SASS, LESS, or some other CSS Post Processor to make it easier to create than put it in a USS file.
me
oi, got it for 99% 😄 Just something weird happening. I made a template of the cards i want to instantiate, but it adds a weird element upon instantiating lol
i cant get rid of the templatecontainer 
it adds a flex object to the ui, invisible, but still making stuff jump away
this seemed ok to me 
public class ShopUISlot
{
public VisualElement itemContainer;
public Button buyButton;
public Label itemName;
public VisualElement itemImage;
public PlantData item ;
public ShopUISlot(PlantData plantData, VisualTreeAsset template)
{
TemplateContainer itemCardContainer = template.Instantiate();
itemContainer = itemCardContainer.Q<VisualElement>("itemCard");
itemImage = itemCardContainer.Q<VisualElement>();
itemName = itemCardContainer.Q<Label>();
buyButton = itemCardContainer.Q<Button>();
this.item = plantData;
itemImage.style.backgroundImage = new StyleBackground(plantData.plantSprite);
itemName.text = plantData.plantName;
buyButton.RegisterCallback<ClickEvent>(OnClick);
}
public VisualElement Build()
{
itemContainer.Add(itemImage);
itemContainer.Add(itemName);
itemContainer.Add(buyButton);
return itemContainer;
}
public void OnClick(ClickEvent evt)
{
Debug.Log("Item clicked: " + item.plantName);
}
}
guess its something with the first 2 lines of the constructor 
I am not seeing it mentioned under the pinned resources, so i'll ask if there is a plugin or configuration for auto-completion, intellisense, etc. of UXML in VS
I have set uxml to use xml editor experience, and there seems to be Unity schema for this purpose, but it does not seem to work properly.
Ok, this seems to have to do with changes to UIToolkit boilerplate syntax perhaps. By simply saving the .uxml inlineStyle file in unity, it auto switched itself to ui, instead of engine (which was the initial boilerplate config before saving. the file was not in dirty state.). so it is, in fact, working. it just needed to be saved before any editing of the file takes place
I would prefer to use SCSS theoretically (esp. because no calc support in Unity), but I haven't checked out the sass extension yet. Have you tried it?
How do i get the grouping seperation for the Dropdown field?
You see how even with the slashes every option shows as one line instead of creating submenus as it did in previous versions
I ended up getting bored after asking that and added scss and sass file compilation into Unity. On Import I just ended up making Unity convert them over into USS files with scss and sass style support. Thank god for ProcessStartInfo. Made it a lot easier than expected. So now I just am writing my styles in scss format and letting them get converted over.
Tried to upload a video to Disocrd to show it off, but Discord won't embed the video and I don't want to have people have to download it to see it.
there's already a plugin out there that does the same thing
Mainly aiming for the learning how to do things without relying on plugins. Some plugins you can't put in redrtibutable packages. So for example if someone wants to release a community package of helper scripts if they rely on a third party plugin they might end up breaking that plugins agreement.
How do I add C# functionality to an uxml file? Like when I drag my custom .uxml file into the UIBuilder I want to the things in my C# script to happen. Or alternatively, how do "assign" the uxml file to my C# script?
Depends on which version of Unity you are using. Is it 2023.2 + or an version older than that. They updated the C# Attributes in 2023.2
Also technically the UXML is the structure of the UI that is visually represented which Unity takes build the C# class objects for based on that UI structure in the UXML and when the C# class objects are created is when the logic is run in C#.
I am using 2022.3.7, but I wouldn't mind upgrading
Upgrading is always a self risk for a project.
Mainly you can create your own custom control or visual element and let it be revealed inside of the UI BUilder.
Basically you create a custom class and have it inherit from Visual Element or any other class that is a child of Visual Element.
For that version you use the UXML Factory class in the custom control. This allows the new code to be seen by the UI Builder tool.
For Visual Elements they run their code in the constructor of the class most of the time unless you have another class tell them to init which can be down anyway you want.
Documentation link for that version of Unity that goes through the process.
They also have examples in the documentation that goes step by step.
https://docs.unity3d.com/Manual/UIE-create-custom-controls.html
Ye, I've seen that, but is there no way to 'prebuild' the VisualElement Tree in the UIBuilder and than 'load' it in the script? Like, this is what it looks like:
Having to do that in code would take way longer.
Ah wait, I somehow figured it out, I can drag the C# file into the UI Builder, than tweak the values and than 'Create Template' and it will remember the script and the style.
Yes, so you can load the UXML file with AssetDatabase.LoadAtPath.
The UXML file in C# code is type of VisualTreeAsset.
The template creator is also a nice handy way to deal with that sort of thing as well.
ahh, but I can't change the values of the children. Guess I have to do it with LoadAtPath
... unless I add the children from the UIBuilder and not the script
Depending on what you are aiming to do there are a few different ways. It mainly depends on the over all structure of the system.
Most of the time to simplify stuff I usually just follow a MVVM style system just to make life easier.
I seperate the logic, structure of the UI, and the data used in the logic into their own pieces.
What do you think, is this behaviour a bug?
Issue with sprites from SpriteAtlas
is there a way to easily convert something from UI toolkit into a normal canvas? I made a really nice UI in UI toolkit that I want to move into the world space (probably through a canvas) and remaking it is a little time consuming. if there is an easy way to convert, that would be much appreciated. thanks!
hello, this is my script for a dash the script and the timer works but the forst dash dosent recharge with the ui is it the issue with th ui or is it my code
https://gdl.space/utebizopoq.cs
else
{
selectableArray[i].interactable = false; // Enable the corresponding toggle
}
why is this not working for the first ui dash why is it not making it false
https://gdl.space/itugutobaf.cs updated code
Did anyone find a "work around" for the lack of grid and gap etc in UIToolkit?
at the moment i do it like this, where i add a bottom and right margin to the buttons 
I just add margins to grid elements and margin/padding to their container
well so did i now, as in adding margin to the elements on right and bottom
How/What value should I store from a GraphView to be able to store the positon inside the graph view where the editor is so that when the user reopens the graph view it goes back to the previous place it was?
i have big graph views and every time the user has to start from 0,0, but im not sure which value to change to move it back to the last position
Hey, since the newest update, an UXML file which worked properly does not work anymore, it is the following file:
<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="True">
<ui:ScrollView binding-source-selection-mode="AutoAssign" item-template="Skillcard.uxml" data-source-type="Systems.Visual.UI.SkillSelectionList, Assembly-CSharp" fixed-item-height="204">
<Bindings>
<ui:DataBinding property="itemsSource" data-source-path="skills" />
<UI.Scripts.SimpleScrollBinding property="MyRefresh" />
</Bindings>
</ui:ScrollView>
</ui:UXML>
now, ingame it still renders, but the scrollbinding is not instantiated anymore (I have debug log in the SimpleScrollBinding constructor as well as update, both are never called)
Also, when opening that file, I get
UI Builder Failed to open Assets/UI/LevelUp/SkillCardList.uxml asset. This may be due to invalid UXML syntax or UXML syntax the UI Builder does not yet support. Check console for details.
UnityEngine.Debug:LogError (object)
Unity.UI.Builder.BuilderAssetUtilities:ValidateAsset (UnityEngine.UIElements.VisualTreeAsset,string)
Unity.UI.Builder.BuilderToolbar:LoadDocument (UnityEngine.UIElements.VisualTreeAsset,bool,bool,string)
Unity.UI.Builder.Builder:LoadDocument (UnityEngine.UIElements.VisualTreeAsset,bool)
Unity.UI.Builder.Builder:OnOpenAsset (int,int)
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
However, this is the only message in the unity console, no other message to "check the console for details" for
how can i create like my own ui what apps are recommended?
I use Figma to design the ui
It’s also free
As someone who just now discovered UI Toolkit, is it worth implementing, for something like an inventory system?
thx
are you asking about the graphics before unity or a way to put together a good UI inside unity?
no i just want to design an inventory layout
the ui tool kit is helpful but can be a little overwhelming...
if you want to side chat DM me... maybe I can help
I have a inventory system that I have tweeked over time that I use when needed..
is it for a survival game
because i am working on a survival game
and i am wondering is it good to use scriptable objects in inventory system and for crafting and stuff
I started a survival game a ways back.. followed a tutorial...
Are you following a tutorial or doing it on your own?
i am following tutorial for the inventory system not for a whole survivak game
For the survival game i was following this tutorial.... you can pull up the play list its 47 parts... inventory is #5
#survivalgame #tutorial #unity
In this tutorial series, we will create a 3D survival game with Unity & C# as the scripting language.
We are going to start with basic FPS movement, build an inventory, and crafting systems.
Learn how to pick up items and more.
Little by little, we are going to add different features that are common to survival op...
#survivalgame #tutorial #unity
In this tutorial series, we will create a 3D survival game with Unity & C# as the scripting language.
We are going to start with basic FPS movement, build an inventory and crafting systems.
Learn how to pick up items and more.
Little by little, we are going to add different features that are common to survival ope...
yes i wathced the beginning of the tutorial but i think the inventory system wasnt that great
you can only carry one item and cant stack
is a basic understanding of things.. if you already understand the basics than, a more advanced tutorial may be https://www.youtube.com/watch?v=N9SrHSmkY-Y
The easiest advanced Inventory System I've developed thus far! Consider Subscribing! (it helps!)
#devlog #inventory #tutorial
Assets I used: https://www.kenney.nl/assets/voxel-pack
✅ Join the Discord : https://discord.gg/K4fQ6s82Q4
🔴 Subscribe! : https://www.youtube.com/erencant
🔵 Twitter: https://twitter.com/_Peli_can_
🧡Support the channel: ...
DM me if you need more help.. sometimes I have random ideas that lead people to their answer lol
no, got busy, and started working on another project... something that complicated takes at least 1 more person to find your errors and bounce ideas off of...
are you working on project rn?
Hello, is there any possibility to enable more fps on scrollview? In my point of view it has 30 fps... Thank you! 🙂
what version of unity are you on?
i believe there is an elasticanimationms property that controls the framerate
or something like that
but it was added somewhere around 2021.3.37-ish
@wind gorge i am using version 2023.2.12f1, and I tried to set Elastic animator interval ms to lowest number which is 1, but my feel is that still movement is not perfectly smooth
Is it possible to make a custom visual element with a description property of custom type?
anyone?
Hi, very new to UI toolkit, I'm trying to create a first custom control for runtime. Is it best practice to create the structure via c# script, or by referencing a UXML? if it's the latter, what's the best way for the c# script to reference the uxml?
what am i missing here to get this to bind to my field _graph in my monobehaviour ? the field is type GraphAsset. It lets me set a GraphAsset scriptable object into the object field but its evidently not binding because the field _graph is always null after choosing a scriptable object
if i do it in code:
var bind = e.Q<ObjectField>();
bind.bindingPath = "_graph";
bind.objectType = typeof(GraphAsset);
then it works but in ui builder it does not work
i don't get what i am missing in the ui builder to get it to work so i can write less annoying code all the time
Hi everyone
I want Lobbies List for my multiplayer game
but I use ui toolkit
How can I prefab interface elements
Hi! I found this cool tech on IG. Does anynone know the tech behind it? https://www.instagram.com/p/C5ubY5jt_qd/
Water simulation vibe. #Holomat #tech #programming #ironman #3dprinting
15292
is it possible to place a lable over player head? usually with canvas we would set the recttransform position of a text, above the player using screenposition. is there something similar available for ui toolkit?
nvm figured!
has anyone else gotten problems with not receiving any input events anymore?
I do not know if it has something to do with the unity version, but the event debugger is not showing any clicks when I click
and I also don't get the result from the bindings anymore
So this is my input manager
I also do get events in the event debugger from my bindings (change events) and the right UI is displayed
however, when I click into the window, nothing happens -> the bindings are not called and also the event debugger shows nothing
does anyone know what might be going on?
deleting the Library folder worked
Anyone happen to have some custom UITK events that they're sending around and can show me an example?
am I the only one getting a white background even with its color set to clear on visual elements with some border radius? (6000.0.0f1)
where do you set the color to be clear? C# or uss?
uss
send code/screenshot
just an style set in UI Builder nothing special
so no overriding selectors?
it looks fine in UI Builder but i get a white background in game
yes, also from UI Builder using a custom uss file
yes as there are overrides?
I mean i have some overrides for text elements, or .unity-button for example
to set the font and make all buttons rounded
and it is working perfectly in 2022 lts
what do u mean with custom event? maybe i can help u
im sure it is, you should probably start sending some materials so we can actually take a lool
cutom trickle up/bubble down events to send through the hierarchy
I will now
In-Game... as u can see the NKY soundcloud button gets a white background, and I think text fields are also gettings a white background because I cant see any input (and no, font color isnt white)
and this is the UI Toolkit Debugger, if I remove the unity-button class in NKY soundcloud badge the white background is removed, so problem is coming from there
Maybe this can serve as an example for u? It is a custom hover button I made, I dont rly use trickle/bubble elements that much
[UxmlElement]
public partial class HoverButton : CustomButton
{
public HoverButton()
{
RegisterCallback<PointerUpEvent>(OnPointerUp);
}
protected override void HandleEventBubbleUp(EventBase evt)
{
base.HandleEventBubbleUp(evt);
if (evt.eventTypeId != PointerDownEvent.TypeId()) return;
_onHover?.Invoke(true);
}
void OnPointerUp(PointerUpEvent evt) => _onHover?.Invoke(false);
event System.Action<bool> _onHover;
public void AddListener(System.Action<bool> callback) => _onHover += callback;
public void RemoveListener(System.Action<bool> callback) => _onHover -= callback;
}
Is there a known 'gotcha' with UI.Button where the highlight stay goes away and won't come back until you clicked somewhere else?
I think there isnt
the only problem I had with highlight state was in mobile devices when switching the currently active panel, with visual elements from the new panel getting highlighted automatically because the pointer position was over them (I ended up disabling highlight state in mobile, as it doesnt makes sense since there is no mouse to hover at all)
I worked around the issue by deselecting the gameobject after the click happens. The highlight comes back correctly if I do that.
which one shows whats wrong?
oh yes sry, buttons capture the pointer when u click them
I also made a similar workaround long time ago by making Clickables not interactable (pickingMode to ignore and not focusable) and using UnregisterCallbacksFromTarget just for a momment (during click animation)
the In-Game one
check it compared to the UI Builder
u see a white background instead of NKY (soundcloud logo)
question I cannot get a linerenderer to show on my game but it shows in scene
any idea?
just learning UI toolkit and I want to understand the best way to access UI elements in a script. for example, say i want to set the items in a dropdown at runtime. the dropdown itself is designed into the UI document but I want to modify its contents at runtime. am i just querying the UI document hierarchy, either directly or with https://docs.unity3d.com/Manual/UIE-UQuery.html? is there an easier way? for example, in ugui i can just drop in a reference to the ugui dropdown in the inspector and then i don't have to query the ui object hierarchy.
i guess uquery is realtively simple if you just have a good naming system...
As far as I'm aware .Query and .Q are the way to do it. The strings are a pain, but personally I "just wrote a tool to scrape all the UXML files in my project and generate a static class with a bunch of constants for each name so there's no issue of mismatching case or spelling or whatever.
you can as well iterate down the hierarchy via vis.Children()
True. I find relying on hierarchy a suboptimal approach though. Generally speaking you want to be able to move your elements around the place and not break references to them, but there are certainly scenarios where getting all the first descendant children of an element is useful.
Query is like Linq basically, you can chain them pretty easily
visParent.Query<Label>("fparent").First().Query<DropdownField>("childname").Where(//conditionHere);
Thanks guys
Hello, I am creating mobile game and I have problem with ui toolkit performance. My scene has only camera and one ui document which is displaying few buttons and one sprite. When I run it on mobile and profile it I am getting 30 fps, which are causing on CPU side: Semaphore.waitforsignal on GPU usage side I am getting 30 FPS too, reason you can see on image below.
Do you have any idea how to fix it? Thank you! 🙂
How to make font pixelated in UITK?
Well the first step would be to get a pixelated font.
I already have one.
Is shader support on the roadmap for UITK?
Has anyone noticed the CreateInspectorGUI called around 4 times in Editor? Is it fixed on the latest versions of Unity?
Hi all,
I read somewhere that the Editor UI for authoring components was done with UIDocument, i would like to set an interface in game for one of my authoring data, can i reuse in any way the ui that is using the editor? or should i rewrite every single authoring inputs to a new uidocument? Basically I want my Editor UI for authoring on my game interface:
Hey all,
I would like to use the TabView element to create an Horizontal Tab View with a TwoPaneSplitView to achieve something similar to the Project Settings windows. The Tab header would be on the left, and the tabs content on the right. They would be separeted by an adjustables splitter. But I feel like the TabView doesn't provide enough control to achieve this... I can't make it work, any idea ?
Anyone using UI Toolkit for a splitscreen game? How are you handling it?
Hi all, I'm doing a "minimap" using an uidocument with a visual element with background render texture and a camera with that render texture. Nothing scripted, everything by ui. It says
IvalidOperationException: EnsureRunninngOnMainThread can only be called from the main thread.
Anyone knows how to solve it? Maybe something to do with Entities usage in my project?
InvalidOperationException: EnsureRunningOnMainThread can only be called from the main thread
UnityEngine.Object.EnsureRunningOnMainThread () (at <347e9cb990044b19a415d80dc9c7be25>:0)
UnityEngine.Object.GetInstanceID () (at <347e9cb990044b19a415d80dc9c7be25>:0)
UnityEngine.Object.IsNativeObjectAlive (UnityEngine.Object o) (at <347e9cb990044b19a415d80dc9c7be25>:0)
UnityEngine.Object.CompareBaseObjects (UnityEngine.Object lhs, UnityEngine.Object rhs) (at <347e9cb990044b19a415d80dc9c7be25>:0)
UnityEngine.Object.op_Inequality (UnityEngine.Object x, UnityEngine.Object y) (at <347e9cb990044b19a415d80dc9c7be25>:0)
UnityEngine.UIElements.UIR.MeshGenerator+TessellationJob.ApplyInset (UnityEngine.UIElements.MeshBuilderNative+NativeRectParams& rectParams, UnityEngine.Texture tex) (at <6603732cfe894bf1a78f54f7a10a3710>:0)
UnityEngine.UIElements.UIR.MeshGenerator+TessellationJob.DrawRectangle (UnityEngine.UIElements.UnsafeMeshGenerationNode node, UnityEngine.UIElements.MeshBuilderNative+NativeRectParams& rectParams, UnityEngine.Texture tex) (at <6603732cfe894bf1a78f54f7a10a3710>:0)
UnityEngine.UIElements.UIR.MeshGenerator+TessellationJob.Execute (System.Int32 i) (at <6603732cfe894bf1a78f54f7a10a3710>:0)
Unity.Jobs.IJobParallelForExtensions+ParallelForJobStruct`1[T].Execute (T& jobData, System.IntPtr additionalPtr, System.IntPtr bufferRangePatchData, Unity.Jobs.LowLevel.Unsafe.JobRanges& ranges, System.Int32 jobIndex) (at <347e9cb990044b19a415d80dc9c7be25>:0)
anybody have a tutorial or source for how to do runtime data bindings with listview?
ok i found something... https://gist.github.com/LeMartinParadis/3e4c7ad5fd1b57221f0978584a07443b
Created a ticket for it here: https://issuetracker.unity3d.com/issues/ensurerunningonmainthread-error-in-tessellationjob-dot-applyinset
When tessellating the UI geometry, it is possible to get an error because a null check is performed on the job thread. {noformat} In...
Is there a default stylesheet I can use for a Settings menu? Without one, it's a bit..tight
So i understand that you can add a selector to a button and it gives it some functionality like hover over changes a color. is there a way to add a selector through C# code,
I am trying to make a you click the button and the style changes until another button is pressed (kind like the tab system but i can't use the tab system). I can't find a way to add a selector to a button at runtime
Is it normal behaviors for the viewDataKey persistence to not work when the element is cleared then re-added to a container ? I've a Tabs system that when changing Tab it clear the contentPane and load the selected tab View. In those tab view I've some foldout that have a unique viewDataKey but the expanded state is not persisted when changing tab.
Complete UI Toolkit newbie, and I'm stuck on my first visual element. It's stretched from top to bottom and I can't change it even if I change the height. If I change the height in the size property, nothing happens.
Canvas height is 1080. The visual element's height is 500.
I've gone through most of the properties looking for one that might cause it to stretch, but I didn't see anything. I'm following a video and they did not have this problem.
Changing the Max Height seems to affect the height, but I can't drag the handles around to resize Element
Adding more visual elements make them each resize to take up an equal amount of screen height too
your flexgrow property is set to 1
What should it be? Changing it doesn't change anything
tried 0?
0 makes the height 0, but it doesn't allow me to change the height
Ok, I deleted it and added a new one and changing grow to zero does allow me to change the height now! I must have toggled on some other option that overrode that when I was messing with it.
Thanks!
You could use USS to add a margin to all direct children of the container
What do you mean in some sides?
you can add the margin only to the top of the elements
Not sure what you mean, but probably you need to use code to add and remove style classes as needed
I have a custom element that needs to "spawn" other elements (ideally instantiate them from a uxml template). The spawned elements are NOT children of the custom element, they're added somewhere else in the visual tree.
Ideally, I would like to bundle the custom element, its children, and the template of the element it's supposed to spawn, all together in a single self-contained uxml template. Is there a way to do this?
try making the property itself rgb(...)
Hi everyone, this may be the wrong channel to ask this, though given its tangential relation I figured here would be best. But I've been using UIToolkit for a while now and quite like it, I understand that it is very simular to HTML and css, with the UXML and uss files. My question comes from this, though unrelated to Unity specifically are their simular HTML and css designers / builders like with the UI Document designer. I'm exploring the use of web apps (Blazor) at the same time as my game dev and one of the things I have noticed is that most editors HTML / css, like Rider or WebStorm are all strictly code based. Does anyone know if there is anything similar to Unity's implementation for generic webpages?
(again sorry if this is not the right place to ask this)
Not sure if this is the right place to ask this, but I honestly don't know where else I would put it. I'm using unity UI to make a main menu, with some text on the bottom. The canvas is using Screen Space - Camera. For whatever reason, the background tries to render in front of the TMP Text object I'm using. This only appears to happen in a sort of cone outwards, where the area where the text will actually appear shrinks towards the center the closer it gets to the background. I could just move it outwards, but then it starts appearing in front of other objects that it shouldn't be appearing in front of (such as a black image for a fading effect). I've tried messing with the scale and looked up this problem in as many ways as I could, but couldn't find anything that actually helped me.
I'm kind of a newb when it comes to UITK, is it possible to recreate ugui's filled image effect? I know you can mask child objects using overflow: hidden, but from what i can tell you can only round the corners on the rectangle used, you cannot change the length of the rectangle for a horizontal fill effect without affecting the size of child objects as well
It Depends on how you want the fill to happen
If you want a progress bar type fill then it's just an absolute position rect with an increasing width
Same with vertical
Solved by creating text object as a child of the canvas rather than as a sibling. Only an issue if you use the top-left "+" to add your objects.
How do I add an image using Unity UI Builder?
create a visual element and in the style tab you should have an background image field
Oh
UI Builder was too confusing, I stuck with using normal UI
I'm trying to change the background color of a list view item when it is hovered, using just the .unity-list-view__item:hover selector did not seem to do it, however if i create a class called .List and attach it to the ListView, i can use the descendent selector .List .unity-list-view__item:hover to modify the color and this is fine, but i'd rather not have to add .List to every list view or every document with a list view in it. Is there some specific reason that using just .unity-list-view__item:hover to change the background-color did not work?
I feel like i might be misunderstanding how selectors work
Hi guys, looking for some advice. I'm trying to make some UI parts with images (or backgroundImage). The problem is they behave very strange when I change screen resolution (the image size changes, even though I set it in px)
I assume this is due to Scale With Screen Size option. Any ideas on how this can be fixed? I haven't found anything similar to pixel-perfect for the UI (2021.3.4f)
Thanks 🙏
Try it with one of the unity selectors for the ListView. Like .unity-list-view > .unity-list-view__item:hover and see if that works. If that works then maybe it has something to do with the selector being more specific. I think that's a thing with css. You can also try to search for the stylesheets that sets this value in UI Toolkit Debugger and then copy the same specific selector that it uses
Look to see if there's something with a higher priority selector using the UITK Debugger
Because I imagine you're just not doing it specific enough to override default behaviour
Quick sanity check: am I seeing it correctly that, when assigning a Texture2D to a Button's "Icon Image" field, that Texture2D is actually displayed on a hidden VisualElement under the newly created Image element?
This is very bizarre, because even though the newly created Image element has a custom class (.unity-button__image), you can't really do much styling for it, because it is always covered by a hidden element. So that bars you from setting the icon from USS or e.g. changing it on hover.
My only workaround seems to be to assign a transparent texture as the "icon" so you can see through to the Image element "behind".
{
experimental.animation.Position(new Vector3(endPosition.x, endPosition.y, transform.position.z),
Mathf.RoundToInt(tweenDuration * 1000)).Ease(Easing.OutQuad);
}```
Does anyone know whats vector3.z stands here for in UnityEngine.UIElements.Experimental animations ?
For animating the (bringing front , behind ) actions ?
Try using constant pixel size on your PanelSettings. Otherwise, the px unit acts more like pt
Thanks for the advice. Yes, I tried that option and it works, but I have to use the Scale option to keep the UI looking the same at any resolution so I'm trying to find a way how to fix it with scaling 😔
Can someone please help me with grouping these items in a DropdownField
https://docs.unity3d.com/6000.0/Documentation/Manual/UIE-masking.html
Supposedly supported on 2021.3 and 2022.3 and 6000, according to the docs.
This references using an SVG to mask elements in UI Toolkit.
However, I cannot import SVG's. What am I missing / doing wrong?
Problem: Mask an arbitrary shape in UI Toolkit.
var field = new TextField(500, true, false, '*') {
label = label ?? string.Empty
};
field.SetVerticalScrollerVisibility(ScrollerVisibility.AlwaysVisible);
Is there some way to have both multi-line and word wrapping?
Is there anyway to render markdown text correctly with UI Toolkit?
Should I be importing TMPro for use with UI Toolkit? I'm starting a new projecrt in 6000.0.3f1 and was wondering if this is still essential or if UI Toolkit supercedes TMPro
TextField {
white-space: normal;
}
.dialogue-graph-node TextField {
flex-grow: 0;
width: 100%;
}
seems to have solved it 👍
how to get asset by url() ? i tried like this
--pd__asset-logo__unity: url('Assets/ProjectDoc/Graphics/Icons/unity_logo');
but didn't work, currently i need to use ui builder for that, but i it's just inconvenience
You'd need addressables for something like this, or use the editor only AssetDatabase.
Anyone experienced with creating your own custom VisualElements? I have a class extending VisualElement with an UxmlFactory as well as an UXML file defining the element.
However after I clone the VisualTreeAsset, and check the new object in the debugger, it doesn't seem to have any children. Am I doing it wrong..? Is there a concise documentation on creating and initializing custom elements? Can't seem to find it. Or maybe some examples?
Guys I am not sure how to overcome this issue, I have a text mesh pro in one scene with a blue fill color and a dark blue outline. I have another scene with a text mesh pro but I want it to be only white no outline, but everytime I change that, the text in the first scene changes too. Can someone please tell me how to fix that?
How is that related to UI toolkit?
You should use separate material for each text if you don't want them to share properties.
Sorry someone told me I should put that here
My bad
I have created custom VisualElements by creating the hierarchy manually in the object's constructor. I was under the impression that using UXML files for custom elements was not the way to go, but I may be wrong. If this ends out working for you lmk since I would be interested.
Also, how is it that you access the VisualTreeAsset from the factory / custom element constructor?
How to address the expand/collapse and item height inside ListView?
Actually I succeeded after that. There were a few issues, like not adding the new visual element to the hierarchy correctly and it's container being collapsed. After fixing those it worked.
I load the VisualTreeAsset via addressables (a reference would work too) in my MonoBehaviour UI manager, then clone the tree and add it to the UI document root.
I thought you were trying to clone the tree inside the custom VisualElement definition, not the UI document root. For example, I thought you were doing this within the CustomElement constructor or with the UxmlFactory so that when adding the custom element in UI Builder, the tree would be populated
The tree is populated. The c# custom visual element class is linked to the uxml.
I don't need to clone anything in the visual element definition. It's the custom visual element that gets referenced by the uxml, not the other way around.
Oh okay I get it now, I misunderstood
Anyone knows how to make a blurred background that doesn't eat too much performance?
Hey, any ui builder bro who knows why a simple listview with property field wont expand and get the correct height?
hey I probably have the same problem, did you find any solution?
thanks a lot mate!
Is the unity ui toolkit better then the classic ol' ui system with game objects?
I need a main menu and a HUD but im not sure if the ui toolkit is suitable, or if it even has any benefits at all
See the comparison docs that are pinned
Ty
I'm using UITK to create a radial menu and I'm getting some odd what appears to be aliasing artefacts (?) when drawing each segment arc.
ptr.BeginPath();
ptr.Arc(new Vector2(width * 0.5f, height * 0.5f + _radius), _radius, -halfRad-90, halfRad-90);
ptr.Stroke();
the only thing i'm doing at that point to position each individual segment is
bottom = MathF.Cos(angle * Mathf.Deg2Rad) * Radius,
left = Mathf.Sin(angle * Mathf.Deg2Rad) * Radius,
rotate = new Rotate(angle),
it doesn't really make any sense because all the other edges look fine and everything seems to be anti-aliased as you'd expect
How do I make a circle? lol
Trying to use the UI Toolkit to make a circle. I'm not sure how to make shapes.
Either make a square by setting width and height to the same value and set the border radius to 50%, or apply a circle texture to a square, or use the Vector API (a resource is pinned)
Thank you so much
I'll Youtube to find out how to make a square
Builder pro
Not UI Toolkit?
This suggestion is irrelevant to this channel and what they need to do.
It's just a VisualElement with styling that has width and height to be the same (and flex grow should be 0)
Can anyone help about this problem or any idea 🫤
https://discussions.unity.com/t/graph-view-list-view-problems/363699
Thanks Vertx, that worked
How do I set flex grow to 0 using a stylesheet? My stylesheet for other settings is working, but adjusting flex grow on it isn't affecting the VisualElement.
If it's not affecting the element then it's likely it's overridden inline
If you expand these images, you'll that things are pretty plain
The line on the left and the bolded text means it's overridden inline
so doing something in a stylesheet will do nothing
Which line and bolded text?
Ahhhh, sorry was hard to make that out from the crop
Sorry about that
But you have the other one selected
Yeah, Discord has the preview cropping
the UXML, and it has the override I screenshotted
I selected one in one image, and the other one in the other image
Yeah, so the second one is doing nothing because it's overidden inline in the first
How do I stop the inline from overriding
has anyone here made a shared ui for couch coop? How do you handle the focus/active states, as well as ui control segregation? Is my only option to essentially ignore, and disable all the default unity tech, and write my own from scratch?
how do you select just the first child of an element in uss
i tried .group > Label
but this gets all the first generation labels of .group not the first generation & first found
did you try .group:first-child ? dunno if it is supported in uss, but it is the one to use in css
What I usually do is find the first one by code, add a class and then just change the uss accordingly
doesnt seem supported
ah im using the builder
Then I'd do the same as taunting said
Using UIBuilder can work in pair with a C# class
Won't you link it to a script... ever?
kinda wish they would support the pseudo classes for :first-child
same for last-child
Hey all , I have a few questions on the graph view and UI side. After adding a map to the graph view, I think there is no support for Z-order on the USS side.
1:
The only way I can do Z-order is to edit its place in the hierarchy?
2 : After changing the hierarchy order, when I add the map before the toolbar, put it in floating mode and then put it in anchor mode again in a higher position, the position of my toolbar is distorted, how can I prevent this?
3 : When I click on the visual elements in the map, the root visual goes towards them, but how can I do to make this happen when I click on empty areas?
4 : In some cases, the representative visuals of the visual elements inside the map overflow out of the map, how can I access the representative visual elements inside to prevent this from happening, if I make their overflow hidden with uss, can I fix this?
5 : When the root visual resizes ( the main editor window) , I want map always stay at the same point, probably the editor window has an onResize callback, but how can I do this without breaking the main structure. Sometimes the map stays in different positions when the window resizes.
I am using UI Toolkit but the scrollview doesn't work in-game when I try to use the scrollwheel on the mouse
anyone know why that could be?
this is the setup
It does work in the UI Builter
Do you have an event system in the scene? I've recently found that having one is somehow preventing uitk scroll views from scrolling
I have one but it doesn't matter if I remove it or not
Hey guys, how's it going?
I have a visual element, and I"m able to see it in the preview viewport. However, when I start my game, I'm not able to see my element unless I add flex grow to see.
I'm looking to add a circle, but if I add flew grow, it takes up the whole screen.
Hello ! I would like to display a vfx above a button(the button will be invisible) but I struggle a lot.
technically this is what I got
But when I make this button spawn (it a simple dialog box) everything spawn except the vfx or lets say it spawn because I found it in the hierarchy but the camera don't render it.
And I use cinemachine for the camera and feel a little lost even if I guess I have to have a specific camera with a specific layer to display it (it don't work)
You can use the UI builder/toolkit debugger to see the properties of your ui and adjust them to see what's causing it to collapse.
- Cinemachine doesn't affect what and when the camera renders. It only moves and rotates it around and maybe modifying some properties like the field of view.
- It seems like you're using a canvas ui? In that case this channel is definitely unrelated. Ask in #📲┃ui-ux if you think that the issue is related to UI.
That's what I'm using to trying to debug. I found out that if I put fletch at 1, then the whole screen gets taken. If I put .5, then the circle goes takes the upper part of the screen.
I'm not sure what to adjust to make the circle not stretched on the sides.
For the position, I'm guessing the transform needs to be adjusted.
Why are my ValueChangeCallbacks fired when I change the selection of the object in the editor and it's inspector is created?
This is how a code to bind to my property fields looks like currently:
[CustomEditor(typeof(Controller), true)]
[CanEditMultipleObjects]
public class ControllerEditor : UnityEditor.Editor {
public override VisualElement CreateInspectorGUI() {
var controller = (Controller)target;
var root = new VisualElement { name = "root" };
var editor = Resources.Load<VisualTreeAsset>("UI/controller_editor").Instantiate();
root.Add(editor);
if (controller.SdfScene == null)
root.Add(new HelpBox("This node must be a descendant of a SdfScene node to work", HelpBoxMessageType.Error));
var defaultInspector = new VisualElement();
InspectorElement.FillDefaultInspector(defaultInspector, serializedObject, this);
root.Add(new Label("Default inspector:"));
root.Add(defaultInspector);
defaultInspector.Query<PropertyField>().ForEach(
propertyField => {
var capitalizedProperty = propertyField.bindingPath[0].ToString().ToUpper() + propertyField.bindingPath[1..];
if (!PropertyContainer.TryGetProperty(controller, new PropertyPath(capitalizedProperty), out var p))
return;
if (p.GetAttribute<ShaderPropertyAttribute>() is not null)
propertyField.RegisterValueChangeCallback(_ => controller.OnPropertyChanged(capitalizedProperty));
if (p.GetAttribute<ShaderStructuralAttribute>() is not null)
propertyField.RegisterValueChangeCallback(_ => controller.OnStructureChanged());
}
);
return root;
}
}
I am quite new to UItoolkit so I don't really know best practice for writing custom inspectors in UITK yet
struggling w/ ui toolkit, trying to align the background image of the bottom image with the top image. Both source images have identical dimensions, but I can't figure out how to keep them aligned
when I scale the UI up or down, they get out of line with each other
The bottom element should be Absolute position with 0 left, right, top, bottom
that way it's positioned identically to its parent
@gritty crescent
Is there a CSS/USS intellisense extension on Visual Studio to code faster?
Can anyone tell me where is the "Disconnect all" menu event added from to contextual menu ?
I can't find it anywhere in the source (Graphview, Port ,etc ).
And its broken its not activating button although already connected to other node , need to read source .
Thanks
If you find anything can you let me know 😅
how to set an element to auto fill rest of the available space in the row ?
found it : flex-grow = 1
how to prevent button overflow ? ( overflow is already set to hidden )
not perfect , but at least this will not force the horizontal scroll bar to appear : white-space: normal;flex-shrink:1;
how do I change the color of a property field label in code?
nvm, wrote a USS and just applied styles for .my-class Label {...}
is the ui toolkit worth it? I have a chess game, basic menu for offline vs online play with a network connection I used text mesh pro, but now I want to make it look niceer
Yes, for the most part I think it is. You should try it yourself. It is a lot easier to work with.
i don't get it why align item center on visual element(parent of text field and button) make button goes outside the visual element?, the text field flex grow is 1, because i want its to take remaining space after other element(in this case button)
I've watched a few videos on it... do you have a favorite tutorial?
nope, experimenting all the way 😅
in my case I as motivated by the quickly incoming deadline, so I had to learn it fast, so I read docs rapidly and used what I needed
I'm also not really a YT tutorial kind of person
Any tips on how to properly draw a property field for [SerializeReference]<Interface> field? I just want it to only accept monobehaviour components that implement this interface. Preferably generic solution for interfaces but I can settle on creating property drawer for each interface my self.
Just wanna know if there is any thing I could look in to or read about it.
I know I can technically just make base monobehaviour that implements it, but I really wanna do it this prettier way without boilerplate inheritance
I would also like to know the same...
although how do you even manage to serialize interfaces with [SerializeReference]? I remember it wasn't working at all and serialization wasn't possible for any objects derived from UnityEngine.Object
SerializeReference is powerfull and it works, there is just no support for inspector other than for Monobehaviours and SO.
public sealed class DeviceChangePublisher : MonoBehaviour
{
[Header("Input Actions")]
[SerializeField, NotNullProperty] InputActionReference positionInputAction = null!;
[SerializeField, NotNullProperty] InputActionReference deltaInputAction = null!;
[SerializeField, NotNullProperty] InputActionReference interactInputAction = null!;
[Header("")]
[SerializeReference] IDeviceChangeListener?[] listeners = Array.Empty<IDeviceChangeListener?>();
[SerializeReference] IDeviceChangeListener test;
Have you tried using it with unity objects? For example when you have a SomeComponent : MonoBehavior, ISomeInterface and try to use [SerializeReference] ISomeInterface iface field which you assign SameComponent attached to a GO?
I remember trying and unity complaining that it can't serialize UnityEngine.Objects
dang you are right 😦
yeah, that's why I forfeited and had to design without iterfaces...
too bad Unity doesn't support such a basic C# feature...
so I can only think of not so nice work around but I am yet to test it: ```CSharp
public sealed class DeviceChangePublisher : MonoBehaviour
{
[SerializeField, RequireInterface(typeof(IDeviceChangeListener))] MonoBehaviour?[] listenerComponents = Array.Empty<MonoBehaviour?>();
IEnumerable<IDeviceChangeListener> Listeners => listenerComponents.Cast<IDeviceChangeListener>();
}
You can't use SerializeReference with UnityEngine.Object subtypes
But there's nothing stopping you from serialising them within the type you used
So i did it that way: ```CSharp
[CustomPropertyDrawer(typeof(ImplementsAttribute))]
public class ImplementsDrawer : PropertyDrawer
{
ImplementsAttribute ImplementsAttribute => (ImplementsAttribute) attribute;
Object? cacheReference;
public override VisualElement CreatePropertyGUI(SerializedProperty property)
{
var propertyField = new PropertyField(property);
propertyField.RegisterValueChangeCallback(OnValueChange);
return propertyField;
}
void OnValueChange(SerializedPropertyChangeEvent evt)
{
var property = evt.changedProperty;
var newObject = property.objectReferenceValue;
if (newObject != null && !ImplementsAttribute.InterfaceType.IsInstanceOfType(newObject))
{
property.objectReferenceValue = cacheReference;
property.serializedObject.ApplyModifiedPropertiesWithoutUndo();
}
else
{
cacheReference = newObject;
}
}
}
just note that propertyField.RegisterValueChangeCallback(OnValueChange); will trigger OnValueChange when an inspector is instantiated
to give style to Label inside textfield i can use uss #file-renamer__search-field > .unity-label { min-width: 0px; }
but can i acces it using C# only?, like for a case i make a simple editor script, and i just dont like to make uxml file or uss file for such simple stuff, is that possible?, for now i can do
var searchFieldLabel = searchField.Q<Label>(className:"unity-label");
searchFieldLabel.style.minWidth = 0;
``` that's quite fine, but can i just access the child only via it's class name or visual element name?, without need cast it type?
How do I make the dropdown label field width the same as above?
answer: .unity-base-field__aligned
source: https://forum.unity.com/threads/how-can-we-align-a-textfield-from-a-propertydrawer-to-the-properties-label-content-wise.1507340/
hey, if I make a change in the field nothing changes after refocusing SO , what am I doing wrong?
[CustomPropertyDrawer(typeof(GPSelectionData))]
public class GPSelectionDataPD : PropertyDrawer
{
private SerializedProperty _serializedSelectionProperty;
public override VisualElement CreatePropertyGUI(SerializedProperty property)
{
var container = new VisualElement();
_serializedSelectionProperty = property.FindPropertyRelative("_valSerialized");
if (_serializedSelectionProperty != null)
{
object deSerialized = GPSelectionData.DeserializeValue(_serializedSelectionProperty.stringValue);
if (deSerialized is int)
{
var field = new IntegerField();
field.label = "Selection";
field.SetValueWithoutNotify((int)deSerialized);
field.RegisterValueChangedCallback(OnValueChange);
container.Add(field);
}
else if (deSerialized is string)
{
var field = new TextField();
field.label = "Selection";
field.SetValueWithoutNotify((string)deSerialized);
field.RegisterValueChangedCallback(OnValueChange);
container.Add(field);
}
}
return container;
}
private void OnValueChange<T>(ChangeEvent<T> evt)
{
_serializedSelectionProperty.stringValue = GPSelectionData.SerializeValue(evt.newValue);
_serializedSelectionProperty.serializedObject.ApplyModifiedProperties();
_serializedSelectionProperty.serializedObject.Update();
}
}
I fixed the data change bug now its changing i guess but now i get this when i edit and press CTRL-S on scriptable object SerializedObject of SerializedProperty has been Disposed any idea ?
The value change callbacks that i am registering cause that , when GUI disposed its still trying to do that and throwing error ?
And how can i unregister when inspector disposed in property drawer ?
After hours of research and trials, I finally found a result.
There is a problem in version 2022.3.15.f1, manipulating the value of a data managed with SerializationCallback on scriptable object with custom property drawer causes this error.
SerializedObject of SerializedProperty has been Disposed
2022.3.33f1 Look clean for now.
What should go into a binding and what should go into a custom element?
For example I want to display a graph to the user. The game logic will create that graph and at some point update a datasource with the graph data
Now I could just have the binding only trigger onSourceChange and basically draw everything that is needed from the datasource onto the screen right?
I do not really need custom elements here?
Anyone has a clue how to keep the TextField "active" after hitting enter? I want to be able to keep on typing, like how you can in discord for example.
Has to be a multi line text field
No, that's no what I'm aiming for.
Anyhow I got it working somehow. I had to Focus() on the deepest element in the TextField hierarchy. I'm not sure if it's enough just to focus on it or all(several) of the elements. Will have to test it out later.
Calling Focus only on the Text element itself doesn't seem to produce the desired result
How do I layer visual elements on top of each other?
Just put those you want in front lower in the hierarchy
You mean within the game objects hierarchy?
No. The visual elements tree
anyone else getting crashes when using ui toolkit when running the editor in dx12 or vulkan ?
Not in the editor, but it’s worth noting there’s an issue with Qualcomm GPUs on some Android devices that will prevent uitoolkit from rendering. The only option is to force OpenGL until this gets fixed
fk ...
So after endless googling and poking around I seem to have come to a wall.
Why is this white box background behind my integer display?
None of the colors or images in the background or text settings do anything about it, and adding a background image doesn't remove it, the box just appears OVER the background image.
It does expand with the size of the display box.
But for some reason the visual elements are being placed adjacent to each other instead of overlapping each other
That must be due to the flex settings of the parent element.
And/or the positioning settings of each of the child elements
Thanks!! I couldn't figure it out changing the flex settings of the parent elements, but changing the positioning settings of the child elements helped 🙂
How do I make the children not inherit the parents opacity?
So I can set my own opacity?
I guess changing the A value of the background color of the parent is an alternative, instead of changing it's opacity
see what im click, that give the color to that
TextField>#unity-text-input
{
background-color: whatever
}
or if you like via Code
var ui = YourTextField.Q<VisualElement>(name: "unity-text-input");
ui.style.backgroundColor = whatever
read all my reply, i show you how to access it
Hello everyone, I did some editor scripting using UIToolkit. And I reference to a variable in objectfield. But then it broke after I move script that contain that variable to specific assembly definition in my project. And it gives this error message. (It was longer. I can provide more if needed)
I suspect that binding path of UIToolkit go for only Assembly-CSharp.
TypeLoadException: Could not load type 'Card.SoGameObjectCollection' from assembly 'Assembly-CSharp'.
I can think of 2 main solutions which I think there may be a better way.
- Assign Assembly definition reference of that variable in Assembly-CSharp.
I would not like to go for this as it may messed up default assembly of unity.
- Move my script out of Assembly Definition
I don't want to go for this as it will break my logic boundary in my project.
what about asign object type via script? have you tried it?
@dark blade
I don't know if this is what you mean. But here is how I reference it via script.
I get the reference of visual element and then Q it from the root.
var root = new VisualElement(); UXML?.CloneTree(root); var myPresetField = root.Q<ObjectField>("Preset");
ObjectField field = new ObjectField();
field.objectType = typeof(FileRenamer);
``` this my example
well of course instead of new, you get via Q<ObjectField>() from your uxml
May I have your educated guess why it did work before I moved my script into Assembly definition?
sorry if that didn't work out, i just see you tried assign the type via uxml, so i thought maybe assign via scripts can be more easier
I'm trying your solution out. I appreciate your help. I just try to figure out exactly what is happening. Thank you for your thoughtfulness.
Ok, somehow it does work now. Thank you very much @dark blade 🫡🫡🫡
I investigate a little more and found out that assembly definition is defined in UXML in order to reference that variable. 😅
I'm having a problem setting positions for a moderately complex UI element. We want to use styles to set the position of child elements and set the position of the root element in code (it's an overlay that is supposed to follow an object in the game view). It looks like setting the translation on the root element causes the translate style on the child elements to be ignored, so they all end up sitting on top of each other.
This is how we set the root position:
This is what the styles on the child objects look like:
It looks like the styles are set correctly:
Ignore all this, I'm dumb 🙂
Hi there everyone... Does anyone knows wich is the right way to make the slider pointer bigger? I've done it by changin those values, but i don't think is the right way to do that...
I also wanna know how to limit the sides of the pointer... how could i do that?.
You use the width and height in the Size category/foldout
You basically never want to use scale as it doesn't respect layout properly and if you have things like a border, it will make the border thicker/thinner than the specified size. Along with other things.
hmm, that cause this...
You need to change the top margin to be a negative value as well iirc. About 1/4 of the size of the dragger.
ok, that's fixed... but @still lantern how could i limit the range...?
it's avoiding the margin...
does anyone else get this weird inspector alignment in Unity 2022 of Serializable classes?
Could anyone explain to me why this updates my useInstanced variable in the Inspector, but the Label I am making does not update?
I am assuming that CreatePropertyGUI must be called differently than the old IMGUI workflow.
/// Options to display in the popup to select constant or variable.
/// </summary>
private readonly List<string> popupOptions = new List<string>
{ "Use Instanced", "Use SO Variable" };
public override VisualElement CreatePropertyGUI(SerializedProperty property)
{
var container = new VisualElement();
// Get properties
SerializedProperty useInstanced = property.FindPropertyRelative("UseInstanced");
PopupField<string> popupField = new PopupField<string>(popupOptions, useInstanced.boolValue ? 1 : 0);
popupField.RegisterValueChangedCallback(evt =>
{
useInstanced.boolValue = evt.newValue == popupOptions[0];
useInstanced.serializedObject.ApplyModifiedProperties();
});
Label label = new Label($"{useInstanced.boolValue}");
PropertyField propertyField = new PropertyField(useInstanced);
container.Add(popupField);
container.Add(propertyField);
container.Add(label);
return container;
}```
It's just weird to me that the label I am making wouldn't be constantly grabbing the new value of useInstanced.boolValue as it changes
(This is a PropertyDrawer for the Editor, btw)
Actually now I am noticing it does update, but only if I click on some non-field part of the Inspector (like the background) after I update the checkbox
when you see my mouse go to the bottom right, that is me clicking and only then the label updates
(I know I could just update the label inside of RegisterValueChangedCallback, but this is just a test question. What I am really trying to do is draw one PropertyField or another based on the value of useInstanced)
Probably better asking in #↕️┃editor-extensions
Hey, could someone help me with this? #↕️┃editor-extensions message
My VisualElement width and max-width is always showing as 0, but in my editor and debug window, it's not showing as 0.
Here's what I'm using to get the values which are showing as 0:
myCircle.style.width.value.value
myCircle.style.maxWidth.value.value
how to fix this ui position and size changing in game windows?
maybe use myCircle.resolvedStyle.width will give actual width after calculation
sorry i dont understand, what is that?
Hi! I have a single element and the only setting I've changed is set flex grow to 1. I want it to fill my editor window but it only stretches horizontally and its height remains 0
It's annoying because it works in UI Builder but not when I instantiate it for the actual window
It was apparently the fault of the Template Container that is generated automatically
Another problem I have is that I want to place elements with absolute positioning inside a scroll view but they don't show up even when I give them a fixed width and height (hovering over them shows their shape but they don't show up visually)
(If I don't give them the fixed width and height, the scroll view container will have 0x0 dimensions since flex doesn't work with absolute positioning)
I just don't get why they don't appear
its the actual value of style after calculation
var middleContainer = rootVisualElement.Q<VisualElement>("middle-container");
multiColumnListView = new MultiColumnListView()
{
fixedItemHeight = 24,
itemsSource = files,
showAddRemoveFooter = false,
showAlternatingRowBackgrounds = AlternatingRowBackground.ContentOnly,
showBorder = true,
showFoldoutHeader = false,
horizontalScrollingEnabled = false,
reorderable = false,
selectionType = SelectionType.None,
virtualizationMethod = CollectionVirtualizationMethod.FixedHeight,
showBoundCollectionSize = false,
}
.AddClassList("renamer__multi-column-list-view");
var column_name = new Column
{
name = "Name",
makeHeader = MakeColumnHeader("Name"),
makeCell = MakeCell_Name
};
var column_path = new Column
{
name = "path",
makeHeader = MakeColumnHeader("Asset Path"),
makeCell = MakeCell_Path
};
var column_ext = new Column
{
name = "ext",
makeHeader = MakeColumnHeader("Extension"),
makeCell = MakeCell_Ext,
};
multiColumnListView.columns.Add(column_name);
multiColumnListView.columns.Add(column_path);
multiColumnListView.columns.Add(column_ext);
middleContainer
.AddChilds(multiColumnListView);
somehow this look a lot of stuff just for making a MultiColumnListView, am I doing it correct?, or there's better way?
i actually already fix it, ty for ur help tho
That worked, thanks
I am making a custom Visual Element using this script:
public class Connection : VisualElement
{
Vector2 origin;
Vector2 target;
public Connection(Vector2 _origin, Vector2 _target)
{
origin = _origin;
target = _target;
}
void OnGenerateVisualContent(MeshGenerationContext mgc)
{
var paint2D = mgc.painter2D;
Debug.Log("Test");
paint2D.fillColor = Color.magenta;
paint2D.lineWidth = 10.0f;
paint2D.BeginPath();
paint2D.MoveTo(origin);
paint2D.LineTo(target);
paint2D.ClosePath();
paint2D.Fill();
}
}
I am adding this to my editor window like this:
boardArea.hierarchy.Add(new Connection(new Vector2(0.0f, 0.0f), new Vector2(500.0f, 500.0f)));
The element appears in the hierarchy, however the line that I am trying to draw doesn't appear.
What should I change? Do I need to define some more data to instantiate the Visual Element?
I had to add this in the constructor and the method is being called now but I still don't see the line being drawn
generateVisualContent += OnGenerateVisualContent;
(Fwiw, I just had to reset the Unity layout cause it was a bit buggy)
hey im a begginer to UITK. how come I can't edit the label or checkbox of toggle?
If you are trying to edit the text, you should see a "Label" property in the inspector if you select your "#RunTogle" Toggle element
My guess is that the "Label" underneath isn't part of the UXML hierarchy. It's an element that adds a Label and VisualElement through "factory" code.
If you want to edit other style properties of the Label, you should be able to do it through USS with selectors like .run-toggle > Label if you add "run-toggle" to the style class list
ah I see got it working, ty
i kind lost it, so i make list view and this is my make item
private VisualElement MakeItem()
{
var container = new VisualElement() { }
.AddClassList("item-container");
var toggle = new Toggle()
.SetName("item-toggle");
var label = new Label("Song Name")
.SetName("item-label");
container.AddChilds(toggle, label);
return container;
}
and this is my Bind item
private void BindItem(VisualElement element, int index)
{
FileInfo file = files[index];
var label = element.Q<Label>(name: "item-label");
label.text = file.name;
var toggle = element.Q<Toggle>(name: "item-toggle");
}
``` so for toggle to work do i use
``` toggle = file.isSelected``` or ```file.isSelected = toggle.value``` and this file info is not a Serialized Property, just a struct
I think I have the same question as above. How to determine if a toggle is selected or not in code?
nvm it toggle.value
I don't get it. Nothing I do makes OnPointer move work. The root element fills the entire screen, and has picking mode enabled. no other UI elements above the background have a picking mode or anything.
The event never gets fired, at all.
I dont get it. The Event Debugger shows the event firing, on #Container so why is it not firing? Even with tricke down enabled?
Does the UI Toolkit support World Space positioning, say I wanted to use it for a VR game? Thanks.
Not atm, but I heard they are working on it. Although, you can render UI to a texture and display that in world space if you wanted.
https://docs.unity3d.com/6000.0/Documentation/Manual/UI-system-compare.html
Not out of the box. But unity's App UI package has a solution for world space documents it also has some useful controls
It just has you render the document to a render texture and has a component that will raycast against a plane with that texture on it for interacting with the ui
I am curious, have you used App UI, especially in a VR / world space context? If so, do you have a quick summary or some pros/cons of using it?
How could i disable right click for specific element? The thing i am trying to achieve is having a disabled element with right click context menu available.
I don't do vr so I have no experience with that. But I have made some world space UI documents with it. It's still uitk though, app UI just adds a bunch of controls and a theme and stuff
How do i prevent a serialized property change? Hell i hate UI
Hi guys, I have a root element like this
m_Root = GetComponent<UIDocument>().rootVisualElement;
And I'm placing two VisualElements over it:
m_Root.Add(m_OuterSquare);
m_Root.Add(m_InnerSquare);
But for some reason, even with PickingMode set to ignore on the OuterSquare and m_Root, and picking mode set to position on the InnerSquare, the inner square is not detecting clicling.
I even set up a ClickEvent like such:
m_InnerSquare.RegisterCallback<ClickEvent>(OnBaseInnerSquareClick);
And have setup the event function to print to console on it's first line.
anyone have any idea how I could make his in UITK?
my list view setting,
edit: Item Template are none, i tried to use Make Item, since its so simple....
and this is my make item, and unfortunaly the binding to target property are failed
private VisualElement ListView_MakeItem()
{
var toggle = new Toggle { bindingPath = "Selected" }
.AddClassList("list-view__renamer__item-toggle");
var textField = new TextField { bindingPath = "Name" }
.AddClassList("list-view__renamer__item-textfield")
.SetIsReadOnly(true);
return new VisualElement()
.AddClassList("list-view__renamer__item")
.AddChilds(toggle, textField);
}
only when i use Item template as Make Item, with same binding path, the binding to target property is working, why??
can someone explain to me how to make the box wider but the frame small like these?
hello, i have some problems with ui documents.
When i place the red block under the canvas, it shows up in the game view, and when i place it correctly inside the canvas it doesnt show up in the game view. Why does it have a strange offset?
How can i add element to Group-Scope object with AddElementWithoutNotify ? There is remove element without notify but why not add ?
There is no method to override or anything all is private or internal
I am trying to do add undo/redo logic on onGroupElementAdded / onGroupElementRemoved
solved I didn't think it would be so easy xd
{
MethodInfo method = typeof(Scope).GetMethod("AddElementInternal", BindingFlags.NonPublic | BindingFlags.Instance);
if (method != null)
{
method.Invoke(this, new object[] { element });
}
}```
Here's a weird problem I'm having with Labels. I have multiple Labels set up to display game information. One, works perfectly fine, it's updated twice per second to display score. The other, the life display, only updates when the script is called from within the UI Manager script. If it is called from any other script (IE, the main game script) it returns a NullReferenceException. I have swapped the score and life Label setters to ensure it isn't a mistype or the Label is just set up wrong. Pictured below, I called the same function to print the Label's current text two times. Once from the UI Manager's Start function, once from the main game script. Same function, no change to it's operation, two results.
To note, the Null code is called on the line of code that references the Label specifically, not any of the functions.
Turns out I had 2 EventSystems active
What's the difference between setting the background image as a texture vs sprite? Is there any preference for performance?
storing images that are used together in sprites is usually better for performance
can a Painter2d have multiple lines with different settings?
ah, it helps if you call LineTo instead of just MoveTo
I've created a uxml template and want to add functionality to it
Are there any tutorials or documentation on how to do so?
Specifically I wanna create custom attributes and callback events for the template that I've created
If someone can just point me towards the right direction I would really appreciate it
For context, I'm using unity 6
and all the documentation seems to use UxmlFactory, which is deprecated in that version
nvm I found something that could work
Hi ! Quick question: in Unity 6, we can use UxmlElement to define custom controls, and it appears to generate an additional file. the issue is it triggers my stylesscop (and block the CI). Is there a way to define the rule for such generation ?
Ref the Unity documentation on Property Paths (UI Toolkit):
https://docs.unity3d.com/6000.0/Documentation/Manual/property-paths.html
What do they mean by "cache property paths"? When looking through the profiler now I see that there is much both CPU time and GC generated by resolving the data context during "should update". I expect such a cache solution would help with this so that you don't need ot run PropertyPath.Combine() that much. Anyone worked on this?
Anyone know why having a custom editor (just the mere of existence of it) breaks UIElements-based propertydrawers?
this results in the "no gui implemented" being displayed
whereas if I delete the CustomEditor it works fine
Because you're missing either OnInspectorGui or CreateInspectorGui definition ?
Right now your editor code is just an empty shell
Im pretty sure that is totally fine, it should default to base.CreateInspectorGUI when there is no implementation ever since UI Toolkit became default. In any case, this also yields the same result
what does your property drawer look like ?
expected behaviour:
and all I did for this to work again is to comment out the code seen here.
by any chance, is your property drawer made with imgui ?
no its UIElements based
The only thing that comes to my mind with this error is that at some point part of your inspector is using imgui and englobes your code. But the way you call it should work. you can check if a bigger context is a imguicontainer through the UiToolkit debugger...
Yeah... well, if you remake the implentation yourself it shoudl work
a quick way to do it is by iteraring the property and create PropertyField for each property
damn
but is it me or is this strange? When using UI elements only through code for both inspector and property drawer, I feel like that combination should work out of the box.
because as is, there is no point in using UI Elements (at least for propertydrawers) as it just wont work with any type of custom inspector
Well it is weird for sure. out of curiosity on which version are you ?
Unity 2022.3.15f1
maybe in this version it's not totally migrated to ui toolkit and the default behaviour is to generate an imgui container
it was the case in 2022.2
Potentially. I think its the only explanation.
@tall vortex I asked on the forums and they have explained how to get it to work:
As the title says, it appears that Property Drawers implemented through UI Elements do not appear as expected in an UIElements implemented Custom...
Ah good to know that it returns null ._.
Yup. I assumed it worked the same way IMGUI works, that would have been nice
Hi All, I'm using a custom inspector to process some data collected within my unity game. In this each users data is listed in a ListView, with an export button and a time offset (some files have been recorded with slightly different timings from a different file so this is just to sync them up). The main thing is that I need to be able to input the offset time into these files, however I can't seem to click on the floatfield directly to edited the value (by keyboard).
I can however click and drag the value. But since some values are REALLY big, I do not want to drag for ages to do this. Does anyone know if there could be a cause for why I cannot interact with the text input part of the float field directly?
Could anyone help me with this? #↕️┃editor-extensions message
Just to understand what you are trying to do, have you clicked on the window itself in the UXML editor and changed the size their?
You can also click MatchGameView to copy the shape of the current game resolution
when i check that it gets smaller...
and if I reduce every single element so it fits then on the game view it gets eveen smaller
You may want to size things by percentages rather then absolute pixels
Where you are setting the sizes for visual elements fi the screen size changes but you have set an specific pixel size as the width / height of the VisualElement it will remain the same size. If instead you do it by percentage it takes it from the parent VisualElement (or in the case of elements without parents it will take the screen size)
So in your case, the size of the "screen" is 312*554, if you check the size of your 'start-menu-root' and its child elements my guess is that they are much larger
If you want to change the way it sizes you can either type 'px' or '%' after the numbers you put in to change if its a absolute value or you can click the dropdown to change them ^-^
Hope that helps
Oh, it does... but how cuould i mantain original proportions for example on the title image or in button images?
and when the screen is too different images get deformed
So this is something I ran into a while ago about, what you want is a way that keeps the aspect ratio of the image. I'll have a quick look at my other projects to see how I did this, I think I had to use someone elses logic for visual elements that maintain shape (scale proportanally)
Ill see what I can dig up xD
Oh, could you do that for me? :>
Thaankss ❤️
Ah okay, sorry try this first. in the background section of the image element you should see scale mode
Try selecting this
This will make the image maintain its maximum size without messing with the aspect ration
The only thing is, it may cause gaps, try it first though and let me know the results.
You may need to have the parent container list the child elements and have them align to the center, (this may solve it but not sure xD)
Dooonee! Just working with thaat!
Excellent! Glad to hear!
And one last thing if you don't care... Do you know if is it possible to defform a bit that image vertically without editing it in photoshop?
What do you mean deform sorry?
like to make it taller
Oh! to move it up?
You can add a margin to it
If you click the image, just add some margin to the element at the bottom
Or do you mean stretch it?
no... to alarge it
like i want that image to be deformed
Do you know what i mean?
Yeah I get you, just having a think
The problem is that scale to fit will lock the image to a specifc aspect ratio which removes the ability to do what you want their. A potential solution is to get something else to force the aspect to remain the same and then scale the image based on that parent.
I'm going to do a quick test, give me 5 mins and ill get back to you and let you know if this will work
If not i'd just edit the image with ph hehe
Don't break too much your head 😉
All is good the thing I was thinking of will work, so worth having a look at, but might be easier to edit it for now.
using System;
using UnityEngine.UIElements;
public class SquareElement : VisualElement
{
private MainSide _type;
public SquareElement()
{
RegisterCallback<GeometryChangedEvent>(GeometryChanged);
}
private void GeometryChanged(GeometryChangedEvent evt)
{
switch (_type)
{
case MainSide.Height:
style.width = resolvedStyle.height;
break;
case MainSide.Width:
style.height = resolvedStyle.width;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
public new class UxmlTraits : VisualElement.UxmlTraits
{
private readonly UxmlEnumAttributeDescription<MainSide> _side = new()
{ name = "Type" };
public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
{
base.Init(ve, bag, cc);
((SquareElement)ve)._type = _side.GetValueFromBag(bag, cc);
}
}
public new class UxmlFactory : UxmlFactory<SquareElement, UxmlTraits> { }
private enum MainSide
{
Width,
Height,
}
}
This is some code for a square element (this isn't my code so I will see if I can find the OP for this too, but its useful for forcing elements to maintain their aspect ratio)
If you use this as a container for the image elements you can change their size independently skew them as much as you want ^-^
No trouble, ill post the OP once I find him in a bit (I think it was a unity forum post) as they deserve the credit on this one. Not sure where i found ti though as the project I used it in is pretty old xD
I can't seem to find the original post but I did find this:
https://docs.unity3d.com/2023.2/Documentation/Manual/UIE-create-aspect-ratios-custom-control.html
Worth having a read as this may be a better approach (more control over the aspect ratio). Seems like the same idea though, have a parent element control the aspect ration and then the child elements just exist within it controlling their shapes relativly
Sorry to ping you again @serene harbor hehe... but do you know why does percentages doesn't work with the label?
Could you click on the box that the labels are in?
It may be that the container is expanding but the font size is staying the same
If that is the case, then you will need to look into making it update its font size correctly to match the label elements bounds. I found this, https://discussions.unity.com/t/ui-toolkit-text-best-fit/248895/3 which a few people have already implemented some good solutions for it (check "curbol"s reply)
and how could i apply this script the guy has posted to my text?
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class LabelAutoFit : Label
{
[UnityEngine.Scripting.Preserve]
public new class UxmlFactory : UxmlFactory<LabelAutoFit, UxmlTraits> { }
[UnityEngine.Scripting.Preserve]
public new class UxmlTraits : Label.UxmlTraits
{
public override IEnumerable<UxmlChildElementDescription> uxmlChildElementsDescription { get { yield break; } }
public override void Init(VisualElement visualElement, IUxmlAttributes attributes, CreationContext creationContext)
{
base.Init(visualElement, attributes, creationContext);
}
}
public LabelAutoFit()
{
RegisterCallback<AttachToPanelEvent>(OnAttachToPanel);
}
private void OnAttachToPanel(AttachToPanelEvent e)
{
UnregisterCallback<AttachToPanelEvent>(OnAttachToPanel);
RegisterCallback<GeometryChangedEvent>(OnGeometryChanged);
}
private void OnGeometryChanged(GeometryChangedEvent e)
{
UpdateFontSize();
}
private void UpdateFontSize()
{
UnregisterCallback<GeometryChangedEvent>(OnGeometryChanged);
var previousWidthStyle = style.width;
try
{
var width = resolvedStyle.width;
// Set width to auto temporarily to get the actual width of the label
style.width = StyleKeyword.Auto;
var currentFontSize = MeasureTextSize(text, 0, MeasureMode.Undefined, 0, MeasureMode.Undefined);
var multiplier = resolvedStyle.width / Mathf.Max(currentFontSize.x, 1);
var newFontSize = Mathf.RoundToInt(Mathf.Clamp(multiplier * currentFontSize.y, 1, resolvedStyle.height));
if (Mathf.RoundToInt(currentFontSize.y) != newFontSize)
style.fontSize = new StyleLength(new Length(newFontSize));
}
finally
{
style.width = previousWidthStyle;
RegisterCallback<GeometryChangedEvent>(OnGeometryChanged);
}
}
}```
sorry for the late 😅 but my pc send me notifications when it wants
This script is a new visual element, you can add it by just dropping the script into Unity somewhere and then inside the UXML editor (UI Builder), go to the Project tab instead of library, there should be a new element (looks like a scipt called LabelAutoFit)
Inside custom controls
So for me I have the script I sent earlier in my project so SquareElement is in there, if you add that script somewhere Unity will recognise it as a new custom VE and let you add it, just replace your old label with that one ^-^
Should hopefully work, I'll have a look myself in a bit if you cannot get it sorted. Just a bit busy right now with something else xD
I'll try it with your script then :>
This might be a really silly question, but why is the "clickable" area of my button (I've set this TMP text as the target graphic) so much longer than the text box? The extended white outline scales with the vertical dimension of the text box, but not the horizontal one. It also doesn't seem to have any relation to the text object or button object sizes...
this channel is for UI Toolkit, try #📲┃ui-ux
if I use painter.Stroke(); after each line/shape (eg square) is that going to murder performance or not really affect anything?
why I can't I use transition animation on height?
I've made sure to use pixel units but it doesn't work
Hi ! I got a question regarding ListView. I wanted to bind my list view to a property and define a custom bindItem but it appears to create some sort of conflict (some fields trigger a redraw of the list which is not desired) so I assume I'm not doing it correctly. See code below. If I remove BindProperty on the list view the conflict is not here anymore, but the ListView does not know of the array. Maybe I should set the itemSource directly, but i'm not sure it is possible having only access to a serializedProperty.
UnityEngine.UIElements.ListView rulesListView = new UnityEngine.UIElements.ListView()
{
virtualizationMethod = CollectionVirtualizationMethod.DynamicHeight,
showAddRemoveFooter = true,
showBoundCollectionSize = false,
};
rulesListView.makeItem = () =>
{
PropertyField propertyField = new PropertyField()
{
label = null
};
return propertyField;
};
rulesListView.bindItem = (element, index) =>
{
UnityEditor.SerializedProperty ruleElementProperty = rulesListProperty.GetArrayElementAtIndex(index);
PropertyField propertyField = element.Q<PropertyField>();
if (propertyField != null)
{
propertyField.BindProperty(ruleElementProperty);
}
};
rulesListView.BindProperty(rulesListProperty);
rootElement.Add(rulesListView);
have you tried changing virtualizationMethod to fixed height ?
I tried to see if I was misunderstanding this option, but no, it does not change anything and I need it to be dynamic since I don't know the size of the item when I bind it.
.uss file contains a selector
UI Builder shows above selector applied to target element
UI Debugger shows selector not applied to target
question about Listview
this is my make item
private VisualElement ListView_MakeItem()
{
return new VisualElement()
.AddClassList("pa-scroll-view--vertical__item")
.AddChild(
new Label().AddClassList(StyleSheetsUtils.labelClassname)
);
}
.pa-scroll-view--vertical__item {
margin: 2px;
}
```as you can see i add that class name, to parent of my label to give margin, so the idea for each item will have margin 2
and i did set listview virtualization method to dynamic height
but then here, only margin left and right are applied, margin up bottom is unnafected
even when i set the margin directly on make item like this
private VisualElement ListView_MakeItem()
{
return new VisualElement()
.SetMargins(2)
.AddChild(
new Label().AddClassList(StyleSheetsUtils.labelClassname)
);
}
public static T SetMargins<T>(this T target, float value) where T : VisualElement
=> target.SetMarginTop(value).SetMarginRight(value).SetMarginBottom(value).SetMarginLeft(value);
```its still give up and bottom margin 0, why?
Making a assumption here but I think the scroll view force the spacing between items. You can either change the border width without applying any color or the padding as a workaround I guess.
thanks, currently, the workaround is giving the container paddding, with transparent background color, thanks
Regarding UI toolkit:
Any reason why this itemUI.Q<VisualElement>("TechSlotImg").style.backgroundImage is a null but this itemUI.Q<VisualElement>("TechSlotImg") is not?
The element "TechSlotImg" does have a background image assigned
Trying to set the background image of a visual element to something else:
itemUI.Q<VisualElement>("TechSlotImg").style.backgroundImage = Resources.Load<Texture2D>(tech.techImgPath)
Resources.Load<Texture2D>(tech.techImgPath) is also null for some reason
tech.techImgPath is a string i got from copying path from the image in my project folder
itemUI is gotten from here
public VisualTreeAsset techSlot; var itemUI = techSlot.Instantiate();
how could i move that letter to the front?
Where can I find the UIElements.xsd. My template generated with a relative schema path and the file doesn't seem to exist in my packages or project.
I have since moved the file so I think the schema path is not resolving correctly.
Resources.Load is relative to a Resources/ folder, so it's possible you're passing the wrong path.
For examlple my-project/Assets/Foo/Bar/Resources/Baz/image.png would be Resources.Load("Baz/image.png").
Is this to be expected?
namespace EffortStar.UiToolkit.Elements {
public sealed class Banner : BaseVisualElement {
public new class UxmlFactory : UxmlFactory<Banner> {}
public sealed class Main : VisualElement { public new class UxmlFactory : UxmlFactory<Main> {} }
public sealed class Detail : VisualElement { public new class UxmlFactory : UxmlFactory<Detail> {} }
The scan doesn't look at nested classes?
itemUI.Q<VisualElement>("TechSlotImg").style.backgroundImage this you trying to get what image already assign to background image, if currently is none, then its return null,
while this itemUI.Q<VisualElement>("TechSlotImg") you get the visual element,
then resources .load path is start after the resources folder, so if u copy path from the asset you better use AssetDatabase.Load
So does anyone know how to do that? 😭 #🧰┃ui-toolkit message
i don't understand the question, "move that letter to the front?" which one?,
Yeah
The settings one
I've been trying to do it for two days 😅 @dark blade do you know what I mean?
No, you haven't properly described what you mean
Sort order is defined by the hierarchy, elements further down are displayed above
that's exactly what i want
It's supposed to be like that... but is not being applied in my case for some reason
@rough scarab as you can see in the hierarchy the settings image is abobe the settings pannel, but despite that the image is displayed under the pannel
Yes, if something is above in the hierarchy then it's sorted below the other thing
is there a way to sandwich a gameobject between two visual elements?
maybe they need to have their own script. all of mine are separate . . .
It's not about files, but I put them directly in the namespace and it works.
Instead of nesting them
so if they're not a nested inside of another ui element, it will work?
Dunno what you're styles are but I just solved this problem by reversing the order of the elements and using flex-direction: column-reverse
Yeah I guess it doesn't look at nested classes for some reason
At least in the version I'm using
okay, that's good to know . . .
Kinda weird, I would have thought they'd just show up in the same reflection query
But I can't remember what it looks like to scan types
So something like this:
<VisualElement class="container">
<ThingBelowTitle />
<Title />
</VisualElement>
.container {
flex-direction: column-reverse;
}
.container Title {
margin-bottom: -20px;
}
The margin bottom will allow the title to overlap
It's pretty shit that there's no z-index support but what you gonna do
... well?
or do I have to create two different ui documents and somehow communicate between them just for this to work?
ah ig ui toolkit is just not ready yet for my purposes
What's the best way to add logic to UI toolkit elements? Right now I am creating UI Document in editor, inserting it in Canvas, adding separate C# Script to retrieve Visual Asset Tree and add listeners. but my issue is it doesn't have any integration with UI itself, no idea what elements there are without looking back at the UI editor. Is there a better way to do this?
Hello is there a way how to insert image into ui toolkit, but the original aspect ratio of that image will be kept in all cases?
Hello there. My name is Erick and recently I've been experimenting with UI Tollkit. I want to draw a textured mesh using the meshAPI, but for some reason it doesn't display the texture I am passing through the .Allocate() method. I checked the documentation, and even tried the snippet provided there, to no avail. Here are the scripts I am using to generate the UI.
using System.Collections;
using UnityEngine;
using UnityEngine.UIElements;
[RequireComponent(typeof(UIDocument))]
public class Grid : MonoBehaviour{
[SerializeField]StyleSheet sheet;
UIDocument document;
CustomElement icon;
private void OnEnable(){
StartCoroutine(WaitDocumentSetup());
}
private void OnValidate(){
if(Application.isPlaying)
return;
StartCoroutine(WaitDocumentSetup());
}
private void Update(){
if(Input.GetMouseButton(1)){
Vector3 coord = new Vector3(
Input.mousePosition.x,
-Input.mousePosition.y + Screen.height
);
icon.style.top = coord.y;
icon.style.left = coord.x;
}
}
private IEnumerator WaitDocumentSetup(){
document = GetComponent<UIDocument>();
icon = new CustomElement();
yield return new WaitUntil(() => document.rootVisualElement != null);
UpdateUI();
}
private void UpdateUI(){
var root = document.rootVisualElement;
root.Clear();
root.styleSheets.Add(sheet);
icon.AddToClassList("debug");
root.Add(icon);
}
}
.debug {
border-width: 2px;
border-color: red;
border-radius: 3px;
}
using UnityEngine;
using UnityEngine.UIElements;
public class CustomElement : VisualElement
{
private Texture2D tex;
public CustomElement()
{
generateVisualContent += OnGenerateVisualContent;
tex = Resources.Load<Texture2D>("Sprite-0001.png");
}
private void OnGenerateVisualContent(MeshGenerationContext context)
{
GenerateMesh(context);
}
private void GenerateMesh(MeshGenerationContext context)
{
// Example vertices (a simple quad)
var vertices = new Vector3[]
{
new Vector3(0, 0, 0),
new Vector3(100, 0, 0),
new Vector3(100, 100, 0),
new Vector3(0, 100, 0)
};
// Example UVs
var uvs = new Vector2[]
{
new Vector2(0, 0),
new Vector2(1, 0),
new Vector2(1, 1),
new Vector2(0, 1)
};
// Example indices
var indices = new ushort[]
{
0, 1, 2,
2, 3, 0
};
// Create a mesh write data
var meshWriteData = context.Allocate(vertices.Length, indices.Length, tex);
// Set the vertices, UVs, and indices
for (int i = 0; i < vertices.Length; i++)
{
meshWriteData.SetNextVertex(new Vertex()
{
position = vertices[i],
uv = uvs[i],
tint = Color.white // Optionally set vertex color
});
}
for (int i = 0; i < indices.Length; i++)
{
meshWriteData.SetNextIndex(indices[i]);
}
}
}
oh, i did not received the notification of your response
Thank you soo muuchh!
That really helped me a lot
And one more thing... How could I add a 12px margin between both containers?
margin-right?
Or margin left
There is no support for gap which is the idiomatic way in css
You can do justify-content: space between on the parent
And then set a max width on both the boxes
Then there will be a space when the container is wide enough
That's probably the cleanest way
in both containers parent?
There is only one parent
I don't know what that means sorry
Despite the edits
The container that has the things that need to be separated by a space
Just look up how the rule works
Gl
lemme try
hmm, i'm not getting you...
@sullen bay, I wanna add those margins
Add 6px padding to the parent and add margins to the children
I don't know what you're asking
Just add the margins
margin: 6px
I'm considering switching from UGUI to UI Toolkit, but is it possible to integrate particles into the UI? For example, glowing border particles around a UI card, etc.
In UGUI I can use ParticleEffectForUGUI package, is there something free also available for UI Toolkit?
oh, thankss, done!
And do you (or anyone else) know why I can't change the checked mark in a toggle?
sorry I've never used the UI builder
My guess is that it would be something to do with the :checked pseudo-selector
But I don't know how it works
I'm yet to use a checkbox
I'd recommend using the debugger to see where the image is specified
In HTML it'd be something like:
input[type="checkbox"]:checked:after {
display: block;
content: ' ';
background-image: url(...);
}
But definitely that is not how this works
because unity doesn't have a bunch of those concepts
It's something weird... :checked works with size and everything else but not with the image or bg... or at least I can see it
show me the XML
I've never used HTMl 😅
sure
Just the checkboxes themselves
They might have another element beneath them
Check one first too
in the debugger I mean, not the file
this doesn't look like it's from the debugger
you need to see how it looks at runtime
like this
"UI Toolkit debugger"
you click on "pick element" at the top, then click on the checkbox
while checked
and it should show you where the check is coming from
I know how to debug it when its an editor window... not when is an app UI 😅
the screenshot above is from a game UI
It's the same I believe
although sometimes the pick element doesn't work properly and it just selects the game pane
let me see how I acces it... one sec
ok, got it
can you see an element for the check?
look for the element with the check on it
you'll need to expand the children and look for the one with the background image
probably a child of .unity-toggle__input
let me see
the selected one is the check
cool, well you can use its class or name to create a selector for it
that overrides background-image
#Switcher #unity-checkmark {
background-image: <your cool thing>
}
presumably?
so, do i delete checked pseudo selector, right?
Potentially not needed, just comment it out and see if it works
It's possible that the pseudo-selector just hides and shows the check element
not working 😦 not hiding the check when i click on it
this is the code: css .settings-switchers #unity-checkmark { background-image: url("project://database/Assets/UI%20Toolkit/UnityThemes/UnityDefaultRuntimeTheme.tss?fileID=7433338533053954386&guid=23a3b2f17ca804f449438b260136c639&type=3#check@2x"); height: 160px; width: 160px; -unity-background-image-tint-color: rgb(255, 255, 255); background-color: rgba(0, 0, 0, 0); border-left-color: rgba(0, 0, 0, 0); border-right-color: rgba(0, 0, 0, 0); border-top-color: rgba(0, 0, 0, 0); border-bottom-color: rgba(0, 0, 0, 0); }
Probably need the checked selector then
I've added it, but is the same
Any ideas?
Show me the uss
here it is
.settings-switchers {
}
.settings-switchers #unity-checkmark {
background-image: url("project://database/Assets/UI%20Toolkit/UnityThemes/UnityDefaultRuntimeTheme.tss?fileID=7433338533053954386&guid=23a3b2f17ca804f449438b260136c639&type=3#check@2x");
height: 160px;
width: 160px;
-unity-background-image-tint-color: rgb(255, 255, 255);
background-color: rgba(0, 0, 0, 0);
border-left-color: rgba(0, 0, 0, 0);
border-right-color: rgba(0, 0, 0, 0);
border-top-color: rgba(0, 0, 0, 0);
border-bottom-color: rgba(0, 0, 0, 0);
}
.settings-switchers:checked {
}
The checked one is empty
.settings-switchers:checked #unity-checkmark {
background-image: url("project://database/Assets/UI%20Toolkit/UnityThemes/UnityDefaultRuntimeTheme.tss?fileID=7433338533053954386&guid=23a3b2f17ca804f449438b260136c639&type=3#check@2x");
height: 160px;
width: 160px;
-unity-background-image-tint-color: rgb(255, 255, 255);
background-color: rgba(0, 0, 0, 0);
border-left-color: rgba(0, 0, 0, 0);
border-right-color: rgba(0, 0, 0, 0);
border-top-color: rgba(0, 0, 0, 0);
border-bottom-color: rgba(0, 0, 0, 0);
}
That assumes that .settings-switchers is the class on the checkbox itself
I need to go to sleep now, good luck
Finally done!
Thank you so much for your help
hi! I have a very tiny issue related to the editor UI size. I use a mac ( M1, Monterey ), and i wanted to increase the UI text size - not ingame UI, the editor UI. I tried increasing the entire macs font size, but that makes everything else unusable. Is there a way to increase the editor UI text size?
Why do the stylesheets added to the Theme not show in the list of selectors?
Eg, I have my Theme set to include a bunch of utility stylesheets:
But the UI Builder only shows selectors from stylesheets directly added to the current UI Document:
Hi ! Quick question: in Unity 6, we can
why is that button active not working? I've changed tint property...
why is that button active not working? I
Is there a way to do VisualElement::after{ content: "text" } in USS?
You have the list of pseudo classes here : https://docs.unity3d.com/Manual/UIE-USS-Selectors-Pseudo-Classes.html
::after doesn't seem to be part of it
hence the question
so, it seems the solution is to manipulate the elements in .cs
Since it doesnt exist, in uss it's not possible. you'll have to do it through c#
I am getting No Gui Implemented error even tho i did. (Unity 6000.0.2f1)
I created a Drawer for a PropertyAttribute, it was working before but not now.
- Project does not uses IMGUI for Editor (set in
ProjectSettings>Editor>UseIMGUI) - Yes, i already implemented what they told.
- Using
[CustomPropertyDrawer(xx, true)]not works
I found the issue but dont know why it happens. I had an CustomEditor for the MonoBehaviour. When i disable the custom editor, the attributes works. But when i open the custom editor, it breaks the attributes.
Resolved: An empty CreateInspectorGUI() in your CustomEditor will break your custom property fields even tho it is drawn in the Inspector. It will show an error of No Gui Implemented for every custom PropertyDrawer you created. To resolve this, you shouldnt rely on the Unity and use InspectorElement.FillDefaultElement(). This is obviously a bug of Unity 6000.0.2f1
What do you mean by "An empty CreateInspectorGUI()"?
Because if you either haven't implemented it, or you're returning null, then this is the expected behaviour, and it's not a bug
In Unity 6000.0.2f1, if you return null or didn't implemented at all, it will draw the default inspector but buggy. Test it yourself: (Unity UI Package 2.0.0)
You will see custom PropertyAttribute drawers wont work
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
[CustomEditor(typeof(XXX))]
public sealed class XXXEditor: Editor
{
public override VisualElement CreateInspectorGUI()
{
var rootElement = new VisualElement();
InspectorElement.FillDefaultInspector(rootElement, serializedObject, this);
return rootElement;
// return null;
}
}
extract inlined styles to new class doesn't even do it's job. It creates a new style sheet but doesn't bother actually applying properties to the sheet....why is ui toolkit sooo buggy
Hey guys when using list view, think of the items in the list view, for example, two text fields, two of them have uniqe view data keys, even for a moment, when one has the other's data, the values in it change, how can I prevent this?
In my project, I have a uniqe viewDataKey according to the node and index of each text field for my undo / redo system.
In the objects recycled in the list view, I update it with bind, for example, text field key -> {node.viewDataKey + bindIndex}, but this time all the data in it starts to be the same.
Solved* just dont use viewDataKey use userData under visualElement .d
You will see custom
PropertyAttributedrawers wont work
They work fine if they have IMGUI implementations. Which is what the Editor in question draws with if you have a custom editor that hasn't overriddenCreateInspectorGUI
When I check the list you give as data source in the listView.itemsRemoved action in the list view, I see that there is still no missing when I check the number in this action.
How can I get how many data you have properly?
At the same time, the way to get the created elements properly is to open an extra variable and keep each item created with the make item action there,then need to index and remove the IEnumareable int in the remove item action from there and use that list ?
I can't find what's wrong with my ListView class.
When I delete the first element, the second element also disappears.
Did you check your remove method is not called twice ?
yes non of them called except clear and it was only triggering once when i remove element inside the list view i remove matching data from sender too but i didnt do anything inside list view @tall vortex
Anyone know of a way to make tooltips with ui toolkit?
Can only find something about a VisualElement.tooltip thingy, but it only works in editor which seems kinda useless
From what I understand of ui toolkit all elements are usually contained inside a visualElement, but for a tooltip I want it to kinda follow the mouse and overlap with other elements without affecting them.
Could make a new uiDocument now that I think of it though, hmm
In that case, anyone know of a good way to make a lone visual element on screen follow the mouse?
Anyone can help ?
When i remove last item i get out of range from list view it doesnt show which line
When i remove first element it removes first two
whats wrong with this code block ?
i just want to reflect items remove action to another the original list and rebuild list view itemSource with clearing and adding them again
Is there a way in UI Toolkit Debugger to add new style properties
I may be wrong here, but iirc, itemsRemoved is triggered after the ListView removed the item from the collection "on its own" after the default - button is clicked. Therefore, you're trying to remove an item that is already gone.
@tall vortex i guess no i checked the code after itemsRemoved triggered it return list of ints indicies that be going to remove after that i take those indicices and i remove my originial data collection then i need to update list view but ...
When i update my originial data collection draw the list view again by sending new original data collection list view still wants to remove the that old indicies
i need to a callback or something after itemsRemoved action and all items removed in it
no unlucky you have to create for that some testing debugging buttons to do it 😦
I looked in the past but couldn't find it.
@tall vortex i was right i guess finally found if u need to action after elements removed we need to use size change raise sections finally solved xd
It's unity default behaviour are your code ?
its base list view code unitys api
Then, I was wrong about the timing but I was right that the listview already handle item removal xD
I had the same issue before I changed how I handle listview
The default footer behaviour is a pia to override
yeah
now i need to find a way to override when pressed plus i need to show a pop up to select creation type xd
Good luck on this. On my end I made a custom display and hide the default footer so that I have more control on list manipulation
but if we hide default footter also hiddens the size of the collection and size change things right
but your solution is more consistent i guess xd
Yeah, it requires to recreate basic stuff. Not the quickest way for sure, but the simplest way to customise how my lists look.
You are absolutely right, let's see xd
@tall vortex hey again 😄 , do you have a proper solution for get actual visual elements related to list view item source datas
not sure I understand your question
I want to get the visual elements that the list view creates in itself, for example, I gave 15 int and let's say it created 15 labels.
How can I access the 15th label
Ah right
Logically absurd because it recycles according to the scroll position, but I need to handle it because even if that label is not visible, the undo redo actions in it are still there and I need to provide it somehow.
Well, you can give a name to the visual element in makeItem so that it's easier for you to identify them, and you should be able to gather them with Query<T>("your-name")
hımm i get it i tried now but again i failed some point when i create 100 element and if i change 100st element text and make undo it will change but when i scroll up and try that again it cannot find because it recycle
one way i need to add extra commands to scrolling event to re creation otherwise it cannot recycle and re create that element or idk 😄
After scroll to index function there is still no update for elements what should i do to trigger their bind items immediately ?
Can anyone tell me how to wait for the item in the index I made after scroll to item index in scroll view to be visiable?
I tried list view refresh items and rebuild but it doesn't work, should I wait with schdule and wait for an unspecified period of time?
Is there a point where I can verify that it is drawn and binded as a guarantee?
Does anyone know how I can trigger the on geometry changed event?
This is not triggered even if I do MarkDirty 😦
MarkDirtyRepaint, to be clear?
It's not bubbled, so the event must be subscribed to the specific element that changed
I tried but unfortunately it was not triggered after I did it, this was supposed to be guaranteed, right, if so, I will look for the problem on my side 😄
Also, if you've subscribed via a non-allocating method multiple times then only one will register
Does UI toolkit not allow math operations in fields? On 2022.3.17f1 and it's not available, wondering if they added it in a more recent version.
Am I missing something or does ui toolkit not work well with pixel art games with 640x360 reference resolutions scaling up?
Bottom is ui builder, top is in game
your scale is 3, that make visually blurry in editor
Ah I think I understand now. So when I actually set the resolution higher my games internal res will still be the small # and will scale up accordingly and will fix this issue with the text but not mess with any pixel art stuff
with an EventBase how to I get the element it came from?
oh, target?
Trying to change the text color of a text field when it's focussed. Any ideas? I've tried overriding all the selectors I can find with the :focused psudo selector.
It's blue when focused i.e clicked the text or clicked inside the input field
Hey there, has anyone expierenced issues for when MarkDirtyRepaint() is called on a custom component then a video on the same panel stutters?
its ``` :focus````
Hi kutub, I did this and tried it on many different selectors for the text field but none of them seemed to work.
so what are you try to style?, the label, or the text inside the textfield
The label (in the screenshot Input Option text)
.unity-text-element:focus:enabled {
color: red;
}
.unity-label:focus:enabled {
color: red;
}
.unity-base-field__label:focus:enabled {
color: red;
}
.unity-base-text-field__label:focus:enabled {
color: red;
}
.unity-text-field__label:focus:enabled {
color: red;
}
None of these seemed to work (I tried with and without the enabled selector as I'd had issue without that on buttons)
.unity-text-field:focus > .unity-label {
color: aliceblue;
}
``` this for styling the label
and this
.unity-text-field:focus > #unity-text-input {
color: aliceblue;
}
``` for styling the textfield text
and here more info about it https://docs.unity3d.com/Manual/UIE-about-uss.html
Can someone please help me with this issue of the DropdownField no longer grouping the elements by slash separation. It used to work in Unity 2021 but has not worked since 2022 and no exaggeration this is probably the like the 8th time I've asked for help on this and always get told that it should work but it doesn't.
Has any one else actually faced this and definitively know how to resolve the issue?
So this works for say, font size, but not color so I guess there is a more specific selector that is being set after this one
Okay, adding the enabled selector solves it...
.unity-text-field:focus:enabled > .unity-label {
color: red;
font-size: 40px;
}
Thank you for your help @dark blade