I tried searching the forums, the docs, and the internet to no avail.
How do I set the cursor style for a VisualElement to one of the predefined classes in code? (Arrow, Text, Split Resize Left Down, etc)
I am aware the cursor can be set using style.cursor = SomeCursorStyle;
The problem is I want to use the SplitResizeLeftRight cursor and I can’t seem to find where the static classes are defined. Obviously I can do this though a stylesheet, but I want to do it through code.
What I ended up doing was to create a style class in USS for each cursor I needed. Then I would call AddToClassList/RemoveFromClassList to set the desired cursor.
Using USS styles is the recommended approach for assigning default cursors. Most cases of default cursors are while hovering anyway, which uses the :hover pseudo state, and pseudo states are equally not accessible in C#.
Hi, I am a bit lost with this in Unity 2021.3. When I set a cursor via USS, all I can specify in UIBuilder is a texture. How do I change its size and hotspot? Or how do I specify a standard cursor type like “resize horizontal”?
This still seems to be a relevant issue since 2019. For example, I can’t define Unity’s built-in cursors in UIBuilder even with Editor Extensions Authoring enabled. So it seems the USS is the only way to achieve that,
I don’t know if this was valid back in 2019 when this quote was written, or if I misinterpreted it, but in CSS, for example, and probably USS too, if you set the cursor to the element, it becomes the cursor for the element when hovering. In other words, there is no need for pseudo states nor they are relevant in this scenario.
Sure it works, but it is via USS, not via code. Instead of setting the name of the element, which is useful for other purposes, I suggest you add a class:
public static class UnityDefaultCursor{
public enum CursorType
{
Arrow = 0,
Text = 1,
ResizeVertical = 2,
ResizeHorizontal = 3,
//....
// you can check this from ui debugger, so if u dont know what im saying then dont use this solution..
}
private static PropertyInfo _defaultCursorId;
private static PropertyInfo DefaultCursorId
{
get
{
if (_defaultCursorId != null) return _defaultCursorId;
_defaultCursorId = typeof(Cursor).GetProperty("defaultCursorId", BindingFlags.NonPublic | BindingFlags.Instance);
return _defaultCursorId;
}
}
public static Cursor DefaultCursor(CursorType cursorType)
{
var ret = (object) new Cursor();
DefaultCursorId.SetValue(ret, (int) cursorType);
return (Cursor) ret;
}
}