#🧰┃ui-toolkit

1 messages · Page 18 of 1

gusty vapor
#

I'm not so sure about it tbh, as said I'm not knee deep into this whole uitoolkit event system yet 🥹

#

what you're making actually? by the way I forgot asking this in the 1st place 😄

sullen bay
# gusty vapor what you're making actually? by the way I forgot asking this in the 1st place 😄

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...

Release Date

To be announced

▶ Play video
#

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

gusty vapor
#

I'm pretty sure you noticed already that UItk isn't production ready

sullen bay
#

It's come up a few times though

sullen bay
#

Have you used it?

gusty vapor
#

but uh,., uitk is like way worse than ugui

sullen bay
#

the layout works though

gusty vapor
#

at least in 2022

sullen bay
#

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

gusty vapor
#

uitk cant do z-order, custom shader, vector support and the list goes on

sullen bay
#

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

gusty vapor
#

all I want for uitk is to have a propery inline apis

wind gorge
#

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

hushed kraken
#

!code

analog sorrelBOT
wind gorge
#

nice, they introduced a new regression where elements with an overflow hidden and border radius now turn completely white

gusty vapor
# wind gorge Uitk is not runtime ready and probably never will be

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)

glacial lantern
#

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.

wary wadi
#

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?

wary wadi
#

^ it looks like I needed to be using ui:Label rather than ui:TextField 🫠 Not sure why TextField causes big white blocks tho...

rough scarab
#

Presumably the background color is white and the text color is also white

rough scarab
wary wadi
#

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 👍

wanton wraith
#

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

wind gorge
# gusty vapor give the team more time to work on them, that said, I've high hopes for this ui ...

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.

jolly lodge
#

I can't resize height in Unity Toolkit

rough scarab
# jolly lodge

Presumably flex grow is 1, so it's growing to fill the height of the parent

median sphinx
#

is there any way to bind button click actions without having to query the button?

#

I mean, visual binding

manic marlin
#

does anyone know how to make a dropdown submenu?
like i want categories in the dropdown
which extend another dropdown
next to it

wind gorge
#

You have to get a reference to the button in order to subscribe to events

median sphinx
#

find it via it's name/classes

#

in the old ui you can assign the event via ui

wind gorge
#

Oh that

#

No, you can't do that

median sphinx
#

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

wind gorge
#

You can't reference elements through the inspector as they are non serializable

median sphinx
#

I meant in the ui builder add a unity event that should be called when the button is pressed

wind gorge
#

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

median sphinx
#

but you can do data binding

#

it's almost the same thing

median sphinx
#

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

wind gorge
#

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

median sphinx
#

I think it's an abomination when you have to query the ui element with the exact name to then modify it

wind gorge
#

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

median sphinx
#

well, you'll mostly bind it using the ui builder I guess

#

most people will

wind gorge
#

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

glacial lantern
#

I saved my .uxml and now it cant be used or opened anymore saying its causing a 'stackoverflow'. This a common issue?

wind gorge
glacial lantern
wind gorge
#

Open it via a text editor

delicate talon
#

Are you trying to open it with Ui Builder?

wind gorge
#

It's a text file

glacial lantern
#

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.

delicate talon
#

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

glacial lantern
#

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?

delicate talon
#

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

glacial lantern
#

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.

delicate talon
#

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.

glacial lantern
#

Ah alright, I'll keep that in mind for the future, thanks :)

delicate talon
#

So that worked for you?

glacial lantern
#

I have not managed to cause the bug again so far, so we'll see.

delicate talon
#

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.

wind drum
#

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?

delicate talon
#

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.

gentle raft
#

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?

deep hawk
#

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

wind gorge
deep hawk
#

yaeh that was it , thanks trigger

wind gorge
#

np

sly folio
#

qq: Is it possible for TextMeshPro compenents to drop shadows?

#
  • based on lighting. in world space.
hexed coyote
dire nova
muted geyser
#

how to set ui builder theme to editor style and not runtime?

hexed coyote
empty obsidian
#

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
muted geyser
small wigeon
#

is it better to use textures or sprites with uitoolkit?

reef crater
#

