#↕️┃editor-extensions

1 messages · Page 24 of 1

bright phoenix
#

I tried this, and sadly no. The first time you enter a scene they actually do seem to be the same, but if you go through any other scene or perhaps even if you have a multi-scene setup - the IDs won't match :/

#

Thought of that, but feels a bit dirty. What if user saves in-between these steps? Or some other weird thing happens.
It is an option though, perhaps I should explore it more, but it does feel like it has a large room for issues to be discovered later. 🤔

#

I think there was a way to set things as "don't show in inspector" and "don't save" with some flags, though I'm not sure whether they work nowadays - last I checked they had issues. But if they do work, it might be a pretty decent option to add some marker component with some ID, just like I need it. 🤔 Thanks @tender olive, will explore! And let me know if you have alternative ideas. 🙂

peak bloom
#

Today I found out that [InitializeOnEnterPlayMode] is much earlier than playModeStateChanged, good to know. That is very important to know

tender olive
bright phoenix
#

Making a debugger helper of sorts where you can right click an object and say "I wanna debug this guy", and then in code you can add a conditional breakpoint that only breaks on the selected objects.

#

This works, but I'm storing the objects by ID or instance, either way, that doesn't quite work when exiting entering play mode, which may be a bit annoying because you can't select some object to debug and carry that over multiple sessions.

#

Not sure it's that big of a deal. It helps me anyway and is just a few clicks, but am planning to put the code on some public repo for people to use, so I thought I'd look into making some improvements that I can think of. 🙂

peak bloom
#

I wonder if making a static resetter package would be worth a hassle 🤔 , so the idea is to disable the domain-reload in the editor and just crawling all statics via their namespace and set their default values (for value types) and null for (for classes)

worthy mist
#

I'm trying to create a tool to automagically write a cs class containing the structure of an ui prefab... so far I've got it working but whenever I try to add the feature to include nested prefabs into the generated class, the info I need from the asset yaml doesn't seem to be present... Unity doesnt seem to add the stripped part of the prefab pointing to the monobehaviour/prefab =(... does anyone know some api that could help me here?

bright phoenix
queen niche
#

Hey there, I am facing FileIOPermission present both System.Security.Permissions and mscorlib problem, anyone knows the solution?

waxen sandal
#

Get permissions

half idol
peak bloom
#

default for classes is "null"

half idol
#

Yeah that's what I mean...

You said default for value types and null for classes... but to generalize you could just use default for both value and classes, right?

worthy marlin
#

Does someone know if it's possible to have shared library built for a unity game ?
I have a .csproj outside of unity game folder and i want to buiild it to use it inside of the game.
I tried MSBuildForUnity but it didn't work

wary gate
#

Hi,
anybody else having the Problem, that the Rider Editor Plugin of Unity is not compatible with Riders flatpak?

specificly both are installed through Flathub.
I first thought that It might be a problem with flatpak isolation, but that cant really be it, because Vscodium is seen just right. so its prolly just that the editor extension does not support the flatpak for rider?

(and no, I cant use the toolbox, because im running an immutable distro (Kinoite) & the rider plugin wont allow me to run that one inside one of fedoras toolboxes)

wary gate
#

I found a Workaround, which lets bot h Flatpaks Connect, and tells me that the Editorplugin for Untiy is the Problem:

Ive just Installed Rider through toolbox and flatpak, so I can select it.
and if I manually open the flatpakversion (the one that actully works under immutable systems) It is ablle to connect to unity.
So the Problem has to lie in the way that the Unity Editor Extension discovery.

plucky knot
#

Does anyone know how to access the settings asset field there (at top)? I need to for a niche case, but even after looking at the editor on github I can't find that field. Plus I don't know what this panel is Resources-wise so I can load it up in the first place LUL

plucky knot
#
try {
    var graphicsSettingsAsset = AssetDatabase.LoadAssetAtPath<Object>("ProjectSettings/GraphicsSettings.asset");

    serializedObject = new SerializedObject(graphicsSettingsAsset);
    var iterator = serializedObject.GetIterator();
    iterator.Next(true);

    while (iterator.Next(true)) {
        if (iterator.propertyPath == "m_SRPDefaultSettings.Array.data[0].second") {
            iterator.objectReferenceValue = hdrpSettings;
            serializedObject.ApplyModifiedProperties();
            break;
        }
    }
} catch (Exception e) {
    Debug.LogError($"Failed to set m_SRPDefaultSettings to {hdrpSettingsPath}: {e}");
}

I figured it out 👍

nimble urchin
#

Hello, I want to write a rightclick menu that converts all the materials on a gameobject in my scene (or prefab!) and converts them into another type of material suitable for the current SRP. I'm struggling with a couple of concepts around this though - specifically if I just replace the sharedMaterial nothing happens, and if I replace material in the renderer, unity tells me I've made a mistake. Whats the correct process for something like this?

#

some thoughts: should I be making assets out of these upgraded materials? If so, is there a way to trace back where a material in a scene came from asset wise?

#

so I can plonk it next to it?

gloomy chasm
#

Is it possible to draw a selection outline without using a GameObject? The only options I am using are Handles.DrawOutline that takes either GameObjects or MeshRenderers, but I am drawing a mesh with the Graphics API.

gloomy chasm
alpine bolt
#

Is it an outline in the scene?

gloomy chasm
#

Only method though looks to require one sadly

bright phoenix
nimble urchin
#

if anyone else ever runs into it

#
//This works
Material[] materials = rend.sharedMaterials;
for (int i = 0; i < materials.Length; i++)
{
    materials[i] = someReplacementMaterial;
}
rend.sharedMaterials = materials;```
but

rend.sharedMaterials[i] = someReplacementMaterial;

alpine bolt
#

Has anyone ever managed to use UIElements.PropertyField and built a derived class selector? It seems that PropertyField is quite limited for this kind of thing and requires a dummy ScriptableObject with T Value instance in order to work.

bright phoenix
nimble urchin
#

yeah, I thought setting the element directly would be okay, so that caught me off guard

gloomy chasm
gloomy chasm
native geode
#
[CustomPropertyDrawer(typeof(AnimCommand))]
public class AnimCommand_Drawer : PropertyDrawer {
    float totalHeight;

    public override float GetPropertyHeight(SerializedProperty property, GUIContent label) {
        return totalHeight;
    }

    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
        EditorGUI.BeginProperty(position, label, property);

        ...

        Rect startRect = new Rect(position.x, position.y, position.width, EditorGUIUtility.singleLineHeight * 4);
        property.isExpanded = EditorGUI.Foldout(startRect, property.isExpanded, new GUIContent("Animation"));
        totalHeight += startRect.height;

        if(property.isExpanded) {
            ...
            EditorGUI.PropertyField(...);
            totalHeight += pos1.height;
        }

        EditorGUI.EndProperty();
    }
}

This is code and I left out code that is not needed

Basically, in list, every instance of the AnimCommand takes 'totalHeight' value from the last element in the list
it works fine outside list.
Anyone have idea what might cause this? So far chatgpt and google didnt give me answer, might be that iam not asking right keywords

#

Basically i calculate totalHeight in onGUI, based on selections and save it
then get height just returns that value

this is just simple prototype but it will have lots more options

bright phoenix
#

you're kinda not supposed to do that... getHeight is called first and should calculate the height and then that height is passed to OnGUI

#

but, my assumption would be that here it calls all of them through the same prop drawer (not sure if it does it otherwise), so of course the height is based on the last thing that was drawn

#

@native geode

gloomy chasm
#

So, exactly what Pulni said haha.

native geode
gloomy chasm
bright phoenix
#

generally that's what you're supposed to do, yes... if it makes you too unhappy, you could try storing them in a dictionary by serialized property, but that's kind of a hack

bright phoenix
#

not sure how that's even more unhappy 😄

native geode
gloomy chasm
native geode
native geode
gloomy chasm
native geode
gloomy chasm
native geode
gloomy chasm
alpine bolt
#

Have you seen Jason Weinmann’s video on creating concrete objects that derived from abstract classes and interfaces using a GitHub package?
I’m testing how UIToolkit handles setting managed reference properties and the issue that I’m seeing is that when you change a property of this type is that it will multiply the choice field because it already exists in the previously drawn property drawer

#

I achieved a successful result but I had to use an unsaved scriptable object instance with a generic class type and use their serialized properties to build a proper Property Field

atomic sable
#

anyone know what could cause this error?

Cannot create Settings Provider for: CreateSettingsProvider
UnityEditor.SettingsService:OpenProjectSettings (string)
TerraPunk.Editor.PathDataBuilder:OpenSettings () (at Assets/Content/UnitManagement/Scripts/PathData/Editor/PathDataBuilder.cs:661)

I was changing the settings provider after it has been working for almost a month and it seems to have stopped working. I renamed some stuff, moved some stuff around... but even if I just comment everything out so it just returns a blank settings provider i still get the same error. :/

#

what I mean by that is:

[SettingsProvider]
public static SettingsProvider CreateSettingsProvider()
{
    return new SettingsProvider("Project/Path Data Settings", SettingsScope.Project);
}
atomic sable
#

ah, there was an exception occurring in the class, but outside that method, that was not being logged.

heady shadow
#

Is there a way to override how these are rendered? I would like to change the text ideally, but if that's not possible, whatever is possible (color/shading)

alpine bolt
# heady shadow Is there a way to override how these are rendered? I would like to change the te...
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;

[InitializeOnLoad]
public static class UnityHierarchyScenes         
{
    static UnityHierarchyScenes()
    {
        EditorApplication.hierarchyWindowItemOnGUI += OnHierarchyWindowItemOnGUI;
    }

    private static void OnHierarchyWindowItemOnGUI(int instanceID, Rect selectionRect)
    {
        for (var i = 0; i < SceneManager.sceneCount; i++)
        {
            var scene = SceneManager.GetSceneAt(i);
            if (scene.GetHashCode() == instanceID)
            {
                if (scene.isLoaded)
                {
                    var content = new GUIContent("S");
                    var color = new Color(0.5f, 0.5f, 0.5f, 1f);
                    var backgroundRect = selectionRect;
                    backgroundRect.width = 18.5f;
                    EditorGUI.DrawRect(backgroundRect, color);
                    EditorGUI.LabelField(selectionRect, content);
                }
            }
        }
    }
}```
#

This will draw something. What you need to do after is match the background color, match the font weight, size and position and draw over it.

heady shadow
alpine bolt
#

FYI, a Scene is a struct, but just wanted to showcase this

alpine bolt
#
private static void OnAttach(AttachToPanelEvent evt)
{
    evt.destinationPanel.visualTree.RegisterCallback<DragPerformEvent>(Dragged, TrickleDown.TrickleDown);
}
        
private static void OnDetach(DetachFromPanelEvent evt)
{
    evt.originPanel.visualTree.UnregisterCallback<DragPerformEvent>(Dragged, TrickleDown.TrickleDown);
}

private static void Dragged(EventBase evt)
{
    Debug.Log("Drag performed");
}```
I'm having trouble using this `DragPerformEvent`. It never triggers on drop/release
#

OnAttach and OnDetach work fine

gloomy chasm
alpine bolt
gloomy chasm
gloomy chasm
#

I see the example, but they have changed the input system and the drag and drop system a couple of times now, so the examples are probably no longer up to date. Assuming you copy pasted the entire class 1 to 1 and it isn't working.

alpine bolt
#
private static void OnAttach(AttachToPanelEvent evt)
{
    _dropArea.RegisterCallback<DragPerformEvent>(Dragged);
    _dropArea.RegisterCallback<DragExitedEvent>(DragExited);
    _dropArea.RegisterCallback<DragLeaveEvent>(DragExited);
}

private static void OnDetach(DetachFromPanelEvent evt)
{
    _dropArea.UnregisterCallback<AttachToPanelEvent>(OnAttach);
    _dropArea.UnregisterCallback<DetachFromPanelEvent>(OnDetach);
            
    _dropArea.UnregisterCallback<DragPerformEvent>(Dragged);
    _dropArea.UnregisterCallback<DragExitedEvent>(DragExited);
    _dropArea.UnregisterCallback<DragLeaveEvent>(DragLeft);
            
    _dropArea = null;
}``` Changed the target. PickingMode is set to Position. DragExited works. DragPerformed, nope
alpine bolt
#

