#🧰┃ui-toolkit

1 messages · Page 9 of 1

dark blade
#

i did use its for label name, and i dont see any problem at least for now, except in uxml inspector its shown Sidebartitle and not SideBarTittle, probably i need those dash for name

#

but i just close the project for now, its 2 am in Bali now

dark blade
#

the things that always make me confused is, if my uss like this

* {
    margin: 0;
    padding: 0;
    border-radius: 0;
    border-width: 0;
    border-color: transparent;
}

.side-bar {
    padding: 5px;
    background-color: rgb(47, 47, 47);
    flex-direction: column;
}

.side-bar__element {
    background-color: rgb(32, 32, 32);
    border-width: 1px;
    padding: 5px;
    margin-top: 2px;
    margin-bottom: 2px;
    transition-property: border-color;
    transition-duration: 0.2s;
    transition-timing-function: linear;
}

.side-bar__element:hover {
    border-color: rgb(168, 255, 243);
}

.side-bar__element-button {
    width: 30px;
    height: 30px;
}
``` why my side bar are taking all the available space???, what i i want the size of size bar came from size of its child + its padding, where did i do wrong??, thanks
#

do i really need to spesify size of size bar???,

#

so, my side bar for now should have width of 35, and heigth of 400

vast maple
#

Hi, is there a way to render certain panels underneath canvas elements?

vast maple
#

but yea I guess you have to specify a max width/height

dark blade
gusty estuary
#

that's the only thing that applies size

#

everything else is irrelevant

#

use debugger to inspect why

stoic orbit
#

Hi!! I am new to using the UI Toolkit... actually I am playing with it and trying to make a custom editor for a scriptable object. I am having trouble with saving the values after they are changed inside the inspector... so for instance if I have a float field with a default value of 0, I change it to 10 from the inspector. The next time I click on that asset, it goes back to 0. I got comfortable with the styling part of the system... but am yet to learn how to use it with C#

#

some suggestions would be really helpful

#

🙂

dark blade
dark blade
dark blade
#

@gusty estuary sorry to ping, here is the current update of my "side bar" visual Element custom Control https://pastebin.com/hHJg2pph
got the error abount override content container and i believe this part

        VisualElement sideBarContentContainer;
        public override VisualElement contentContainer => sideBarContentContainer;

and the error is, what i am do wrong here?

gusty estuary
#

error says you are trying to parent object to itself

dark blade
#

so if i want visual element(in this case side bar element) when i drag to side bar custom control, its goes to side bar content container, what should i do?

stoic orbit
stoic orbit
dark blade
obtuse jay
#

I'm using the UI Builder. ¿How can I fix this field that doesn't fit in the canvas?
I want it to shrink so it fits. But the label (or space between the label and the input, not sure) doesn't shrinks.

#

Setting a max width prevent it from getting outside the box, but the input vanishes...

tacit dragon
#

How can you style the dropdown? Why is it even locked in the first place?

pliant mortar
#

Hello, from script, I would like to set label text color to a vertical 2 colors gradient. Could you please tell me if it is possible and how ?

dark blade
pliant mortar
#

It is not possible to set a Vertical color gradient to label from script ?

lapis topaz
#

Hey, I need to check is pointer over UI. Currently, I'm doing EventSystem.current.RaycastAll, which works fine, except it also raycasts on transparent VisualElemens with focusable property set to false. Is there any way to check if the pointer is over Visual Element that is marked as focusable / not transparent?
My UI check:

        public static bool IsOverUI(this Touch touch)
        {
            RaycastResults.Clear();
            var eventDataCurrentPosition = new PointerEventData(EventSystem.current)
            {
                position = new Vector2(touch.screenPosition.x, touch.screenPosition.y)
            };
            EventSystem.current.RaycastAll(eventDataCurrentPosition, RaycastResults);
            return RaycastResults.Any();
        }
static canyon
gusty estuary
#

you can also use panel method

#

to get visual element at coordinates

rose acorn
#

how to make numberOfSteps more than 11 in Scrollbar?

#

the initial number of steps is definitely more than 11

#

is it even possible?

gusty estuary
#

wrong chat

rose acorn
gusty estuary
#

wrong one

copper solar
#

quick question"

 var chatTab = w_TextChatWindow.Query(className: "chat-tab");

this searches fol all elemeents that have correct class.

  var chatTab = u_Patterns.Query(name: "-pattern");

this finds all that have namer -pattern. How should I write if I want to find names that contains "-pattern"? Or only way is to assign class to visual element?

gusty estuary
dark blade
#

            public override IEnumerable<UxmlChildElementDescription> uxmlChildElementsDescription
            {
                get
                {
                    yield return new UxmlChildElementDescription(typeof(SideBarItem));
                }
            }
``` i search in doc override this to decide what can add to custom control, but as for now, why im still able to add anything??, what can i use so my custom control only able to add spesific thing?
gusty vapor
#

yes it does

#

@copper solar see that

copper solar
#

Thank you. But what issue states was correct, as it does not have function "contains", so I need to check every string. So I could use where name contains specific string. I created more simple approach which works. But thank you for your help!

gusty vapor
#

you can do early exit too, with .First as the tail

gusty vapor
#

@gusty estuary proly knows

gusty estuary
formal wyvern
#

in my process in designing a weapons upgrade (or more like a customization) menu i stumbled upon Unity UI toolkit and the standard UGUI
what i got from my studies is that the Unity UI toolkit doesn't react to things such as light sources or world space event interactions (whatever that means)
if I were to make a UI that needs to see the weapon/character you're buildling then it's best i use UGUI instead right?

gusty estuary
#

ugui is game object based

#

with uitk you can only have pure UI in screen space

#

with uGUI you literally create game objects which are observable by camera, but act as ui. And thus also have all capabilities of game objects

formal wyvern
#

hm

#

in noob terms, what can I do w/ uGUI where uitk can't?

#

or are there things where ugui isn't necessary and i can do better with uitk?

gusty estuary
gusty estuary
#

when all you want is menu

#

settings and etc

#

uitk will do just fine

#

if you want some super specific style

#

or to use specific textures

#

you might want to go with ugui

#

uitk styling options are very limited compared to ugui

formal wyvern
#

righto

in cases where I want the stuff in the background be visible (but not interactable), ie semi transparent, would uitk do well or it's less hassle to do it with ugui?

gusty estuary
#

just fine

#

uitk is literally rendering over screen

formal wyvern
#

thabks

#

is it possible to use both systems and have a script handling the transition were I want to use functions limited to UGUI?

gusty estuary
formal wyvern
#

alright

#

so just use both at the same time?

gusty estuary
#

mixing two will be painful

formal wyvern
#

okay

#

for things such as "draw a "lookie here" tag" on top of a 3D object objective, i should use UGUI?

gusty vapor
#

quoting : UI toolkit doesn't react to things such as light sources or world space event interactions

Yeah, bcos UIToolkit can't do custom materials ootb for now...

#

they're working on it

#

and for your worldspace question, uitk can't do z order for now, so yeah, no worldspace ufortunately @formal wyvern

formal wyvern
#

thanks

#

i guess i'll fiddle with UGUI for most things except for the most simple ones

gusty vapor
#

for your use cases, just use UGui, yeah...

stoic orbit
#

hey guys!! I need some help with binding a ui element in c#... I am aware of the uxml way by using "binding-path" but I am trying to play with the C# style... am stuck😶... this is my code:
Editor:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;