Is it possible to turn of those purple squares when using sprite shape?

pseudo sentinel
reef crater
#

Thanks

untold trench
#

Do you mean ReadOnly?

untold trench
#

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...

▶ Play video
lyric saddle
#

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 ^^

lyric saddle
#

Thanks! I'll check that a bit later!

timid arrow
#

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

reef crater
#

Why isnt the gameobjects showing on the camera

sullen bay
#
    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.

rough falcon
#

"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.

wind gorge
#

it's barely even ready for runtime, let alone 3d

rough scarab
rough falcon
#

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')

merry schooner
#

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

lone socket
#

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.

obtuse sigil
#

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

hexed coyote
obtuse sigil
hexed coyote
#

UI in general, well, the theme to "light"

#

for shadergraph, no idea

obtuse sigil
slow mulch
#

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 ❤️

pseudo sentinel
slow mulch
#

Elements by code? 👀

pseudo sentinel
#

ye

#

its pretty easy

slow mulch
#

Hmm okay I haven't really found anything about adding it by code yet 🙃

slow mulch
#

Holy shit how did I miss this yesterday notlikethis

#

I guess after searching too long you'll overlook things

slow mulch
pseudo sentinel
#

should work eitherway

#

you can use the same function in your logic

slow mulch
#

oh gotcha CoolPepe

upper plaza
#

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.

old badger
#

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

sullen bay
#

Do you have an example of this?

sullen bay
wind gorge
#

The runtime material thing seems to be unused

sullen bay
wind gorge
#

Yes

#

I used it to add mix-blend-mode and masking

shadow quartz
#

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.

wind gorge
#

me

slow mulch
#

i cant get rid of the templatecontainer think

#

it adds a flex object to the ui, invisible, but still making stuff jump away

#

this seemed ok to me thonk

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 sad

rough falcon
#

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

rough falcon
#

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.

rough falcon
#

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

sullen bay
errant harbor
#

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

shadow quartz
# sullen bay I would prefer to use SCSS theoretically (esp. because no `calc` support in Unit...

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.

wind gorge
#

there's already a plugin out there that does the same thing

shadow quartz
#

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.

upper plaza
#

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?

shadow quartz
upper plaza
shadow quartz
# upper plaza 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

upper plaza
#

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.

shadow quartz
#

The template creator is also a nice handy way to deal with that sort of thing as well.

upper plaza
#

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

shadow quartz
#

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.

tawny flax
#

What do you think, is this behaviour a bug?
Issue with sprites from SpriteAtlas

deft quartz
#

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!

old badger
#

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

old badger
#

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

slow mulch
#

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 thisisfine

tawny flax
# slow mulch

I just add margins to grid elements and margin/padding to their container

slow mulch
#

well so did i now, as in adding margin to the elements on right and bottom

kindred mountain
#

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

flint bough
#

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

high crest
#

how can i create like my own ui what apps are recommended?

shy light
#

It’s also free

hollow plaza
#

As someone who just now discovered UI Toolkit, is it worth implementing, for something like an inventory system?

high crest
night fern
high crest
night fern
#

the ui tool kit is helpful but can be a little overwhelming...

#

if you want to side chat DM me... maybe I can help

night fern
high crest
#

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

night fern
#

I started a survival game a ways back.. followed a tutorial...

#

Are you following a tutorial or doing it on your own?

high crest
#

i am following tutorial for the inventory system not for a whole survivak game

night fern
#

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...

▶ Play video
#

#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...

▶ Play video
high crest
#

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

night fern
#

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: ...

▶ Play video
high crest
#

i will check it out

#

thx

night fern
#

DM me if you need more help.. sometimes I have random ideas that lead people to their answer lol

high crest
#

this tutorial looks really good

#

did you finish the survivak game you made

night fern
#

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...

high crest
#

are you working on project rn?

umbral sonnet
#

Hello, is there any possibility to enable more fps on scrollview? In my point of view it has 30 fps... Thank you! 🙂

wind gorge
#

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

umbral sonnet
#

@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

wind gorge
#

No clue then, guess it doesn't work

#

Try updating to latest, maybe it'll help

vocal thunder
#