So in order to DragPerformedEvent to fire, DragAndDrop needs to be updated. Solved.

plucky knot
#

So various things update when you re-focus the editor (like modifying the manifest, or resolving packages), so is there a way to force a "re-focus" so I don't have to click out and back in of the editor?

plucky knot
#

Not sure what that has to do with this hmm Found EditorUtility.RequestScriptReload(); so I'm using that for now (reloads scripts, but doesn't recompile them).

alpine bolt
#

I misread

north sphinx
#

any idea on how to calculate IMGUIContainer from UI Toolkit layout correctly to match underlying inspector size?

#

var imgui = new IMGUIContainer(() => { inspectorElement.editor.OnInspectorGUI(); });

#

I basically have this where editor is UnityEditor.Editor

#

but layout auto resolves to just default 22f

#

which is incorrect

#

and looks like this

#

things just overlap each other

alpine bolt
#

What class and namespace is that inspectorElement variable?

#

@north sphinx

north sphinx
#

It's just my own helper

        private class InspectorElement : VisualElement, IDisposable
        {
            public UnityEditor.Editor editor;
            public IMGUIContainer container;

            public void Dispose()
            {
                if (container != null)
                {
                    container.Dispose();
                    container = null;
                }

                if (editor != null)
                {
                    Destroy(editor);
                    editor = null;
                }
            }
        }
#

to properly dispose things

alpine bolt
#

That’s why you aren’t using Unity’s InspectorElement?

north sphinx
#

oh

north sphinx
#

yeah, found it

#

let me see

#

I wasn't aware of that even

#

lol

alpine bolt
#

new InspectorElement(asset);

north sphinx
#

it appears to have same problem

alpine bolt
#

What’s the code like now?

north sphinx
#
            _root = new ListView
            {
                makeItem = () => new VisualElement(),
                bindItem = (element, i) =>
                {
                    var comp = _components[i];
                    element.Add(new UnityEditor.UIElements.InspectorElement(comp));
                },
                unbindItem = (element, _) => { element.Clear(); },
                itemsSource = _components
            };
peak bloom
#

where's your imguicontainer?

north sphinx
#

don't need it with InspectorElement

#

it creates it for me

peak bloom
#
                //var NormalInspector = new IMGUIContainer(() => {       getEditorGui.DoDrawCustomIMGUIInspector(component); });
                InspectorElement uieNormalInspector = new InspectorElement();
                uieNormalInspector.Bind(new SerializedObject(component));
#

thats from the source example

north sphinx
alpine bolt
#

Is the Editor you are trying to draw your own or is it default?

north sphinx
#

I just want to draw whatever normally gets drawn

#

for game objects for example

#

it may be IMGUI one (Odin Inspector) or VisualElements one

alpine bolt
#

The list elements you are drawing, is it a custom editor or a default editor?

north sphinx
#

what list elements?

#
        private void CreateGUI()
        {
            _root = new ListView
            {
                makeItem = () => new VisualElement(),
                bindItem = (element, i) =>
                {
                    var comp = _components[i];
                    element.Add(new InspectorElement(comp));
                },
                unbindItem = (element, _) => { element.Clear(); },
                itemsSource = _components
            };

            FillData(typeof(Transform));

            rootVisualElement.Add(_root);
        }

        private ListView _root;
        private readonly List<Component> _components = new();

        private void FillData(Type type)
        {
            _components.Clear();
            foreach (var guid in AssetDatabase.FindAssets($"t:{nameof(GameObject)}"))
            {
                var assetPath = AssetDatabase.GUIDToAssetPath(guid);
                var asset = AssetDatabase.LoadAssetAtPath<GameObject>(assetPath);
                if (asset.TryGetComponent(type, out var comp))
                {
                    if (comp.GetType() == type)
                    {
                        _components.Add(comp);
                    }
                }
            }

            _root.Rebuild();
        }
alpine bolt
#

You are using list view, are you not?

north sphinx
#

here's whole code

#

it is a list view, yeah

alpine bolt
#

So the list has visual elements that populate the list view

peak bloom
native geode
#

I have my own property drawer and it uses foldout.
I want so that when I hover on the header of fouldout to glow whiter, to signal to the user that he can interact with the foldout
How would I do that
This is current state

public class MicroBarAnimation_Drawer : PropertyDrawer {
   public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
      EditorGUIUtility.AddCursorRect(headerRectWithArrow, MouseCursor.Link);
      if(headerRectWithArrow.Contains(Event.current.mousePosition) ||
          property.isExpanded) 
      {
          Microlight_DrawUtility.DrawHoverGlow(headerRectWithArrow);
          Microlight_DrawUtility.DrawHeaderBottomOutline(headerRectWithArrow);
      }
   }
}

It works and glows but with huge delay, basically when OnGui is called
Calling OnGui every frame is bad so what i thought I would do is have property Hovering
which when changes state from true or false, calls OnGUI, on top of regular OnGUI

anyone know how maybe default implementation is done? like button or list hover?

peak bloom
#

I used it to display default component inspector

#

AND in a ListView too

north sphinx
peak bloom
#

so same like your case

north sphinx
#

so my problem is figuring proper item height

#

on it's own it doesn't work properly

alpine bolt
peak bloom
alpine bolt
#

But maybe try to figure out why it overlaps first?

peak bloom
alpine bolt
#

Where’s the source to that?

north sphinx
#

while it's clearly more than that

#

question is, how to figure actual item height

#

and how to apply it

peak bloom
alpine bolt
alpine bolt
#

I'll test it. But still, this post is very old

peak bloom
#

yeah my snippet is very ancient too

peak bloom
#

you can basically apply your own guistyle for the imgui part

north sphinx
#

according to your code

#

your IMGUI part is never called

#

you only use inspector element

peak bloom
#

proly, there was issue with propfields, the inspectorElement one was to workaround it iirc

north sphinx
#

I mean

#

I'm fine either way

#

but either way I don't have proper size

#

for inspector

peak bloom
#

oh! you meant the commented imguicontainer, yeah, but it was working fine other than the quirks with propsfield

#

it's basically copy/pasted from the old uitollit source

#

it was commented bcos I changed the custom editor for the component to uitoolkit iirc

north sphinx
#

it's whatever, I just need proper size of that thing notlikethis

peak bloom
north sphinx
#

check how your list view gets created

#

there may be a mention of item height somewhere

peak bloom
north sphinx
#

huh?

peak bloom
#

it's shown in the snippet file

north sphinx
#

I don't get how that affects anything or returns me content height

peak bloom
#

lmao the old one is much more complete than that

north sphinx
#

I bet they just added imgui support to that inspector element

peak bloom
#

proly yeah

peak bloom
north sphinx
#

I just want list view to look readable

native geode
#

Also

public class AnimCommand_Drawer : PropertyDrawer {
    public override float GetPropertyHeight(SerializedProperty property, GUIContent label) {
        return totalHeight;
    }
}

This is custom drawer for my AnimCommand class
MicroBarAnimation_Drawer has list of the AnimCommand classes
how to access height of AnimCommand_Drawer from the MicroBarAnimation_Drawer which has list of AnimCommands?

real spindle
#

I usually have a similiar hover check to yours but then then inspector needs to be constantly updated (requiresConstantRepaint) so there are probably better ways lol

native geode
real spindle
#

Hmm actually that might block you from interacting with the foldout

visual stag
north sphinx
#

To have auto size

native geode
#

I wanted to add the red button to my custom Property Drawer and that seems as really hard task but I have seen it everywhere like Odin Serializer.
I don't think they are using UI toolkit since that is not a new tool.

How would I create button of custom color?

gloomy chasm
native geode
native geode
#

i have been trying to use other colors. but on labels and didnt work

gloomy chasm
native geode
#

thanks, that was good find, will help in other areas too

gloomy chasm
waxen sandal
#

Or you can provide a more neutral white button

barren moat
#

Can I override or augment the behaviour of an existing asset importer?

#

More specifically, can I write my own importer that runs after an importer in a UPM package, or disable the importer from that package and use my own fork or subclassed package?

waxen sandal
#

What kind of existing asset importer?

barren moat
#

this one specifically

#

I want to fork it

#

Ideally just disalbe the one in the package and rewrite that importer

#

But obviously I can fork the whole package.

waxen sandal
#

I wonder if they ever implemented registering a scriptedimporter with an existing extension

#

It's been a complaint for years

barren moat
#

I have never really used importers before

#

But this one has a wontfix limitation

#

And replacing it seems to be the easiest way forward for my particular situation

#

@waxen sandal you know what... Most of the API I'd need is private anyway so I think I'll just fork the whole project.

waxen sandal
#

Yeah that's usually how it turns out :/

dull verge
#

I found this script to create a text file on the current folder I'm in and it works great.
https://pastebin.com/XrufxuYj
Is it possible to modify it so that, when I create a new text file, I instantly go to edit it's name? Just like when creating a C# Script.

waxen sandal
#
    ProjectWindowUtil.CreateAssetWithContent(filePath, contentAsString, texture2DOptional);
``` If oyu need a unique path
vestal sand
#

How do I unlink a project from the version control?
I want it to then link to a fresh new repo

waxen sandal
#

This channel is about creating editor extensions, not about how to use Unity products

dull verge
waxen sandal
#

Yes?

dull verge
#

Is it possible to mimic that?

waxen sandal
#

Doesn't CreateAssetWithContent also do that?

dull verge
#

Oh it does? Oh ok

waxen sandal
#

I think it does

#

There's an api that also lets you do that manually but I forgot what it's called

#

ProjectWindowUtil.StartNameEditingIfProjectWindowExists

#

But that's a lot more complicated

dull verge
#

thanks

indigo condor
#

Does anyone knows how to create that message created with IMGUI but with unity UI Toolkit?

gloomy chasm
fickle quarry
#

I am working on a git package, which means the contents are imported in the Packages folder.
I still need to change the material (or shader) of a renderer in a prefab when a different render pipeline is detected.
Is this allowed? I am not sure if the packages are editable when imported

visual stag
devout saddle
#

I am making android apk update pop up using google play in app update plugin, where user gets a pop in app when there is new update available for the app, but in 'AppUpdateInfoOperation' this is giving app not owned anyone know whats the reason

pale carbon
#

is there a details explore view in unity editor ?

fickle glacier
#

Is there a way for me to create a custom open behavior for a custom asset type in the editor? Like for example, when you double-click on a C# file, it opens it in your IDE, or when you double-click on a prefab, it opens it in an isolated scene. I'm trying to make an asset type that automatically creates a C# file of the same name, and double-clicking it will open the C# file in the IDE.

twin dawn
#

there any known pitfalls with UI Toolkit TreeView in an editor window that would cause it to always automatically expand all nodes on a domain reload? I have Auto Expand disabled, and even when manually calling treeView.CollapseAll(); it still ends up fully expanded after each domain reload.

rotund lava
fickle glacier
rotund lava
#

I think there might be a way to do that
I have used it mostly for opening custom editor windows, so I needed to know the type

#

i think you can use Selection.activeObject and just check the type of the object that way

#

can't remember if we are meant to post screenshots of code but just as an example:

fickle glacier
# rotund lava i think you can use ``Selection.activeObject`` and just check the type of the ob...

It doesn't seem like that would work for me, since I would need to check the file extension rather than the type. I'm trying to make a custom asset that's basically a json file with a special extension, and only want to run the OnOpenAsset for that extension. Is there a way for me to get the file extension from the object or the instance id? I don't really see anything that includes the file path.

rotund lava
#

I think it is possible
The docs page hints that you can use external tools to open it but doesn't give an example
You can get the relative file path via AssetDatabase.GetAssetPath and I imagine then just check the path to see if it contains the extension?
Alternatively, you could use Path.Join() and get the full path if you need that instead
I'll post what I've got in a sec

#

Also turns out previous me didn't realise you can just use the instanceID instead of messing around with Selection.ActiveObject

public class TempCommandTest
{
    [OnOpenAsset]
    public static bool MyOpenAssetMethod(int instanceID, int line)
    {
        Object obj = EditorUtility.InstanceIDToObject(instanceID);
        string relativePath = AssetDatabase.GetAssetPath(obj); // in my case this returns: 'Assets/New Custom File.myextension`
        return true;
    }
}
#