[CustomEditor(typeof(TestScript))]
public class TestEditor : Editor
{
    public VisualElement root;
    public VisualTreeAsset main_window_uxml;
    public StyleSheet main_window_uss;

    public TestScript _target;

    public SerializedProperty serialised_FullName;

    public void Initialise()
    {
        root = new VisualElement();
        if (main_window_uxml == null || main_window_uss == null)
        {
            main_window_uxml =
                AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(
                    "Assets/--DEBUG_AND_TESTING/TestUI.uxml");
            main_window_uss =
                AssetDatabase.LoadAssetAtPath<StyleSheet>(
                    "Assets/--DEBUG_AND_TESTING/TestUss.uss");
        }

        main_window_uxml.CloneTree(root);
        
        _target = target as TestScript;
        
        serialised_FullName = serializedObject.FindProperty(nameof(TestScript.mFullName));
    }


    public override VisualElement CreateInspectorGUI()
    {
        Initialise();

        var fullnameTextField = root.Q<TextField>("f_fullName");
        fullnameTextField.bindingPath = "m_Fullname";
        
        fullnameTextField.Bind(serializedObject);
        
        fullnameTextField.RegisterValueChangedCallback(OnNameChange);
           
        return root;
    }

    private void OnNameChange(ChangeEvent<string> evt)
    {
        serialised_FullName.stringValue = evt.newValue;
        _target.DebugFullName();
         
    }
}
#

Monobehaviour Script:

public class TestScript : MonoBehaviour
{
    public string mFullName;
    public void DebugFullName()
    {
        Debug.Log("New Name: "+ mFullName);
    }
}

the uxml:

<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" xsi="http://www.w3.org/2001/XMLSchema-instance" engine="UnityEngine.UIElements" editor="UnityEditor.UIElements" noNamespaceSchemaLocation="../../UIElementsSchema/UIElements.xsd" editor-extension-mode="False">
    <Style src="project://database/Assets/--DEBUG_AND_TESTING/TestUss.uss?fileID=7433441132597879392&amp;guid=2df1d85562576e442a9bdbf169afe026&amp;type=3#TestUss" />
    <ui:VisualElement name="root" class="defaultLayout">
        <ui:TextField name="f_fullName" picking-mode="Ignore" label="Full Name: " value="Name: " text="" />
    </ui:VisualElement>
</ui:UXML>

vale charm
#

Question: Do I have to use UI builder to create a custom Inspector? I just want to use the default inspector with just a few added fields based on whats in a list.

#

Like say the List has 2 items. for each item in items, Create a Header, and then display the variable x and y

gusty estuary
#

you might just get away with custom property inspector for your specific item instead

#

no need to override whole script

vale charm
#

Not really sure where to start though. Can you point me in the right direction

lapis topaz
#

Hey, I need to send an event to all elements when the panel is hidden. I've tried creating my own event (inherited EventBase) and sent it though SendEvent, but it never gotten anywhere. Rn I'm doing query for interface, but maybe there's a better way of doing it, or I didn't get how custom events work

RootVisualElement.Query<VisualElement>().Where(element => element is IViewShownHandler).ForEach(
                element => { ((IViewShownHandler)element).OnViewShown(this); });```
#

For events I did

using var viewHiddenEvent = ViewHiddenEvent.GetPooled();
RootVisualElement.SendEvent(viewHiddenEvent);```
#

I event tried cs using var viewHiddenEvent = ViewHiddenEvent.GetPooled(); RootVisualElement.RegisterCallback<ViewHiddenEvent>(_=>print("test")); RootVisualElement.SendEvent(viewHiddenEvent);

#

test never gets to console

trail oasis
#

so i have a visual element and i set its width and height to 50% yet it seems to span the entire screen height - what am i doing wrong

#

the width worked fine

gusty estuary
trail oasis
#

why would it grow full height when there are no children elements

gusty estuary
#

Grow equals fill

trail oasis
#

oh

gusty estuary
#

And value is it's part (if there multiple grows)

trail oasis
#

whats the simplest way to just center the element on screen based on a size then

gusty estuary
#

If you want to simply center

#

Make parent do it insted

trail oasis
#

so an empty parent and center its content

gusty estuary
#

Kinda

trail oasis
#

im trying to create a ui of a fix width and height that appears in the middle of the screen

#

but this doesn't seem very simple compared to the old anchor setup

gusty estuary
#

I know

gusty estuary
#

I even have premade style class

#

That does it

trail oasis
#

im not sure i know how to setup the parent to do it either tbh

gusty estuary
#

Just look over style options in ui builder

#

I don't remember names at all

trail oasis
#

align and justify content i presume

gusty estuary
#

Yeah, I think those

#

You also want to define size of element precisely

#

So center is true

#

Position absoulte, width height 100%

trail oasis
#

i think i have it working now

#

seems i just need to make more child elements to align things

trail oasis
#

is there a way to combine ui together

#

such as if i disable a component i want to disable elements in the tree

#

seems to me i can only make one full ui thing and i can't seperate them into parts

dark blade
#

so still on my side bar custom control so as you see from uxml hierarcy, side bar has Register Callback when its click its will expand the side bar width, and the side bar item also has click event when its clicked its will invoke action, the problem is when i click on the side bar item instead of just invoke the action, the side bar click event also triggered, which lead to expand the side bar width, did try to use evt.StopPropagation() and evt.StopImmediatePropagation still the parent event triggered, what i am doing wrong?

        private void OnClick_Button(ClickEvent evt)
        {
            if (sideBar == null)
            {
                Debug.LogError("Bind Side Bar to use");
                return;
            }

            sideBar.ClickItem(this);
            evt.StopPropagation();
        }
trail oasis
#

so this is unity's idea of a ui toolkit demo to learn from

#

what an absolute mess

gusty estuary
trail oasis
#

i cannot figure out how that mess some how becomes a nice layout when you press play

#

its a complete joke

gusty estuary
trail oasis
#

thats the ui in the builder

gusty estuary
#

Ahem

trail oasis
#

how does all that suddenly become laid out nicely when i press play

#

makes no sense

gusty estuary
#

check other themes

trail oasis
#

wdym

gusty estuary
#

At top right

trail oasis
#

top right has no theme option?

gusty estuary
#

Only editor and default runtime?

trail oasis
#

oh

#

theres 3 others but they just swap out sprites

#

they dont change the mess hell that you see on the screen

gusty estuary
#

Yes

#

Well, they used very bad approaches

trail oasis
#

doesn't really tell me much on how this suddenly becomes nicely laid out when i press play

gusty estuary
#

when used themes

trail oasis
#

im looking at the code

#

i can tell you they dont do anything in the code other than assign events

gusty estuary
#

that's pretty much it

trail oasis
#

wat?

#

how would setting events make the layout work

#

that doesn't even make sense

gusty estuary
#

They disable some stuff

#

Keeping only necessary active

trail oasis
#

pressing play looks like this

gusty estuary
#

But I find it terrible approach

trail oasis
#

the code doesn't do anything

#

it just some how looks nice when you press play

gusty estuary
#

Open ui builder

trail oasis
#

i am trying to figure out wtf this system is doing

gusty estuary
#

Set resolution

#

is it better?

trail oasis
#

ah god damn it

#

thats what it was