Is it possible to make a custom visual element with a description property of custom type?

upper grove
#

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?

trail oasis
#

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

oblique whale
#

Hi everyone

#

I want Lobbies List for my multiplayer game

#

but I use ui toolkit

#

How can I prefab interface elements

wanton pier
rugged bridge
#

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?

rugged bridge
#

nvm figured!

flint bough
#

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?

flint bough
#

deleting the Library folder worked

rugged matrix
#

Anyone happen to have some custom UITK events that they're sending around and can show me an example?

rough pewter
#

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)

rugged matrix
#

where do you set the color to be clear? C# or uss?

rugged matrix
#

send code/screenshot

rough pewter
#

just an style set in UI Builder nothing special

rugged matrix
#

so no overriding selectors?

rough pewter
#

it looks fine in UI Builder but i get a white background in game

rough pewter
rugged matrix
#

yes as there are overrides?

rough pewter
#

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

rough pewter
rugged matrix
#

im sure it is, you should probably start sending some materials so we can actually take a lool

rugged matrix
rough pewter
rough pewter
rough pewter
# rough pewter

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

rough pewter
# rugged matrix cutom trickle up/bubble down events to send through the hierarchy

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;
}
sly folio
#

Is there a known 'gotcha' with UI.Button where the highlight stay goes away and won't come back until you clicked somewhere else?

rough pewter
sly folio
#

I worked around the issue by deselecting the gameobject after the click happens. The highlight comes back correctly if I do that.

rugged matrix
rough pewter
rough pewter
#

check it compared to the UI Builder

#

u see a white background instead of NKY (soundcloud logo)

rugged matrix
#

got it

#

ill take a look later!

tropic rune
#

question I cannot get a linerenderer to show on my game but it shows in scene

#

any idea?

scenic mirage
#

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...

gritty viper
#

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.

gusty vapor
gritty viper
gusty vapor
scenic mirage
#

Thanks guys

umbral sonnet
#

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! 🙂

vocal thunder
#

How to make font pixelated in UITK?

gritty viper
#

Well the first step would be to get a pixelated font.

vocal thunder
pale comet
#

Is shader support on the roadmap for UITK?

unborn bluff
#

Has anyone noticed the CreateInspectorGUI called around 4 times in Editor? Is it fixed on the latest versions of Unity?

lone socket
#

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:

viral marsh
#

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 ?

hollow apex
#

Anyone using UI Toolkit for a splitscreen game? How are you handling it?

lone socket
#

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)
scenic mirage
#

anybody have a tutorial or source for how to do runtime data bindings with listview?

lucid adder
tulip sundial
#

Is there a default stylesheet I can use for a Settings menu? Without one, it's a bit..tight

hot stump
#

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

viral marsh
#

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.

restive zenith
#

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.

restive zenith
#

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

rugged matrix
restive zenith
rugged matrix
#

tried 0?

restive zenith
#

0 makes the height 0, but it doesn't allow me to change the height

restive zenith
# rugged matrix tried 0?

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!

dense zodiac
#

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?

wind gorge
#

try making the property itself rgb(...)

serene harbor
#

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)

cosmic rain
#

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.

wanton cedar
#

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

wind gorge
#

If you want a progress bar type fill then it's just an absolute position rect with an increasing width

#

Same with vertical

cosmic rain
fading ferry
#

How do I add an image using Unity UI Builder?

pseudo sentinel
fading ferry
#

UI Builder was too confusing, I stuck with using normal UI

wanton cedar
#

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

shrewd prism
#

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 🙏

solid maple
# wanton cedar I'm trying to change the background color of a list view item when it is hovered...

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

rough scarab
#

Because I imagine you're just not doing it specific enough to override default behaviour

winged nexus
#

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".