if you need the fully qualified path i think there would be a bit of fiddling around involved because both AssetDatabase.GetAssetPath() and Application.dataPath contain the Assets/ portion of the path

fickle glacier
#

Thanks, this works great! I'll just use string.EndsWith to check for the extension.

rotund lava
#

nice, glad to help
i find the custom editor stuff very confusing sometimes lol

pale carbon
rotund lava
# pale carbon using UnityEditor; //add into c# code for AssetDatabase.GetAssetPath() relativeP...

thanks for the input, realise I could have included the using UnityEditor; tag but I notice that a lot of people in here don't bother
the person who asked the question just wanted to find the file extension, however just thought I'd clarify:

the issue with just appending the strings as I think you suggested (or even using Path.Join()) is that both AssetDatabase.GetAssetPath() and AssetDatabase.dataPath() include the Assets\ folder, meaning that path would be incorrect, as below:
D:\Unity\Projects\MyGame\Assets\Assets\MyFile.json
there might be an existing or alternative way of getting the full path for an asset, but if you decide to use those two strings you would need to truncate Assets\ from one of them

gloomy chasm
indigo condor
# gloomy chasm It is in the editor namespace, the name is the same a well, `HelpBox`

so how could i add inside this scrollview? ```html
<ui:ScrollView scroll-deceleration-rate="0,135" elasticity="0,1" mode="VerticalAndHorizontal" name="TemplateListScrollView" style="left: auto; width: 100%; margin-right: 0; padding-top: 15px; padding-right: 3px; padding-left: 3px; background-color: rgba(0, 0, 0, 0); margin-left: 0; flex-grow: 1; padding-bottom: 3px;" />

gloomy chasm
indigo condor
#

and then...?

gloomy chasm
#

<eu:HelpBox/> or maybe it is ue...?

indigo condor
#

lemme try :>

indigo condor
gloomy chasm
#

Ahh it is uie

indigo condor
#

and to add it text it would be like this?

gloomy chasm
#

No, there is a message property I think

indigo condor
#

thanks!

gloomy chasm
#

nice!

indigo condor
# gloomy chasm nice!

And do you happen to know any website with usable icons for the Unity editor or icons in general... no? Because I want to add a trash can icon to this button, and I don't really know what resolution the icon should be or anything... I just know that the color it should have is one that in hexadecimal is like this #eeeeee (I can quickly change it in Photoshop).

gloomy chasm
# indigo condor And do you happen to know any website with usable icons for the Unity editor or ...

This goes over a bit how to make them .
The style of icon is called Material Design. Google has a bunch of icons. But the issue with them is that they are 24x24 pixels where as the Unity ones need to be 16x16. So what I tend to do is to find one on google icons that works for what I need, and then recreate it (ish) but staying on a 16x16 grid.
https://www.foundations.unity.com/fundamentals/iconography

indigo condor
#

Thank you so muchh

gloomy chasm
#

You're welcome 🙂

pale carbon
pale carbon
atomic sable
#

theoretically this would set this element to have a height of 50 pixels with no max height, right? What instead happens is that the height gets set to 50 pixes and stays at 50 pixels no matter how tall the window is. :/ am I missing something?

#

in fact thats what looks to happen in the preview, yet in the editor window it does not.

visual stag
#

If not, they won't grow to fill the space that contains them

atomic sable
visual stag
atomic sable
visual stag
atomic sable
visual stag
#

TemplateContainer can be targeted in USS, or you can style it inline via code

pale carbon
#

what does it need in package manager to be included to support webp, similar but (not .psd), here is a example file that works in browser, but unity editor needs smth? file:// gstatic1_webp.webp

atomic sable
# visual stag TemplateContainer can be targeted in USS, or you can style it inline via code

Hey vertx, what is the proper way to do this? Right now I basically have a few UXML docs and instantiate them in the script and add them to the root in the CreateGUI method of an editor window. If I style the template container, it's applied to all template containers as my uss is applied to all the UXML docs. I don't think I should have to create a new style sheet right? Is there some way to add a style class to the template contianer?

indigo condor
#

how could i make the text to look like this when the window is smaller?

pale carbon
#

SmallFonts

visual stag
indigo condor
barren summit
#

hello guys! I need help!

I am creating a editor extension for slicing sprites and create animations.
Everything is working, except one thing.I want to organize states in my state machine so it doesn't look like this.

controller is my AnimatorController and I used controller.layers[0].stateMachine.states[i].position bud didn't work.

My code:

void StatePosition()
{
    for (int i=0; i < controller.layers[0].stateMachine.states.Length; i++)
    {
        controller.layers[0].stateMachine.states[i].position = new(3 * i, 0, 0);
    }
    AssetDatabase.SaveAssets();
}```

And sorry my poor English and feel free to correct me, both in code and in English.
abstract olive
#

does anyone know how I can sample a 3D animation given a frame on a gameobject in a preview window?

civic light
#

Nevermind, I tested it, and it works perfectly! Thank you very much @bright carbon , this issue was driving me up the wall!

visual stag
#

I would use the generic version of LoadAssetAtPath instead of this casting and typeof stuff

#

otherwise, looks fine 👍

violet jetty
#

Hey guys. Hope it is correct section for the question 🙂
Does anyone know how to add Sprite field here? ( see picture ).

Trying to learn this stuff. Code should be something like nodeContainer.mainContainer.Add(sprite).
But I get an impossible conversion. Object that is passed to method should be of type UIElements.VisualElement

gloomy chasm
violet jetty
#

Actually already found info on some random video. Had to to:
var sprite = ObjectType()
{
type = typeof(Sprite)
}

I wanted field to appear on node editor panel, so that I can assign sprite

gloomy chasm
#

Oh yeah, you just add a ObjectField VisualElement.

violet jetty
gloomy chasm
#

Oof, that's rough

atomic sable
#
using (new Handles.DrawingScope(color))
    Handles.Label((gridSystem.GridLayout.GetCellCenterWorld(path.first) + gridSystem.GridLayout.GetCellCenterWorld(path.last)) / 2f, new GUIContent($"{path.first} : {path.last} | {path.target}"));
```What I do wrong? Why isn't it colored? (Color should be the same as the path line)
last marten
#

Hello, I am trying to run the editor in batchmode to make an android build. I use -builtTarget Android and the logs say it switches successfully. Later in our build pipeline we check EditorUserBuildSettings.activeBuildTarget however it always seems to return Windows instead of the actual active platform. I don't see anything else in our code that changes the build target.

Is this expected behaviour? If so, how do I get the actual build target? From command line?

#

I'm using 2021.3.31f1

last marten
#

Nvm, I think the build agent is using a different unity install that's missing the android module

alpine bolt
#

Anyone knows why sometimes I have to do cs propertyField = new PropertyField(property); propertyField.Bind(property.serializedObject); // <======= THIS LINEin order for the property to draw?

gloomy chasm
alpine bolt
# gloomy chasm Because otherwise it won't be bound to a serialized object...

Yeah but doesn't this line in the source code deal with that? Doing just the propertyField = new PropertyField(property); is usually enough for it to work.

public PropertyField(SerializedProperty property, string label)
    {
      this.AddToClassList(PropertyField.ussClassName);
      this.label = label;
      this.RegisterCallback<AttachToPanelEvent>(new EventCallback<AttachToPanelEvent>(this.OnAttachToPanel));
      this.RegisterCallback<DetachFromPanelEvent>(new EventCallback<DetachFromPanelEvent>(this.OnDetachFromPanelEvent));
      if (property == null)
        return;
      this.bindingPath = property.propertyPath; // this line
    }```
gloomy chasm
#

The reason why you only 'sometimes' need to do it is because custom Editor automatically do call the .Bind() method, and you don't need to for custom PropertyDrawer because it is propagated down from further up.

#

You do need to do it for EditorWindow because where should it get that value from otherwise?

alpine bolt
gloomy chasm
alpine bolt
#

because custom Editor automatically do call the .Bind() method this part

gloomy chasm
wispy delta
#

If the issue is that your changes to the state positions is not persisting you may need to mark the asset as dirty before saving assets

barren summit
wispy delta
barren summit
#

my script is already serving its purpose, but I want it to result in an organized state machine

wispy delta
barren summit
# wispy delta Try setting the AnimatorStateMachine dirty. I think that's where the states are ...

don't work.I think the problem is not when saving. See this code. In my debug log it is showing the position without my change that I made in the previous line, that is, it does not even change the position of the states.