gusty estuary
#

Check their panel settings asset

#

This will tell resolution they used when making ui

trail oasis
#

what does it mean when an element is greyed out

gusty estuary
#

?

trail oasis
#

like its disabled or something but i dont see a disable option

gusty estuary
#

Probably display style

trail oasis
#

display drop down is disabled too

#

🤔

gusty estuary
#

It's a style

trail oasis
#

theres no style sheet

gusty estuary
#

It disables drawing of element

gusty estuary
#

Or inlined

#

You can check when selecting it

#

Matching selectors

trail oasis
#

i think i might just go back to old ui this is so overly complicated

gusty estuary
#

Weak

trail oasis
#

its a mess theres no way to understand why something is disabled

gusty estuary
#

Demo is terrible

trail oasis
#

theres no style sheet so where would the global style even be

gusty estuary
#

Yeah

gusty estuary
trail oasis
#

sure but youtube is terrible too they only cover absolutely basic stuff

trail oasis
#

lol

#

the manual

#

good joke

gusty estuary
#

It's most up to date source

gusty estuary
trail oasis
#

i read that first before going on to the demo

gusty estuary
#

Out of everything

trail oasis
#

it doesn't cover everything not even close

gusty estuary
#

Only manual gave me proper understanding of uitk

trail oasis
#

well the themes isn't causing the elements to be greyed out

#

they just change the sprites

gusty estuary
#

Maybe, I am not aware how they manage it in this awful demo

trail oasis
#

how would you be even able to disable it in the builder

gusty estuary
#

I closed it as soon as I realised it's bad 🤣

trail oasis
#

since its not a game object i see no setting for disable

gusty estuary
#

From flex to None

trail oasis
#

display is also disabled

gusty estuary
#

Huh?

#

Oh

#

Bruh

trail oasis
#

the display settings are greyed out i cant change the display style

gusty estuary
#

Nvm this

#

It's element created via code

trail oasis
#

it cant be im not even running the game

gusty estuary
#

Uxnl has no access to it

#

Complex controls might create additional elements

#

Seems like they created screen as custom control

trail oasis
#

what

#

the whole tree is greyed out but the char screen parent has contents set to be visible

#

¯_(ツ)_/¯

gusty estuary
#

check what class this uxml belongs to

#

And find it in code

#

It creates all elements in constructor

#

i honestly don't like this approach

#

But it's valid

trail oasis
#

all i can find is this:

        // Toggle a UI on and off using the DisplayStyle. 
        public static void ShowVisualElement(VisualElement visualElement, bool state)
        {
            if (visualElement == null)
                return;

            visualElement.style.display = (state) ? DisplayStyle.Flex : DisplayStyle.None;
        }
#

kinda useless though as that shouldnt mean its disabled in the builder

#

preventing me from doing ant kind've edits

#

when not even in play mode

#

i checked the flex settings and thats not set to none

gusty estuary
#

It's not it

#

Display has nothing to do with it

#

Controls can create elements via code

#

And you can't modify those in uxml

trail oasis
#

wdym by controls

gusty estuary
#

Button

#

IntField

#

ListView

#

All thst

trail oasis
#

its just a uxml like the #HomeScreen is but that one is not disabled

#

even if by code - the game isn't running

#

right now no code is doing anything

#

i just want to know how its disabled in the builder

#

not during run time

gusty estuary
#

It's not disabled

#

It's just not available for overiding

trail oasis
#

how though

#

what did they do in the builder to do that

gusty estuary
trail oasis
#

it is an uxml

gusty estuary
#

Check option to show class

#

In hierarchy

trail oasis
#

you mean this?

gusty estuary
#

this is style

#

There's also class

#

C# one

trail oasis
#

but again this is for run time im not playing the game this code isn't running right now so its irrelevant

gusty estuary
#

No

#

That's not it

trail oasis
#

well what are you referring to then

gusty estuary
#

Button is a class

#

With uxml factory

#

I think this screen is same aproach

#

Hierarchy has an option to show assoiciated class

#

Somewhere

trail oasis
#

🤔 what

#

i have no idea what you referring to

#

i searched the code for char screen and only one file seems to be related to it lol

gusty estuary
#

you should read manusl 😅

trail oasis
#

the manual doesnt explain the demo

gusty estuary
#

It explains uitk

trail oasis
#

yes but not to this level of complexity

gusty estuary
#

this demo sucks

#

Don't do it same way

#

🤣

trail oasis
#

ok but im trying to know how they disable a simple element in the builder

gusty estuary
#

They don't

trail oasis
#

even you're struggling to explain which highlights how hard it is

gusty estuary
#

Check class IntField

trail oasis
#

i literally cannot change any values on the elements - they clearly have them disabled

gusty estuary
#

And it's constructor

#

They create label and some other elements inside

trail oasis
#

and they are all disabled

#

i cant change those element's values

#

i cant change their layout the text size or anything

gusty estuary
#

yes

trail oasis
#

so you agree they are disabled

gusty estuary
#

no

#

They are simply not created via uxml

trail oasis
#

so how are they created

gusty estuary
#

In code

trail oasis
#

because i already said the code is not running

#

so how come i can still see them in the builder

gusty estuary
#

Code is running

#

Uitk is c# based ui engine

trail oasis
#

if that were true there would be a script some where for it

#

but there isn't

gusty estuary
#

There is

#

Check VisualElement

trail oasis
#

thats pretty vague

gusty estuary
#

Everything inherits from it

trail oasis
#

which one

gusty estuary
#

Dud

#

Read manual on custom controls

#

This exolains it in depth with examples

#

I also suggest exactly 2022.2+ one

trail oasis
#

i already told this is the only script that even mentions character screen

#

but you keep saying there is some other script that doesn't appear to exist

#

if it exists i have no idea where it is or what its called

gusty estuary
#

That's why it's better to read manual before jumping into advanced framework usage

trail oasis
#

nevermind i'll ask on another server

#

im fully aware of what controls are and thats not relevant here

gusty estuary
#

Then you should be aware that listview creates tons of elements

#

same ss intfield

#

Oe any other field

#

And you also can't modify thel via uxml

trail oasis
#

not relevant though the docs clearly say we should be able to modify control properties

gusty estuary
#

but those are not controls

trail oasis
#

i can't do that second line because its all disabled

gusty estuary
#

they are sub elements

trail oasis
gusty estuary
#

Of main control

trail oasis
#

the controls manual says we can apply properties in ui builder

#

but they are all disabled

gusty estuary
#

you can't apply anything that is not defined by uxml

#

If your control crrates additional visualelement - it's read only

#

If you open uxml you won't see any of those

trail oasis
#

but theres no way to edit them because there is only one uxml file

gusty estuary
#

As they are part of runtime code (which also runs in ui builder)

gusty estuary
trail oasis
#

right but then they are not relative to the parent

#

so their layout is broken

#

eg if i open in isolation

#

the layout is all over the place

gusty estuary
#

👴

trail oasis
#

which is of little use if i want to align it based on the parent

#

without the parent its all overlapping and broken

#

like all the other elements

#

so i cant adjust it whilst its a child element to make sure its right

#

which is silly

gusty estuary
#

Create your own uxml

#

Add listview

#

And try to modify it's content

#

🙂

trail oasis
#

yeh modifying my own works fine

#

always has in other projects

gusty estuary
#

expand listview