tidal crater
#
        {
            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 ?

lucid adder
shrewd prism
errant harbor
#

Can someone please help me with grouping these items in a DropdownField

fathom steppe
wet sand
#
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?

kindred mountain
#

Is there anyway to render markdown text correctly with UI Toolkit?

potent ginkgo
#

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

wet sand
dark blade
#

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

regal quarry
#

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?

humble drum
#

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?

regal quarry
humble drum
#

My bad

solid maple
fallow patio
#

How to address the expand/collapse and item height inside ListView?

regal quarry
regal quarry
solid maple
regal quarry
#

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.

solid maple
surreal abyss
#

Anyone knows how to make a blurred background that doesn't eat too much performance?

rugged hull
#

Hey, any ui builder bro who knows why a simple listview with property field wont expand and get the correct height?

rugged hull
chrome linden
#

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

rough scarab
chrome linden
thick niche
#

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

sick wolf
#

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.

rough scarab
# sick wolf How do I make a circle? lol

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)

sick wolf
#

I'll Youtube to find out how to make a square

supple sail
sick wolf
supple sail
#

I think it’s in there if not

#

Go to packages

#

And look up builder pro

rough scarab
rough scarab
tidal crater
sick wolf
#

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.

rough scarab
sick wolf
#

If you expand these images, you'll that things are pretty plain

rough scarab
#

The line on the left and the bolded text means it's overridden inline

#

so doing something in a stylesheet will do nothing

sick wolf
#

Which line and bolded text?

rough scarab
#

this stuff is not a style sheet btw

#

this is all inline in the UXML

sick wolf
#

This is my stylesheet

rough scarab
#

Ahhhh, sorry was hard to make that out from the crop

sick wolf
#

Sorry about that

rough scarab
#

But you have the other one selected

sick wolf
#

Yeah, Discord has the preview cropping

rough scarab
#

the UXML, and it has the override I screenshotted

sick wolf
#

I selected one in one image, and the other one in the other image

rough scarab
#

Yeah, so the second one is doing nothing because it's overidden inline in the first

sick wolf
#

How do I stop the inline from overriding

rough scarab
#

Right-click and remove it

#

So there's not a value set there

sick wolf
#

Oooh I see

#

Thanks @rough scarab ❤️

#

That worked!

acoustic shadow
#

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?

trail oasis
#

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

tall vortex
fallow patio
tall vortex
#

Using UIBuilder can work in pair with a C# class

fallow patio
trail oasis
#

kinda wish they would support the pseudo classes for :first-child

#

same for last-child

tidal crater
#

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.

hearty kraken
#

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

wanton cedar
hearty kraken
sick wolf
#

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.

zinc creek
#

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)

regal quarry
regal quarry
sick wolf
hexed coyote
#

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

gritty crescent
#

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

rough scarab
#

The bottom element should be Absolute position with 0 left, right, top, bottom

#

that way it's positioned identically to its parent

#

@gritty crescent

surreal abyss
#

Is there a CSS/USS intellisense extension on Visual Studio to code faster?

tidal crater
#

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

tidal crater
deep hawk
#

how to set an element to auto fill rest of the available space in the row ?

#

found it : flex-grow = 1

deep hawk
#

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;

hexed coyote
#

how do I change the color of a property field label in code?

hexed coyote
#

nvm, wrote a USS and just applied styles for .my-class Label {...}

night fern
#

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

deep hawk
#

why is the popup always shows up below the component ?

#

it clearly needs more space

hexed coyote
dark blade
#

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)

night fern
hexed coyote
#

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

undone warren
#

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

hexed coyote
#

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

undone warren
#

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;
hexed coyote
#

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

undone warren
#

dang you are right 😦

hexed coyote
#

yeah, that's why I forfeited and had to design without iterfaces...

#

too bad Unity doesn't support such a basic C# feature...

undone warren
#

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>();
}

rough scarab
#

You can't use SerializeReference with UnityEngine.Object subtypes

#

But there's nothing stopping you from serialising them within the type you used

undone warren
#

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;
        }
    }
}
hexed coyote
#

just note that propertyField.RegisterValueChangeCallback(OnValueChange); will trigger OnValueChange when an inspector is instantiated

dark blade
#

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?
hexed coyote
#

How do I make the dropdown label field width the same as above?

tidal crater
#

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();
    }
}
tidal crater
#

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 ?

tidal crater
#

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.

flint bough
#

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?

regal quarry
#

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.

wise cargo
#

Has to be a multi line text field

regal quarry
# wise cargo 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