void StatePosition()
{
    /*o objetivo desse método é organizar a posição dos states na state machine,
    mas não está funcionando*/
    
    for (int i = 0; i < controller.layers[0].stateMachine.states.Length; i++)
    {
       controller.layers[0].stateMachine.states[i].position=new(300*i,0);
       Debug.Log(controller.layers[0].stateMachine.states[i].position);
    }
    EditorUtility.SetDirty(controller.layers[0].stateMachine);
    AssetDatabase.SaveAssets();
}```
I tried set dirt before and after the loop "for"
wispy delta
#

Ah. Looks like ChildAnimatorState is a struct so when you index into states[i] you're getting a copy of the state, not a reference. Try doing something like this

// Get copy of state
var state = controller.layers[0].stateMachine.states[i];
// Change position
state.position = new(300*i,0);
// Reassign state to array
controller.layers[0].stateMachine.states[i] = state;
barren summit
gusty mortar
#

Hi ! I have a question about EditorApplication.delayCall : in the documentation, it is said that each function is only called once. Do I still have to make the handler unsubscribe from it afterward or is it handled automatically ?

waxen sandal
#

You don't have to

gusty mortar
#

Nice. Thanks !

visual island
#

Hey people. Trying to write some custom property drawers, but implementing it with ui toolkit approach(CreatePropertyGUI) causes a No GUI Implementation error in the inspector. I'm using unity 2022.3 and Use IMGUI Default Inspector is turned off. I thought the inspector is supposed to be rendered by ui tookit in this situation, but it doesn't..? the inspector is not any custom editor. Just a serialized MonoBehaviour.

#

And the code is something like this:

public override VisualElement CreatePropertyGUI(SerializedProperty property)
{
    var container = new VisualElement();
    var owner = property.FindPropertyRelative("Owner");
    var size = property.FindPropertyRelative("Size");
    container.Add(new PropertyField(owner));
    container.Add(new PropertyField(size));
    var slots = property.FindPropertyRelative("ItemSlots");
    for (int i = 0; i < slots.arraySize; i++)
    {
        var slot = slots.GetArrayElementAtIndex(i);
        var slotContainer = new VisualElement();
        slotContainer.Add(new PropertyField(slot.FindPropertyRelative("Item")));
        slotContainer.Add(new PropertyField(slot.FindPropertyRelative("Amount")));
        container.Add(slotContainer);
    }
    return container;
}

Is there an issue with the code maybe?🤔

waxen sandal
#

Can you show the whole class?

visual island
#

Just this:

    [CustomPropertyDrawer(typeof(Inventory), true)]
    public class InventoryDrawer : PropertyDrawer
    {
        public override VisualElement CreatePropertyGUI(SerializedProperty property)
        {
            var container = new VisualElement();
            var owner = property.FindPropertyRelative("Owner");
            var size = property.FindPropertyRelative("Size");
            container.Add(new PropertyField(owner));
            container.Add(new PropertyField(size));
            var slots = property.FindPropertyRelative("ItemSlots");
            for (int i = 0; i < slots.arraySize; i++)
            {
                var slot = slots.GetArrayElementAtIndex(i);
                var slotContainer = new VisualElement();
                slotContainer.Add(new PropertyField(slot.FindPropertyRelative("Item")));
                slotContainer.Add(new PropertyField(slot.FindPropertyRelative("Amount")));
                container.Add(slotContainer);
            }
            return container;
        }

    }
#

Could it be that NaughtyAttributes package somehow forces the IMGUI mode?

#

I see it in the stacktrace when trying the OnGUI version

#

Also, one thing I'd like a confirmation for: custom properties are basically a nice way to display data that unity can serialize anyway, right? It's not like I can access the object instance and draw fields for whatever of it's members that I want, even those that can't be serialized?

#

Basically, if I want to create a property drawer for an inventory containing array of slots that contain abstract-generic type item instances, I'm fecked?

    [Serializable]
    public abstract class ItemInstanceBase
    {
        [SerializeField]
        private Item definition;
        public Item Definition { get => definition; protected set => definition = value; }
        public ItemSlot Slot { get; internal set; }

        public ItemInstanceBase(Item definition)
        {
            Definition = definition;
        }
        //public abstract bool CompareDefinition(ItemInstanceBase otherItem);
        //public abstract bool CompareDefinition(Item otherItem);
    }
    public class ItemInstance<TItemDef> : ItemInstanceBase where TItemDef : Item
    {
        new public TItemDef Definition => (TItemDef)base.Definition;
        //public event Action ItemDataChanged;

        public ItemInstance(TItemDef definition) : base(definition)
        {
            //base.Definition = definition;
        }
    }
//There are different generic type instantiations, like
ItemInstance<ConsumableItem>
#

I just want to see a list of item definitions, that are SOs, so no problem to serialize them, but I can't seem to get to them via serialized properties.🥲

#

Is a custom editor window with some reflection my only option?

gloomy chasm
visual island
visual island
#

in the code above there's the private Item definition; field. I just want to draw a list of those in the inspector. The problem is that it's a class field of a non serializable abstract ItemInstanceBase and/or generic classes that extend it.

gloomy chasm
visual island
#

For debugging purposes mainly

gloomy chasm
#

Ahh

#

You have two options. You could serialize them ([SerializeReference]) or you could get the value of the parent class that is serialized using boxedValue (PLEASE read the docs page on it though!!)

visual island
#

How would I access the SerializeReferenced field? With just FindPropertyRelative?

gloomy chasm
visual island
gloomy chasm
#

Sure thing!

winter snow
#

Hi there 👋

I have a custom editor that is on a Prefab. Is there a way to detect when Prefab is instantiated / drag'n'drop into the Scene (not in runtime) ?

#

I tried to use OnEnable on my customeditor but I need to select the GO containing my customeditor to trigger OnEnable

#

I'd like to catch an event as soon as my custom editor is added to the scene

gloomy chasm
winter snow
visual stag
surreal delta
visual stag
#

Yeah, I have my own UITK package that I use

surreal delta
visual stag
#

What do you mean? Like [Label]?

surreal delta
#

like for example, i have an attribute that add a title to the inspector, you can either set a constant string to that title or a dynamic one that uses reflection to grab the string value of something and set the title text to that

#

with ImGUI the inspector always updates based on GUI events, but with UI toolkit the inspector only updates when needed, i need it to basically always refresh and cant figure out how to do that

visual stag
#

I don't really know what the purpose of such a label would be lol

surreal delta
#

its cool to have, you can have it display the date and time

#

or maby a debug value

#

you can basically have it update dynamically based on whatever you want

visual island
visual stag
#

You can modify things after they have been drawn

#

You can modify built-in behaviour

surreal delta
visual stag
#

You aren't living in the dark age

surreal delta
#

you can also use the UI builder window to not have to code the layouts

visual stag
#

You can easily draw an entire inspector for an object without doing some disgusting stuff

#

You can easily draw vector shapes

#

In a few Unity versions your extensions will still work

surreal delta
visual stag
#

Using IMGUI means that your work is on a timer and will be incompatible in the future

#

No comment on when that will happen, but it will

visual island
#

Hmm... But it's all about presentation, right? It's not like it changes the way you access the data, right?

visual stag
#

IMGUI repaints constantly, UITK repaints when things change

#

so yes, it's got different data access

#

More:

  • Amazing debugging tools
surreal delta
visual stag
#

🤷 schedule an event and mark your element as dirty

visual island
visual stag
#

You bind it, and then it checks for changes and does not update the UI unless there are any

#

so if the data isn't changing, the cost of the UI is 0

visual island
#

Okay, but that doesn't change how you access the data. Or rather, you're still limited to the serialized data. Unless you use reflection.

surreal delta
visual stag
#

Well, UITK can be used to draw non-serialized properties easily

visual stag
#

It requires the properties package which for some reason isn't yet integrated, but you can find it in the entities package and in my ECS project I use it to draw some non-serialized data without actually iterating it myself

#

it's a similar setup to the 2023 runtime data binding

visual island
visual stag
#

I think the entities team must have taken the properties stuff and ran with it while the UITK team focused on runtime binding and we have a bit of an SRP situation where these things may get merged back together in a unified way in a few years time ):

surreal delta
#
public override VisualElement CreatePropertyGUI(SerializedProperty property)
{
  var root = new VisualElement();

  var label = new Label(GetNewName(property));
  var propertyField = DrawProperty(property, label);

  root.Add(propertyField);

  propertyField.RegisterCallback((ChangeEvent<string> changeEvent) => Debug.Log("sadsadsd"));

  return root;
}

ok i rly dont understand this, the RegisterCallback should run every time the property field is changed, right? why doesnt it do that, im modifying the value in the propertyField and nothing

visual stag
surreal delta
#

ok that works, but for some reason if i try to change the label text it doesnt

#
        public override VisualElement CreatePropertyGUI(SerializedProperty property)
        {
            var root = new VisualElement();
            var label = new Label(GetNewName(property));
            var propertyField = DrawProperty(property, label);

            propertyField.RegisterCallback<SerializedPropertyChangeEvent>((changeEvent) => 
            { 
                label.text = GetNewName(property);
                Debug.Log("sadsadas");
            });

            root.Add(propertyField);

            return root;
        }
#

isnt there an event that always updates?

barren moat
#

Is there any way to hook into the "Save" or "Save project" command specifically (and not run callback on creation of new assets etc)

atomic sable
#

I'm making a snapping script to snap the centroid of some game objects to our grid. For some reason, the transform.position of the selected gameobject is not outputting what the transform.position reads in the inspector

#
for (int i = 0; i < Selection.gameObjects.Length; i++)
{
    Undo.RecordObject(Selection.gameObjects[i].transform, "Snap Objects");
    Debug.Log(Selection.gameObjects[i].transform.position);

    centroid += Selection.gameObjects[i].transform.position;

    oldParents[i] = Selection.gameObjects[i].transform.parent;
    Selection.gameObjects[i].transform.SetParent(falseSnapper.transform, true);
}
#

the Debug.Log line there outputs this:

#

but the selected object is this:

#

and it doesn't have a parent :(

visual stag
atomic sable
supple willow
#

is this a bug? when I maximize a view in the editor, left click stops working. 2022.3.20f1

#

and it's LTS...

#

hopefully there's a hacky fix?

#

seems as if the maximized window never has focus. even when I select all , they won't turn blue

lapis tree
#

2024-03-12T15:06:25.5532] @firebase/database: FIREBASE WARNING: Provided authentication credentials for the app named "[DEFAULT]" are invalid. This usually indicates your app was n initialized correctly. Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURI." and is from the correct project. How do i fix this?

waxen sandal
#

Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURI."

grand robin
#

I've found a serializable dictionary but it kinda carries a problem

#

it doesn't seem to update it's values in real time

#

i'm using it to update radius on a gizmo

#

but it only update when I click play or I save a new code

#

and I would like it to update everytime the value changes

#

do you guys have any idea what could be the problem?

gloomy chasm
grand robin
alpine bolt
#

Is there a fix for this? It should appear below the EnumField.

warm ember
#

hi. How I can play an animation in the insepctor. I set in the onclick listener an object and access to its animator but I don't see any play function. I don't know if this is the channel but I need extremely rapid help.

last marten
#

If the play function does not show it might not have supported parameters. You can create another script and attach it, then reference the animator in it and call your own function instead.

public class AnimatorPlayer : MonoBehaviour {
    public Animator Animator;

    public void Play() {
        Animator.Play(); // Whatever play method you want to run.
    }
}

Now you can attach the script, drag the object in the onClick listener, then call your Play method.

#

@warm ember

earnest talon
#

Hey, I've got an issue I haven't encountered before. When trying to load an icon using Resources.Load from a directory where an Editor Window class is (knowingly, and for that Editor Window), the icon is found but returns as a single pixel.

I've made sure the format is PNG /RGBA8, and that the type of import is for an Editor GUI / Legacy UI. It's set to no compression and no filtering mode. This is a 1024x1024 image being loaded as a Texture2D

#

using the exact same path for a GUILayout.Label call, however, shows the icon just fine.

#

okay nevermind, it's just a very long string name that's the issue

brazen tiger
#

I am making a small editor script, is there a way to detect which canvas was created last ??

waxen sandal
#

No information of creation time is stored

wide pike
#

How do you pin a tab on the editor? Unity Version Control tab always disappears at relaunch

waxen sandal
#

Wrong channel, this is about creating your extensions not about using the editor

median lance
#

How to link IMGUIContainer to EditorWindow method?

<ui:IMGUIContainer onGUIHandler="IMGUIContainerTest" />
#

And here is my method

void IMGUIContainerTest()
    {
        EditorGUILayout.TextField("Test");
    }
surreal delta
median lance
#

So its possible only via C#

surreal delta
#

yeah

earnest talon
#

I started using UIElements to help extend functionality better and, honestly, it's going a lot more nicely with a mixed UIE/IMGUI approach than it would've with IMGUI alone in some cases. I've had to do some extra handling but the C# UI Elements toolkit is helpful

atomic sable
#

how do I add lines to this sub menu as I have in the first menu? I tried setting the "second prioirty" of the menu item to really small/large numbers but it doesn't seem to do anything.

#

the issue is if I set one of those sub menu items to a low priority, it changes the location of "Path Data" on the main menu dropdown.

median lance
#

How to get a specific property value from ui element?

waxen sandal
#

Can't you just use the serializedproperty/object that you bound to?

median lance
#

It is not bound to any object. I have radiobuttons with respected type. So the type is a property of a radiobutton node. Then I want to read and parse this value to enum.

waxen sandal
#

Cast it to RadioButton, then access value

median lance
#

The value of radiobutton is a boolean

waxen sandal
#

Yeah?

#

It's a toggle?

median lance
#

GroupBox and Radiobuttons inside of it

#

I've found View Data Key.

#

I've been working with jquery for a half of a year. It was so easy to acess user defind properties. Like <button custom-prop="someValue"/>. and then acess it using one of jquery method.

waxen sandal
#

I think the solution is to use RadioButtonGroup instead

#

I don't think GroupBox is how you should be doing this

#

With RadioButtonGroup you get the index of the active element

median lance
#

You don't understand the question

waxen sandal
#

Probably

#

There's very little info here

median lance
#

I have the following UXML code

<VisualElement custom-property="value"/>

Then in C# code i want to access the custom-property attribute to get a value from

#

Things i can access are style, text, value. But i cannot access the custom-property

gloomy chasm
median lance
#

I see a way to handle this.
Create an extension method that

  1. Receives an UI Elelement and attribute name as a string
  2. Fetches the XML markup of it
  3. Parses it and finds needed atribute
gloomy chasm
median lance
#

Ok, thanks

fiery canopy
#
Editor.CreateCachedEditor(property.objectReferenceValue,
                null, ref editor);

            IMGUIContainer imguiContainer = new IMGUIContainer(() =>
            {
                EditorGUI.indentLevel++;

                EditorGUILayout.BeginVertical(GUI.skin.box);
                if (editor.serializedObject != null)
                {
                    editor.OnInspectorGUI();
                }

                EditorGUILayout.EndVertical();

                EditorGUI.indentLevel--;
            });

I'm using this code to expose values of a variable that isn't attached to a script, but when I destroy the attached GameObject I get SerializedObject target has been destroyed. error. Anyone know how to fix this?

gloomy chasm
#

Man... I'm really fighting the urge to make a OdinInspector/NaughtyAttributes 'replacement' using UIToolkit that actually follows the editor styling guidelines and look. And have some sort of 'bake' ability so you could ship editors you make with it.

But also, I have other projects I can work on and do we really need another "Make custom editors using attributes" package...? 🤔

fiery canopy
fiery canopy
#

Hold on this is gonna take a bit of explaining 😅

gloomy chasm
#
var inspector = new InspectorElement(property.objectReferenceValue);

This works...? Important to not do property.serializedObject.target my mistake.

fiery canopy
#

So I have something like this

#

OH damn message to long 😅

#
public override VisualElement CreatePropertyGUI(SerializedProperty property)
    {
        ExpandableAttribute att = attribute as ExpandableAttribute;

        VisualElement container = new VisualElement();

        PropertyField field = new PropertyField(property);
        field.SetEnabled(att.Editable);

        field.RegisterValueChangeCallback(
            evt => 
            {
                if (att.Should_Expand)
                {
                    Foldout foldout = root.Query<Foldout>("PropertyFoldout");
                    foldout.style.display = evt.changedProperty.objectReferenceValue != null ?
                        DisplayStyle.Flex : DisplayStyle.None;

                    foldout.SetValueWithoutNotify(evt.changedProperty.isExpanded);
                }
            });
        container.Add(field);

        Foldout child_foldout = new Foldout();
        child_foldout.name = "PropertyFoldout";
        child_foldout.text = "Property Data";
        child_foldout.style.display = property.objectReferenceValue != null ?
            DisplayStyle.Flex : DisplayStyle.None;
gloomy chasm
#

If it is code then use a site

#

!code

grave hingeBOT
fiery canopy
#

I have never used that site before so I hope it saved my code

gloomy chasm
#

Yeah this is going to break for sures if you ever have to draw two at once

#

InspectorElement should do exactly what you want

fiery canopy
#

The left is the correct way with the code I shwoed you
The right is the wrong output with what you told me to use

#

For some reason it is giving me the base class even though that isn't what I asked for.

gloomy chasm
#

Just for testing, try setting the height of the InspectorElement to something like 250

fiery canopy
#

How do I do that I'm not seeing a SetHeight like with other visual elements

#

Infact doesn't this just add the element without exposing the visual element variable that is created?

gloomy chasm
fiery canopy
#

Yeah I know but I can't do that since I don't have access the visualelement that was created with InspectorElement.FillDefaultInspector

#

It returns a void

gloomy chasm
#

wat are you talking about?

fiery canopy
#

Ok that works

#

What I did try was before doing the change you just suggested I created an empty visualelement and did the last thing you suggested and I still got the wrong output but with just a style height change

#

So there must thing with InspectorElement.FillDefaultInspector only drawing the main serializedobject instead of the variable that should be exposed.

#

Also I didn't know you could call new on InspectorElement. I alwasy thought you had to call the static function FillInspector. But now I know 😅

gloomy chasm
fiery canopy
# gloomy chasm FillDefaultInspector actually just loops through the properties and adds a Prope...

Funny thing is the way I was doing it before was perfectly fine. There was an underlying issue where I was removing something from a list while destroying the serialized object at the same time. And Unity was looking for an object that was destroyed.

Because I was still getting an error with the code you suggested. Had to use an Editor Coroutine to give the editor time to delete the objects before updating the inspector.

crimson hamlet
#
            var addComponent = gameObject.AddComponent(type);
            var serializedObject = new SerializedObject(addComponent);
            var serializedProperty = serializedObject.FindProperty("m_Script");

I need to get fileID and guid from m_Script: {fileID: 11500000, guid: bd3bdbcd6702bc0bdabd531c0e4243d9, type: 3} How to do that?

crimson hamlet
waxen sandal
#

Find the asset instead

wary cairn
#

So I'm using grid snapping and rotation increment snapping to build levels in Unity but it seems that it snaps to unrounded values a lot of the time. For example instead of snapping exactly to 1, it moves the asset to 1.002 or the rotation to -.06. This can make my assets not connect properly. How would I go about making this a perfectly rounded value?

silver wave
elder wasp
#

Hi!

#

I've been trying to make a node editor, and found a quirky thing. There's this attribute from NaughtyAttributes, AllowNesting that makes my parameters look nice.
with allow nesting attribute

#

Without AllowNesting

#

So i looked into what the attribute actually does, and it's only this

[CustomPropertyDrawer(typeof(AllowNestingAttribute))]
public class AllowNestingPropertyDrawer : PropertyDrawerBase
{
    protected override void OnGUI_Internal(Rect rect, SerializedProperty property, GUIContent label)
    {
        EditorGUI.BeginProperty(rect, label, property);
        EditorGUI.PropertyField(rect, property, label, true);
        EditorGUI.EndProperty();
    }
}

So since I need it for all the fields on all the nodes, and I already have a custom editor for the node, I was thinking of hardcoding those lines. However i'm not sure how to translate it for UI Toolkit
Basically, this is the method I call to generate each field

VisualElement CreateVisualElement(SerializedObject bj, FieldInfo field){
    if(field.GetCustomAttribute<HideInInspector>() != null || field.GetCustomAttribute<InputAttribute>() != null)
        return null;
    
    PropertyField propertyField = new PropertyField(){
        label = field.Name,
        bindingPath = field.Name
    };
    propertyField.Bind(bj);
    return propertyField;
}

and works with the attribute and without, that visual element gets added to the nodeview. So i need to add those kinda lines there, but im not sure how or what I could use?

#

I checked, and the PropertDrawerBase doesn't do anything else. So basically, those three lines make it so all attributes work as expected. What I want to do is, when Im creating those properties by code, have a way to also add those three lines so that they are taken into account by default

#

If it was normal editor code it would be trivial, but im not sure how to translate it with UI Toolkit

median lance
#

I have a BaseEditor that has an EnumPopup edit mode selection.
I also have ChildEditorA and ChildEditorB. How to render a specific editor based on selected mode value?

chilly steeple
#

It's a bit scuffed but can't really think of other solutions rn blobsweat

elder wasp
#

Mmmm, do you know where I can find the source code for it? the decompiled version of property field is around 1000 lines

chilly steeple
#

I just looked on GitHub, search for EditorGUILayout in the file and you should find it relatively quick

elder wasp
#

But isn't that the normal PropertyField? not the UIElements one

chilly steeple
#

Ui elements Property field yes

#

Is using an imgui container and editorgui.propertyfield in the background afaik

elder wasp
#

Uff, I see now the code

chilly steeple
#

Maybe you can query the imgui container and simply rebind it's onguihandler

elder wasp
#

I didn't understand half of that, im too new with UI Builder, how do I rebind a onguihandler?

median lance
#

How to get window from custom inspector. I want to open Tile Palette window from custom inspector

chilly steeple
#

Imgui container works similar to a regular IMGUI method. To know what to draw every frame, you pass in a function that handles the imgui drawing

#

So the Imgui container instance should have a property called OnGUIHandler

#

Which just points to a function to draw IMGUI controls

#

And just to avoid any confusion, an IMGUI container is just another visual element.

waxen sandal
surreal delta
# median lance I mean this

just have those in different functions and call them OnInspectorGUI depending on which value is in the enum

median lance
#

It creates a mess in a code

median lance
waxen sandal
#

Editor.CreateCached > call OnInspectorGUI on the child

median lance
#

Some editors could have not only the OnInspectorGUI method.

waxen sandal
#

What does that mean

median lance
#

OnSceneGUI for example or OnEnable

waxen sandal
#

Then call those as well?

median lance
#

Thanks

oblique nymph
#

Is it possible to store data in the PropertyDrawer?
I have a Resource Database Scriptable Object, and, on the instances where i need to select a Resource, i want to Select the Resource Database, and then select a Resource from it...
I have a ObjectField to select the Resource Database, and then a Dropdown to select the Resource, but the value of the Resource Database isn't stored once i exit the window and go back....

#

and Adding the ResourceDatabase to the Resource seems quite redundant... Specially since i made the Resources to be very small (byte wise) and efficient

wary cairn
oblique nymph
#

On another note...
Can i not set a value of a property with RegisterValueChangedCallback?

                var selector = CreateResourceSelector(ToDropdownChoice(SelectedResource));

                selector.RegisterValueChangedCallback(evt =>
                {
                    var resource = Database[FromDropdownChoice(evt.newValue)];
                    property.boxedValue = resource.ID;
                });

selector is just a DropdownField with all the Resources on a Database...

Debugging i can see that the resource is getting set, but when i refresh the Inspector it resets to default

#

property being the SerializedProperty coming from CreatePropertyGUI(

#

can't seem to find anything about it on the docs/forum

silver wave
sullen crystal
#

||is there a lore reason|| why my Move function isn't listed in the Event Trigger component?

#

note, i have the gameobject selected and not the script

sullen crystal
#

@visual stag ah... that makes sense... thanks for the response. my paremeter is not supported by Event Trigger... the reason im trying to even do this is to get my controller working for mobile. I'm using the built in On-ScreenButton script to simulate keyboard input and it works perfect in the editor, but in the build its very unresponsive and just doesnet function properly. been trying to find workarounds

fiery canopy
#

Is there a way to rotate icons drawn with Gizmos.DrawIcon()? I can get the icon to follow the objects position but not its rotation.

fiery canopy
#

I'm starting to think its a bug or DrawIcon just isn't allowed to be rotated

gloomy chasm
fiery canopy
#

I'm honestly thinking screen space

#

All other Gizmos will rotate when changing Gizmos.Matrix

vivid folio
#

hey guys. can smb help me out? visual studio doesnt recognize unity code for some reason. although i have unity extension installed for the ide. and as always, theres no info on how to config it.can smb help me out? thx

willow nova
#

Try Edit-> Open C# Project
try retarting your pc
try restarting unity and vs
check your ide preference in Preferences -> External tools or something like that

safe sorrel
#

Can I check if Unity can serialize a type? I wrote some code to look for references I forgot to assign, but I noticed that it’s incorrectly flagging fields that hold types Unity cannot serialize.

#

It doesn’t look like I can just check if the type has the System.Serializable attribute

#

Oh! I was looking at FieldAttributes instead of TypeAttributes

#

Let’s have a look at that..

visual stag
#

I don't know if there's a good answer, but there is a class in the source called UnitySerializationLogic that has the entire logic (WillUnitySerialize) in a very readable flow

#

There's even a fun lil dictionary called TypesThatShouldHaveHadSerializableAttribute (unrelated)

safe sorrel
#

ah yeah, Type.IsSerializable alone is not helpful. It says most of this stuff isn’t serializable

safe sorrel
#

sneaking in to Unity HQ to make it just return true every time

queen wharf
#

bit of a weird question but i'm editing a scriptableobject via code in an editor tool and using AssetDatabase.FindAssets at the start of the function i have for some data i need to reference but theres this weird inconsistent issue where it seems like if the request is too much/too long the changes i do to the so after the findassets code just don't apply?

#

the code still runs, i get debug logs and all that, no errors either

#

its like it hits this mystery request threshold and just refuses to actually do what im telling it to do

visual stag
#

Are you correctly dirtying the scriptable object?

queen wharf
#

Probably not!

#

can you put me on

visual stag
queen wharf
#

bet ok ill do that. was going to post code/more context but figured it would be something where someone is like "oh it's probably x thing" haha

out of curiosity, what is this inconsistent behavior im getting?

visual stag
#

I have absolutely no idea what you're seeing, the description is too unclear, but if you don't dirty an object then changes won't persist

safe sorrel
#

I see that I’m not allowed to just copy paste the CS reference, so I will simply be inspired by the code instead 😉

visual stag
#

I am not copy pasting, I am simply applying the keystrokes ctrl-c and ctrl-v in an order that duplicates

safe sorrel
#

I also might just mark these unused fields with NonSerialized

#

to make sure Unity isn’t trying anything funny

peak bloom
# safe sorrel Can I check if Unity can serialize a type? I wrote some code to look for referen...

I had to do a ugly workaround for this, tho it will fail if SerializedReferences are used

var attr = obj.GetAttributes();
// then do check if contains serializeField
attr.AttributeClass.Name == "SerializeField")

//Unity supports a very small amount of types to be serialized so this is ok-ish approach ig.
var types = new List<string> { "dec" , "string", "int" };
bool valid = !types.Contains(obj.Type.Name));

safe sorrel
#

I already check for SerializeField, yeah

#

This is only a problem in a few places where I use a public field

#

But my public fields are usually non-serialized anyway

hidden oak
#

Heya!
In 2021 this code works flawlessly. The button is focused then clicked.
But in 2022 the button is only focused and no click even goes through.

Anyone else had this issue? Or how am I supposed to send click events to UI-toolkit? I've tried different keys, capturing and sending mouse events, and this follows the documentation provided.

public static void Click(this Button btn)
{
    var clickEvent = new Event()
    {
        keyCode = KeyCode.KeypadEnter,
        type = EventType.KeyDown,
    };
    btn.Focus();
    using KeyDownEvent keyDownEvent = KeyDownEvent.GetPooled(clickEvent);
    btn.SendEvent(keyDownEvent);
}
hollow smelt
#

I'm trying to make a property drawer for an array based on a generic enum argument. The idea is that it displays specific enum values for specific indices of an array (where specific position is tied to an enum). This works fine until I have a class with a generic TEnum argument. Any workarounds?

#

I basically need to know the Enum type in my generic class, EnumerableArray<TEnum, TStored> so that my TStored[] internalArray can use this property drawer

hollow ore
#

how do I update materials/shaders properly, so that my renderers don't use fallback shader?

elder wasp
#

So I added the option of having groups into my node editor

#

Is there any wayt to make them collapsable?

#

Im using UI Toolkit and GraphView

chilly steeple
#

The group or the nodes? @elder wasp

median lance
#

How to remove last undo operation from Undo stack?

peak bloom
#

quick quesiton, does the assemblyreloadevent still be triggered even when we turned off the domain reload from project settings?

gloomy chasm
#

Would test though

elder wasp
chilly steeple
#

@elder wasp what does your code look like?

elder wasp
#
public NodeView(InfiniteLandsNode node){
    this.node = node;
    CustomNodeAttribute attribute = GetAttribute(node.GetType());
    AddToClassList(attribute.type);
    this.title = attribute.name;
    
    this.viewDataKey = node.guid;
    style.left = node.position.x;
    style.top = node.position.y;
    styleSheets.Add(AssetDatabase.LoadAssetAtPath<StyleSheet>("Assets/sapra.InfiniteLands.Visual/UIBuilder/NodeView.uss"));

    SetPosition(new Rect(node.position, Vector3.zero));
    CreateOutputs();
    CreateInputs();
    DrawParameters();
    RefreshPorts();
    RefreshExpandedState();
}

this is the constructor of NodeView (that inherits from Node)

#

and here the responsible to generate the parameters

protected void DrawParameters(){
    VisualElement element = new VisualElement();
    FieldInfo[] fields = node.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public);
    SerializedObject bj = new SerializedObject(node);
    foreach(FieldInfo field in fields){
        VisualElement fieldElement = CreateVisualElement(bj,field);
        if(fieldElement != null)
            element.Add(fieldElement);
    }   

    if(element != null)
        extensionContainer.Add(element);
}
#

It's intersting, I can collapse the nodes if one of the inputs/outputs is empty, but as soon as they are all connected I can't

#

With the workaround

public NodeView(InfiniteLandsNode node){
    .... stuff fro before

    SetPosition(new Rect(node.position, Vector3.zero));
    CreateOutputs();
    CreateInputs();

    //WORKAROUND for uncollapsable nodes 
    Port hiddenPort = InstantiatePort(Orientation.Horizontal, Direction.Input, Port.Capacity.Single, typeof(int));
    hiddenPort.style.display = DisplayStyle.None;
    if(inputContainer.childCount > 0)
        inputContainer.Add(hiddenPort);
    else
        outputContainer.Add(hiddenPort);
    //End of workaround

    DrawParameters();
    RefreshPorts();
    RefreshExpandedState();
}
chilly steeple
#

@elder wasp are you setting Node.expanded anywhere in your code too?

elder wasp
#

Nop

chilly steeple
#

Have you tried setting that and then refreshing expanded state?

elder wasp
#

Im actually trying that, and Im getting weird behaviour

#

Where ToggleCollapse makes it look nice, but changing expanded state makes it look weird, incoming pictures

#

usual collapsed

#

changing expanded to false

#

Opening and closing fixes it

#

This is using the workaround, without it I cant open neither close

#

Withut the workaround, and expanded set to false

chilly steeple
#

Right

#

That's so bueno

#

My guess is that internally the node doesn't collapse of it detects all its ports are connected

elder wasp
#

that's a weird funcionalioty

chilly steeple
#

It makes sense, cuz ports that are connected should not be collapsed, no?

#

So if all ports are connected, don't bother collapsing anything.

elder wasp
#

the thing is that collapse shouldn't collapse ports, only the expandedContainer

#

I mean, setting the ToggleCollapse it shows as expected, ports are shown, but the expanded container is hidden

elder wasp
chilly steeple
#

Doesn't collapse also hide non-connected ports like in Shader Graph?

elder wasp
#

I can't remember, been a long time since i used shader graph

#

But then more reason even, if the port are connected, it should be shown

chilly steeple
#

Me neither haha, I just remember seeing something like that

elder wasp
#

but here once all ports are connected i can't collapse anything

#

For reference, this is the expanded state

chilly steeple
#

Ok so the issue is that if all ports are connected, expandedContainer is no longer collapsed properly?

elder wasp
#

So if all ports are connected, I can't manually click on the collapse button

#

It's greyed out

chilly steeple
#

Ah

elder wasp
#

Expected look

chilly steeple
#

Oki, sorry I misunderstood the problem

elder wasp
#

Actual look

elder wasp
chilly steeple
#

Ok so I think I found it still, I believe the issue is what I described earlier accidentally lmao

#

One second, trying to copy the code on phone :pain:

#
private void OnPortConnectAction(Port port)
        {
            bool canCollapse = false;
            var updatedInputs = inputContainer.Query<Port>().ToList();
            var updatedOutputs = outputContainer.Query<Port>().ToList();
            foreach (Port input in updatedInputs)
            {
                if (!input.connected)
                {
                    canCollapse = true;
                    break;
                }
            }

            if (!canCollapse)
            {
                foreach (Port output in updatedOutputs)
                {
                    if (!output.connected)
                    {
                        canCollapse = true;
                        break;
                    }
                }
            }

            if (m_CollapseButton != null)
            {
                if (canCollapse)
                    m_CollapseButton.pseudoStates &= ~PseudoStates.Disabled;
                else
                    m_CollapseButton.pseudoStates |= PseudoStates.Disabled;
            }
        }
#

This sits in the Node class

elder wasp
#

this is weirder

chilly steeple
#

As you can see, whenever a port is connected it will:

  • Loop through all input ports, of any of them have no connection, "canCollapse = true"

  • If all inputs are connected, check all outputs to see if any of them have no connections.

  • If all ports are connected, disable collapse button

#

Idk why this would be a thing tho

elder wasp
#

Why does this exiiiist, doesn't make any sense! :((

#

I really hope a Unity Dev explains why this is necessary

chilly steeple
#

Maybe on the node you can get the collapse button by querying node.Q(name: "collapse-button");

#

The above method is bound to port.onconnect

#

Which happens on RefreshPorts

#

So maybe create a custom method that wraps RefreshPorts and then subscribes another action to the port.onconnect callback that hard-code insets the disabled state

elder wasp
#

In simpler terms?

chilly steeple
#

On my phone rn, can I get back to you first thing in the morning with some (pseudo) code?

elder wasp
#

always

#

I just checked and OnConnect is innacessible

autumn geyser
#

Hey does anyone know of an editor extension that lets you organise prefabs that you can use to build your scenes?

#

I have a lot of stuff in my game at the moment, but it's a pain in the ass to find anything spesific

#

Kinda just want a dropdown or something that lets me only search materials/prefabs/etc

#

Kinda also don't want to bother coding it myself XD

gloomy chasm
# autumn geyser Hey does anyone know of an editor extension that lets you organise prefabs that ...

It depends on what you want exactly. The Unity Search window has a way to save a search, so you can quickly search for the same assets again. Could be a way to for example find all prefabs at the path x with y in their name.

There is a paid asset called SmartLibrary that lets you create collections of assets either by dragging and dropping them in to a collection, or using rules to find them, kind of like the Save Search feature in Unity Search.
https://assetstore.unity.com/packages/tools/utilities/smart-library-asset-manager-200724
(Full disclosure, I made the asset.)

There are not really any free options that do this sort of thing.
If you want a menu that replaces Unity's Object Selection window (the one that opens when you click the circle next to a object field), there is no option as far as I know.

autumn geyser
#

Thanks for your help, and the search window link

gloomy chasm
#

Sure thing! 🙂

twin dawn
twin dawn
#

Boooo

gloomy chasm
twin dawn
twin dawn
#

my ideas right now are:

  • Actually do load an extra scene and do some shenanigans to make it work
  • Use a separate floating editor window at the bottom of the hierarchy window, sort of like the Preview window in the inspector
gloomy chasm
#

hmmm... I remember there being a HierarchyProperty struct, you might be able to use that with the hierarchy window to do something... maybe not though

twin dawn
#

any documentation on that you can find would be appreciated

gloomy chasm
gloomy chasm
twin dawn
#

If I can do that I feel I can do what I want

gloomy chasm
twin dawn
#

oooh... is it that easy? 🤔
What would be my entrypoint though?

#

I'd need to do it whenever the hierarchy window loads right?

gloomy chasm
#

Resources.FindAllOfType(hierarchyType)

#

Yeah, that is the only icky part, the only way I know to do it is to check each frame if the number of windows has changed

#

There is no "Window Opened" type of event sadly 😦

twin dawn
#

oof

short tiger
#

But it's not entirely fake it seems. There's some underlying scene.

twin dawn
twin dawn
gloomy chasm
#

Good luck 😛

chilly steeple
#

@elder wasp could you check if any of the following code overrides the disabled state

chilly steeple
#

Would've been kinda surprised if it did but would have been the easiest solution, I'll try and think of other work arounds

elder wasp
#

No problem, and thanks!

#

Now I have another problem. Im trying to make a dropdown field to select other scriptable objects. But I need two things
1- The label text updates in relation to the selected scriptableObject name
2- When clicking on the dropdown field, it shows an updated list of the available scriptables objects

#

I created the dropdown field, and managed to get the list of scriptable objects, plus being able to assign it, so i have a variable always holding a reference

#

Now the problem is how can I bind it properly? I tried with the RegisterValueChangeCallback, to change the value and assign the new reference, the problem is that when I try to rebind i get stack overflow

#
DropdownField dropdown = new DropdownField();
dropdown.RegisterValueChangedCallback((ChangeEvent<string> ev) => ReselectOutput(dropdown, ev));

and then

void ReselectOutput(DropdownField dropdown, ChangeEvent<string> changeEvent){
    LocalInputNode nd = node as LocalInputNode;
    string parentAsset = AssetDatabase.GetAssetPath(this.node);
    object[] asset = AssetDatabase.LoadAllAssetsAtPath(parentAsset);
    foreach(object st in asset){
        if(st is LocalOutputNode newNode){
            if(newNode.OutputName.Equals(changeEvent.newValue)){
                nd.output = newNode;
                dropdown.bindingPath = nameof(newNode.OutputName);
                SerializedObject bj = new SerializedObject(newNode);
                dropdown.Bind(bj);
            }
        }
    }
}

but this breaks

chilly steeple
#

Where does it throw the overflow exactly?

elder wasp
#

i cant check because the UI breaks completly. Im guessin that after rebinding, it calls the register value changed callback and starts breaking

chilly steeple
#

Ok so why is the serializedobject getting bound to a dropdown?

elder wasp
#

So that if there are any changes on the object, the label changes live too

chilly steeple
#

Right, so if the SO gets renamed it also updates on the graph automatically?

elder wasp
#

yup

#

Its not the SO name perse, but a variable called OutputName, but it has the same purpose

chilly steeple
#

So the SO has a variable on it that can change, and is displayed in a dropdown?

elder wasp
#

yup

chilly steeple
#

Is that variable gonna change while the dropdown is visible?

elder wasp
#

Nope

chilly steeple
#

Then maybe just rebuild the dropdown values in something akin to a OnEnable?

elder wasp
#

ah no sorry, yes, the value will change when the dropdown is visible. I thought you meant the dropdown select window

chilly steeple
#

Cuz what really needs to happen is for the dropdown content ( a list of strings) to be updated when your variable changes

elder wasp
#

Basically you can see this. If I modify dsd text field, i want to get the dropdown to update too

chilly steeple
#

Ok so the variable name can be found on the graph also?

elder wasp
#

Yup, I got that handled, and I got a method to find those variables in the node

chilly steeple
#

So when you update the text in the local output, you want the dropdown on local input to update?

elder wasp
#

exactly

chilly steeple
#

Aight, so what if your local output OnChangeEvent is broadcasted for local input nodes to listen to, which triggers the dropdown to refresh?

elder wasp
#

But also, the dropdown field should show all the updated texts of all local outputs, meaning that switching to another should change the label to that one and update when the new one changes

chilly steeple
#

Also what's the reason you can't just use an object reference to that output node?

#

Instead of using strings

elder wasp
elder wasp
#
Label field = new Label{
    text = nd.output != null ? nd.output.OutputName : "None",
};
if(nd.output != null){
    field.bindingPath = nameof(nd.output.OutputName);
    SerializedObject bj = new SerializedObject(nd.output);
    field.Bind(bj);
}

so i wanted to change that to a dropdown field

chilly steeple
elder wasp
#

For the rebuild I was hoping to register into an onclick event of some sorts, to reupdate the list

#

and then on select/change value rebind the text

chilly steeple
#

I guess you could register a OnMouseDown callback on the dropdown that also just rebuilds the dropdown contents

elder wasp
#

Okay found a simpler solution with a button and a generic menu

#

So im doing this

Button btn = new Button(){
    text = nd.output != null ? nd.output.OutputName : "None",
};
btn.clicked += () => CreateMenu(btn);
btn.style.minWidth = 80;

var label = output.contentContainer.Q<Label>("type");
output.contentContainer.Remove(label);
output.contentContainer.Add(btn);
#

and then

void CreateMenu(Button btn){
    GenericMenu menu = new GenericMenu();
    string parentAsset = AssetDatabase.GetAssetPath(this.node);
    object[] asset = AssetDatabase.LoadAllAssetsAtPath(parentAsset);
    LocalInputNode nd = node as LocalInputNode;
    foreach(object st in asset){
        if(st is LocalOutputNode newNode){
            menu.AddItem(new GUIContent(newNode.OutputName), newNode.Equals(nd.output), () => {
                nd.output = newNode;
                btn.bindingPath = nameof(newNode.OutputName);
                SerializedObject bj = new SerializedObject(newNode);
                btn.Bind(bj);
            });
        }
    }
    menu.ShowAsContext();
}
#

my issue now is that removing label from the port makes it impossible to click on the port

#

Alright, this fixes it

#
btn.clicked += () => CreateMenu(btn);
btn.style.minWidth = 80;
btn.style.marginTop = 0;
btn.style.marginBottom = 0;      
  
var label = output.contentContainer.Q<Label>("type");
label.style.color = new StyleColor(new Color(0,0,0,0));
label.style.marginLeft = 0;
label.style.marginRight = 0;
label.Add(btn);
#

xD

peak bloom
#

is there any trick to bind a min value to floatA while max value to floatB with a minmax slider in uitoolkit?

gloomy chasm
peak bloom
#

guess I have to resort to registervaluechanged, yeah no undo/redo for me 😅

gloomy chasm
# peak bloom guess I have to resort to registervaluechanged, yeah no undo/redo for me 😅

What I normally do is this:

minMaxSlider.RegisterValueChangeCallack(evt => {
  minProperty.floatValue = evt.newValue.x;
  maxProperty.floatValue = evt.newValue.y;
  minProperty.serializedObject.ApplyModifiedProperties();
};
minMaxSlider.schedular.Execute(() => {
  if (minProperty.floatValue != minMaxSlider.minValue)
     minMaxSlider.minValue = minProperty.floatValue;
 if (maxProperty.floatValue != maMaxSlider.minValue)
     minMaxSlider.maxValue = maxProperty.floatValue;
}).Every(100);
#

Or something like that. Could also store the contentHash of the min and max SerializedProperty and check if it has changed. Probably more reliable then checking if the float values are different.

peak bloom
#

now we're talking! Will do just that, thanks, Mech!

gloomy chasm
#

Sure thing!

hardy apex
#

I'm losing my mind trying to set a SecondaryTexture via an asset importerer for a sprite. When a normal map is imported in a specific folder, the AssetImporter "OnPostProcessTexture" method finds the original texture importer (for the other texture, not the normal map), sets the secondary texture on the original texture importer to the OnPostProcessTexture, and calls "save and reimport" on the original texture importer

However, in practice, this is resulting in the secondary texture being created and given a name, but set to null. Is this because the OnPostProcessTexture Texture2D is temporary?

peak bloom
#

will it cause issues if I'm not unsubbing the callback @gloomy chasm ?

peak bloom
#

nice UnityChanThumbsUp

lone halo
#

Hi, I don't know if anybody has here has experience with this, but I am trying to check out files on perforce with this command:
https://docs.unity3d.com/ScriptReference/VersionControl.Provider.Checkout.html
I am not giving it a cl number because I am trying to create a new changelist with a given description. So I am using ChangeSet changeset = new ChangeSet(description: "Some description!"); which seems fine, I am getting no errors from this.
How can I create a new cl with a description?

#

I'm thinking maybe it needs a cl number, but I don't have it yet. So is there a seperate command to create a new cl?

alpine bolt
#

In UIElements' Foldout, is there a way to animate expand/collapse?

gloomy chasm
#

it sets the display style property by code, so uss can't override it.

wispy delta
#

I'm doing some inverted-hull outline stuff and would like to automate the baking of smooth normals into some other part of the mesh data like vertex colors. I can figure out most of this, but I'm curious if the normal recalculation used by Unity's model importer is exposed anywhere so I can more easily generate smooth normals with a more advanced algorithm. Mesh.RecalculateNormals won't really cut it since split vertices always have hard edges

queen wharf
#

Weird question but does anyone know the best way to clear an assetbundle tag from an asset?

#

i could be doing it wrong but just setting them to string empty via assetimporter seems to be assignining them like string empty assetbundle, instead of actually not having one

chilly steeple
elder wasp
#

2023 now,targeting 2021-2022 up

#

but honestly wathever version supports my needs

hollow ore
#

is there any way to support intellisense in Rider inside the Temp/ directory?

waxen sandal
#

Add it to your csproj

hollow ore
#

how to do it though?

#

for example when I click a "view generated shader" in the shadergraph asset inspector

hollow ore
dapper coral
#

I'm trying to automate setup of a component that has a custom inspector from another script, but its inspector has a bunch of fields and code ... so I'm wondering, can I somehow use the actual inspector instance from code?

specifically, say that I do this in my own editor script ```csharp
Foo foo = obj.AddComponent<Foo>();
// ... call/assign something on an associated FooInspector?