trail oasis
#

but once its a child of another uxml i can't modify it and then i have no control over how to lay things out relative to the parent

gusty estuary
#

try to modify content

#

Not listview itself

#

Ah

#

I get it now

#

You can't modify children

trail oasis
#

yeah

gusty estuary
#

And uxml instance

#

Is creating them via code

trail oasis
#

but then how do you make sure the child layout works under a parent

gusty estuary
#

By parsing uxml

#

If you want to modify uxml - open actual one

#

Not the one that simply instantiated it

trail oasis
#

i see

gusty estuary
#

Ui builder does not support overrides yet

#

But uxml does

#

Surely, tricky engine part is not explained in manual, but template instancing is

#

so I stand by my words - manual is best and seems like the only way to underdtand uitk

#

Atm

trail oasis
#

most of it makes sense though some parts become quite technical

dark blade
#

Repost:
so still on my side bar custom control so as you see from uxml hierarcy, side bar has Register Callback when its click its will expand the side bar width, and the side bar item also has click event when its clicked its will invoke action, the problem is when i click on the side bar item instead of just invoke the action, the side bar click event also triggered, which lead to expand the side bar width, did try to use evt.StopPropagation() and evt.StopImmediatePropagation still the parent event triggered, what i am doing wrong?

        private void OnClick_Button(ClickEvent evt)
        {
            if (sideBar == null)
            {
                Debug.LogError("Bind Side Bar to use");
                return;
            }

            sideBar.ClickItem(this);
            evt.StopPropagation();
        }
``` sorry keep asking this, because this looks so basic but still cant figure out, and i guess many people also want to know
gusty vapor
#

did you set the pickingMode ?

wide spoke
#

Is there any known bugs about the Tmp text changing it's positioning when played after a plastic scm import?

pliant mortar
#

Hello. I have a label. I want to center it on screen, so I set:

  • position = absolute
  • left = 50%
  • top = 50%
  • align = center
  • Transform.Translate (-50%, -50%).
    Now the text is correctly centered.
    Now I would like to have a transition effect: The text comes from the outside on top of the screen and scroll to the center of the screen.
    To do that, from a script, I set the label Top = 0 and then I set the Transition Animation top duration = 3s, and then I set the label Top = 50%.
    I can see the label move from 0 to center in 3s.
    The problem is that, at 0, I can see the half of my label because of the Translate Y -50%.
    Instead of 0, I need to init the Top to (0 - "Height of the Label" / 2).
    Could you please tell me how to do that ?
gusty estuary
#

and when you remove it

#

transition animation will animate from this -50 to 50%

pliant mortar
gusty estuary
#

whatever animated container is

pliant mortar
pliant mortar
#

If my label height is 30px and my screen height is 400px if I set top to 50% it if 200px. Right ?

gusty estuary
#

top is local to existing container

#

so if your container is size of screen

pliant mortar
#

I'm in absolute position

gusty estuary
#

then 0% will mean at the top

gusty estuary
pliant mortar
gusty estuary
#

height has nothing to do with it

#

top specifies distance to top point

#

so as long as you specify top bigger than your label

#

at the start

#

it'll appear out of nowhere

#

when aniamted

pliant mortar
#

Ok I try

gusty vapor
gusty estuary
#

it will be outside of screen bounds

#

so it will be out of nowhere

#

no matter what

pliant mortar
gusty estuary
#

then specify top accordingly

pliant mortar
#

This is my first question

#

how to specify the top, as it is dependant of the label size

gusty estuary
pliant mortar
# gusty estuary try specifying bottom isntead then

It doesn't work, I still dependant of the size of the label... I need to center it on screen. I don't see a way to position it outside of the screen and then make a transition to the middle of the screen without using the size of the label somewhere.

gusty estuary
pliant mortar
gusty estuary
pliant mortar
gusty estuary
#

there's literally style for that

pliant mortar
gusty estuary
#

open ui builder

pliant mortar
#

It is more a parent property no ?

#

I'm in

gusty estuary
#

and simply look at text section

pliant mortar
#

Align ?

gusty estuary
#

I don't remember names

pliant mortar
#

It's to center the text in the label area, not in it's parent

gusty estuary
#

oh

#

if you want that

#

if you need to apply some styles to parent instead

pliant mortar
#

The parent let the child processing it's transition from top to middle ? What property hsould I use for the transition ?

gusty estuary
#

in parent element

#

align I think?

#

2 styles

#

1 to align vertically

#

and 1 to allign horizontally

trail oasis
#

is there a way to make the parent element expand horizontally or vertical based on the child elements

#

i want to add buttons dynamically and make sure the container grows to accomodate how many i add

#

right now it doesn't stretch horizontally

#

i got flex grow set to 1 thought that would solve it but evidently not

trail oasis
#

no that just makes the visual element the entire width of the screen

#

or does auto constrain to the min/max

#

i was hoping it would auto choose the smallest

#

so i didnt have to set a min/max

gusty estuary
trail oasis
#

for example constrained width but no constrained height

#

it defaults to full height which is weird

gusty estuary
#

Parent style also affects layout

trail oasis
#

that is the parent

#

my tree is:

visual element¬
button
button
etc

gusty estuary
#

to affect how buttons size (with auto size) you set parent style

#

If parent is at root - you need to manually set size

trail oasis
#

oh it cant auto calculate the height from the children and padding/margins ?

gusty estuary
#

Or create additional fullscreen pare t

trail oasis
#

well no because it went full height by default

#

instead of stopping once it encapsulated all the buttons

gusty estuary
#

Do you have flex grow?

#

It forces full fill

trail oasis
#

yeh i have grow set to 1

#

because i want it to grow horizontally

#

i put direction to row

gusty estuary
#

Horizontal fill can be controlled by parent

trail oasis
#

i see

#

thats fiddly

gusty estuary
#

I believe it's copied from css? Could be wrong

trail oasis
#

what about padding between each button

#

would that have to be applied to each button

gusty estuary
#

Sadly there is no spacing in uss

trail oasis
#

i see so each button has to have its margins set

#

i guess i'll make them their own ui document and copy paste

gusty estuary
#

Or you can make custom control which adds empty spacings inbetween

#

i had that idea for a while

#

But didn't get to use it

trail oasis
#

by the time i get around to doing it i would not be surprised if unity adds some kinda grid element

#

to do it for us

#

which is what typically happens after wasting my own time writing my own

gusty estuary
#

Maybe it's already written, but not exposed to ui builder

#

This is a case for a bunch of elements

trail oasis
#

seems they working on it

#

Soon tm

gusty estuary
#

Under consideration

#

😅

#

means totally not soon and no promises

dark blade
rough scarab
dark blade
rough scarab
#

yes

dark blade
#

thanks

gusty vapor
#

btw, that's a workaround, it shouldn't be like that in css even

#

or use justify + flex-wrap on the parent, and pick the space-between for the justify, I forgot what it's called you should check

trail oasis
#

i see

#

im just trying different combinations to see how it works

gusty vapor
# trail oasis yeh i have grow set to 1

you can set flex-grow to 1 but set the initial size + padding preferably (roughly)smaller than the child so it would expand. Then set flex-grow on the children as well with 100% width and whatever height value, then justify to center or flex-wrap should work

#

that's not how supposed to be done in css even, they're working on it (hopefully)

gusty estuary
#

And here you suggest some monstrocity

#

Why

#

👴

gusty vapor
#

🥳

dark blade
# rough scarab *yes*

below element still trigger its callback, here the scripts

        public SideBar()
        {
            this.AddClasses(ussClassName, activeClassName);

            StyleSheet styleSheet = AssetDatabase.LoadAssetAtPath<StyleSheet>(ussFilePath);
            this.styleSheets.Add(styleSheet);

            elementContainer = new VisualElement()
            .SetName("side-bar__title-container")
            .AddClasses(elementClassName, titleContainerClassName);
            hierarchy.Add(elementContainer);

            // button = new Button(On_ClickSideBar)
            button = new Button(() => Debug.Log("Test"))
            .SetPickingMode(PickingMode.Ignore)
            .AddClasses(buttonClassName);

            icon = new VisualElement()
            .SetName("side-bar__icon")
            .AddClasses(buttonIconClassName);
            button.AddElement(icon);


            titleLabel = new Label()
            .AddClasses(labelClassName, titleClassName);

            elementContainer.AddElement(button, titleLabel);

            separator = new VisualElement()
            .SetName("side-bar__separator")
            .AddClasses("side-bar__separator");
            hierarchy.Add(separator);

            sideBarContentContainer = new VisualElement()
            .SetName("side-bar__content-container")
            .AddClasses(contentContainerClassName);

            hierarchy.Add(sideBarContentContainer);
            this.RegisterCallback<ClickEvent>(evt => On_ClickSideBar());
        }
``` as you see button currently only do log when its click, and base element has Click Event when its click the width of side bar will expand, but when i clicked button, not just log test, its also expand the side bar, so clearly the event on base element still triggered, what  am do wrong? thanks
gusty vapor
#