sick wolf
#

How do I layer visual elements on top of each other?

regal quarry
sick wolf
regal quarry
deep hawk
#

anyone else getting crashes when using ui toolkit when running the editor in dx12 or vulkan ?

wise cargo
#

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

deep hawk
#

fk ...

queen rapids
#

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.

sick wolf
regal quarry
#

And/or the positioning settings of each of the child elements

sick wolf
sick wolf
#

How do I make the children not inherit the parents opacity?

#

So I can set my own opacity?

sick wolf
#

I guess changing the A value of the background color of the parent is an alternative, instead of changing it's opacity

dark blade
#
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

queen rapids
#

Hmm. I see where it says background, but all the options are greyed out.

dark blade
queen rapids
#

Ah, right, gotta open the code layer... Joy.

#

Thank you!

clear ember
#

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.

  1. 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.

  1. 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.

dark blade
clear ember
#

@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");

dark blade
#

well of course instead of new, you get via Q<ObjectField>() from your uxml

clear ember
#

May I have your educated guess why it did work before I moved my script into Assembly definition?

dark blade
#

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

clear ember
#

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.

clear ember
#

I investigate a little more and found out that assembly definition is defined in UXML in order to reference that variable. 😅

golden loom
#

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:

golden loom
#

Ignore all this, I'm dumb 🙂

thick widget
#

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?.

still lantern
#

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.

thick widget
still lantern
thick widget
#

it's avoiding the margin...

rugged hull
#

does anyone else get this weird inspector alignment in Unity 2022 of Serializable classes?

kindred temple
#

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)

thick widget
sick wolf
#

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
velvet basalt
#

how to fix this ui position and size changing in game windows?

dark blade
velvet basalt
raven ermine
#

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

raven ermine
#

It was apparently the fault of the Template Container that is generated automatically

raven ermine
#

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

dark blade
#
 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?

velvet basalt
raven ermine
#

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?

raven ermine
#

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;
raven ermine
#

(Fwiw, I just had to reset the Unity layout cause it was a bit buggy)

fiery lotus
#

hey im a begginer to UITK. how come I can't edit the label or checkbox of toggle?

solid maple
solid maple
#

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

fiery lotus
#

ah I see got it working, ty

dark blade
#

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
fiery lotus
#

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

glacial lantern
#

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.

glacial lantern
#

I dont get it. The Event Debugger shows the event firing, on #Container so why is it not firing? Even with tricke down enabled?

fallow ginkgo
#

Does the UI Toolkit support World Space positioning, say I wanted to use it for a VR game? Thanks.

solid maple
wanton cedar
#

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

solid maple
unborn bluff
#

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.

wanton cedar
unborn bluff
#

How do i prevent a serialized property change? Hell i hate UI

sick wolf
#

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.

fiery lotus
#

anyone have any idea how I could make his in UITK?

dark blade
#

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??

velvet basalt
#

can someone explain to me how to make the box wider but the frame small like these?

empty sentinel
#

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?