#

if it helps, the custom inspector is made using UI Toolkit

tough cairn
#

is there a quick way to get a string search result of all the game objects in the scene similar to how the search bar in hirarchy works ?

tough cairn
#

so basically :

    public static void Select( string search = "" ) {
        if( string.IsNullOrWhiteSpace( search ) || string.IsNullOrEmpty( search ) ) {
            Selection.objects = null;
            return; }
        var scene_search = SearchService.CreateContext( "scene", search );
        SearchService.Request(scene_search, ( context,list) => {
            var selection = new List<GameObject>();
            foreach( var item in list ) {
                var obj = item.ToObject();
                if( obj is GameObject ) selection.Add(obj as GameObject);
            }
            Selection.objects = selection.ToArray();
        } );
    }
elder wasp
#

Im tyring to change the borer color of a port created with UI Elements

#

But it doesn't matter what I set that it automatically becomes the default

#

How can I override this kind of changes?

#

Color never changes, but border-color gets reseted every time I hover

alpine bolt
#

The property is used in the Port element (this TvPortView is a custom element I made derived from Port)

#

Native code

public class Port : GraphElement
{
    private static CustomStyleProperty<Color> s_PortColorProperty = new CustomStyleProperty<Color>("--port-color");
    private static CustomStyleProperty<Color> s_DisabledPortColorProperty = new CustomStyleProperty<Color>("--disabled-port-color");
    (...)
}```
elder wasp
#

Ooooh,I will try it tomorrow ,thanks!

#

So is that absolutely needed to achieve that or can you do it without the extra class? Not for amy reason in particular just to understand it better

alpine bolt
#

I don’t remember. It’s a been a long time tbh.

chilly steeple
#

You could try setting those in a global stylesheet and load that onto your root element

#

Wouldn't scale well but might work fine in a one off situation

alpine bolt
#

Note: Maybe Port.port { works, but since I'm rocking a custom Port derived element, it doesn't.

elder wasp
#
.port.optional{
    --port-color: #FF0000;
}

this just worked for me!

#

optional is a class I have on the port

#

Oooh, and this happens! NEAT

elder wasp
#

where can I find all the icons that Unity has in the editor to use them on my custom editors¿?

gloomy chasm
elder wasp
#

It's for a package Im making and I want to keep it with as less dependencies as posible

#

Are the icons on that package the same unity uses? aka the file id is the same?

#

Im trying to set it on the uss file, as background image, but no luck

alpine bolt
gloomy chasm
alpine bolt
#

Open the files in GitHub

gloomy chasm
#

All the pacakge is doing is showing you the icons that are in Unity that you could use. Clicking on one will show you the icon resource path of the icon. You just copy that path and load the icon in your own editor

elder wasp
#

Mmmm, i see

#

Let me try one thing, because I wanted to set them on the uss file

gloomy chasm
elder wasp
#

aaaaa resource, that's what I was looking for

#

yes, thanks!

gloomy chasm
#

Yeah, bit hard to find and not really documented. I don't even remember how I found it haha 😅

elder wasp
#

i cant belive that I cannot find the icon I need

#

There's this two icons on the animator window

#

the eye open and closed

#

And there are some variations in that package, but none that match style and color

#

I guess it's animationvisibilitytoggleon, but the color is not the same?

alpine bolt
#

I need some translation

NullReferenceException: Object reference not set to an instance of an object.
UnityEngine.Bindings.ThrowHelper.ThrowNullReferenceException (System.Object obj) (at <579f6a25593149bdb5b2b685692d23ea>:0)
UnityEditor.SerializedObject.get_objectVersion () (at <adf0e73faa2b4739bc17dcc108877e1a>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingBase.GetViewHashCode () (at <2050825fd3274799a79980c703b0ce2d>:0)
UnityEngine.UIElements.VisualTreeDataBindingsUpdater.GetDataSourceVersion (System.Object source) (at <1478f14db9ca4624bdcc87040fae8937>:0)
UnityEngine.UIElements.VisualTreeDataBindingsUpdater.Update () (at <1478f14db9ca4624bdcc87040fae8937>:0)
UnityEngine.UIElements.VisualTreeUpdater.UpdateVisualTreePhase (UnityEngine.UIElements.VisualTreeUpdatePhase phase) (at <1478f14db9ca4624bdcc87040fae8937>:0)
UnityEngine.UIElements.Panel.UpdateDataBinding () (at <1478f14db9ca4624bdcc87040fae8937>:0)
UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.UpdateSchedulers () (at <1478f14db9ca4624bdcc87040fae8937>:0)
UnityEngine.UIElements.UIEventRegistration.UpdateSchedulers () (at <1478f14db9ca4624bdcc87040fae8937>:0)
UnityEditor.RetainedMode.UpdateSchedulers () (at <2050825fd3274799a79980c703b0ce2d>:0)```
wispy delta
elder wasp
#