set it the picking mode to position instead

#

hmm... that fluent extension you're using looks very familiar 😃

dark blade
gusty vapor
#

did you also stopimmediatepropagation?

dark blade
#

button doesn't have evt came as parameter, unlike using RegisterCallback, so im not call evt.StopPropagation or Immediate Propagation

#

but i believe, did try before i change button as Button from just Visual Element, and still the event triggered

#

is there not any built in from unity, like when we use Unity UI, its has Block Raycast and if we tick, the below Ui will no interact

gusty vapor
#

that's what basically pickingMode is for

#

as said bu the other guy before too

#

button.clicked already has stoppropagation, so it's mostly related to your setup

dark blade
#

hmm, weird....currently

``` this removed from my side bar, and let side bar icon button, do the job for expanding or not the side bar, but i just think will be great if click anywhere inside the side bar just not any button or other child element has event callback, do the expanding side bar
#

anyway leave for now, i will came asking later on....

#

thanks

quasi forum
#

You guys, how do I expand/edit the dropdown choices here in the UI toolkit?
I can only edit the dropdown itself but not the choices(the part circled with blue)

gusty vapor
#

iirc dropdowns are generated on runtime and it's very tricky to know which one when using debugger due to UIElements.DropDownMenu and it's container aren't derived from VisualElement class.

#

I heard they're planning to changed it to the generic version, and if so, you can peek all of them through debugger with no problem

quasi forum
#

Looks like extra work. For now I'll stick to uGUI.

gusty vapor
#

it is yeah, that's the nature of uitk at lest for now... hope they would make it much easier in the future

dark blade
# quasi forum Anyone?

did check, and i think currently you can't style that, custom control probably the best thing you could do atm

teal belfry
#

if Display is set to none

#

is it still interactable

mellow silo
#

Why does the view of the UI in the UI builder view never match the size of the UI in the main editor's Game view? I have "Match Game View" option turned on, and everything is on the canvas in UI-Toolkit, so I don't know what could be happening.

serene harbor
#

Hi everyone, I wanted to ask about some help with the resolution / display used for UI toolkit. I'm building a simple app for android and testing it on a Galaxy Note S9, the resolution for this phone is listed online as 2960x1440 pixels. When putting this into the game view and testing it in Unity my screen looks like this:

#

However, when building it and running it on the phone, the screen is compressed and zoomed very far in.

#

I'm a bit confused for why the scale is so completly different on the build when the same resolution in the editor seems to work fine without an issue. Any help on solving this would be appriciated.

worthy beacon
#

Maybe you set sizing to auto. Have you checked with the intended reso on the sim?

mellow silo
rancid jolt
#
  • I am going to use ui toolkit for an inventory ui. Obviously i need a responsive item counters and stats. Should i bind my inventory cell objects to visual elemetns via unity's api, or do it manually with c# events? I heard that binding is heavy, and in my case there are going to be a lot of objects to bind
rancid jolt
#
  • Ah, missed that. So custom event buses it is then. Thank you
unborn bluff
#

I have a custom element with a label inside how do I update the label when the element is repainted using VisualElement.MarkDirtyRepaint?

#

I can't do it inside GenerateVisualContent, so is there another method/event?

gusty estuary
#

just update label's text

#

myLabel.text = newText;

serene harbor
gusty estuary
#

I think your theme is wrong

fossil stag
#

Hi! is there a way to Serializefield a value like a List of ScriptableObject in a custom EditorWindow? Thank you

serene harbor
# gusty estuary I think your theme is wrong

What do you mean by this? The font should just be the default font built in to Unity since I havn't changed anything? Why would that also change the size of the text if the text size is the same?

gusty estuary
#

also

#

for proper resolution you should use % based styles

#

and select matching scaling type in panel settings

#

for text

unborn bluff
#

Is there something else called when it's bbeing redrawn?

gusty estuary
#

don't touch low level stuff

unborn bluff
#

I have a custom element to show some custom value and I want to show the max amplitude

gusty estuary
#

That doesn't explain why you can't just apply value to label

serene harbor
# gusty estuary

Ahh, good point. I'll move over to percentage based sizes. Do you know what axis the percantage is taken from? With my lacking knowledge of css you could do vw or vh, but it doesnt seem to let you do this in Unity

unborn bluff
unborn bluff
#

Maybe I 'm just not in the right mind right now 😛

gusty estuary
#

%'s are usually based on parent container

gusty estuary
serene harbor
#

I know, but if you have a container that is 200px by 200px, but then shrink it to 50px by 200px then the container has shrunk to 25% its size vertically, but remained the same horiztontally

#

So for the text, I am unsure on what the percentage size really means in terms of relation to the parent

gusty estuary
#

oh, it's always using matching axis

serene harbor
#

Does it take a percentage size from the height, or width. or does it combine both

#

matching axis?

#

Sorry I'm quite new with this stuff

gusty estuary
#

it takes value from parent

#

so width = 50%, will mean 0.5f*parent.width

serene harbor
#

for the text size though its a single field is it not?

gusty estuary
#

for text you use px

serene harbor
gusty estuary
#

panel supports text scaling

serene harbor
#

My panels all use percentage, but if its the text thats driving it then that could be why they are forced to expand

#

This is my panels settings, there using percentages for the size

gusty estuary
#

by Panel I mean IPanel from uitk

#

inspect your UIDocument

#

and see panel settings asset yourself

#

there you will find scaling options

#

but keep in mind, so far it only works for text (maybe something else, but I haven't noticed)

serene harbor
#

Ah thank you, Scale Mode was on constant physical size

#

Ive set this to Scale with screen size now

#

Im going to do a quick build now and see, thank you for your help ^-^

#

Working perfectly now

#

Thank you

teal belfry
#

so I have a scrollview

#

I want to be able to click a button and it goes to a certain part of the scrollview...is there a way to do this?

#

aka when it opens it starts, say scroll midway, or scroll all the way down

gusty vapor
#

you can use ScrollTo to scroll to the child element

trail oasis
#

am i dumb, but when i click a ui toolkit element its not blocking the raycasting in the actual game like old ui system does

#

is there some toggle to deal with that

worthy beacon
worthy beacon
trail oasis
#

tbh im very confused with how the ui works

#

i made a container and saved it as a document then i imported it in another document

#

now i want to drag buttons into said container

#

but it wont adhere to the layout i had set

#

so it doesn't really work like a prefab

#

when i made iconswapper i told it to make the child elements align horizontally and wrap around

#

so now i add 2 slots in another document and it ignores the layout entirely

trail oasis
#

just the ui system is confusing to setup

#

i dont think it works like prefabs in the rest of unity

#

either that or its bugged

#

is a template instance specific to the current document or will editing effect all documents that use that template

gusty estuary
#

You can only implement overrides

trail oasis
#

So how do you make dynamic prefab ui components

gusty estuary
#

what is Exact use scenario?

trail oasis
#

Item container to populate at run time but I want the item container in different documents for different menus

gusty estuary
#

Oh

#

why overrides not enough then?

trail oasis
#

as per the image above it ignores all the settings of the alignment i had

#

the overrides seem to be a parent element in the template so it doesn't work properly

#

i made the document set icons to span horizontally and wrap around

#

then i put the document in as a template and added icons and it no longer spans horizontally

gusty estuary
#

I'm not sure you did everything correctly, templatt instance is just same as any other control technically

trail oasis
#

no because when i drag it in it is a child of some other element for some reason

#

the settings i set was set in the child element with the red arrow

#

but because i cant add icons to it - i can only add it to the parent version it ignores what i set

#

the way i did it was made the container and saved as template - then i added it to my new document

#

then added the two icons as child elements and as you can see they stack vertically

gusty estuary
#

Wait

#

You add to uxml

#

You should not do that lol

trail oasis
#

but the icons need to align based on the settings i put in the template

#

how else are you suppose to do it

gusty estuary
#

make a template, instantiate, override

#

No nested templates

trail oasis
#

when you say instantiate do you mean drag it into the hierarchy ?

gusty estuary
#

Did you read manual on instancing?

#

It has examale

trail oasis
gusty estuary
#

But not into another template

trail oasis
#

no its inside my ui document

#

which contains two templates

gusty estuary
#

Oh

#

Yeah, sorry

trail oasis
#
visual element¬
     template 1 : icon swapper¬
                template 2: icon
                template 2: icon```