tidal crater
#

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 });
            }
        }```
queen rapids
#

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.

sick wolf
lusty dagger
#

What's the difference between setting the background image as a texture vs sprite? Is there any preference for performance?

small wigeon
#

storing images that are used together in sprites is usually better for performance

small wigeon
#

can a Painter2d have multiple lines with different settings?

#

ah, it helps if you call LineTo instead of just MoveTo

tidal fable
#

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

tidal fable
#

If someone can just point me towards the right direction I would really appreciate it

tidal fable
#

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

tall vortex
#

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 ?

tiny dew
#

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?

rugged matrix
#

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

tall vortex
# rugged matrix

Because you're missing either OnInspectorGui or CreateInspectorGui definition ?

#

Right now your editor code is just an empty shell

rugged matrix
#

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

tall vortex
#

what does your property drawer look like ?

rugged matrix
#

expected behaviour:

rugged matrix
# rugged matrix

and all I did for this to work again is to comment out the code seen here.

tall vortex
#

by any chance, is your property drawer made with imgui ?

rugged matrix
#

no its UIElements based

tall vortex
#

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...

rugged matrix
#

Ill have a looksies thanks!

#

I guess it is treating it as an imgui container?

tall vortex
#

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

rugged matrix
#

pepepains 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

tall vortex
#

Well it is weird for sure. out of curiosity on which version are you ?

rugged matrix
#

Unity 2022.3.15f1

tall vortex
#

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

rugged matrix
#

Potentially. I think its the only explanation.

rugged matrix
#

@tall vortex I asked on the forums and they have explained how to get it to work:

tall vortex
#

Ah good to know that it returns null ._.

rugged matrix
#

Yup. I assumed it worked the same way IMGUI works, that would have been nice

serene harbor
#

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?

thick widget
serene harbor
#

You can also click MatchGameView to copy the shape of the current game resolution

thick widget
thick widget
serene harbor
#

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

thick widget
thick widget
serene harbor
#

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

thick widget
#

Thaankss ❤️

serene harbor
#

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)

thick widget
serene harbor
#

Excellent! Glad to hear!

thick widget
serene harbor
#

What do you mean deform sorry?

thick widget
serene harbor
#

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?

thick widget
#

like i want that image to be deformed

#

Do you know what i mean?

serene harbor
#

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

thick widget
#

Don't break too much your head 😉

serene harbor
#

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 ^-^

thick widget
#

Oh, It may work3

#

Thank you so much for your help 🙂

serene harbor
#

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

thick widget
#

Sorry to ping you again @serene harbor hehe... but do you know why does percentages doesn't work with the label?

serene harbor
#

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

thick widget
#

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);
    }
  }
}```
thick widget
serene harbor
#

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

thick widget
latent saffron
#

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...

small wigeon
#

if I use painter.Stroke(); after each line/shape (eg square) is that going to murder performance or not really affect anything?

tidal fable
#

why I can't I use transition animation on height?

#

I've made sure to use pixel units but it doesn't work

tall vortex
#

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);
small wigeon
#

have you tried changing virtualizationMethod to fixed height ?

tall vortex
#

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.

drifting glacier
#

.uss file contains a selector
UI Builder shows above selector applied to target element
UI Debugger shows selector not applied to target

dark blade
#

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?
tall vortex
dark blade
queen cedar
#

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();

thick widget
#

how could i move that letter to the front?

sullen bay
#

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.

sullen bay
sullen bay
#

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?

dark blade
dark blade
thick widget
dark blade
thick widget
#

The settings one

#

I've been trying to do it for two days 😅 @dark blade do you know what I mean?

rough scarab
#

Sort order is defined by the hierarchy, elements further down are displayed above

thick widget
#

It's supposed to be like that... but is not being applied in my case for some reason

thick widget
rough scarab
#

Yes, if something is above in the hierarchy then it's sorted below the other thing

tidal fable
#

is there a way to sandwich a gameobject between two visual elements?

undone blaze
sullen bay
#

Instead of nesting them

undone blaze
sullen bay
sullen bay
#

At least in the version I'm using

undone blaze
sullen bay
#

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

sullen bay
#

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

tidal fable
#

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

runic shuttle
#

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?

floral mauve
#

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?

fickle sleet
#

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]);
        }
    }
}

thick widget
#

Thank you soo muuchh!

#

That really helped me a lot

#

And one more thing... How could I add a 12px margin between both containers?

sullen bay
#

Or margin left

thick widget
#

something like this

#

but when i add it, the right container gets hidden...

sullen bay
#

There is no support for gap which is the idiomatic way in css

sullen bay
#

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

thick widget
sullen bay
#

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

thick widget
#

lemme try

thick widget
#

@sullen bay, I wanna add those margins

sullen bay
#

I don't know what you're asking

#

Just add the margins

#

margin: 6px

hollow halo
#

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?

GitHub

Render particle effect in UnityUI(uGUI). Maskable, sortable, and no extra Camera/RenderTexture/Canvas. - mob-sakai/ParticleEffectForUGUI

thick widget
#

And do you (or anyone else) know why I can't change the checked mark in a toggle?

sullen bay
#

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

thick widget
thick widget
sullen bay
#

Just the checkboxes themselves

#

They might have another element beneath them

#

Check one first too

#