Aha! THat was it, the D is important, damm

#

Thanks!

wispy delta
#

Np. Yea the UI Elements and IMGUI debugger windows are super helpful for this 👍

gloomy chasm
alpine bolt
gloomy chasm
alpine bolt
gloomy chasm
#

Do you add remove any dynamically in the PropertyDrawer? (like adding to a list, or changing a managedReference)

hard pine
#

Hey all. I am trying to make a context menu that lets me add sets of assembly references to an assembly definition. I am having an issue setting the new array of assemblies once I have it.

assemblyDefinition.assemblyReferences = assemblyDefinition.assemblyReferences.Append(GetAssemblyWithName("Unity.Logging")).ToArray();

The assemblyReferences set() is internal. Is there a proper place to set this?

hardy apex
craggy nebula
#

So in the area of things that don't matter, but just set off my OCD. How can I get the spacing to draw like the standard ones?
Here is my current OnGUI drawer for that element.

public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
    var typeIdProperty = property.FindPropertyRelative("assemblyQualifiedName");
    Initialize();
    if (displayName.IsEmpty() && !typeIdProperty.stringValue.IsEmpty()) {
        var currentIndex = Array.IndexOf(typeFullNames, typeIdProperty.stringValue);
        if(currentIndex >= 0 && currentIndex < typeNames.Length) {
            displayName = typeNames[currentIndex];
        }
    }
    EditorGUILayout.BeginHorizontal();
    EditorGUILayout.LabelField(label, GUILayout.Width(EditorGUIUtility.currentViewWidth * .4f), GUILayout.MinWidth(120f));
    if (GUILayout.Button(displayName, EditorStyles.popup)) {
        SearchWindow.Open(new SearchWindowContext(GUIUtility.GUIToScreenPoint(Event.current.mousePosition.Add(y: 30, x: 10))), 
            new StringListSerachProvider("Type List", typeNames, x => {
                displayName = x;
                var currentIndex = Array.IndexOf(typeNames, x);
                if (currentIndex >= 0 && currentIndex < typeFullNames.Length) {
                    typeIdProperty.stringValue = typeFullNames[currentIndex];
                    property.serializedObject.ApplyModifiedProperties();
                }
            }));
    }
    EditorGUILayout.EndHorizontal();

}
#