#

thats the layout but icons are ignoring the template 1 alignment data

gusty estuary
#

if you swap your templates with other elements, does it behave the same?

trail oasis
#

yeah

#

it seems to ignore the align data of the template

gusty estuary
#

If it acts the same

#

Then it's not template

#

It's your alignment

#

Template is no different to VisualElemnt

#

Same thing

trail oasis
#

let me show you images of it so you can see what i mean

#

ill post some images later i got work to do atm -_-

gusty estuary
obsidian sedge
#

Hey folks, I'm working on building a game for Android, but I'm running into some trouble. I've made a UI using Visual Elements , but it's not rendering properly with OpenGLES3. Anyone got any ideas on how to fix this?

gusty vapor
teal belfry
rancid jolt
#
  • A quick question about uss: where do i define a variables so that they're visible everywhere, just like built-in ones?
gusty estuary
#

but don't think any intellisense will pick it up

rancid jolt
# gusty estuary add uss to theme asset
  • As far as i read, i have to create a new tss file, inherit it from the default theme asset and add my variables in there. In case it's right, how do i inherit? I don't see any tss files other than mine in the whole project
gusty estuary
#

it's pretty straightforward

rancid jolt
# gusty estuary it's pretty straightforward
  • Maybe it is for you, but not for me. How do i locate default themes? Importing the path specified in the documentation did not work, and the assets in the selection window are not found
    @import url("Assets/UI Toolkit/UnityThemes/UnityDefaultTheme.tss");
gusty estuary
#

default theme is globally accessible

#

and for some reason it also duplicates itself

rancid jolt
#
  • So far i've been prototyping with borders and background colors, but now i want to replace it with textures. The problem comes with aspect ratio
    If i set fixed size, it obviously doesn't scale with different screen sizes
    If i make it scalable, the image is stretched, hence borders are below, not around the elements
    I can't use 9-sliced etc., because the image is not optimized for this

  • So how can i get around this? In a nutshell, i need to make a scalable image, preserve its aspect ratio while also making sure that all children elements are aligned properly inside of it

gusty estuary
#

I never managed to create a proper health bar

rancid jolt
#
  • So i should stick to either no textures or fixed size elements?
gusty estuary
#

but so far with uitk best achieved via vector graphics

#

(best relative to uitk)

#

it's not mature enough, so styling options are really lacking

teal belfry
#

Did youever do this?

lean barn
# teal belfry Did youever do this?

Hello, nope I didn't had the time to do it. I made a small changes to the gist because I found something really annoying during a game jam but no optimisation yet

teal belfry
#

modified your file anyway so it prints like this

#

not sure why the public variables were in it tbh 😄

lean barn
teal belfry
#

ah that makes sense then

lean barn
#

And also because the auto generated classes are overrided pretty often so I don't want to store anything custom inside

teal belfry
#

makes sense

#

I just plan to copypaste the stuff from generated classes into new class anyway

lean barn
#

I see, I could also make partial classes so you can inherit from them but the names of the classes are a bit weird in that case

teal belfry
#

😄

#

I could barely figure out how to modify the other file to print it out like this lol

lean barn
#

It's made to fit in a single file so yeah it's a bit compressed

teal belfry
#

I was only trying to change lines like 200 and down anyway lol

#

which was the easy stuff 😄

teal belfry
#

I feel it would be fairly easy...but I barely understand how this works lmao

lean barn
#

It's probably the simplest solution without breaking anything with retro compatibility

#

The IDs are also inside the queries so might be doable even without writing anything extra 🤔

teal belfry
#

what if I just change this

#

that would make it so the script "ends" if the file exists already right?

lean barn
#

Yes, but it will never update even if you add new auto-reference class

#

It will just work the first time

teal belfry
#

awesome

#

that would be a huge speed increase though right?

#

since almost all code wont execute if the file exists?

lean barn
#

Depends the size of your UIDocument I guess, I didn't had much waiting time on the game jam I was talking about but I need to try with bigger files

#

But yeah the GenericScriptContent method is probably the most taxing one

#

Also I could try to make the writing of the file async, I don't remember if Unity support that

teal belfry
#

normally takes 5s to save/generate file for one doc

#

now takes 0s if script already exists 👌

trail oasis
gusty vapor
#

show me the code for your mouse event

#

did you stop the propagation or nah?

lean barn
teal belfry
lean barn
teal belfry
lean barn
#

But in the gist case it's simply native c# async stuff

teal belfry
#

guessing thats just cause unity is dumb and refreshes a bunch of stuff when something changes

lean barn
#

Nothing should change at least in the script 🤔 it wasn't reloading on my side

#

Oh but you are changing the script after it's generating right?