in the debugger I mean, not the file

sullen bay
#

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

thick widget
sullen bay
#

It's the same I believe

#

although sometimes the pick element doesn't work properly and it just selects the game pane

thick widget
thick widget
sullen bay
thick widget
#

that's the toggle... tell me if you gess smth 😃

sullen bay
#

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

thick widget
#

let me see

thick widget
sullen bay
#

that overrides background-image

#
#Switcher #unity-checkmark {
  background-image: <your cool thing>
}
thick widget
#

that would be enought??

#

let me try :>

sullen bay
#

presumably?

thick widget
sullen bay
#

It's possible that the pseudo-selector just hides and shows the check element

thick widget
thick widget
# sullen bay Potentially not needed, just comment it out and see if it works

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); }

sullen bay
thick widget
thick widget
sullen bay
thick widget
#
.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 {
}
sullen bay
#
.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

thick widget
#

Thank you so much for your help

wheat scarab
#

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?

thorn ginkgo
#

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:

cursive quail
#

Hi ! Quick question: in Unity 6, we can

thick widget
#

why is that button active not working? I've changed tint property...

tall vortex
#

why is that button active not working? I

drifting glacier
#

Is there a way to do VisualElement::after{ content: "text" } in USS?

tall vortex
drifting glacier
#

hence the question

#

so, it seems the solution is to manipulate the elements in .cs

tall vortex
#

Since it doesnt exist, in uss it's not possible. you'll have to do it through c#

unborn bluff
#

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

rough scarab
unborn bluff
# rough scarab What do you mean by "An empty `CreateInspectorGUI()`"? Because if you either hav...

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;
    }
}
glacial verge
#

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

tidal crater
#

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.

tidal crater
#

Solved* just dont use viewDataKey use userData under visualElement .d

rough scarab
tidal crater
#

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 ?

tidal crater
#

I can't find what's wrong with my ListView class.

When I delete the first element, the second element also disappears.

tall vortex
tidal crater
#

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

queen cedar
#

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?

tidal crater
#

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

drifting glacier
#

Is there a way in UI Toolkit Debugger to add new style properties

tall vortex
tidal crater
#

@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

tidal crater
#

I looked in the past but couldn't find it.

tidal crater
#

@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

tall vortex
tidal crater
tall vortex
#

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

tidal crater
#

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

tall vortex
#

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

tidal crater
#

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

tall vortex
#

Yeah, it requires to recreate basic stuff. Not the quickest way for sure, but the simplest way to customise how my lists look.

tidal crater
#

You are absolutely right, let's see xd

tidal crater
#

@tall vortex hey again 😄 , do you have a proper solution for get actual visual elements related to list view item source datas

tall vortex
tidal crater
#

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

tall vortex
#

Ah right

tidal crater
#

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.

tall vortex
#

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")

tidal crater
#

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 😄

tidal crater
#

After scroll to index function there is still no update for elements what should i do to trigger their bind items immediately ?

tidal crater
#

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?

tidal crater
#

Does anyone know how I can trigger the on geometry changed event?
This is not triggered even if I do MarkDirty 😦

rough scarab
#

It's not bubbled, so the event must be subscribed to the specific element that changed

tidal crater
#

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 😄

rough scarab
#

Also, if you've subscribed via a non-allocating method multiple times then only one will register

slow bear
#

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.

potent ginkgo
#

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

dark blade
potent ginkgo
#

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

small wigeon
#

with an EventBase how to I get the element it came from?

small wigeon
#

oh, target?

copper spire
#

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

tranquil geode
#

Hey there, has anyone expierenced issues for when MarkDirtyRepaint() is called on a custom component then a video on the same panel stutters?

copper spire
dark blade
#

so what are you try to style?, the label, or the text inside the textfield

copper spire
#

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)

dark blade
#
.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
errant harbor
#

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?

copper spire
#

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

sullen bay
#

How do I bind to focus next/prev actions for UIToolkit?

#

i.e. change from default of tab/tab + shift.

sullen bay
#

WTF

#

How do you do navigation then?

#

This seems to be a lie, the WASD bindings just remove the current selection, they do not highlight the next one