Also it's a button that opens a search window, which I don't think there is a default one by unity.

gloomy chasm
craggy nebula
#

I tried this but it still does grow at the same rate.

float margin = position.width * .4f;
EditorGUI.LabelField(position.With(width: margin), label);
if(EditorGUI.DropdownButton(position.With(x: margin).Add(width: -margin), new GUIContent(displayName), FocusType.Keyboard)){
    SearchWindow.Open(new SearchWindowContext(GUIUtility.GUIToScreenPoint(Event.current.mousePosition.Add(y: 30, x: 10))),
        new StringListSerachProvider("Type List", typeNames, x => {
            displayName = x;
            var currentIndex = Array.IndexOf(typeNames, x);
            if (currentIndex >= 0 && currentIndex < typeFullNames.Length) {
                typeIdProperty.stringValue = typeFullNames[currentIndex];
                property.serializedObject.ApplyModifiedProperties();
            }
        }));
}
gloomy chasm
peak pawn
#

Where to start if I want to get a nice-looking editor script like the post-processing volume ?

gloomy chasm
craggy nebula
# gloomy chasm Use PrefixLabel instead, it returns a rect which is just the 'field' part of it ...

Wow. That works magic. Thank you.
Working code:

Rect rect = EditorGUI.PrefixLabel(position, label);
if(EditorGUI.DropdownButton(rect, new GUIContent(displayName), FocusType.Keyboard)){
    SearchWindow.Open(new SearchWindowContext(GUIUtility.GUIToScreenPoint(Event.current.mousePosition.Add(y: 30, x: 10))),
        new StringListSerachProvider("Type List", typeNames, x => {
            displayName = x;
            var currentIndex = Array.IndexOf(typeNames, x);
            if (currentIndex >= 0 && currentIndex < typeFullNames.Length) {
                typeIdProperty.stringValue = typeFullNames[currentIndex];
                property.serializedObject.ApplyModifiedProperties();
            }
        }));
}
gloomy chasm
#