teal belfry
vital raptor
#

good evening everyone. how can i add an input overlay of mouse and keyboard on screen while using my project.

gusty estuary
#

input overlay?

#

what's that?

vital raptor
gusty estuary
#

oh

vital raptor
#

input (keyboard and mouse) overlay

#

so that when I press a key it highlights in the overlay

gusty estuary
#

there is no built in functionality

#

so you gotta implement it on your own

teal belfry
gusty estuary
#

yeah, honestly it's up to user to use those

vital raptor
#

otherwise I need to make an info menu to show the user which buttons to use within the project. So maybe it is more convenient. Then illustrate that we move with WSAD etc.

gusty estuary
#

usually there are tutorials for that

trail oasis
#

how do you center the root visual element center of the entire window

#

i tried 50% top on the position settings

#

but thats not factoring the size of the actual element

#

i found how to center horizontally using align self but not vertically

gusty estuary
#

and use both align styles in it

#

to make children elements appear in center

trail oasis
#

ah ok

fast escarp
#

Hello, anyone know how to fix this rich text problem?

fast escarp
#

some tags works some tags doesnt, seems pretty random

rancid jolt
#
  • When i set panel settings to scale with screen size, is it affected by the game's view resolution option?
gusty estuary
#

yes

candid eagle
#

I have a label with rich text. I have an anchor tag with href set to "link-test". It display as a link, how do I intercept a click on actual anchor content instead of the whole label? And how do I extract data from the click, like the value of the href attribute?

candid eagle
#
if (App.User.IsAuthenticated)
{
    var usrMsgLabel = RootElement.Q<Label>("user-msg");
    usrMsgLabel.text = $"Hi, {App.User.Name}. <size=15><a href=\"test-link\">Not you?</a></size>";
    usrMsgLabel.RegisterCallback<PointerDownLinkTagEvent>(ev =>
    {
        Debug.Log($"Event: Link Text: {ev.linkText} | Link ID: {ev.linkID}");
    });
}
else
{
    AppUI.Modal<UserAuthView>(false);
    App.User.OnLogin += OnUserLogin;
}

And it does style the Not you? like a hyperlink. But the mouse cursor doesn't switch to pointer and the PointerDownLinkTagEvent isn't triggering either. Is there another way to achieve what I'm trying to do here?

trail oasis
#

is using monobehaviour the way to animate things like progress bars based on game code or does unity have some new setup for all that

#

i know there is transition stuff but that doesn't seem like its for actually relating to game code

gusty vapor
#

you can use transitions to animate your uis.. it's a pain to use tho

#

the easiest is to interpolate the style values like you usually would via Upadate

#

keep in mind that both would mostly likely trigger the mesh bug, you'd notice that your verts count get multiplied to a massive amount

gusty estuary
trail oasis
#

seperate how ?

gusty estuary
#

Unless ofc your progress bar for example is self sufficent (like windows xp one which simply loops)

trail oasis
#

just wasnt sure if i should be using update or late update or what

#

or if there is an entirely different ui update function im not aware of

gusty estuary
#

You can change data on elements at any points

trail oasis
#

yes but what is best practice

gusty estuary
#

It's layout calc is asyn mostly

trail oasis
#

does ui update every update frame

#

because if not then i dont see the point in using update

gusty estuary
#

It does, but heavy work only done on changes

#

Best practice is to have 1 way interaction with ui layer

#

You only send data when you want ui to change

trail oasis
#

well yeh why would you send data if its not changing 🤔

gusty estuary
#

You check yourself whether new value is same as previous

#

To avoid wasteful calculation

#

Of layout

trail oasis
#

well sure - though that is a bit of a micro op for me right now

gusty estuary
#

I'm just providing concept here

trail oasis
#

just was surprised we still have to use monobehaviours in the heirarchy when the ui has been seperated into ui documents

gusty estuary
#

So you avoid doing bad practice later

gusty estuary
#

But monob is just most convinient for unity

trail oasis
#

well theres no other kind've update loop provided by unity outside of a monobehaviour for ui documents

gusty estuary
#

it's 0 overhead anyway compared to ui gui

trail oasis
#

schedule ?

gusty estuary
#

It's property

#

Lets you make some element loops

#

but honestly, I find this a bit anti pattern

trail oasis
#

i see

#

its annoying that there is a style.width and a bounds.width and a resolvedStyle.width

#

why must there be so much bloat like that -_-

gusty estuary
#

They are different

#

I avoid using those

#

And instead rely on high level styles

trail oasis
#

are we not suppose to use resolvedStyle.width?

#

what would you use to adjust a progress bar width

gusty estuary
#

Feel free to use it, but

#

My only use case for it

trail oasis
#

whats the alternative?

gusty estuary
#

Is when I made square element, which made itself square

gusty estuary
#

But it's a bit of exception

#

Because built in progress bar is dogshit

trail oasis
#

it wouldn't let me use that for some reason

gusty estuary
#

Whicj can't be properly styled

trail oasis
#

the only way i could even use a width like that is this stupid syntax :

_bar.style.width = _bar.parent.style.width.value.value * (percent / 100f);
#

for some reason i have to do .value.value just to be able to do any math to it

#

totally stupid

gusty estuary
#

If I was to do it properly I'd make custom control with high level property for fill value

trail oasis
#

so they could've overloaded the operator

gusty estuary
#

You have to provide proper type

trail oasis
#

why wouldn't width be a float

#

why does it need a custom type

gusty estuary
#

It's runtime style

#

Which are created from uss

trail oasis
#

i would've preferred .percentageWidth and .pixelWidth personally

gusty estuary
#

it also has shitload of other options

trail oasis
#

not this .value.value nonsense

gusty estuary
trail oasis
#

yeh and is a lot easier

gusty estuary
#

Style.width is direct style accesor

trail oasis
#

yeah but you can't do much with it

gusty estuary
#

Nothing stops you kek

trail oasis
#

i dont want to be writing code for ui it should be there for me so i can make games -_-

gusty estuary
trail oasis
#

you can't

#

you can't do any math with it you have to extract the raw value first

gusty estuary
gusty estuary
#

This is anti pattern

#

Besides

#

For raw px

#

Go for resolved style

trail oasis
#

because this should just work: float ratio = _bar.style.width / _bar.parent.style.width;

gusty estuary
#

this is anti pattern

trail oasis
#

instead it has to be like this:

float ratio = _bar.style.width.value.value / _bar.parent.style.width.value.value;
gusty estuary
#

You rely on ui code

trail oasis
#

you cannot tell me that is better ^

#

the latter is terrible abstration

gusty estuary
#

I would't do it at all

trail oasis
#

its not anti pattern is pretty understandable i want to divide the two widths to get a ratio

#

you literally just said you use style.width 2 minutes ago

gusty estuary
#

I set up all ui ratios in uxml

trail oasis
#

🤔

gusty estuary
#

And in code I only set % of width

trail oasis
#

the ratio changes every frame based on progress bar

gusty estuary
#

From 0 to 1

#

Which represents progress of my loading

trail oasis
#

i display the text by doing ratio*100+"%"

#

the only way to know the true % is divide the two widths

gusty estuary
trail oasis
#

it is just box filling left to right

gusty estuary
#

so I suggest to just write a custom control for it

gusty estuary
trail oasis
#

works perfectly fine but your suggesting to use uxml for some reason

