#🧰┃ui-toolkit
1 messages · Page 1 of 1 (latest)
Does iStyle have no "parent" selectors? I.e. for border, i expected:
borderColor
borderWidth
but instead i have to go like this:
tell me guys, because I'm overwhelmed looking into ui toolkit for the first time - am I supposed to make the entirety of the game ui in one visual tree asset?
No, break screens logically into separate UI documents
I have several, for example a settings doc, a HUD, a pause menu etc
Are you using UI Builder? I think there is an option to instantiate other 'child' UXML templates in the hierarchy of the currently-edited UXML file. If this is what you're looking for?
For the rest: I'm playing around with the Panel Settings of my UI, and want the UI to be scaled according to screen size. However, I also have a UI element that sometimes needs to follow the position of the cursor. If I change the screen resolution with the Scale Mode set to 'Scale With Screen Size', the displayed position of the element no longer matches the mouse position and the element starts drifting.
I can correct this if I know the scale factor that the Panel Settings is applying to the UI, and multiply the element's position by this value. However, the scale factor doesn't seem to be readable anywhere - in which class/API can my code read this information at runtime?
Hi, whenever i change screen, built-in navigation (arrows/sticks/etc...) doesn't work anymore (using new input system btw). My screens mostly have buttons (they are in some cases instantiated). I remember reading that current panel has to be focused for navigation to work (or something along those lines). I currently set focus through code on some element in each screen (which works). Still I can't navigate afterwards. What gives?
After some investigations, it seems that only my simple start menu made of buttons works, anything different doesn't regardless of order of apparition.
I might be an idiot and don't know what to google, but there's still the issue that mouse events don't pass between different ui documents. Say I have one which adds some UI on the sides - that makes it cover the whole screen. If there's other navigation on the layer below no events get to it - they're all consumed by the top layer, regardless of transparency.
this also immediately gives me pause as to how I'm going to implement mixed-target tooltips if there's no way to filter out when the mouse is in fact over visible UI elements.
(this was a filter I employed before raycasting over the scene to find e.g. character avatars)
Hello, i'm started to use ui toolkit and i have some problems with listview items styling. Margin doesn't works, hover and checked styles too. How can i fix that?
I am trying to create a world-space element with UITK. I have had some success in getting the position transformed (worldToScreen).
What I am struggling with is making sure they follow properly... I cant tell what is wrong with it, but it feels... off...
public class WorldSpaceElement : VisualElement
{
private Camera camera;
private Vector3 offset;
private GameObject controlPoint;
private bool isLeft = false;
public WorldSpaceElement(GameObject target, bool left)
{
camera = Camera.main;
controlPoint = target;
isLeft = left;
AddToClassList("plus-icon");
Move();
}
public void Move()
{
var leftPosition = Manager.Instance.InstanceAR.instances[0].GetComponent<BoxCollider>().bounds;
//add Y offset to center on object
offset = new Vector3(0, leftPosition.size.y / 2, 0);
//add offset for left/right
if (isLeft)
{
offset -= new Vector3(leftPosition.size.x, 0, 0);
name = "left";
}
else
{
var rightPosition = Manager.Instance.InstanceAR.instances.Last().GetComponent<BoxCollider>().bounds;
offset += new Vector3(rightPosition.size.x, 0, 0);
name = "right";
}
var screenPosition = camera.WorldToScreenPoint(controlPoint.transform.position + offset);
style.bottom = screenPosition.y;
style.left = screenPosition.x;
}
}
They don't scale with perspective
right, hmm. gonna need to find a way to scale that 🤔
probably just interpolate the distance and clamp it so it doesnt get too small
so this is a really late reply, but that should work just fine
from where do you call Move()?
this move function is called whenever a finger moves or the camera moves
my world space UI Element works like this
public void UpdatePosition(Vector3 vpPos)
{
transform.position = new Vector2(vpPos.x * panel.visualTree.contentRect.width, (1 - vpPos.y) * panel.visualTree.contentRect.height);
}
where UpdatePosition is being called from a monobehaviour with _camera.WorldToViewportPoint(transform.position);
it doesn't scale with distance because that's not part of my usecase, but that should be doable based on distance from camera
in viewport space you're already working in 0,1 range
ah ur working in NDC
ndc?
normalized device coordinates
oh yeah
or at least I use viewport space which is 0,0 = bottom left and 1,1 = top right, and then use that to set it to the correct position in canvas space
yeah, i could do that but working in that space would only make it more difficult to position things correctly I would think
Right now im trying to figure out what is going wrong with the positioning, its better but its still not perfect (I am making a gif of it)
the scale will come after that if I wnt it, cuz im not sure if I do actually
I'm wondering why you're using style.bottom and style.left to position it instead of transform.position?
because I may or may not have known that was equivalent
it's not entirely, but i think transform would be better for this
I'll change it first, then show the current issue. hope you see what im doign wrong
transform is added 'on top' after all the layout; it's worth experimenting with in UIBuilder
Rider is being very slow to index my cs file after restarting it goddamn
bit of a weird issue really, the elements just kinda float on top of the gates that I am drawing
at least they dont change position anymore, but may need to account for z-depth of the elements in the scene
yeah it looks like it's not taking perspective into account
oh, are they offset from each other based on the boxcollider's bounds?
that might look weird because visually they're getting smaller, but the bounds aren't
maybe you could translate points on either side of the object to camera space
translate as in transform into cameraspace not as in move
easiest way would be to have one monobehaviour with its transform control one visualelement
and parent the monobehaviour to the 3d object
with its own transform for offset
im doing it based on the dimensions of the box kinda. we know the actual dimensions of the model
yes but unless I'm mistaken you're not taking into account the screenspace size of the model
I think that's causing it to look weird
instead of doing the offset in code, try doing it in 3d space with a transform and then transforming that to canvas space
I don't know how IMGUI would help here..
imgui containers have literal world space elements dont they?
im pretty sure its built in
ah yea that's totally different
https://gamedev-resources.com/create-a-health-bar-that-hovers-over-the-player-with-ui-toolkit/
here's a neat tutorial that has some handy info
the RuntimePanelUtils class has methods to convert between different spaces
RuntimePanelUtils.CameraTransformWorldToPanelRect seems especially useful for your usecase
this actually looks like what I am looking for
from what I read, it should handle the scaling internally
what the hell kind of parameters does that even expect @pseudo dock
mostly the panel. the other parameters make sense
cuz im not using a panel, its just a visualelement in a document.
visualelement.panel
every visual tree hierarchy has a panel
ah fair
uhm
how do you override the rect of a visual element? That doesnt have a setter
oh nvm
ah dangit, that doesnt fix it
show your code
lol I was going crazy remembering the UIToolkit coordinate system, so if anyone else needs this:
public static class UIToolkitRectExtensions
{
public static Vector2 TopLeft(this Rect r) => new Vector2(r.x, r.y);
public static Vector2 TopRight(this Rect r) => new Vector2(r.xMax, r.y);
public static Vector2 BottomLeft(this Rect r) => new Vector2(r.x, r.yMax);
public static Vector2 BottomRight(this Rect r) => new Vector2(r.xMax, r.yMax);
}```
public void Move()
{
var dimensions = Manager.Instance.InstanceAR.instances.First().GetComponent<DatabaseReference>().reference.dimensions;
//add offset for left/right
if (isLeft)
{
offset = new Vector3(Manager.Instance.InstanceAR.instances.First().transform.position.x - dimensions.x, dimensions.y / 2, 0);
name = "left";
}
else
{
offset = new Vector3(Manager.Instance.InstanceAR.instances.Last().transform.position.x + dimensions.x, dimensions.y / 2, 0);
name = "right";
}
var rect = RuntimePanelUtils.CameraTransformWorldToPanel(panel, offset, camera);
this.transform.position = rect;
}
your naming is a bit confusing, and also the Manager.Instance.... call...
But offset here is not the offset but rather the position, right?
You're creating a Vector3, but then only applying the actual transform's x position, but not y and z
try adding to the actual position, like this
Vector3 wsPos = Manager.Inst..transform.position;
wsPos -= new Vector3(dimensions.x, dimensions.y / 2f, 0);
manager is a singleton, and that has an AR instance. indeed tho, wording and naming could be improved a lot
okay but maybe just cache it at the top so you don't have to retype it every time 😛
okay yeah fair xD
its just that the left side instance is using the first element of the array and the right side is using the last element. but the offsetted position of the button in UITK is moving around more than it should given the position of the object it is tracking
but you're not passing the entire position into the CameraTransformWorldToPanel
so it's hard to tell
currently you're only using worldspace x to track the position
what do you mean im not passing the entire position 🤔
im calculating where the button would be in worldspace, then converting that to screenspace no?
or am I misunerstanding something here?
in the code that you posted, you only use position.x of the AR object
ah yes, because the Y position of them does not change (each element that is put on the simulation is the exact same height)
how about z?
oh that is probably why its not doing it properly...
that did improve it quite a bit actually
I'm really liking the vector drawing when creating custom visualelements, but damn there's a lot of boilerplate code just to get some values to show up in UIBuilder and then AGAIN to also read them from .uss
so I have a weird system, where I want to connect Groups in Graph View using ports
I figured doing it like this
Port port = customNode.InstantiatePort(Orientation.Horizontal, direction, Port.Capacity.Single, typeof(FunctionView));```
but when I get that node, it just returns null
the customNode I made
even though I'm creating the port on it
the port.node returns null
Hey guys, so going through and learning UI Toolkit for the first time, and was curious if there are some other standards for grabbing references to UI objects aside from Querying for string references?
root.Query<Button>("foo") seems very fragile to me
can literally iterate manually all children
but I use a pattern, where I define some containers, query for them and then query them with more generic names
or just straight up foreach(var child in visualElement.Children()) with just c#
Hello! So, I don't use UI builder very often and I'm sure I'm doing something simple and silly, but I have custom editor window that suddenly ceased to open when I try to open it in the editor. Here is a stripped-down .cs file for the EditorWindow-derived class.
using UnityEngine;
using UnityEngine.UIElements;
public class StoryFlowEditor : EditorWindow
{
public const string PATH = "Assets/Editor/StoryFlow";
[MenuItem("Game/Story Editor")]
public static void ShowExample()
{
StoryFlowEditor wnd = GetWindow<StoryFlowEditor>();
wnd.titleContent = new GUIContent("Story Editor");
Debug.Log("Yo");
}
public void CreateGUI()
{
// Each editor window contains a root VisualElement object
VisualElement root = rootVisualElement;
// Import UXML
var visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>($"{PATH}/StoryFlowEditor.uxml");
VisualElement labelFromUXML = visualTree.Instantiate();
//root.Add(labelFromUXML);
visualTree.CloneTree();
// A stylesheet can be added to a VisualElement.
// The style will be applied to the VisualElement and all of its children.
var styleSheet = AssetDatabase.LoadAssetAtPath<StyleSheet>($"{PATH}/StoryFlowEditor.uss");
root.styleSheets.Add(styleSheet);
}
}```
When I click on Game > Story Editor in the Unity editor, "Yo" prints but no window opens. There is no error, so I'm not sure how to begin diagnosing this. Can anyone help?
Don't you need to show the window?
Update: I restarted Unity and it works now. No, the [MenuItem] attribute connects "ShowExample()" to the editor toolbar, and that method when invoked is enough to cause the window to show.
However, though that works, I'm having an issue with a custom element that extends from GraphView as per the following image...
You can see that the UI Builder window is displaying the view just fine (with the grid background), but it doesn't appear in the live window at all though the label does. The whole .cs file is shown in the screenshot.
Okay - some new info... I found out that my custom GraphView has a height of 0 pixels live, even though the UI Builder has grow set to 1 on the Y axis. I'm not sure why this element isn't expanding properly in the live EditorWindow... I set the height to 100 pixels by editing it in the debugger.
However, setting the height on instantiation in code works 1:1...
Solved! I had to include the root VisualElement into CloneTree() for my custom views to render correctly. visualTree.CloneTree(root); For some reason the default Unity stuff worked fine without this. I came across this solution by accident and don't quite understand it.
I'm using a dropdown, and a weird bug has just started in the last couple of builds of the project where it doesn't drop down when you click it (or click it a bunch of times). It does get focus when you click it, shown visually, and then if you press Enter it drops down. So it's not like it's disabled or something. Anyone have any idea why this might be? It's in the actual game, not the editor.
Oh yeah one more thing. If I open the UI Toolkit debugger and do "Pick Element", and then click the dropdown to select it and inspect it, it drops down.
Any idea if there's a way to make VisualElement not take over any clicks?
For example I have VisualElement size of screen
and then another VisualElement size of screen above it
I want that another VE not to take over registered callbacks of first VE
but rn it simply kind of overwrites them, so clicking screen results in nothing, as clicks aren't passed to first VE
picking mode -> ignore
is that inherited by children?
no
hmm, let me check
hmm, seems to work the same way. But I changed it in runtime
Root.pickingMode = PickingMode.Ignore;
all right
looks like this is related to registering callback
which enforces picking
Is it possible to load a "UI Toolkit/UI Document" inside a "UI/Panel"? (and have it grow/shrink inside the panel)
Does anyone know where I can find the default stylesheet for GraphView.Node styling? The same base styling that shader graph uses, etc.
Further to my post above, I noticed that there are default references to DefaultCommonDark_inter.uss and Library/unity editor resources stylesheets on my NodeView object which I can't seem to open. Are these sources which I need to include somehow in order to get default styling, and if so, where can I find them?
jumpButton?.RegisterCallback<ClickEvent>(ev => ToggleButton(ev.target as Button));
so this does not work as intended. If I hold shift and press leftclick on a button, it returns me not a button, but Image which is child object of the button O.o....... Any tips ?
is it intended behavior?
Or should I start bug report?
How do I set the background image to a specific sprite from code?
It is possible to make the buttons selection work with the input (or new) system? It seems like I cannot find proper info
right click on the tab in unity and there's an option to turn it off
Hi, i am trying to set positions "right" and "left" values to "auto", but cant seem to accomplish it. Here's what i have tried (see commented out):
it always expects a Length style (which is float), but in inspector i can set these values too (but need to set them by code).
These are the docs i checked: https://docs.unity3d.com/ScriptReference/UIElements.StyleKeyword.html
you don't seem to have error highlighting, and presumably lack proper autocomplete. You should configure your IDE using the instructions in #854851968446365696
This is another issue i face since longer, i will check the readme section and fix that first, thank you
Thank you very much!
Been stuck on this for 2 hours about
(i will still try to fix my ide right now : )
Fixed intelliSense, thank you again 👋
How can I easily position visual elements from their center points instead of its top-left corner? The 'transform-origin' property seems to only apply for rotation and scale
Currently I'm just manually offsetting its position from half its transform size, which is super tedious. I also don't want to add an empty parent to visual elements that I want to move in its center point
Here's a forum post that outlines the problem and solution, but I'm wondering if there's a more elegant solution out there:
https://forum.unity.com/threads/pivot-origin-issue.1134700/
thanks
I need to utilize images in multiple places in my game (ex: show a picture of an inventory item in a grid view and show the active item selected in a game overlay). Is it best to download the image and save the file locally and then reference it where needed or save the image to an array of images and ref it where needed? Maybe I'm completely off on how to store/access images?
you had this same problem too then? 😅
For anyone interested, the problem that I had was that my GridBackground was the second child of it's parent VisualElement and the container holding all my GraphView.Nodes was rendering under the grid.
Anyone know if it's possible to get "global" keyboard event?
I want to catch the "escape" key in the whole template but it seems to only work if the focus is in a textfield
How can I change parents for ui elements?
Remove it from hierarchy and reparent
Is there any collision checking? All I see is Overlaps() for visual elements
this is probably a frequent question, but UI toolkit is giving me the error
Collection was modified; enumeration operation may not execute.
whenever i change something on the window, this error doesnt effect anything though so i kinda forgot about it until now
yeah, don't use foreach ... that's a common mistake
or if you're insist on using foreach and don't care about allocation, then you can make a softCopy of it via ToList
foreach(var someThing in someThang.ToList())
Can someone explain why the onClick menu looks like this and how can i get it back to the old one?
are you in debug view?
that fixed it, thank you
Hello! For everyone here using Ui toolkit, check out this message in the announcements channel:
*`Hi everyone,
We’re continuing to develop the functionality and experience of ui-toolkit, our newer UI Framework, and The UI team is looking to understand users’ needs and workflows in order to identify areas of opportunity for improvement.
If you have experience with building or designing UI, we would love to get your input via a brief survey which is designed to take no more than 15-25 minutes of your time.
At the completion of the survey, you will have the possibility to opt-in for a follow up interview, where you share more in-depth feedback directly with the team. If interested, you might also be involved in providing feedback on potential prototypes of new features as we address the feedback received.
As always, we value your feedback and ask that you provide your candid and honest opinion.
Please click on the link below to start the survey: https://unitysoftware.co1.qualtrics.com/jfe/form/SV_9Ldsz0Ral8nndNs?channel=Forum`*
You dont
Actually you can now @lucid void
and now that I hid it IDK how to get it back lmao
guys any idea to make inventory like tarkov when using grid layout?
Simplest way would be to use small grid and let larger objects draw outside of boundaries and fill it with dummy objects under those larger objects. That should work.
Wtf lol, I never knew
But still better to have it
Is there a way to make a visual element not block mouse clicks for objects it's overlapping?
Disable Raycast target on it
Set the picking-mode to ignore
How can I register to a "global" MouseUpEvent? I want to know when the mouse is released, even if it's not above my control.
I found a previous answer where they register to MouseLeaveEvent but in my case I would like the user to release the button anywhere.
The easiest way is to add a listener to the root of your hierarchy.
Wouldn't this still fail if the user drags the mouse outside of the root then? In my case this is an editor window
You likely want to use CaptureMouse/CapturePointer on mouse down possibly via a manipulator .
I'll look in to those, thanks!
Np - good luck. I wonder if this example might help you but I haven't looked at it in detail: https://github.com/Unity-Technologies/UIElementsExamples/blob/master/Assets/QuickIntro/Editor/FloatingDemoWindow.cs
Unity project containing examples to use UIElements in the Editor - UIElementsExamples/FloatingDemoWindow.cs at master · Unity-Technologies/UIElementsExamples
yo guys rq how would i change between UXML files? like with canvases you would just deactivate them as you wish, how would i do that with this?
How can I write back values to a SerializedProperty in a PropertyDrawer in UITK? While debugging I find that the in-memory value of my SerializedProperty does change but it doesn't seem to make it back to the editor somehow.
To answer myself: My setup was that I registered to GeometryChangedEvent and pass in SerializedProperty as TUserArgsType. The reason why it didn't work was because I forgot to call ApplyModifiedProperties().
I have a bunch of UIDocument in the scene, each have it's own UXML attached so I can enable/disable them like other gameobject.
Initially tried to load uxml dynamically but it made things way too complex.
I attempted this. But all the fields were blank when I reloaded it. Putting it into OnEnable() didn’t help either. If you have a solution to this it would be very nice
Idk if I'm stupid but is this whole 'Make a custom editor' unnessesary complex?
I saw multiple videos now and all of them use a different approach.
example: Some use OnGUI()
some use CreateGUI()
wheres the difference? When I try creating a button in OnGUI() then it creates infinite buttons.
But when I'm using CreateGUI() I cannot use the Space() Element to create spaces between elements.
In an official unity tutorial, they even used something completely else, where you create the Editor via XML & CSS.
what methode should I use to create my modding tools now?
Or can someone atleast link some good ressources?
or is the correct channel #↕️┃editor-extensions ? o.O I'm even more confused now
bro im with this guy, like, isnt the unity editor already good enough? like come on.
#↕️┃editor-extensions is the right channel for editor authoring questions.
If you use OnGUI/OnInspectorGUI you're using IMGUI (immediate-mode GUI), if you use OnCreateGUI/CreateInspectorGUI you're using UIToolkit, which can be authored in code or use UXML/USS.
You're not forced to use one or the other, but the editor is generally moving towards UIToolkit because it means it'll be unified with the runtime UI, and it supports awesome things like perfect borders, complex hover states, transformations, better performance without additional systems, etc.
If you created infinite buttons in OnGUI then you probably were not using IMGUI.
I still use IMGUI for most things because it's faster to author limited-scope stuff.
Go with uitk from here on...
my only complaint with uitk, sometimes, it can be a bit boilerplatey
other than that, uitk has boost my productivity in huge margin in terms of editor tooling
does the VisualElement.Q<>() not work recursively? I cannot seem to get it to find elements
document.rootVisualElement.Q<VisualElement>("PasswordFieldNeutral").Q<Label>("Password").text = "Password";
this element is a few levels down
passing VisualElement as a type into Q always returns no results. Apparently this is for the sake of performance but I'm not a fan of it either. Just try removing that type and do Q("PasswordFieldNetural") etc instead.
uhm
document.rootVisualElement.Q<VisualElement>("TopAppElements").Q<Label>("Text").text = "LOGIN";
document.rootVisualElement.Q<VisualElement>("TextFieldEmailAddress").Q<Label>("Password").text = "Email address";
document.rootVisualElement.Q<VisualElement>("PasswordFieldNeutral").Q<Label>("Password").text = "Password";
document.rootVisualElement.Q<VisualElement>("TertiaryActionLabelButton").Q<Label>("Text").text = "Forgot Password?";
document.rootVisualElement.Q<VisualElement>("PrimaryActionLabelButton").Q<Label>("Text").text = "Log in";
document.rootVisualElement.Q<VisualElement>("SecondaryActionLabelButton").Q<Label>("Text").text = "Create an account";
document.rootVisualElement.Q<VisualElement>("TertiaryActionLabel-IconButton").Q<Label>("Text").text = "Continue as guest";
this first one works, the rest does not
They may have changed this in recent versions of Unity (I'm still on 2021.2) but I also wonder whether maybe there's some other reason leading you to think the first line is working when it's not.
this entire thing isnt raising any exceptions so I would assume it to be fine
at least query wise
Ah I just re-read your message more thoroughly sorry... yes, the Q syntax won't find children of children - only direct descendants. I may have been talking rubbish here
can I somehow force it to find them?
its not terribly deep, but its 2 levels because of container elements
more than 2 levels
I actually may be talking rubbish. My mind has suddenly gone blank as to whether what I said is true or not. One thing I notice from your screenshot however is that you don't have a Label called Password so that might actually be the issue
you'd want e.g. Q<VisualElement("Password").Q<Label>();
oh
hold on
document.rootVisualElement.Q<VisualElement>("TextFieldEmailAddress").Q<BetterTextField>("Password").Query<Label>().ToList()[0].text = "Email address";
owkay thats a little excessive
Query<Label>().ToList()[0] is identical to Q<Label>()
*maybe not identical but semantically equivalent
I'll give the label a name and search for that tho
I dont need the parent
that doesnt work either
ok I was mistaken
there was another script doing the first one
document.rootVisualElement.Q<VisualElement>("TopAppElements").Q<Label>("Text").text = "LOGIN"; this works tho
ah, function execution order!
you can try using classes to select deep elements like Q<Label>(null, "#Headline #Text")
tho I'm not sure that works with names, you'd probably have to assign classes to those elements and use that as a selector
I have a different problem, my function calls are out of order
I dont know if its even an issue with the queries
ah, have you tried logging the result of other queries to see if they return a valid instance
tho that is next on the list after I get the right execution roder
it's really weird that nothing would happen without some exceptions
there it is
so i had a load function for the ui
but it wasnt being fired on a new ui object when it gets enabled
i forgot to do a call to Load() in my setter
now, some elements arent working but tahts just me being wrong I think
the joys of workign as a team!
TextField vs Textfield
capital F
hey guys, is there an API to probe what color ui-toolkit outputs at a pixel on screen ?
want to check if click should be eaten by the UI or fall through to the game controls and current idea is to look at alpha value of ui-toolkit's output texture under cursor
another idea is to get the element under the cursor, and check against a list of elements that should hijack clicks, but sounds like that will cause additional boilerplate and will be less reliable in cases when controls aren't simple rects
So, with buttons, yknow how to get them to call a method you type
button.clicked += Method;where the hell do i pass in arguments
you mean passing the event? if so, you can use the clickable instead of clicked like this ``` button.clickable.clickedWithEventInfo += (x) =>
{
};```
is there a way to use OS font as fallback in UItoolkit. This effects kanji, as I cannot Build every single kanji and put in font asset.
Legacy text was able to take Kanji from OS, or browser and use it on the go. Maybe someone found the workaround on this?
Sorry, this may have been asked many times, but an internet search didn't net any good results. Anybody ever had this issue?
This happens constantly to my UI Builder, seemingly without a consistent reproduction scenario. Resizing or maximizing the window seems to remove it, only for it to happen again 30 seconds later. Unity 2021.3.4f1.
this chat is dead
Never had that but might be a corrupt file? have you tried reinstalling?
... I would try to play with the UI Scaling settings as well see if it changes anything.
I can try the UI scaling, yeah. The one under Preferences, you mean? I'll take a look, see if it does anything. Thanks.
kinda reminds me of weird rendering glitch I had on OSX a few years back, had to do with GPU accelerated rendering used in certain apps.
I would also make sure the GPU drivers are up-to-date.
They should be, but I guess I can always check that out too
https://stephenhodgson.github.io/UnityCsReference/api/UnityEngine.Experimental.UIElements.html
https://docs.unity3d.com/ScriptReference/UIElements.IStyle.html
pin these two links for the newbies like me, they have all properties
and their types
Am I missing smth or why do I get a nullpointer when trying to access that GroupBox
Box itemInfoBox = rootVisualElement.Query<Box>(name: "item-info-box").First();
Are you sure it's a Box ?
Do you get somethign with
VisualElement itemInfoBox = rootVisualElement.Query<VisualElement>(name: "item-info-box").First();
bruh yeah I just noticed
I need to use GroupBox instead of Box
Unitys tutorial be outdated duh
how do i set the rotate property via script?
probably this:
root.Q<VisualElement>("someElementName").style.rotate = new StyleRotate(new Rotate(new Angle(30)));
but... (speaking from my 20+ year of webdev experience)
I find it more maintainable to set/unset classes instead of playing with style in code.
thanks i managed to do it it just needed new Rotate(x)
but i have another error. when i move a child outside of the area of the parent it dissapears
you need to make sure the parent is set to overflow:visible;
parent(s), the clipping could come for a parent a few level up.
its cray cray cause unity opens the ui programmers job to all front enders with the new toolkit
also overflow worked thanks!
as a web dev, I am not a big fan of ui toolkit
its not easy to implement html/css into a game engine. im sure it will be much more polished in a couple years
they changed a lot of things for no reason, meaning your web dev skills won't transfer and you will have to consult the worst thing ever coinceived: the unity docs
how do i get the visual element from event.target?
you can cast it to a VisualElement
var element = (VisualElement) evt.target;
Why does a TMP_Text element change it's font size when I hit play?
Even when "Auto Size" is deactivated?
Apparently Unity added background image repeat.
But reading the change logs I couldn't find in which version this feature is present.
I don't want to download a bunch of editors just to figure this out. Do you guys have any idea?
I'm trying to remove an item from a ListView
private void RemoveItem()
{
SO_Item item = itemList.selectedItem as SO_Item; // SO_Item It's a scriptablobject
string path = "Assets/MyMod/Data/Items/" + item.name + ".asset"; // The path where the SO is
AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(item));
RefreshItemList();
}
Here's my refresh Methode
private void RefreshItemList()
{
List<SO_Item> allCards = FindAllItems();
itemList.makeItem = () => new Label();
itemList.bindItem = (element, i) => (element as Label).text = allCards[i].name;
// I'm getting an error on the line above.
// "MissingReferenceException: The object of type 'SO_Item' has been destroyed but you are // still trying to access it."
itemList.itemsSource = allCards;
itemList.fixedItemHeight = 16;
itemList.selectionType = SelectionType.Single;
itemList.Rebuild();
}
I'm getting that error
"MissingReferenceException: The object of type 'SO_Item' has been destroyed but you are still trying to access it."
And I don't know why.
Here's my FindAllItems methode
private List<SO_Item> FindAllItems()
{
string[] assetpaths = AssetDatabase.FindAssets("t:SO_Item", new [] {"Assets/MyMod/Data/Items"} );
List<SO_Item> allItems = new List<SO_Item>();
for(int x = 0; x < assetpaths.Length; x++)
{
allItems.Add(AssetDatabase.LoadAssetAtPath<SO_Item>(AssetDatabase.GUIDToAssetPath(assetpaths[x])));
}
return allItems;
}
Basically I'm looping over the Path and getting all the scriptableojbects out of it.
The Scriptableobject is correctly removed once I 'remove' it via the methode above, yet the error shows up plus the actual ListView kind of breaks because all Items below the one I want to destroy are gone after I delete one.
I'm sitting here for multiple hours trying to debug or fix that..
tltr: Can someone help me on how to remove a ListView Item correctly? or update it correctly when I remove an asset in Unity that's inside a ListView?
'BasePopupField<string, string>.choices' is inaccessible due to its protection level
i didn't find any solution for that
https://forum.unity.com/threads/how-do-i-know-what-object-currently-has-focus.1324422/ How do I find what ui element gameobject has focus?
Can I use UI Toolkit with an EditorTool? It seems there's only a OnToolGUI callback that's invoked every frame
You can, that's what I'm doing to build my modding tools
In this video, we are walking you through the basics of creating Property Drawers and Editor Windows using UI Toolkit.
🌏 Check out our Docs to learn more about UI Toolkit:
https://on.unity.com/3kR2LC6
🌏 Learn more about Editor Scripting using IMGUI here:
https://on.unity.com/3oZ3oMq
🌏 Download Unity Royale here:
https://on.unity.com/3jXV9fX
...
I suggest this video.
It teached me the basics to set my custom editor tools up.
I meant specifically the UnityEditor.EditorTools type, not just a window that works like a tool. Normal EditorWindow you use CreateGUI as opposed to OnGUI, but no such distinction exist on EditorTool (it only has OnToolGUI)
Ahh my bad
Try removing it from the listview before removing the asset. Rather than a full refresh grab the itemList.itemsSource. Copy it and remove the item or filter it while copying. Reset the list in the listView then remove from the asset db. If there is a stack trace look at where the error is happening.
Thanks, definitely stuff I can try it. Really appreciate the answer.
I'm having a hard time understanding the proper way to instantiate a re-usable uxml file during runtime.
Most of the examples I see in the docs are for the editor and use the resource folder which they recommend against for runtime, and any runtime UI examples in the docs don't use a uxml file and instead create the various components inside the script.
I did fine one example where you can pass in a UXML as a reference in the inspector using VisualTreeAsset and then calling Instantiate on it, but that would cause it to wrap the whole template in a <template-container> which was throwing off some of my styling(My element would think the container height was 0 when I used size: 100%). I found I could call ElementAt(0) on the template container and use that as the element I add to the root node but that kind of felt funky, and wasn't sure if this is the proper way to do it.
Perhaps my thinking of having separate uxml files for custom elements is wrong?
there really isn't any way around the template container stuff
you can create a custom element and clone your uxml into it with Resources.Load<VisualTreeAsset>("MyAsset").CloneTree(this);
but that would do exactly the same thing as the templatecontainer
and you also can't pass anything into the constructor, you have to add some sort of Init method for that, otherwise your uxml factory will complain
also, what do you mean size: 100%?
there really are only 2 options: either you use Resources.Load to load the uxml or you pass the uxml into a serializedfield and use that
correction, you actually can do that, but it's finnicky
Sorry, I meant when I set the height to 100% of it's parent
But for some reason the template container height is 0 whenever I instantiate it.
you can try setting the min-height
Oh true, I did not think of that
Hi,
I want to create a dropdown list and take a value from it.
How can I get the value when I click on it ?
I use UiToolkit and UiElement for the dropdownList
How do i dynamically add a template container class and access it after? i need to change some of the properties```cs
public class Products : DocumentControl
{
public static bool isPedestrian = true;
[SerializeField] private TemplateContainer template;
[SerializeField] private List<DatabaseItem> pedestrian;
public override void Load()
{
document.rootVisualElement.Q<TemplateContainer>("TopAppBar").Q<Label>("Text").text = "CHOOSE A FAMILY";
var objectRoot = Document.rootVisualElement.Q<VisualElement>("FamilyImageCardsGroupBox");
foreach (var product in pedestrian)
{
objectRoot.Add(template);
}
}
}
I'm confused, is TemplateContainer Serializable?
Did you mean to use a VisualTreeAsset and Instantiate it? Or is this something else
ah that sounds more like what I need. I am trying to instantiate an uxml document inside another
VisualTreeAsset is what you want then 👍
alright. thx!
it appears that templatecontainer is the instance created by the visualtreeelement😏
can you not add an Image Visualelement into the UXML?
you can via code, but from the window in the UI builder?
is there a way to change this default view . for example i need this item to have a front view
Sort serializedProperty ????? any way or idea
When i Bind() in my Editor Window my fields become disabled, any idea what might be causing it? I verified that the SO I bind to exists. My fields have binding-paths set
Hi guys! Is there a way using UI Toolkit to draw default UnityEngine.Object inspector inside some panel? Like in IMGUI
public void DrawObject(Object obj) => Editor.CreateEditor(obj).OnInspectorGUI();
I see there is IMGUIContainer, which i believe i can add in script in place i want
not sure if i'm being dumb but how can i add an image to my ui document? theres not a image control so i'm confused how images are represented else
ah, seems to be just a visualelement with a sprite background attached, is that correct?
correct, but you can also use textures if you need something dynamic
any ideas why the spacing between the 395 and the label is so different?
side note: ui doc canvas size is not the same as game view resolution but they're the same aspect ratio so just getting upscaled
how do I change the size of a viewport without scaling the content?
Don't cross-post. Are you even using UIToolkit?
hello, is there any news about uitoolkit having functionality like css keyframes/animation?
yes, it's called transition https://forum.unity.com/threads/announcing-uss-transition.1203832/
the docs somewhat still a giant mess at the moment https://docs.unity3d.com/Manual/UIE-Transitions.html
especially if you want to go the c# way
is there some sort of react-like engine based on ui toolkit for unity in development?
I was trying to setup some restrictions (UxmlEnumeration) to a UxmlStringAttributeDescription. Why are the restrictions being ignored? It will allow any value to be set within the attribute.
Optimally I would love the list to be a dropdown with the valid values inside of the UIBuilder Inspector. It can't be an enum because the values could change
Ok dumb question, in starting to research Unity UI Frameworks I ran across the UI Toolkit.
Is the UI Toolkit meant to be used for custom UI for the editor and editor tools?
Or is it meant to be used to build custom UI in the games that we build using the Editor?
Docs don't make this very clear.
hey boys I know this isn't coding per say but does anyone know why my custom font doesn't work with the UI Toolkit?
So the Font is applied, I've also created a Font Asset for it, however when I apply it it does the following
https://cdn.discordapp.com/attachments/885300730104250418/1014317581630451833/Unity_bXDwnfG0gY.gif
when you clicked off it and back it seemed to disappear? Maybe it did that because you had the font assigned already. Have you tried switching to only using a FontAsset?
Also, use the UIElements Debugger and see what's up with the end result
@rough scarab Still nothing, not sure what to do as it keeps disappearing, and as for the Debugger not sure what I'm looking for
First, you should change this to use your runtime theme
Then I'd just be looking to see if the font and text you expect is actually assigned in the runtime UI you have in the game view
its barely visible
setting theme helped me realise :)
ty
not sure why tho
nvm got it
ty :)
presumably the default text color is dark grey/black?
yup im just stupid, in the editor i jsut thought it was correct haha
After a few hours finally got my dynamic tabs / part button system working :) only have to add new prefabs to a folder and it update accordingly B)
Is there a way I can read the classes of a USS stylesheet directly from the StyleSheet object?
or will I need to read them directly from the USS file manually?
both
Thanks @lone mantle
Does anyone know: is there any way to have a different mouse cursor over UI elements and the 3D stuff without having something checking where the mouse is every frame and doing Cursor.SetCursor?
if there is, there should be a static bool on EventSystem. but doing a check each frame is totally ok
even then, you'd likely have one or more ui overlays, I do, so that bool wouldn't be worth much anyway
yeah, I simplified the situation a lot to ask the question - I think we've got an OK workaround.
is there some sort of react like engine
Are there any way to make ui for both iphone and ipad if you do not want to make two separate documents?
You need to play around with the design and structure of your document so that it will work on both
make sure your panel settings are setup to scale properly as well
Where can I find info on Rich Text for UITK? (what's supported etc)
On the "new text engine" thread on the forums is the best I've got. Only in 2022.2 did they add support for link and href, other things are still missing too
I see! Here's the thread if someone else needs it in the future: https://forum.unity.com/threads/feedback-wanted-new-text-engine.1007585/
what is the best way to manage the ui assets in combination with addressables. Should all VisualTreeAssets(uxml) be addressable. Should the assets be in sprite atlases or individual assets?
You can get pretty far by just assigning them to their respective fields in GameObjects or EditorWindows. Is this a specific case where you have to/want to use Addressables?
So what I wanted to do was to be able to update some UIs and styles remotely. As for the assets swapping them runtime wasn't a problem I was just curious what's best for the UI
How can I change the cursor in editor from C#? I'm trying to make a simple resize manipulator, so I'd like to change the cursor to the horizontal arrows <-> when hovering the correct element.
Hopefully someone already knows how to work around this - if I click on a UI toolkit button, and then press Escape, the input action (new input system) isn't fired, and code I've attached to it doesn't run, until I click in the camera view again, and then it works. Is there something I can do to "set focus" to the viewport after the button is clicked so that pressing Escape works? The button isn't marked Focusable.
This stuff is pretty tricky and I haven't mastered it. A few hints that might point you in the right direction:
I think this is likely a navigation event. You can listen for this and try to eg prevent the default action (psuedo code): root.AddChangeListener<NavigationEvent>(cb => cb.PreventDefault());
You can also look at changing some of this in the various input settings and be sure to test in builds as in editor isn't necessarily the same.
can you show makeItem and bindItem?
ListView doesn't support horizontal layout in case that's what you're after.
Unfortunately yes for a horizontal list.
That depends (as usual). Setting grow to 1 is very normal if you want the list to fill its parent. The parent can also affect the scroll/list views layout too.
UITK uses a 'flex box' layout approach. Although it's not 1:1, basics like flex-grow/shrink & positioning are pretty much the same as the html equivalents https://css-tricks.com/almanac/properties/f/flex-shrink/
If I want a window to be the same physical size on iPad and iPhone but still be the same relative size on all different phones. How can I make that possible they ui toolkit?
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
You need to switch the theme to the runtime theme in the top right of the editor, otherwise nothing will match
One message removed from a suspended account.
You should have a runtime theme in your project to switch to. I can't remember how to set it up off the top of my head (on mobile)
One message removed from a suspended account.
Create>UIToolkit>Default Runtime Theme
One message removed from a suspended account.
Anyone know of a way to draw the inspector view of a component within a visual element? For example, I select a scriptable object and I want the window to render the same properties as the inspector.
Basically iterating over serialized properties and adding the correct visual elements
nevermind I got it. Basically needed to create a serialized object from the selected object, then use a PropertyField and bind the fields
I have a main menu that will load data (api call after user clicks start button) and then move the player to level 1 and show an inventory menu (shows data from api call)... what's the recommended way to hide/show menus? In the UI Builder view, I'm setting the "display" of the main menu & inv menu to none (equivalent of m_Root.style.display = DisplayStyle.None;)... but their is a visibility property too 🤔
Is it better to set display or visibility when hiding/displaying various UI screens? Or maybe i'm missing another approach
Why does my ListView vanish/stop working
when i set the gameobject it's on do inactive and then active again
setting display to none is like completely deleting the element, so anything whose position is affected by it will update its position accordingly. Setting visibility to hidden is basically like setting opacity to 0 - it continues to take up space, it's just not visible.
Matter of preference, I'd go with making a dummy container..
var dummyContainer = new VisualElement();
root.Add(dummyContainer);
if(someCondition)
// clear the children, if any then add a fresh new child
dummyContainer.ToList().RemoveAll(x => x != null);
dummyContainer.Add(someChildElement);
else
dummyContainer.ToList().RemoveAll(x => x != null);
you may or may not need to check for childCount 1st if you want to if(dummyContainer.childCount > 0)
In before someone with their Karen sword saying Linq is bad! yada yada yada.. this is just for examples mkay
this way your order of child elements in the parent's hierarchy won't be affected
I really want to use the new Unity UI System for my project, but can't get a scrollable area to work correctly
I also don't want to spend another 5 hours figuring it out.
Is there any good documentation on Unity UI Toolkit scrolling mechanics?
Or should I just use the old system?
How do I center an absolute position element horizontally? Such that it has a fixed width and always stays centered. Let's say its 100px wide.
so visibility sounds like the best then?
Yeah if you want everything to stay in the same place.
If you had some ui that was presented as a list or a stack, you’d set display to none and everything would reflow.
Hi I am working on a little clicker game and I am looking for someone that could make a few UI pictures/designs Please Reply or Dm if interested
How you maintain dependencies like visualElement.Q("nested element name")? I feel like it weakest place, when you or someone want to or accidentally change element name in UI Builder, so you need to change it in code accordingly.
might be a bit late, but my trick is to use position: absolute; left: 50%; translate(-50%, 0, 0) to center align absolutely regardless of the width of the element.
obvs, you can make it left: 50%; top: 50%; translate(-50%, -50%, 0) to make it align vertically as well
anyone know if there's a way to set a uss variable via c#? eg.
do this
background-color: var(--colors-bg)
in c# somehow;
myElement.style.backgroundColor = "var(--colors-bg)"
right, but is there a way to use the vars I've set up in uss? Or do you have to manage two lists of constant style variables?
Sure.. Didn't read the uss part. ignore this
var myColor = new StyleColor(new Color(0.141f, 0.440f, 0.231f, 1f));
vis.style.backgroundColor = myColor;
yeah I was looking into that - I couldn't find anything that referenced style variables
oh you mean in the uss.. sorry misread that entirely
hmm, via debugging it looks like VisualElements have a private "variableContext" property which lists all the variables in use as a StyleVariable. Theoretically you could resolve the Color value from that.. but it's not exposed publicly...
that's a bit unfortunate. Looks like I just have to maintain two different variable lists.
Yeah I went with the translate approach as well, seems to work perfectly
Anyone got any idea why this sometimes happens to fonts?
Is there any way to get text to wrap inside a textfield scrollview?
the problem is the scrollview content container expands horizontally for the text, so it thinks it has space... it should only expand vertically
ahh, setting the contentcontainer to flex: column solves it
great
I see in the editor that "Button" is considered a legacy element. What is the intended modern replacement?
Where do you see this?
The TMP version uses Button too, use that instead
fyi, that's UGUI, not UI-Toolkit
I'm seeing after unloading a scene with a lot of UI Toolkit stuff in it, everything is still kept alive in memory. I'm having diffiiculty figuring out why in the memory profiler. Has anyone run into this?
ah, my mistake! Thanks WispBart.
no worries
Seems to me like UI Document is keeping lots of stuff alive after it should have been unloaded after a scene switch
I'm sending a bug report
I don't even think about it, forgot that UGUI once existed in unity lol
Anyone else getting these errors with the demo project?
Also how to make a button in the UI Builder disabled (not interactable). Can't find that option and I know it was there with UGUI 😦
@boreal carbon VisualElement.SetEnabled(bool)
What do I need to change to make a ScrollView grow vertically to fit the entire window? I only have a ScrollView element in my editor window with flex-grow : 1 but it wants to stay 100px tall, even if the window itself is 1000px
Ended up setting Height: 100% and it seems to work fine now
Nvm, changing the window size causes it to never grow back. I'm so confused how it can be this hard
In the UI Debugger there's a "TemplateContainer" visual element, I guess this is what's screwing it up. What causes it to appear? My init logic is just cs private void CreateGUI() { var clone = _previewUI.CloneTree(); rootVisualElement.Add(clone); } where _previewUI is a ref to my VisualTreeAsset
The VisualAsset looks like this, with no USS and a blank TSS:
Anyone can tell me why this happens?
I am having a VisualElement that I want to choose an image as the background. I can click the search and select it from the list but instead of the image the warning symbol is shown and I get this warning.
anyone have any experiences with using figma and converting designs to unity ui toolkit?
Yup. Nothing automated. Make heavy use of SVG.
@static canyon So SVGs are the best route to go then I take it? any other tips or suggestions?
thank you for the help
We prefer it - though not everything renders as crisp as figma so you might want to be a bit flexible about some designs/iconography. We also avoid things like drop shadows. For layout I'd recommend mostly avoiding percentages and instead working more within flexbox layout. Other than that, nothing else that significant springs to mind.
one thing that annoys me when porting from figma is the line height
figma always generates line-height for all text elements but uss doesn't support it
so you have to wrap your text in tmpro tags to make it work lmao
How do I scale the UI good I find that unity automatic scaling is very bad on big screens the text looks like an ant and on smaller screens you can only see one letter
Wow this is shockingly bad
Even just making a health bar from the progress bar element is a nightmare
Hello, I am using UI toolkit for my mobile game. I divide my UI screens to few documents:
- first contains game UI (time, some buttons)
- second contains failed panel (image, failed text, restart button, menu button)
- third contains completed panel (image, text, button for next level, menu button)
- fourth contains pop up panel with items (list of items with buttons for purchase)
Every UI screen has own gameobject with attached UI document, which are located in same scene (on backgroud will be seen actual status of game). Because will be always visible only one panel (UI document) I would like to ask you how I should display or hide this panels. Should I disable UI document component or use DisplayStyle.None/Flex for root VisualElement? Thank you! 🙂
I'm having some trouble with the UI Builder Preview not matching what is displayed in game. For example I have it looking like this in the builder (image 1) and yet when I play it looks like this (image 2) I have no scripts trying to do any logic with these, and other parts of it are working as expected. They were previously displaying but when I attempted to do these through the USS (image3) they began displaying these white circles in playmode. Is there something wrong with how I have this set up? It's not exactly clear to me in any guides or information. In the builder it works great so I just don't understand. Anyone have any insight?
An edit:
each of these circles is a xml template that uses those #need-item-energy .need-border to personalize them, but the shape and sizing comes from the simple .need-item at the bottom there
Make sure you're set to the runtime style, and not an editor style, using the drop-down in the top right of the builder
#🧰┃ui-toolkit message
Dear friends, maybe anyone know about this?
Setting child Picking mode to Ignore helps. Is there any other solution expecially with dynamicly added buttons.
how do i get uiToolkit into my scene?
Can you provide samples for both? Because I had some trouble at the beginning too but now I got it to work mostly fine
Anyone? 😦
EDIT: Okay I just noticed that I just can't use images that are in folders. They have to be in the root Asset folder lol
Can someone tell me why my UI that I made with the Toolkit/Builder is acting like it should in the Builder Preview (hover causes it to get bigger) but in Unity when starting the game it does not respond at all (no hover effect nor click noticing) 😦
Perhaps related to the set up of the UI Document in the scene? Double check you've followed examples of set up for functionality
was this referring to the themes? If so it's my understand this is just for editing purposes, but that my previews of the USS/UXML are not matching the in game version is the problem I'm experiencing. I did mess with those settings but it doesn't change anything.
if you're still having trouble you can use SendEvent to send events to the root document or something. I found that having an Event System or Canvas Raycaster intereres with UI Toolkit
This isn't a UIToolkit issue. It looks like you're just zoomed into the game view https://help.vertx.xyz/interface/game-view/game-view-zoom
Hello I have a question about templates
https://docs.unity3d.com/Manual/UIE-WritingUXMLTemplate.html
In this example we got such template
<engine:VisualElement class="portrait">
<engine:Image name="portaitImage" style="--unity-image: url(\"a.png\")"/>
<engine:Label name="nameLabel" text="Name"/>
<engine:Label name="levelLabel" text="42"/>
</engine:VisualElement>
</engine:UXML>
<engine:UXML ...>
<engine:Template src="/Assets/Portrait.uxml" name="Portrait"/>
<engine:VisualElement name="players">
<engine:Instance template="Portrait" name="player1"/>
<engine:Instance template="Portrait" name="player2"/>
</engine:VisualElement>
</engine:UXML>
How to override portaitImage or currently it is not possible because it is in style property?
You cannot override an element’s name or style attributes.```
I found out that it's the Event System from my Canvas that interferes with my UI Document so that no button clicks on the UI is noticed... Any idea how to fix this?
https://docs.unity3d.com/Manual/UIE-Runtime-Event-System.html
You can also disable the event system or forward inputs to the UI Document elements manually with "SendEvent"
Don't know if that helps I ran into the same problem
Thanks 🙂
I thought about disable the EventSystem too but that sounds a bit hacky..
To make integrating with Canvas/UIToolkit work, I'm rendering UIDocument -> PanelSettings -> RenderTexture -> RawImage that I place on a canvas. So I can render a UIDocument pretty much anywhere other than right on top of the screen
You'd of course still have to tackle the events aspect
@little surge
I read the document you linked but the thing is..
Usage: UI Toolkit elements and uGUI components with legacy Input Manager
Required components: A Standalone Input Module and an Event System components.
Active Input Handling: Input Manager (Old)
I do have that but still doesn't work
Yeah it's kinda vague, I'm out of ideas since I'm new to ui toolkit
Same
Ohhh
@little surge
It's because of the "Screen Space - Overlay"
When I change the Canvas to be "Screen Space - Camera" it works fine
What's the best way to show and hide a Menu (UI Document)?
Like clicking a button to show it and click a Resume button in the menu to hide it again
I tried to enable and disable the UI Document GO but after the disable when I reenable it the Resume button doesn't work anymore
Okay I am doing it like this now. Is it fine?
private void OnResumeClick() {
_pauseMenuDocument.rootVisualElement.visible = false;
}
public void ShowPauseMenu() {
_pauseMenuDocument.rootVisualElement.visible = true;
}
rootVisualElement.style.display = Display.Flex to show, ... = Display.None to hide
Also might want to enable/disable the UIDocument to stop events
That's the way I've saw in some tutorials
Is there a way to have UI scripts execute in editor preview (without game playing) for example I have a script Awake() to set the text color of all the TextMeshPro elements. But it doesn't execute until the game is played, so it's kind of distracting that the text is the wrong color in editor preview
Hello, I'm struggling with nested scroll views on mobile. Currently, it seems that whenever a scroll view is being scrolled, I can't use the other one until it finishes to decelerate completely and stop. Anybody knows how to get a correct behavior ?
So I have a bug on 2022.1.16, where in game mode Dropdown field does not show up on click (it does work on preview mode or if I use uitoolkit debuger). The click event does trigger, so I thought I will just make workaround with ChangeEvent. But I cannot find how do I trigger dropdown menu manually. Anyone could help me with this?
AnydropDown.RegisterCallback<ClickEvent>(evt => {
using KeyDownEvent keyEvent = KeyDownEvent.GetPooled('\0', KeyCode.Return, EventModifiers.None);
((DropdownField)evt.target).SendEvent(keyEvent);
});
Tadaaaa.. Magic. Answering my onw question
what's the difference between IMGUIContainer and Image? or in other words, when would I ever use an IMGUIContainer?
They are completely different things. One is for an image, and the other is for IMGUI content?
oh, the old Immediate Mode GUI. well, that was unexpected. really bad abbreviation. why is there no image control in UI builder?
Anyone know how I can properly resize progress bars? When I make one it's too large. I'm working with a 160x144 resolution
Setting size and absolute positioning does not help
So I recently made a switch to UI Toolkit but I am unable to figure out how would I go about making a joystick in UI Toolkit. Before I just used this joystick asset
https://assetstore.unity.com/packages/tools/input-management/joystick-pack-107631
If anyone knows any asset which works for UI Toolkit or how to go about making one yourself please help me out.
UI Toolkit Joystick
I have drop down field. It is all nice and sweet, but if I press Shift + AWSD + space, it trigger if I clicked on that button. I think it is from story that this combination trigger UI navigation or something. Which I would like to dissable. Any tips?
when does gap come to ui builder?
I overuse it in react and from now on I feel so limited and cannot make a flex look pretty
how come I am the only one wondering about it
I have some problems with Scrollview on after building to a mobile device. When I use the simulator in unity the scroll feels good but when I build it to a device to feels really bad.
It feels like there is a max speed so when I drag my finger fast it goes a lot slower than I expect it to.
It also looks really laggy when i release my finger. As long as I hold my finger on the screen and move it up and down it looks okay but as soon as I release it is like the fps goes form 60 to 5 (I have fps counter and it says 60 all the time).
Is this something that can be fixed? What am I doing wrong?
You're gonna have to use margin-top/bottom like the rest of us peasants
Is it possible to create an implicit conversion from custom control to VisualElement so that it is possible to use Query to find ur custom control?
You can query your custom control directly unless you're referring to a uxml template?
anyone know why my editor is rebuilding (and discarding changes) when i select another window after working in the ui builder? So basically I work in the builder window. Then i need to click an asset or something. No other modifications and it just closes it without any prompt to save and reloads the previous UXML document
sometimes i can just alt tab and come back and it does
Hello, how do I change caret color of a text field?
I'm getting this ugly black caret in my dark theme
trying to use
#unity-text-input {
caret-color: var(--color-text);
}
prints errors to console
(--color-text is defined and works fine in other parts of a stylesheet)
Thanks!
Is there a way to make all children of a visual element with row direction to take an equal amount of space, without growing or shrinking, while still filling whole row?
aka, if I just have a row with flex-grow: 1 children, then they tend to change size when u type in one of them
and overflow way past the container when exceeding limits
Normal fields handle overflow by themselves, not shoting field way past the screen
Does UI Toolkit have any regard to Rect Transform?
what do you mean?
So I'm doing Screen Space - Overlay in Render mode for the Canvas. I have a Canvas nested in a Canvas and I want the nested Canvas to be smaller than the root
Using UI Toolkit seems like the only way to position my canvas is using the uxml layout
I tried to build my game and OOF, does runtime version of UI toolkit doesn't have any fields?
this is what I have after removing UnityEditor import
ahh i think i understand now. Yeah pretty much only though the uxml. It is possible through code to but you're better off using the docs.
those are editor only
could create some custom ones but sadly the editor ones aren't included
yeah i think i figured that out, to build the entire UI there and then just display and undisplay them
here i was creating some canvas system...
Yeah, figured so
and to use them at runtime I need unity 2022
these label elements inside the button container element both have the same USS class selector, however when i attempt to change the styles on one it doesnt update for the other like it should. any ideas why? the top level buttons share a similar class name to each other and changing the styles directly on the button itself changes the other button styles like it should. not sure what the difference is other than that the label is an inner element. help please
are you applying it inline on the specific instance or are you apply it to the style sheet (top left, .button-selection)
if you inline, it will override everything
ui document worldspace possible?
I have a nasty feeling of ui toolkit being better meanwhile worse as I cannot figure how to make a world space canvas with it
each UI document always faces you in the eyes and positioning it gives no use
heeeeey
bye bye ui toolkit
ok but
Is it possible to render UI Document on a render texture?
doing so I will be able to put a document in a world space
though I am still not sure if it will process clicking
maybe you can check this https://assetstore.unity.com/packages/essentials/tutorial-projects/ui-toolkit-sample-dragon-crashers-231178 I think they used ui toolkit x render textures at some point
as for the world space ui. no and yes. You can set ui elements based on the screen space conversion from world space position. Granted you wouldn't have the depth. The ui will always be rendered in screen space overlay. It is possible to scale things as well based on perspective but you'd have to do the math and it would probably get expensive with the ui rebuild
Referring to things like health bars floating above moving characters etc
on the style sheet its top level. though i cant really tell what in the stylesheet window on the right is coming from the stylesheet itself and what is considered inline, watching a youtube tutorial i was lead to believe that turning inline styles on the right panel using the "extract inline styles to new class" button would turn all inline styles into the class styles and then everything in the right side window would control the styles for the class, not the inline styles
it will only do it with the inlined styles that are defined when you click the button
select the class in the upper left and try modifying the values you need in the inspector instead of directly selecting the object in the hierarchy
that must have been what i did
im starting over now on this.
one last thing. when i do something like put in a button, then give that button several child components, is there a way to save that overall component as a 'new' component? so that i can use it later in other UIs / scenes / etc.
kinda like how you can create prefabs for gameobjects?
You could turn it into a template. just right click the object and turn into template
it will save it as its own UXML file and you can just throw it in from the Project -> UI Dcuments
gotcha. thank you for your help, i appreciate it
no problem
Can someone give me a brief hand on the behavior I'm seeing with customuxmltraits?
when using the in-editor designer and I define "UxmlFactory" as follows:
public new class UxmlFactory : UxmlFactory<CommandBuffer, TextField.UxmlTraits> {};```
it displays an inputfield
however, when I use my own:
public new class UxmlTraits : TextField.UxmlTraits
{
UxmlStringAttributeDescription m_Template = new UxmlStringAttributeDescription { name = "template-text", defaultValue = "Default" };
UxmlStringAttributeDescription m_Prefix = new UxmlStringAttributeDescription { name = "text-prefix", defaultValue = "" };
public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
{
base.Init(ve, bag, cc);
var ate = ve as CommandBuffer;
ate.Clear();
ate.templateText = m_Template.GetValueFromBag(bag, cc);
ate.prefix = m_Prefix.GetValueFromBag(bag, cc);
}
}```
it suddenly does not
I'm not instantiating any additional children, but I am calling the base class
so I would expect at least as much as that one instantiates
but for some reason it generates zero children
nevermind it's obviously because I'm clearing the children after the init. It's just so illogical that init gets called at every property update I didn't even think of that
Is there a way to get UI Toolkit working with gamepad/keyboard?
It really feels like it was only designed with mouse/mobile in mind.
When I build in 2022.2.0b8, I cannot click any buttons on my UI Toolkit buttons.
DOTS Project.
It works before upgrading to 2022.2.0b8
Using last LTS
But it still works in Editor
Also can't focus on it using keyboard inputs like tabbing or arrow keys.
Trying to find out if anyone knows why before reporting as a bug
i want to make ListView. i read unity manual but i don't understand. if anyone have best reference video or example suggest me?
Anyone knows what's the way to place hyperlinks via code?
Does Ui builder support sp or dp? Seems to only rely on px and percentage
I'm using the text mesh pro for text. Me and my friend are using git to develop our game. When I pulled changes I got this error in my editor
The file 'Assets/TextMesh Pro/Examples & Extras/Resources/Fonts & Materials/Roboto-Bold SDF.asset' seems to have merge conflicts. Please open it in a text editor and fix the merge.
There is a few more for diferent fonts but I don't know how to fix it. Help appreciated
If i wanted to allow a click through a visualelement that is covering another. How would i do that? For example
Root:
ParentA:
ChildA
ParentB
ParentB (blocks ParentA and ChildA) I want to allow Child A to be clicked.
Problem is I want PB to do an action if ChildA was not clicked.
but PB must be in front
parent B -> picking mode = ignore
Kind of, i wanted to register a click event (in the event that A isn't hit that will activate on PB. Might need to reevaluate the structure
Has UI Toolkit out grown the built-in canvas system yet? Which is more performance friendly? Has more features etc.
I am basically asking If I should start using UI Toolkit for my UI or is it not ready yet?
It's not ready yet. But it's getting there. A lot of the features it lacks most projects I use would need them, like shader support, and the few remaining rich text items that are missing. I also think some of the things that are missing on the USS side make it difficult to do some things, and you'll generally always run into something wrong (usually some annoying UX problem) with a control that you have to work around or spend ages fixing.
In some fronts, like Layout, and the creation of custom meshes (it has an awesome mesh drawing API, similar to web SVG), it's worlds above UGUI.
If you are making something small or limited, I would certainly advise giving it a go. Beyond that I think it's still for those whose hatred of UGUI has reached the point where blood sacrifice to the UIToolkit god of bug reports is preferable
It might be usable for bigger UIs as well, where you would be doing some hacks around ugui, so now you just do different hacks around toolkit
Anyone know why
ve.style.display = DisplayStyle.None
might not be working?
groupbox and visual element difference?
is there any advantage of groupbox over VE?
they feel identical
Thanks for your elaborate response, looks like I'm sticking with UGUI again :/
No worries. Although it sucks, I think everyone's experienced with its problems and workarounds that it's likely the best option for most people for a release or two still
svg's are not supported yet, are they?
Hello! Im looking for a way to add a button to my scene using UI, but I don't want it to stick to the camera. I want to be able to click it and change scenes, but I don't want it to always be on screen, in the same spot. Is this possible?
is there a way to access the properties of the UI Toolkit elements via skript, like the Backgroundcolor of a Button?
found it, it is <UIElement>.style.<whatever you need>
buttonPlay.RegisterCallback<PointerDownEvent>(click =>
{
Debug.Log("button clicked");
});
why pointerdownevent does not work even though it is allowed?
in case I have to see if button down and up
not only a trivial clicked event
oh no no no, magically it has started working again
thank you so much, phantom discord guys
though if you want pointerdownevent to work you should override trickle to trickledown value:
buttonPlay.RegisterCallback<PointerDownEvent>(down =>
{
Debug.Log("button clicked");
}, TrickleDown.TrickleDown);
I honestly have no idea why, can you explain it to me??
It's possible the layout still isn't complete. A suggestion to test this is to try using the schedule api within FirstLayoutCallback(). e.g.
contentContainer.schedule.Execute(evt => ScrollTo(Children().Last()));
Or to be extra sure it's not a matter of which frame i t is: ```cs
contentContainer.schedule.Execute(evt => ScrollTo(Children().Last())).ExecuteLater(200);
So I have a script that whenever you collide with a coin it adds one to a counter and reflects that through text. Oddly enough, whenever I first boot up the game it returns this error message, however after restarting the scene in the game menu, it works as expected. This is my first time working with anything text mesh pro related so I'm kind of lost.
what packages for ui-t do you know?
I have found goofy paid assets on store but they are no use
I mean, you said it.. it's goofy 😃
I am sorry?
ok I have partly figured it out why slider is so wrong out of the box
for some reason its components are set to absolute which makes the slider so small despite what's inside it and moreover it makes down in the hierarchy elements to overflow
I have played around with it and now things are getting clearer and even more ambiguous
to get a slider in a right condition you should set its tracker and dragger to position relative 0 0 0 0
and now it looks as supposed to
I've just learned about PhysicsRaycaster, which is an amazing tool to handle pointer events in an in-game world. But by the looks of it Raycasters are a part of UnityEngine.EventSystems, which is tied to the "old" UI system with events like IPointerDownHandler. There is also ExtendedPointerEventData in UIToolkit which extends PointerEventData from UI. But I concerned whether it's reasonable to use Raycasters with UIToolkit and is there an alternative. 🤔
If I disable and re-enable the object containing UIDocument, how come Doc.rootVisualElement.panel becomes null?
The panel is always necessary to move the UI around, but I can't disable the object otherwise it becomes null forever.
how do you instantiate visual elements?
I cannot see other options to create inventory slots from script
ok ok ok that is how you make an instance of a visual element
and here is an visual element blueprint
I like the fact that there are very few tutorials about UI toolkit on youtube and ones that are present do bad job explaining simple things with over engineered code
How can I tell Unity to open the keyboard for textinput on my phone. When i click on a textinput element nothing happens. Shouldn't the be a Keyboard that pops up?
PS: I am using UI Elements
Just text input
I'm not sure I understand the canvas, canvas renderer etc correctly. What is a "Canvas renderer" and how does it relate to UI objects?
I know I'm supposed to keep the number of Canvasas low, but does the same apply to Canvas Renderers?
canvas renderers are required to render a UI component like an image or a text
Hello, it is possible to create Scroll view with only vertical scroll bar, which will start from bottom? Thank you! 🙂
just woke up and I misread that 🤣 ... that's for the mode not the direction
Hey guys!
We're using UI Toolkit on our project and I'm just creating the screens as we implement their features.
We are doing some housekeeping on our code and project files. One of our tasks is creating and using name rules or everything.
One thing we neglected so far was naming conventions for our UI Documents.
Is there any guides or best practices for UI Toolkit naming conventions?
I only know about the Formal Kit conventions. Basically a mix of underscores and capitals. Basically prepending everything with Formal Kit (FK):
FK_A_Btn or FK_this
Though some prefer the more verbose:
Fkit_a_button, Fkit_a_panel.Q<Fkit_1>() etc
Jokes aside, I'm also interested in if there are conventions out there.
In the web dev world there is a CSS/HTML convention called BEM - (Block, Elememt, Modifier) that can be used to name classes. That be useful to read into
I've been burning brain cells trying to figure out how can I instantiate Foldouts in UI Builder, inside another Foldout
I already have a foldout uxml template
I call a foreach which loops 2 times
Inside that foreach I do
var instance = foldoutLayerTree.Instantiate();
instance.AddToClassList(DOT_FOLDOUT_LAYER);
var newDataEntry = new DataEntry();
newDataEntry.SetFoldoutLayerFields(instance); // Q<> the fields so that they can be set with the SetData
instance.userData = newDataEntry;
newDataEntry.SetData(this, data, _settingsData.dataList); // Sets the foldout child fields to what they are supposed to
```but nothing appears in the window
data is the current object being iterated in the foreach
Where are you actually calling Add?
Canvas renderers are part of UGUI, not UIToolkit
Ah, I didn't see a channel that seemed more fitting to ask basic UI setup questions
Yes maybe UI-UX, I don't know there really isn't one. But nevertheless
having worked a bit with UI Toolkit and a LOT with UGUI, I have to say I never want to touch a rect transform again if I can help it
Yeah I already solved with the help of @rough scarab. Thanks tho
I have an optimisation problem
when I slide scrollbar on mobile build, it is 30fps thought the rest of the game is 60fps
what is to blame?
have you used profiler?
no
it's a great time to do it
and what can I see there
Profiler details how your game is performing
what's causing spikes, what's causing lag, etc...
my game is performing absolutely fine I assure you
it has 5 UI panels and that's all
I have not written a single Update() in any script
in your profiler you will see what is causing a 50% fps drop on scrolling
Is rich text broken in UI Builder?
is there any attribute on ui builder where you can disable a button?
Hey guys, how would any of you go about making scalable text (best-fit) using the UI Toolkit?
Rich text is a fairly new thing in UIToolkit, and not all versions of Unity support it yet. The tags are even partially consumed if it's unsupported. Annoyingly it's taken up to like 2023 to get full support... and I don't even know if it's full-full yet, just most of it
Yeah, lime isn't a color in 2022.3 yet.
Anyone know of a breakdown of the features of the 2023 ui builder vs 2022 and 2021?
2023? in what universe do you live
2021: uncompleted
2022: uncompleted
2023: uncompleted but we keep a strong hope
guys got a tricky situation]
can you create a stylesheet in runtime?
or can I duplicate a stylesheet that exists and apply different parameters to its selectors?
I need it for UI themes feature
consider a class .button-theme with background-color: black and when I switch a new theme it changes to background-color: white
it may sound crazy but I am still not sure
ive learnt that a foreach with UiToolkit gives you errors,
is there anyway to get around this? or do i have to code in a way where i dont use foreach?
Elaborate
sorry i was doing smt else.
InvalidOperationException: Collection was modified; enumeration operation may not execute. other people said that that happens when you use a foreach with UiToolkit 🤷♂️
That happens when you iterate over something and remove/add elements to it
It has nothing to do with UIToolkit specifically
if you're removing stuff as you go, use a reverse for loop (you can autocomplete one with forr)
Is it possible to change a vertical scrollview from scrolling down to scrolling upwards?
I want my items in the scrollview to start to add at the bottom of the scrollview. That I has been able to do with flex direction and align settings. The problem I am having now is that the scrollview only scrolls down even tho all my items are stacked at the top this means I scroll into nothing. How do I solve this issue?
do you want to switch just colors? Could you use nested variables? Not sure if they work for uss as well
Maybe people are confused because if you do that with monobehaviours it will actually work since the destroy is delayed
how to drag and drop uss classes onto objects?
wait how do I change styles in runtime at all?
you cannot add stylesheets in runtime
you cannot change stylesheet values in runtime
Sorry to trouble you UI Toolkit users - I'm a Unity UI user about to start a project with a serious amount of UI, and I'm thinking about switching over to Toolkit... But I really need something that's stable and predictable. If you don't mind me asking, how rock-solid would you say the UI Toolkit is?
That's very useful, @rough scarab , thank you. Sorry if you keep getting hit with the same questions over and over. For the moment, then, I'll stick with UGUI. I'm not doing anything exactly revolutionary, so the stability would be welcome.
My imported vector images are very aliased. I tried bumping the MSAA in pipeline settings to no effect. Any ideas how to improve the look?
so the only way to get a reference to a UI element is still to manually Query the root documentand find for example "MyButton"
wtf
what happens when I designer pops in and changes the name in the UI builder to MyCoolButton
code gets borked
yep
but thats dumb...
I mean if the new Input system can generate Input Action References
honestly, they just need to know that they shouldn't change the name of things especially if you're following the naming conventions.
that's kinda the point though; you hand your designer a list of button names and they hand you back a UXML file
it's been working pretty well for us
Anyone had any luck with binding property to MultiColumnListView? I can't get it working :/
can scrolllview elasticity be modified nowadays?
30 fps is fantastic value unless you see world at more than 30 fps ha-ha-ha
just why...
why is it hardcoded...
people can still see the difference between 30-60 fps
whats the differences between ListView and ScrollView?
Can anyone explain to me what's happening here? I have ListView with all my steam friends. It's working 100% when it's first initialized, but when i start to scroll it seems like the images are getting added to each item 🤔
I’m failing to change edges’ color on my graph view. I’ve checked the layers in the UIBuilder debugger and I found that an Edge element contains a .edge class with CustomStyleProperty(ies) like
—edge-color
—selected-edge-color
Etc
I tried adding a custom class that changes these properties, I tried referencing .edge class and changing the properties and tag them with !important, but nothing changes in the graph view.
So, I had to remove ".edge" class from the Edge element and added ".custom-edge". However....
an edge is still whitish, a selected edges are ok. I can't seem to find what property colors an edge🤦♂️
.custom-edge {
--selected-edge-color: rgba(175, 255, 0, 1.000) !important;
--ghost-edge-color: rgba(175, 255, 0, 1.000) !important;
--edge-color: rgba(175, 255, 0, 1.000) !important;
color: rgba(175, 255, 0, 1.000) !important;
background-color: rgba(175, 255, 0, 1.000) !important;
-unity-background-image-tint-color: rgba(175, 255, 0, 1.000) !important;
border-color: rgba(175, 255, 0, 1.000) !important;
--edge-width: 5;
--layer: -10;
}```
it's all the same color
How does data binding work with UI Toolkit?
I want to make a list view and add and filter the content at runtime. If I remember correctly there is some way of data binding but I can't find any documentation about it
listView.itemSource = myList;
you can easily bind a list with ListView while you can't with ScrollView...
to filter it, you must sort/filter the itemSource in this case, the list
What would the benefits of using a scrollview be then?
Very useful for custom UI stuffs
Ahh I see
don't forget to listview.Rebuild()once you update something on your list
Hi, I'm new here, been using UI Toolkit for a bit. Been having issues with this particular scene in a project I'm working on, don't really know what's causing it.
tldw: UI Breaks on resize (even though the aspect ratio is the same). Also breaks going in and out of the scene.
how can I set background image here?
it is not purely obvious
ok, fantastic. I somehow found it out by myself while furiously clicking through parameters
UIT is awesome and I wish unity team pull themselves together and make what was put down on the roadmap including box-shadows and etc.
I like it so much that it is possible to create your own UI elements templates and create those from script and see UI change on fly
Thanks to UIT I can switch themes simply. For example background-image is subscribed to theme changed Action just like any other individual component here: buttons, labels, icons
I wish they went on expanding its possibilities further
Hello! I'm trying to make an image expand depending on the child text, but even after using horizontal layout group, and content size fitter, the image stays at the same size. What did I do wrong?
@halcyon wraithwrong channel - 1
@halcyon wraith call this method after you change text inside https://docs.unity3d.com/ScriptReference/Canvas.ForceUpdateCanvases.html
BTW if you want to make responsive UI without much pain in the ass better go try UI toolkit
Anyone heard of the UIDocument not updating when calling something like this? I have a normal game hud, and then a menu that swaps between, but while working in the editor, this code call only updates it after I leave the game view window and toggle between scene view or uibuilder and then back to game view, but it also changes other things. But it does update only after I swap the views. Kinda confused on this one?
can you show the pic of it not working?
just to get better understanding of your trouble
yeah one second
For further understanding of the open, this is all that's happening ```
private void Open()
{
_content.style.display = DisplayStyle.None;
_footerBar.style.display = DisplayStyle.Flex;
OpenTab(tabs[0], tabButtons[0]);
}
private void OpenTab(SelectableTab tab, Button button)
{
_selectedTab = tab;
tab.Open();
}```
Jus trying to understand. The UIDebugger also shows the same state problems until I swap windows. Though that doesn't make any sense to me. I went searching through the docs, seems like no one else has mentioned this situation yet that I could find
this looks like a unity bug to me
does that only happen if the ui builder is open?
as in you have it in tabs
No it happens with or without it open
This seems like a basic function of the uiDocument so I'm surprised this is in existence if it is a bug
you can try inspecting the element with the ui debugger to see if it is maybe improperly positionsed
The debugger shows the state as if I didn't hit the button to trigger the display change, but updates when I swap GUI windows still
This also forces an update when I leave unity and come back to unity.
Sorry and thank you! Where should I post those?
one channel above
ui ux is component based UI that uses canvases
and UIT is different
It sounds like fun so I'll give it a look!
I suppose I should use this UIT for the canvas no?
Yup omw
I have to warn you beforehand that there are greatly fewer UIT tuts than 'old' UI tuts
I'll just watch as much as possible, and probably go through the unity course
yeah
Just a question, can it help with scriptable objects?
what?
are you curious if you can use scriptable objects data to create UI elements?
it is possible
I'm trying to make some kind of RPG mixed in with the hearthstone card mechanic. So I'm trying to store the damage, mana, and other effects in variables that I can use later. Will the UIT help styling everything?
yes it will
I am feeling I know what you mean
wait a second
I have my themes as scriptable objects and UIT iterates through the list to create custom theme buttons and give them styling. All the rest of UI gets updated as soon as theme changes
@halcyon wraith 👆
It does look pretty good! I can use that to change the theme when it's the enemy's turn as well!
Also, it seems that while I was trying to try a last few things on the old UI system, I came across this problem: I had an image as a background for some text, and wanted it to scale depending on the size of the text. If UIT can do that I'll cry and start using it right now
do you know the basics of html and css?
if not - better learn it
you should do so bcs UIT inherited web-development style and so has 'margins' and 'paddings'
and just like in web-dev if you put a text inside an empty box, the box will scale automatically
so yeah it is what you are looking for
genshin impact UI is built with UIT by the way
@halcyon wraith
We’re you disabling the game object or the undocument ? I’d you disable a UIDoc everything that you bound in code needs to be rebound. So you might have a reference to a button or a label. When you reenable the doc will rebuild the whole visual asset tree from scratch. Then the label and button won’t be active in the doc. You’d have to queue for them again
I am looking at drawing some arrows from one element to another. Anyone know of some kind of resource that might exist?
Kind of like you’d see with a node graph
And not only for the editor
I had a few tries with both so it shouldn't be too hard to pickup!
it does seem like a better alternative, so I'll make a new project and try to mix in with my current scripts
dang I am currently limited to 2021 😦
Hello! This might sound a bit dumb, but how do I add an image inside my visualelement?
Found it! Background did it
Round 2: I have this UI of a card. I have a script that allows me to create cards info. Is there a way for me to create multiple of those UI (one for each cards info) and interact with them? (scale on hover, dragable,etc)
All I tried to do was change display style to flex/none, is this what you mean? The object never gets disabled otherwise.
My code callbacks persist as a debug in it notes the correct functions are being called
This is not #🧰┃ui-toolkit, but try putting auto size. For better response try #📲┃ui-ux
That's what uxml documents and visualtreeassets are for
I basically have this question, but the unity representative didn't understand his question so he's just referring to the docs:
https://forum.unity.com/threads/setting-the-binding-path-to-a-value-inside-a-struct.839182/
in my particular case: I'm trying to bind an inputfield to the value of a field inside a struct, inside the serializedobject
solved the above, turns out you can just access struct properties by supplying the field name: m_Struct.field
Will give a look thx!
Hi, I wan to use list view for a list of rooms available for my multiplayer game. But I can't understand how to do. I have read the docs. Can someone help me please
Having a weird alignment issue with UI Toolkit. In Ui Builder the layout looks exactly how I set it but when I open my custom editor window it isn't what I set
the ui builder probably has a different tss theme selected
make sure your windows are using the same theme file as ui builder
how to you set a TSS theme. I only see how to make one
it should be in the upper right corner of the ui builder viewport
as to how that can be done for editor windows - i don't know
I've only done runtime ui toolkit stuff, we use panelsettings there for that
Why can't I see the TwoPaneSplitView in UI Builder??
If you ever wanted to see USS selectors for Unity's built-in Visual Elements 👇
I created an editor window to export built-in style sheets. https://github.com/ErnSur/UI-Toolkit-Plus
I just read that you cannot use UI Toolkit in "World Space"
Does this mean that you can't use it to make ingame interactive monitors/screens (i assume each screen is its own canvas) like pic rel?
so you wouldnt use a canvas, you mean?
do you know what they mean by not being able to use UITK in World Space?
it means you can't use a canvas and place it anywhere, yes
you have to render it to a texture
you can't render the actual geometry in worldspace is what they mean
I'm new to these terms and I dont understand this. Wouldn't a render texture applied to a square model located exactly where the computer screen is, function the exact same as a Canvas placed at the same location?
And that square model, you could place anywhere, no?
from what I remember, a canvas does not use a rendertexture
it just renders each element already in worldspace
in comparison, ui toolkit renders each element to a renderterxture after everything has already been rendered
what if its interactive?
you can make it interactive
wouldnt constantly updating the texture be very horrible performance wise
just gotta trace a ray to the plane and map the coords to ui toolkit space and pass in the events manually
ohhh i see
so the difference is that its easier to make a canvas interactive
because its already hooked up to the mouse and is hooked to the mouse/button events
but for a texture, you'd have to manually send a raycast event to the class that controls the UI, for each possible action you want to detect
yes
but otherwise, theres no hassle in putting it into world space
the other problem you will face is one frame delay
the only issue is the lack of native input support
a single frame?
so like, inconsequential if you're just putting some graphs/numbers on the texture
I guess
the issue is that ui toolkit renders after overlays
it is not possible to inject any rendering commands after that
so you'll have to wait until the next frame to render your quad
Also don't forget that you can use both at the same time. And use UGUI for world space
I don't plan to have any actual ingame UI, like a HUD, apart from the Play game, Load, etc. screen
I just want some screens like pic rel
would you use UGUI for this if you were me? I have experience with neither
i would still recommend using ugui instead for anything world-space
I guess Canvas is easier to work with
because passing events is a hassle? (i agree with u)
though it probably wouldnt matter if you used analog buttons instead
like an ingame button object
to control stuff on the screen
because it's a new framework that does not support 3d and any problem you encounter will not have a solution someone else figured out
oh ye, good point as well
if you are an experienced programmer/unity user then go for it
exp in programming, near to nothing in unity unfortunately
then use ugui
gotcha
to add stuff that isnt text
like, custom geometry or a spectrogram or something like pic rel
on the canvas
do you have any idea how you'd accomplish that?
apply a shader to a texture maybe and insert it in the canvas perhaps?
As soon as you want to show something on a monitor in a 3d world like in that screenshot I think you're better off working with a rendertexture anyhow
then you can do all the shader magic you want when displaying that texture
Do I need a UIDocument in order to render my visual tree? is there any other way?
What about combining it, such that the canvas contains the interactive UI - and layered on the screen on top of the canvas is a rendertexture that communicates with the UI script in the canvas?
like this
I mean, you can, just play the rt as a rawimage
im just thinking it would probably be easier
But if you want the UI to feel like it's part of the world (on the screen) it's easier to render it to a texture and put that texture on the 3d model
but i have no exp with either
doesn't a world space canvas UI look perfectly like its part of the world/reacts to lighting/shaders etc?
I thought they were equal in the visuals department
No
damn, okay
what tool would you use for the GUI then?
as in the ingame monitor that i pictured
I just told you
here
You'd use a render texture yeah, but for making the UI I mean
When you use a render texture, you have to manually pass input events right? with raycasting
I'd make the UI in UI toolkit, and render that to a rendertexture and show the rendertexture on the monitor
Alright, thats exactly what I wanted to know, thanks mate
I was going to start creating all this stuff on a canvas and then find out it looks scuffed
so suffice to say you saved me some hours
I haven't generated events for a UIToolkit render texture, but I have done the same with UGUI
have you used any of the open source implementations for passing input events to UI toolkit in world space?
oh okay, I just found something on github since it wasn't natively supported. I also watched a vid about it being done manually
No I just write that kind of stuff myself
https://forum.unity.com/threads/handling-pointer-events-on-render-texture.1158272/#post-7432208
Should be a sample here
I found a full tutorial for it
(note this is just for anyone stumbling across) https://www.youtube.com/watch?v=fXsdK2umVmM&list=WL
We've seen that we can create interactive screens by using worldspace UI. But those are drawn much like normal UI so they don't get lighting and other effects. In this tutorial I'll show you how we can create interactive screens that are fully in-world and will receive lighting etc just like any other object in the world.
Find the code here: ht...
Any ideas what would cause a mismatch in distance between text in ui builder and in game? Match game view is active and the xml looks clean.
<ui:VisualElement name="Middle" style="width: 200%;">
<ui:VisualElement name="Logo" style="background-image: url('project://database/Assets/Visual/logo.png?fileID=2800000&guid=fe7a50efab26c324ca268f9e95e4a0e2&type=3#logo'); width: 100%; height: auto; -unity-background-scale-mode: scale-to-fit; flex-grow: 1;" />
<ui:VisualElement name="Buttons" style="height: auto; align-items: center; flex-grow: 1;">
<ui:VisualElement name="Panel" class="panel_background" style="height: auto; width: 50%;" />
</ui:VisualElement>
<ui:Label text="Version:" display-tooltip-when-elided="true" name="Version" class="label" style="-unity-text-align: upper-center;" />
<ui:Label text="© TEIXHEX LLC, 2022" display-tooltip-when-elided="true" class="label" style="-unity-text-align: upper-center;" />
</ui:VisualElement>
hmm. forcing margin and padding to 0px fixed it. guess it was a default issue.
i have a visualElement where i dynamically put in labels (inventory) from the left to the right. for every 10 labels, i want to start a new row.
do i need an visual element for every row, or is there a setting which can line-break on certain conditions (like exceeding size of the parent-element or something like that) ?
Is google correct in telling me there's no way to clone a visual element that includes the children through scripting?
Edit: other than manual creation, assigning styles etc
This should automatically happen if you are putting children in if your wrap mode is set instead of going straight out under flex
alright, then i have to check the wrap mode and other settings i guess. thanks!
im encountering rendering issues with background-image in ui builder, is this a compression thing?
i switched to clamp + trilinear, still looks kinda shitty
here it is with compression disabled, max size 2048, resize algorithm mitchell, color format automatic
they're all clipped around the edges for some reason
so i think this is a trilinear filtering issue, the assets aren't clipped on point but definitely still need AA
How can I detect when the mouse enters an editor window?
Hey, I've been having some display problems with drag n drop. It's code related to ui-toolkit so I'm not sure if this should be placed in a code channel or here. Let me know if it should be in a code channel and I'll move over.
Overall, the UI-Toolkit is really nice, but since switching to "scale with screen size", my drag n drop display hasn't been working. Depending on the resolution, when grabbing the element, it doesn't go based on cursor position. It looks like it's offset by a particular variable (based on screen size) and I'm not sure what.
Here's my code
Vector3 pos = Input.mousePosition;
visualDragger.style.top = Screen.height - pos.y - (visualDragger.resolvedStyle.width / 2);
visualDragger.style.left = pos.x - (visualDragger.resolvedStyle.height / 2);
The visualDragger is the element that's displayed as the dragged item.
To achieve this I used this thread: https://forum.unity.com/threads/how-do-you-move-a-visualelement-to-the-position-of-a-mouse.1044385/ however nothing there seems to fix this problem.
This used to work normally, and now it only works when I set my game resolution to the same "reference resolution" as the scale with screen size section.
Thank you.
hey idk if this is the right channel but i need a grid layout for my UI Objects but i need to be able to have the cells be different sizes from one another ive checked online and cant find anything that fits my need anyone have any ideas
anyone have some suggestions for getting the scrollview to work with the mouse to drag like you can on mobile? The Scrollview PointerDownEvent listener returns if the input is mouse
Easiest is if you can lock either column width or row height. For instance, if they're all the same height, make a visual element for each column and give each column [amount of rows] children of the same height. If you do need both to be variable, you'll have to update the heights of each visualelement in a row (so across all columns) manually.
If you want to lock width instead of height you can switch column and row in the above.
Can you use the size of the parent element or the panel, instead of Screen.height
I'm pretty sure there was a function to convert coordinates from screenspace to the visualelement's local space too
Sure, next time I work on it I'll try out the panel. That seems a bit more promising
How do you retrieve the size of the panel? It doesn't seem to be easy, looking up the docs nothing is really coming up.
Also I tried local space, and for some reason it would stutter back and forth when I'd do that.
visualElement.panel doesn't seem to have any size properties.
oh nvm I tried that.
I can try it again maybe I did something wrong
Vector3 pos = Input.mousePosition;
pos = RuntimePanelUtils.ScreenToPanel(visualDragger.panel, pos);
visualDragger.style.top = pos.y - (visualDragger.resolvedStyle.width / 2);
visualDragger.style.left = pos.x - (visualDragger.resolvedStyle.height / 2);
Would this be the right way of using it?
seems so
Still doesn't work if changing resolution
Though this time the offset is consistent, rather than decreasing based on distance from the top left corner.
Then that's a different problem
It's above the cursor when I change from 2560x1440 to 1920x1080
The reference res is 2560x1440
well
I used Screen.height because without it, moving up and down is reversed (as in when I move my cursor up, the element moves downwards)
Maybe I shouldn't use screen.height but something else
idk I just set style.position to absolute and change the position
Yeah that's what I do too lol
Do you use scale with screen size?
on the panel settings
would that be like
e.RegisterCallback<OnMouseMove>(evt => ...)
yes, but for a drag operation you also need to capture the mouse so you keep receiving that event
i think I saw a tutorial that did all this somewhere
This is using the built in drag and drop system?
I didn't use that because I couldn't really understand it well, so I did my own
what built in drag and drop system?
Unity UI Toolkit has a built in drag and drop system with DragAndDrop handlers but I couldn't figure it out at the time.
I used this tutorial for placing items, not necessarily moving items around. I might rebuild my drag and drop using this then, thanks
DragAndDrop? That's editor only afaik