Sure thing! 😄

peak pawn
gloomy chasm
peak pawn
#

How do I create a search field that only suggests overrides, and how do I display these overrides that way (with a nice looking dark foldable menu)

#

Right now I'm adding the overrides through AddComponent, but I'd rather have them as, well, overrides of the main script

#

They are using the same UI for the render pipeline overrides

gloomy chasm
#

Ahh, so what is it is just a list of POCOs on the PostProcessing ScriptableObject which is shown in the inspector of the volume.

For the AddOverride menu, it just is checking the type of each post processing effect in that POCO list, and not showing them in the dropdown

peak pawn
#

How does the inspector show them is such a clean way ? The dark foldable menu, the on/off checkbox, the three dots at the end for more info, etc

#

Or rather, what's the function to get a similar looking effect ?

#

Something like DrawCustomOverride(Override override)

gloomy chasm
peak pawn
#

IMGUI

#

But i've always done basic inspectors with the functions Unity gave me

peak pawn
#

Thanks !

#

Do you have the code for the AddOverride button ?

peak pawn
#

I read it all, it feels so incredibly complex

#

There's no simple way to display a dropdown and add the chosen component to the gameobject ?

gloomy chasm
peak pawn
main aurora
#

can somebody please remind me how I can preserve my serialized boolean editor values between my desktop workspace and my laptop workspace when using Unity Version Control? What's kind of weird is that my float values are preserved, but my check boxes for boolean values are not.
...
eh, maybe I unchecked them for some reason and forgot.

real spindle
#

Got that search bar, folders and a nice look to it

dense sedge
#

hi, im doing procedural animation stuff and setting up the positions and rotations during play is a real pain in the ass. Is there a way of overriding the OverrideTransform class and adding a record button which records the value of x or something and updates a scriptable object asset? See my image below to clarify.

#

chatgpt keeps telling me to do target.FindProperty("TPose") but i'd like to know if there was a way to do it without making a child of override transform that stores references to all the pose assets because theres a lot of overridetransforms to set up.

#

unless i make them static references? but then how does that work with a custom inspector?

peak pawn
alpine bolt
#

I’ve done it :> it’s fairly easy

alpine bolt
#

You’d have to build your own indexation feature. The system is a basically organized in a tree-like fashion. Each end point would have an index value.

peak pawn
#

That part I'm familar with (Popup works the same), the issue is getting that index. AdvancedDropdown does not return anything...? That's the reason it must be converted to UIElements, right ?

#

I'm kinda confused, what is the point of the dropdown existing if it does not return the value / index selected in the dropdown...?

peak pawn
#

Aaaaaaah it makes sense now

#

Should I call base.ItemSelected(item) ?

gloomy chasm
#

Don't remember sorry, you can take a peak at the source to see

peak pawn
#

Just found it, it's empty

alpine bolt
alpine bolt
alpine bolt
#

It’s not really representative of endpoint indexation. That’s what I meant

gloomy chasm
#

Yeah, you either need to store the actual values in a dictionary or a class derived from the AdvancedDropDownItem

alpine bolt
#

In my case I made a class that inherits from AdvancedDropdown and acts as a base to all types of dropdowns

#

Then I made an AdvancedPopupField element that implements INotifyValue<object> that accepts any base CustomAdvancedDropdown I throw at it

#

At this point you should learn how to raise UIElements events

indigo condor
#

Hello everyone!

#

Does anyone knows how could i see where i am giving a min size to this so it doesn't crop that much?

chilly steeple
#

You mean the entire editor window or what part exactly do you wish to have a min size?

indigo condor
#

But i don't know how to fixe it

#

That text should crop itself in more lines when the window is smaller than the text size

chilly steeple
#

what is the shrink value set to?

#

should be 1

indigo condor
#

It's already one 😦

chilly steeple
#

its parent?

#

cuz there's a scroll view going on, indicating that it's parent isnt shrinking either

indigo condor
chilly steeple
#

no the entire scrollview thing

indigo condor
chilly steeple
#

ill try and reproduce on my end, one sec

indigo condor
#

Do you want the uxml code?

chilly steeple
#

would save time, yes!

chilly steeple
#

just to be sure, there's no custom elements here?

indigo condor
#

that message i've needed to recreate itself entirely by code...

chilly steeple
#

HelpBox is your custom thing, then?

indigo condor
#

Now I read you all, i'm going to have lunch :>

gloomy chasm
chilly steeple
#

the elements are set to shrink as far as the screenshots show

#

what elements make up the HelpBox? @indigo condor

indigo condor
# chilly steeple what elements make up the HelpBox? <@716683518473928806>

Just this:html <ui:HelpBox message-type="Info" text="List is empty! Create new JSON templates to store different data types by clicking &apos;New JSON Template&apos;." name="EmptyListMessage" style="margin-left: 12px; margin-right: 12px; margin-top: 0; margin-bottom: 0; min-width: auto;" /> I think is just a deffault boxhelp...

#

Here is the entire code if you need it

indigo condor
indigo condor
#

and sorry for the late on answering you... I was having lunch 😦

indigo condor
chilly steeple
#

Helpbox doesnt seem to be in UI builder :pain:

indigo condor
chilly steeple
#

cringe Unity moment

#

can you see what the helpbox label flex settings are?

indigo condor
#

sure!

indigo condor
chilly steeple
#

sorry, one sec

#

so what I think is happening is that the Label element of the helpbox doesn't have the correct style settings

#

as the label grows with the text, but doesn't respect the boundraries or wrapping rules

indigo condor
#

so... is there any way to fixe that?

#

It happens that too with another Label that i have

chilly steeple
#

wait, try and set the scrollview's scrollmode to vertical only

indigo condor
#

that fixe it

chilly steeple
#

aight nice

#

nice looking asset btw

indigo condor
#

Thanks! :>

indigo condor
#

And how could i add like an hover text when i pass the mouse over the toggle text?

#

or just over some buttons

#

is that made by code editing the uxml or is there any way to make it visually on unity UI toolkit?

gloomy chasm
#

You can do something like

.my-text {
  display: none;
}

.my-text:hover{
  display: flex;
}
indigo condor
gloomy chasm
#

There isn't a good way to do a custom tooltip with other visual elements inside of it. But you can just set the tooltip property on the VisualElements if you just want to set the text

indigo condor
#

Thanks!

indigo condor
#

Hey, I need some specific help with something that I really have no idea how to do...

#

Alright, i need the first boxhelp to have the same height the second one. that's currently working, but the point is that i don't want the first pixel boxhelp to be bigger than the second one

#

so when that happens i want a verticall scroller to appear...

#

Did i explain well myself?

#

In a few words, i need the Add Data boxhelp to always have the first column height, adding a scrollview if it's necessary

gloomy chasm
indigo condor
gloomy chasm
indigo condor
#

So sorry for the low quality 😅

gloomy chasm
indigo condor
gloomy chasm
indigo condor
#

without flex grow it looks like this

#

changed...

#

and is the same

gloomy chasm
#

Ahh, uhh. remove the flex grow from the scrollview instead

indigo condor
#

like this?

gloomy chasm
#

yeah

indigo condor
#

the same 😦

gloomy chasm
# indigo condor the same 😦

I would open up the UIElements debugger and play around with the styles in there. It will be faster to figure out and easy to play with. Sorry, I ma not sure atm what to do to get what ya need

indigo condor
#

It's fine hehe :>

tough cairn
#

which editor method auto formats the fields names ? for example from "m_CPMaterial " -- to -- > "CP Material"

tough cairn
#

thanks mech !

#

any ideas how to calculate PrefixLabel's rect ?

#

im doing the following :

float step = position.width * 0.4f;
var rect = position; 
rect.x += step; 
rect.width -= step;
#

which is sort of reasonable , not perfect but it does the trick