gusty estuary
#

where you set % values

trail oasis
#

no you can't use style.width i just told you that

gusty estuary
#

Then I guess my progress bar does not work 😅

trail oasis
#

it literally wont allow you do calculate the % with it

#

do you want me to show you the error

#

to prove it

gusty estuary
#

I don't calculate anything

#

I just send value to it

#

I never use getter property

trail oasis
#

i have to use resolvedWidth

gusty estuary
#

see, you are trying to do some calculation of layout

trail oasis
#

yes

gusty estuary
#

why?

#

just set width value

#

let engine do it for you

trail oasis
#

because the script doesn't know the % it only knows the progress bar's width

#

even if i set the width i need to know the % by calculating its relative width to the parent

gusty estuary
#
        private float _storedValue;

        public float LoadingValue
        {
            get => _storedValue;
            set
            {
                if (Math.Abs(_storedValue - value) > 0.1f)
                {
                    _storedValue = value;
                    SetValue(value);
                }
            }
        }

        private void SetValue(float value)
        {
            _bar.style.width = new Length
            {
                value = value,
                unit = LengthUnit.Percent
            };
        }
#

here all I do

trail oasis
#

mines a bit more compelx than that

gusty estuary
#

<ui:VisualElement name="loading-bar" style="background-color: rgb(49, 255, 0); height: 100%; align-self: flex-start; width: 50%;" />

#

here all uxml required

trail oasis
#

my bar lerps to a new percentage based on its previous position at a normalised speed

gusty estuary
trail oasis
#
    /// <summary>
    /// Animate to percentage
    /// </summary>
    /// <param name="percent">A value between 0 and 100</param>
    public void AnimateTo(float percent)
    {
        percent = Mathf.Clamp(percent, 0, 100);
        _target = _bar.parent.resolvedStyle.width * (percent / 100f);

        float span = Mathf.Abs(_target - _startVal);
        _tSpeed = _speed / (span / _bar.parent.resolvedStyle.width);

        _t = 0;
        _startVal = _bar.resolvedStyle.width;

        enabled = true;
    }
gusty estuary
#

you are trying to rely on values calculated by layout

#

this is super fragile at least

trail oasis
#

if you set the width by applying the value how does it know you're giving it a % and not a pixel

gusty estuary
#

look at my code

#

I provide specific type

trail oasis
#

oh i see

gusty estuary
#

it actually gets implicitly converted

#

because original is StyleLenght

#

which also has a bunch of properties

#

but they are not relevant

trail oasis
#

so i might not need to care about the true pixel widths

#

i might try refactor it then

gusty estuary
#

you don't care about anything inside UI elements

#

with proper pattern you only set values to it

#

1 way direction data flow

#

(only exception to it are callbacks)

trail oasis
#

if you get the value style.width will it automatically be percentage then

#

since thats what you set it to be

gusty estuary
#

you'll get style applied to it

#

if it was set as %

#

it'll be percent

#

if it was set as px it'll be pixel

trail oasis
#

i see

gusty estuary
#

and I advice against using getter of it

trail oasis
#

so then how do you get data from elements

#

because inventory slots you might want to know their positions for drag and drop etc

gusty estuary
#

or potentially other system integrated into whatever you use to manage your ui

#

That convo I talked about concepts more

#

because you don't really want your game logic code to reference UIElements namespace

trail oasis
#

i read the docs and dont recall them talking about manipulators

gusty estuary
#

(what if you later would want to switch UI to ugui?)

trail oasis
gusty estuary
trail oasis
#

you'd have to use that namespace to even query for elements

gusty estuary
#
    public class LoadingScreenPresentation : MonoBehaviour
    {
        private UIDocument _doc;
        private VisualElement _bar;

        private void Awake()
        {
            _doc = GetComponent<UIDocument>();
        }

        private void OnEnable()
        {
            _bar = _doc.rootVisualElement.Q<VisualElement>("loading-bar");
            SetValue(LoadingValue);
        }

        private float _storedValue;

        public float LoadingValue
        {
            get => _storedValue;
            set
            {
                if (Math.Abs(_storedValue - value) > 0.1f)
                {
                    _storedValue = value;
                    SetValue(value);
                }
            }
        }

        private void SetValue(float value)
        {
            _bar.style.width = new Length
            {
                value = value,
                unit = LengthUnit.Percent
            };
        }
    }
#

this is service class

#

my game logic knows nothing about UIElements

#

it just accesses this class

#

and sets LoadingValue

#

for even further abstraction, I can implement interface

trail oasis
#
        private UIDocument _doc;
        private VisualElement _bar;

these are part of UnityEngine.UiElements namespace

gusty estuary
#

with float LoadingValue property

trail oasis
#

you can't not reference to it in order to use them

gusty estuary
#

it's ui code

trail oasis
#

sure but its in a monobehaviour is my point

#

which is part of a game object

gusty estuary
#

nothing stops you from doing all that in usual C# class

#

I did it for convinience

#

outside of my ui framework

#

because by the time I need to implement loading screen

trail oasis
#

sure i know that but if you need animation at some point you need the game update loop

gusty estuary
#

my ui is not loaded yet (it has to load translations async)

trail oasis
#

its impossible to completely seperate them

#

i used the old ui for 5 years and animated it in a similar way

gusty estuary
#

game update loop != ui update loop

trail oasis
#

void update is the game update loop

gusty estuary
#

unless it's part of game logic at least

trail oasis
#

there is no other update loop except fixed and late

#

they have not provided a seperate ui update loop

gusty estuary
#

well, you can use schedule if you really want UI specific loop (but it's same Update)

#

in Unity everything runs on main thread

trail oasis
#

ok but you would still be referencing UiElements namespace

#

its 100% impossible not to

#

otherwise you couldn't even query an element from root

gusty estuary
#

that's not what I meant

#

I meant to use presentation (or VIewModel) layer inbetween

#

because ViewModel

#

can be tweaked to use different UI framework for example (or if you heavily refactor existing one)

#

while game logic can stay intact

#

there is nothing worse than a need to modify game logic because you modified ui

trail oasis
#

i do it slightly different

gusty estuary
#

there are different patterns to it

#

MVP, MVVM, MVC

#

I like MVVM

trail oasis
#

i make it a component of the gameobject that i am interested in to make a progress bar and get component for <IProgressBar>

gusty estuary
#

yeah, this is pretty much service like structure

trail oasis
#

so what ever game script has that interface it'll hook to automatically

gusty estuary
#

so IProgressBar here is your ViewModel

#

but still

#

reading layout values is ugly 😅

#

besides

trail oasis
#

yeh i didnt realise i could apply a % directly

gusty estuary
#

it's all consts anyway

trail oasis
#

thought i had to apply pixel widths

gusty estuary
#

oh, all right then

trail oasis
#

ill clean it up - it will make my code cleaner too thankfully

gusty estuary
#

generally you want to avoid that too

#

(at least imo)

#

progress bar is exception

#

because you don't want to have 100 styles for each % fill

#

but in general I prefer to declare USS style

#

for each interaction

#

and then just apply them

#

layout engine will figure everything itself

#

this also allows to use transition animations fluently

trail oasis
#

i haven't got around to learning differeent styles atm

#

just learning to connect it to game data atm

unborn bluff
#

What is the current recommended way of making animations for UI elements?

#

other than defining the pseudo states