#↕️┃editor-extensions

1 messages · Page 18 of 1

astral oar
#

hm, it seems like it's not null, I was wrong but I still can't access anything

#

well I don't seem to get any errors or anything, it just doesn't reflect in game at all

dense agate
#

let me quickly write a script and see how it behaves on my end

astral oar
#

I wrote custom editor extension that compiles game scripts in my own language and checks for errors when I change them and if they compiled successfully call method if editor is in play mode to force game load new scripts

#

I can do that manually, just would be nice if I could do that automatically so when I make changes to scripts (not the C# ones) it'd immediately reflect in game

dense agate
#

i can access GameObjects at runtime through an Editor Script without problems

astral oar
#

hm

#

I'll see what interferes in my case but ty for testing

dense agate
#
        [MenuItem("VoxelMMOnsters/Helper/Help a Stranger")]
        public static void HelpAStranger()
        {
            foreach (var monsterStatus in Object.FindObjectsOfType<MonsterStatus>())
            {
                if (monsterStatus.gameObject.activeInHierarchy)
                {
                    Debug.LogError(monsterStatus.gameObject.name + " Stamina: " + monsterStatus.CurrentStamina);
                }
            }
        }

this is the script i used. Maybe it helps oyu figure out your pitfall 🙂

astral oar
#

sorry, it was the dumbest thing possible, I just forgot to set a flag on my game controller that allows reloading scripts at runtime

#

this is all disabled for normal builds, I just forgot to turn it on

dense agate
#

haha. glad you figured it out : )

oblique sky
#

with Odin you can simply append [NestedScriptableObject] onto the SO field

#

[InlineEditor] also helps in a similar way

dense agate
agile badger
#

Hey y'all. I'm writing a custom Project Settings page that's backed by a ScriptableObject. So far it's going well but I'd like to clean the code up a lil. Right now I have this in the backing SO

public void OnValidate()
{
    if (this.themeSettings == null)
    {
        EditorGUILayout.HelpBox("Please create and assign a Theme Settings asset to enable UI component theming.", MessageType.Error);
    }
}

That way my SettingsProvider's guiHandler can call OnValidate on the object instance. (Otherwise it never gets called by Unity because it's not being viewed in the Inspector)

#

That way I can display help boxes to the user to make sure they don't leave mandatory fields blank

#

I'm wondering if there's a way to get Unity to call OnValidate automatically instead of exposing it as public

#

I'd also like to refactor this. It's based on the SettingsProvider example in Unity's docs.

public static AcidicGUISettings FindSettings()
{
    var settings = AssetDatabase.LoadAssetAtPath<AcidicGUISettings>(settingsPath);
    if (settings != null)
        return settings;
        
    settings = CreateInstance<AcidicGUISettings>();
    AssetDatabase.CreateAsset(settings, settingsPath);
    AssetDatabase.SaveAssets();
    return settings;
}

I'd like to refactor it such that, instead of finding/creating the asset in a hardcoded path like in the example, I'd like to have the user create a settings asset themselves wherever they want it and then assign it in a field in their Project Settings.

#

Just like how you would with URP and HDRP settings (I'm aware those packages create their settings assets for you but you know what I mean, you can move them around)

queen wharf
# agile badger I'd also like to refactor this. It's based on the SettingsProvider example in Un...

Only 50% of what your looking for but this is what I currently have. This code is a modified version of some example code Odin provides in regards to it's ValueDropdown atrribute

    public static ScriptableManagerSettings GetScriptableManager()
    {
        List<ValueDropdownItem> newScriptableObjects = new List<ValueDropdownItem>();
        IEnumerable<ValueDropdownItem> scriptableObjects;

        scriptableObjects = UnityEditor.AssetDatabase.FindAssets("t:ScriptableObject")
        .Select(x => UnityEditor.AssetDatabase.GUIDToAssetPath(x))
        .Select(x => new ValueDropdownItem(x, UnityEditor.AssetDatabase.LoadAssetAtPath<ScriptableObject>(x)));

        foreach (ValueDropdownItem item in scriptableObjects)
        {
            if (item.Value.GetType() == typeof(ScriptableManagerSettings))
                return ((ScriptableManagerSettings)item.Value);
        }
        return (null);
    }
#
    [SerializeField] public ScriptableManagerSettings scriptableManagerSettings
    {
        get
        {
            if (_scriptableManagerSettings == null && Application.isPlaying == false)
            {
                OnGetScriptableManager();
                _scriptableManagerSettings = HelperFunctions.GetScriptableManager();
            }
            return (_scriptableManagerSettings);

        }
    }
agile badger
#

What's that meant to do?

queen wharf
#

Basically when scriptableManagerSettings is null and the game isn't running it will run GetScriptableManager which gets every ScriptableObject in the project and checks if any are of the scriptableManager type and returns that

#

Doesn't solve your issue in regards to having it hooked up to the project settings but means it's not hardcoded

agile badger
#

Ah.

#

Was hard for me to tell, I was reading it through text-to-speech

#

I love being blind

#

But... I could see a way to make that code a lil more efficient. Instead of querying AssetDatabase for all ScriptableObjects, you could tell it to query only for the type of ScriptableObject you're working for (there should be a filter parameter that takes a string of the format "t: MyDesiredTypeName")

#

That narrows down the amount of GUIDs you have to look up asset paths for

#

Unless I misread the code and it's already doing that

queen wharf
#

Yeahh it's not the best cook aha. Been putting off refactoring it since it's run very infrequently. Just figured might be some good food for thought for your problem but you might be a couple steps ahead of me 😛

agile badger
#

I guess the only way to solve my issue is to figure out how to store something in the ProjectSettings directory

#

Maybe a JSON file that just holds the asset GUID of the user's desired settings asset

#

Then I can just use an object field inside the guiHandler to give the user a UI for setting this GUID

queen wharf
#

Only package i've seen add stuff to Project Settings so far is Bakery

agile badger
#

TextMeshPro, URP, and HDRP all do

agile badger
#

NOT TOO SHABBY

#

That's PART of the problem

gloomy chasm
agile badger
#

I got it all working the way I want

errant shale
#
  • I struggle to find any information on how to undo AssetDatabase.CreateAsset. So far i've been trying to use Undo.RegisterCreatedObjectUndo(AssetDatabase.LoadAssetAtPath<...>(...), ...), but it leaves a ghost asset behind that disappears only after the project is saved. Is there any way to handle it better?
alpine bolt
north sphinx
#

I am looking into modifying my prefabs with code (some refactoring).
After I set some serialized fields to that object. How do I record changes to disk?
Will that do?
Undo.RecordObjects(recordedObjects.ToArray(), "Convert inlined materials to templates.");

gusty mortar
north sphinx
#

how do I serialize it?

#
            foreach (var prefabGuid in prefabs)
            {
                var path = AssetDatabase.GUIDToAssetPath(prefabGuid);
                var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(path);

                if (prefab == null)
                {
                    continue;
                }

                shapeList.Clear();
                prefab.GetComponentsInChildren(shapeList);

                if (shapeList.Count == 0)
                {
                    continue;
                }
#

here's what I mean

gusty mortar
#

What are you actually modifying on the prefab ?

north sphinx
gusty mortar
#

Maybe AssetDatabase.SavesAssets() will be more suited to what you're doing

north sphinx
#

So, like this?

gusty mortar
#

After your modifications, but yes

north sphinx
#

hmm

#

doesn't seem to work

#

git does not pick it up, meaning it will be gone on reimport

gusty mortar
#

Can you show the actual modification code ? The fragment you shared earlier only show that you're loading an asset

vapid prism
north sphinx
gusty mortar
#

PeppeJ's answer will probably more helpful than mine. I forgot that prefab were handled differently than other assets

real spindle
#

Is it possible to modify a .meta file from a script?
I'd like to make some tooling for stuff that is too tedious with the FBX importer

waxen sandal
#

Just open it like a text file?

real spindle
#

For example, copying curves & events from on anim to another

real spindle
waxen sandal
#

Yes

real spindle
#

Oh well if that works then great. I will try when I get home

gloomy chasm
#

I have a editor window that is referencing a ScriptableObject instance that lives in the scene. Is there a way to get the window to keep the reference when closing and opening Unity?
I was thinking GlobalObjectId, but it can't create one for the ScriptableObject, I assume because it isn't really 'in the scene' like a GO or Component is.

waxen sandal
#

No, it wouldn't have a GUID

#

You can make your own reference type though

gloomy chasm
waxen sandal
#

You probably need some component in the scene to keep track of it

#

Which oyu can then ask for the reference

#

So the reference struct will mostly just contain the scene ref and some unique id

gloomy chasm
#

Oh got it, like that. Yeah I was hoping for a more generic solution since the object maybe not be mine. The window is showing the contents of a field. Sort of like how the AnimationCurve opens a window to edit it, but the window is dockable.

waxen sandal
#

Ah not sure you can do that

stone field
#

when i install the 'Unity for VSC' extension and try to open a project it says smt along the lines of 'this project needs to be updated to the new SDK style'

#

been tryna fix my ide cuz intellisense randomly stopped working

snow pebble
#

none of these work for me by the way

#

i still lose the data

#

im updating the data by editing the target object values

#

so i use set dirty

pine reef
#

is there a way to set LocalizedString with script? i'm making a dialogue editor and i want to add localization editing to it. it seems LocalizationString or StringTable only has getter methods. any hints?

north sphinx
#

It has a constructor

north sphinx
#

I have a prefab inside hierarchy of other prefab.
How can I identify that current MonoBehavior I am inspecting is part of external prefab?

#

Basically, I only want to modify game objects that are part of currently opened Prefab, skipping if game object is part of other prefab (because I want to modify that nested prefab instead)

astral oar
#

figured it out myself:


[InitializeOnLoad]
public static class EditorUtil
{
    private static readonly MethodInfo logEntriesFlagsGet;
    private static readonly MethodInfo logEntriesFlagsSet;

    private const int CLEAR_ON_BUILD = 2048;

    static EditorUtil()
    {
        var assembly = Assembly.GetAssembly(typeof(Editor));
        var logEntries = assembly.GetType("UnityEditor.LogEntries");
        var logEntriesFlags = logEntries.GetProperty("consoleFlags");
        logEntriesFlagsGet = logEntriesFlags.GetGetMethod();
        logEntriesFlagsSet = logEntriesFlags.GetSetMethod();
    }

    public static bool ClearOnBuild
    {
        get
        {
            var flags = (int)logEntriesFlagsGet.Invoke(null, null);
            return (flags & CLEAR_ON_BUILD) != 0;
        }
        set
        {
            var flags = (int)logEntriesFlagsGet.Invoke(null, null);
            if (value)
                flags |= CLEAR_ON_BUILD;
            else
                flags &= ~CLEAR_ON_BUILD;
            logEntriesFlagsSet.Invoke(null, new object[] { flags });
        }
    }
}
lapis sonnet
#

i am working an a event system for my game to make level design easy for my non coder friend, but am running into a editor script GUI issue, #archived-code-general message here is the message, i was recommended to ask it here and i still cant figure it out so i figured ide ask here like i was told lol
should have posted it here in the first place, but i did not put 2 and 2 together on this channels name

gloomy chasm
lapis sonnet
#

im not i said a few msgs after the linked one im on 2021

#

and i dont know where the issue is, only what it is.
i mean, its in EventTriggerEditor.cs in case CommandType.SendEvent

#

but i dont know why its not displaying right as its the same as the main ReorderableList, just as one whole case

#

other than people saying its just messy to work with and that it could be a unity bug for my version of 2021.3.23f1

gloomy chasm
lapis sonnet
#

79 of EventTriggerEditor if im correct,,

#

sendEvent is just meant to store a list of commands inside of the command to send to another eventhandler like the commandList does, so i made a almost 1:1 copy of the main ReorderableList but just, inside of the case CommandType.SendEvent on line 60

gloomy chasm
lapis sonnet
#

says

Assets\Editor\EventTriggerEditor.cs(79,78): error CS1503: Argument 4: cannot convert from 'method group' to 'float'
#

changed it to

                        EditorGUI.PropertyField(new Rect(rect.x, rect.y, 60, EditorGUI.GetPropertyHeight),
                                    nestedElement.FindPropertyRelative("commandType"), GUIContent.none);
gloomy chasm
#

No I meant EditorGUI.GetPropertyHeight(nestedElement.FindPropertyRelative("commandType"))

#

The method returns the height needed to render the property passed in to it

lapis sonnet
#

oh my bad

#

im really not good with editor GUI code

gloomy chasm
#

Also, I would recommend just making a custom PropertyDrawer for Command, it should make this easier for you

gloomy chasm
lapis sonnet
#

i dont know what a PropertyDrawer is

#

this is my first complex GUI script

gloomy chasm
#

lets you make custom editors for normal C# scripts basically

lapis sonnet
#

i changed line 79 to what you recommended and same result

gloomy chasm
#

So any time the normal C# class is drawn in the inspector as a field, it will draw how you tell it to in your PropertyDrawer

gloomy chasm
lapis sonnet
#

i just want a list with the + and - to add to that looks the main gui

lapis sonnet
#

same result

#

but hey, it says send event now in the commandType box

queen wharf
#

oh are you messing with events

#

like unityevents

lapis sonnet
#

no

#

my own system

queen wharf
#

👍

lapis sonnet
gloomy chasm
#

oh @lapis sonnet Part of the issue might be because you are nesting Commands. Is that not throwing a serialization warning in the console...?

lapis sonnet
#

it is

#

2 all the time

#
Serialization depth limit 10 exceeded at 'Command.commandArguments'. There may be an object composition cycle in one or more of your serialized classes.

Serialization hierarchy:
11: Command.commandArguments
10: Command.nestedCommands
9: Command.nestedCommands
8: Command.nestedCommands
7: Command.nestedCommands
6: Command.nestedCommands
5: Command.nestedCommands
4: Command.nestedCommands
3: Command.nestedCommands
2: Command.nestedCommands
1: Command.nestedCommands
0: EventTrigger.commands

gloomy chasm
#

Yuuup

lapis sonnet
#

i was not sure what it ment, and also did not know if it related to my issue

#

i mean, ig reading it it makes sense

#

sorta

#

is it like a GUI feedback loop?

gloomy chasm
#

Unity serializes things as values. Meaning that there can be no null value. As such, if you have a class that has a field of the same type, it creates a infinit loop

lapis sonnet
#

so how do i fix that?

#

(also gonna ask phind to break down what you said in my dumb brains language lol)

gloomy chasm
#

(Please note that I specifically liked to the documentation because it is important to read and understand what it does)

gloomy chasm
# lapis sonnet (also gonna ask phind to break down what you said in my dumb brains language lol...
public class MyClass
{
  public float myValue;
  public MyClass myField;
}

When Unity goes to serialize MyClass, it will first see the myValue field and initialize it to 0 as a default value.
It will then go to the next field, which is 'myField', and because it serializes things by value and not reference, it will create a new MyClass instance, and assign it to myField.

Unity now needs to go in to the instance it just assigned to myField, and serialize all the fields in it.
Go back to top of this message.

#

This is the issue you are having with the serialization depth warning.

lapis sonnet
#

and that is the core issue with my GUI being broken?

gloomy chasm
#

I don't know, but it isn't helping things at all haha

lapis sonnet
#

okay, ill work on fixing it then report back

#

when i click on the warning it brings me to command.cs and highlights nestedCommands

#

so it is something to do with the use of public List<Command> nestedCommands;

gloomy chasm
lapis sonnet
#

i know, i did just figuring out stuff in the only way i can understand

gloomy chasm
#

Yeah the issue is public List<Command> nestedCommands;

lapis sonnet
#

yea, i just dident put together what you were saying before

#

as im slow

wheat notch
lapis sonnet
#

if i can yes

wheat notch
#

:P

lapis sonnet
#

if i cant then ill firgure something else out

#

i feel like im super close to fixing this, but this is my last try

#

i asked here again as i wanted a responce from the correct channel, as i posted wrong in the first place last night

wheat notch
#

Structs + property drawers pretty much deal with most of the formatting stuff u need to do. :0
To modify the list itself (like element count limiting stuff like that), just make a property drawer or editor script of the one that has the field. :P

lapis sonnet
#

i know, just wanted to fix the warning

#

but its not the issue

wheat notch
#

a

lapis sonnet
#

wanted to see if maybe it would work once fixed

#

moving onto this now

#

just,, need to figure out why its not showing the command as a dropdown list like it should

wheat notch
lapis sonnet
#

its doing the same thing that the list did with the non working dropdown, this time though it says nested command and looks better GUI wise

#

i want it to be a dropdown for the command types i add like the one at the top left corner, then once the command is selected show its inputs under it like how the command as a whole looks

lapis sonnet
#

HAHA I WIN UNITY

#

just gotta fix spacing issues now,,,,

lapis sonnet
#

okay, i return for more help, i want to be able to use a sendEvent inside of a sendEvent, but the nested list for sendEvent doesnt have a case for itself as that would need another layer for each layer i want to be able to nest and thats just not an option as i want to be able to use as many layered sendEvents as i want for bouncing commands back and forth, how would i do this? i normally would make it into a method but i cant add the case and add the method into the case as that would not work due to unity loop stuff, so how can i do this? https://pastebin.com/AFcuLFCi

#

so this ^ but working. and yea ik there is no gui code for it just giving an idea of what i want to achieve

long escarp
#

Hi, I have been trying to make a data profiler editor window to be able to follow more effectively what happens at runtime in my game. Problem is, I can't get it to be a scrolling window if needed. It either doesn't fill the whole window or overflows too much horizontally, as the horizontal scroll bar fits the content, and not the containing window. I tried using a rect to make them fit but then the content got pushed out. I can share the code but it is quite long already

safe sorrel
#

My editor window is not sticking around when I close and reopen Unity. A built-in windows doesn't disappear when I do that.

#

Do I need to do something special to make this happen?

#

here's the code, in case it matters

public class GameConfigWindow : EditorWindow
{
    [MenuItem("Pursuit/Game Config")]
    public static void ShowWindow()
    {
        GetWindow(typeof(GameConfigWindow));
    }

    void OnGUI()
    {
        GUILayout.Label("Game Config");

        GameConfig.instance.Mode = (GameManager.GameMode) EditorGUILayout.EnumPopup(GameConfig.instance.Mode);
    }
}
#

It doesn't get saved in layouts either. I do not see any messages in the console when saving or loading the layout. This is in 2023.1.6f1

#

Ah! The file name did not match.

#

Of course. EditorWindow derives from ScriptableObject

#

This only came up just now because I renamed it from GameConfig to GameConfigWindow

snow pebble
#

why doesn't my hover effector on the class detect any applicable elements

#

been trying to figure out why my buttons are non responsive and this appears to be why

gloomy chasm
snow pebble
#

ah that was it

#

thanks!

gloomy chasm
#

np 🙂

snow pebble
#

how do you subscribe to button clicks

gloomy chasm
snow pebble
#

ah

#

i was using register value change

#

which didnt even do anything

gloomy chasm
#

Yeah you would want to use MouseDownEvent

#

which is all the button is doing

#

Actually, it is using a Clickable which inherits from Manipulator and all that does is let you subscribe to multiple callbacks in a clean way if you want to add/remove them all at once

snow pebble
#

never seen this before

#

looks like i broke ui toolkit

snow pebble
#

starting to really like using ui builder for editor ui now

#

shame the performance of it is quite slow to use at the moment

gloomy chasm
snow pebble
#

i am using 2023 😢

gloomy chasm
#

Nice! So you already know!

snow pebble
#

yeh i noticed when you drag an element in and you want to make it a child even if you hover over the element it doesn't make it a child half the time

#

god knows how they managed to make it so slow

gloomy chasm
snow pebble
#

they consider ui builder to be in beta phase?

gloomy chasm
#

This is for the 2023 beta

snow pebble
#

oh .2

#

im on .1 its not nearly as bad as that

#

but its still quite bad

gloomy chasm
#

Ahh, yeah

snow pebble
#

does .2 bring the attributes syntax

#

or is that .3

gloomy chasm
#

The attribute system?

#

Ooh

#

Yeah think so

snow pebble
#

that will make things much quicker

gloomy chasm
#

For sure

#

Idk why they went with the nested class approach to start with

#

2023.2 has the new binding system in it which is cool

#

Haven't really gotten to use it much yet though

snow pebble
#

with unity editors for the new ui toolkit is there a way to still get the default inspector but then add ui elements after it ?

#

or must it require us to replace the whole thing with our ui document

#

surely the default inspector comes with a default ui toolkit version too?

snow pebble
#

how do we use that though its not an override

#

do we just call it and pass in the root with the serialized object

visual stag
#

Yes

snow pebble
#

okay, will give it a try

#

thanks

#

weird its a static and not just using the same setup as the old editor function did by calling the base method

visual stag
#

Means you can call it anywhere

snow pebble
#

why/when would you want to call it in a different location though

visual stag
#

So show an editor nested in another location

snow pebble
#

oh i see

#

interesting

visual stag
#

I just added a comment on DrawDefaultInspector to help those looking

snow pebble
#

wdym

visual stag
snow pebble
#

oh wow thats a neat idea

visual stag
#

It's existed for a while, and previously as a different extension before chrome changed their requirements. Sorry for assuming you knew about it 😅

snow pebble
#

hadn't heard of it before

#

was it stickied or something

#

unity should adopt this idea of user comments/notes as a feature

visual stag
#

I thought it was... but it doesn't seem to be

#

They have considered it in the past I think, but the docs team is understaffed

snow pebble
#

fair enough

#

that would explain why documentation is sometimes non existent for some things 😄

visual stag
#

dammit

snow pebble
#

what the heck were you writing

visual stag
#

Updating the pins, the top one is at capacity it seems

snow pebble
#

maybe an external wiki would be better and then just pin the wiki

snow pebble
#

is there a way to know if the serialized object for the editor is a prefab or an instanced version in the scene

#

since i want different editor ui depending on the situation

waxen sandal
#

I guess you can get the targetobject and then use PrefabUtility?

queen wharf
#

Is there anything that fires off if I stop moving the selected gameobject via its gizmos and/or inspector?

north sphinx
#

hmmm. I have an abstract GameObject reference. I need to know whether this is a prefab or whether this is a instance instantiated from prefab.
All done in Edit-Time (not PlayMode).

Basically, I need to get source GUID of game object. Any tip how can I do so?

brave gull
#

hey folks, does anyone know how to add Version History to my own custom github packages? I can't find any documentation on it.
my packages are using Tags and Releases with MAJOR.MINOR.PATCH formatting and release notes, but they don't show up here.

peak bloom
#

you may want to add another check whether the prefab is disconnected or not

north sphinx
#

I might need to test it further though

tough cairn
#

is there a way to get current folder in Project tab ?

tough cairn
#

got it :

var path = (string)typeof(ProjectWindowUtil).GetMethod("GetActiveFolderPath", BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, null)
quasi hemlock
#

hi im writed a code like this:

using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(GameObject))]
public class ApplyChangesToPrefab : Editor
{
    public override void OnInspectorGUI()
    {
        GameObject go = (GameObject)target;
        if (!PrefabUtility.IsPartOfPrefabInstance(go) || !PrefabUtility.HasPrefabInstanceAnyOverrides(go, false))
        {
            DrawDefaultInspector();
            return;
        }
        EditorGUILayout.HelpBox("This object is a prefab instance with changes.", MessageType.Info);
        if (GUILayout.Button("Apply Changes to Prefab"))
        {
            PrefabUtility.ApplyPrefabInstance(go, InteractionMode.UserAction);
        }
    }
}

but whenever I open this script it happens like this:

#

what is the reason of this?

astral oar
#

I want to write a script that does some modifications to gradle project before building, is it possible to do that? I know I can export gradle project but it still builds it, I can rebuild it I guess but it takes nearly twice as much time

#

wait, nevermind

#

it only exports

snow pebble
#

for ui elements how do we restrict the object field to be a specific scriptable object type

#

right now it lets me choose any object which i dont want

peak bloom
snow pebble
#

doesnt seem to work though

#

it has restricted to that type

#

but it wont load my scriptable objects to select one

#

oh it works now

#

unity must've just had a brainfart

#

thanks!

snow pebble
#

PrefabUtility.IsPartOfPrefabAsset(target) this doesn't seem to work for me for a prefab

#

was hoping to show different ui when i open the prefab

#

but it doesn't seem to be returning true when i open a prefab

snow pebble
#

seems theres no actual way to do it

#

if (PrefabStageUtility.GetCurrentPrefabStage() != null)

this turns out to be the way to test if you're in prefab editor scene or game scene

#

finally worked it out

snow pebble
#

PrefabUtility has no method for it either

#

i tried one but it turns out to be deprecated

#

that seems like a stupid limitation

visual stag
#

I'm not really sure what the context of that quote is

snow pebble
#

turns out the post is from 2015 so was likely in the early days of prefab feature

#
            var transform = target.GameObject().transform;
            int count = _data.Points.Count / 3;
            for (int i = 0; i < count; i++)
                Instantiate(new GameObject("ID: " + i), transform);

this technically works

#

but it also adds gameobjects to the main scene aswell

#

kinda weird

#

they dont end up attached to anything either

visual stag
#

There's a talk pinned to this channel with info on how to do some things with the prefab system

#

PrefabUtility methods is how to do everything

snow pebble
#

which link ?

#

oh i see it now

visual stag
#

The one that says

Talks

Prefab System

snow pebble
#

weird i didnt see it the first time

visual stag
#

There are more APIs and things have changed since then, but it's got the basics

snow pebble
#

Instantiate(new GameObject("ID: " + i), transform);

wait would the new part be creating a gameobject in the scene then instantiate is cloning it ?

#

maybe that would explain why im getting random ones appearing the scene aswell as my prefab

#

ok the slide seems to suggest i can do it

#

though it doesn't actually show any api on how

#

though it says "edit prefab assets" doesnt necessarily mean i can instantiate child elements to it

#

when i tried i get Cannot instantiate objects with a parent which is persistent. New object will be created without a parent.

#

which explains why it spawns them in scene

visual stag
#

Whatever you're trying to do, if you're just wanting to modify the prefab asset I think you can use the method on slide 60

snow pebble
#

i tried that earlier with :

var assetRoot = PrefabUtility.LoadPrefabContents(PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(target.GameObject()));
Debug.Log(assetRoot.name);
#

but it seems to return null

#

target.GameObject() is the prefab since the editor only runs in prefab mode

#

but its not a prefab in a scene its the actual selected prefab in asset folder opened up

visual stag
#

So what's being returned by GetPrefabAssetPathOfNearestInstanceRoot?

#

Because I would try to keep it simple and tackle one thing at a time, if that's not returning the prefab asset then that's where to start

snow pebble
#

appears the path is empty or null

visual stag
#

Then I doubt you are dealing with a prefab instance

snow pebble
#

yeh i know its not an instance

#

its the prefab in the asset folder

visual stag
#

Then why are you using that method?

snow pebble
#

its not in a scene

#

there is no other path method in the prefab utility

visual stag
#

AssetDatabase.GetAssetPath

snow pebble
#

still an empty string =/

#

i tried instance id and gameobject of the target

visual stag
#

Show what object that GameObject is

snow pebble
#

so when i click regenerate tank the idea is it will create child objects based on the layout data

#

debug log of target.GameObject() gives Tank (UnityEngine.GameObject) UnityEngine.Debug:Log (object)

visual stag
#

If you're getting the asset path of something opened in a stage you may need to use PrefabStageUtility.GetCurrentPrefabStage ().prefabAssetPath

#

I am unsure if there's a consistent way to handle it in all cases

snow pebble
#

not sure what a "stage" means in unity

visual stag
#

I have not set something up like this

#

When you have a prefab opened it's opened in the prefab stage

#

which is the temporary view for staging prefab changes before they are saved

snow pebble
#

Assets/Prefabs/Tank.prefab

#

ah that seems to be it

#

ok so thats the word im looking for is stage not scene 😄

visual stag
#

I don't think you should generally allow editing the prefab asset directly when the stage is open, because I think you may have to reload the contents of the stage

#

or, if you do, only support that

#

it'll be annoying to handle all cases otherwise. But you can make your own decisions, just be aware that the stage is a temporary representation loaded from your asset

snow pebble
#

so when i do this:
var assetRoot = PrefabUtility.LoadPrefabContents(path);

and add what i need, i then need to save it to the asset path as a prefab again ?

#

and overwrite basically

visual stag
#

Yes, you need to save and unload it

snow pebble
#

seems simple enough theres a save prefab asset function

visual stag
#

the steps are in slide 60

snow pebble
#

okay trying it now

#

it seems to work \o/

#

thanks for the assitance!

astral oar
#

I'm trying to use it but it never gets called

#

hm it's called after restart

#

nevermind I guess

worthy wyvern
#

After getting a Sprite from my prefab's Sprite Renderer, how do I draw it in the current scene correctly? I'm using GUI.DrawTexture, but I don't know how to set the Rect correctly.

snow pebble
#

any one know why I keep losing the reference value in my object field here? the object is serialized:

        [SerializeField]
        TankLayout _data;

yet it becomes null

#

im using ui elements for my object field

snow pebble
#

oh i see why

#

damn unity makes prefab so much more annoying that it needs to be

timid coyote
#

cant I root.Bind(serilizeObject) and right after i added a new element to an array, make it be shown without deselecting and selecting again the scriptable object?, because it doesnt seem to work (for ui toolkit)

snow pebble
#

@visual stag so after some playing around it seems this:

            PrefabUtility.SaveAsPrefabAsset(asset, path);
            PrefabUtility.UnloadPrefabContents(asset);

doesn't actually seem to save to my prefab

#

it shows it in the stage, but then i drag the prefab to the scene and its all gone

visual stag
#

It's surprising it would even show it in the stage for me

#

but 🤷 you'll have to figure it out, it should save just fine. I imagine it's having the stage open that's causing the issues

snow pebble
#

it seems odd they wouldnt make it simple enough to edit prefabs in stage from editor code

#

less hassle than dragging into the scene then saving it to a prefab

visual stag
#

why not just select the prefab asset?

#

Is it on a sub-object or something?

snow pebble
#

i am selecting it

#

what do you mean by selecting it exactly

visual stag
#

then why open it in the stage

#

Selecting it in the project window

snow pebble
#

because the code instantiates child gameobjects. selecting it in the project window only shows the inspector

#

not the visuals of it

visual stag
#

The code loads the prefab into a temporary scene, does it's work, and saves the prefab. You don't need to open the stage to do that.
But yeah, I'm sure you can make it work with the stage, I just am not familiar with it and it would take too long to test it for you

snow pebble
#

this is basically whats happening

#

when i drag to scene all the data i added is lost

visual stag
#

I am very surprised the API adds children to the prefab in the stage

snow pebble
#

if we can do it manually with a mouse i dont see why we can't with code

visual stag
#

I suspect you have done something different to what was on that slide 60

#

and are actually editing the thing in the prefab stage, and in that case you will just need to dirty it

#

using Undo.RegisterCreatedObject or whatever should do it

snow pebble
#

this is basically the summary of it:

void Load(out GameObject asset)
{
    var path = PrefabStageUtility.GetCurrentPrefabStage().assetPath;
    asset = PrefabUtility.LoadPrefabContents(path);
}

void Save(GameObject asset)
{
    var path = PrefabStageUtility.GetCurrentPrefabStage().assetPath;
    PrefabUtility.SaveAsPrefabAsset(asset, path);
    PrefabUtility.UnloadPrefabContents(asset);
}
private void Regenerate()
{
    Load(out var asset);
    ClearChildTransforms(asset);
    for (int i = 0; i < _data.BiArcs.Count; i++)
    {
        var segment = Instantiate(_segmentPrefab, target.GameObject().transform);
        segment.name = "ID : " + i;
        segment.GetComponent<WallSegment>().Set(_data.BiArcs[i]);
    }
    Save(asset);
}
#

Regenerate called when i hit the button

#

weird it randomly worked this time 🤔

#

unity is being a bit glitchy with it

snow pebble
#

where do i try that to ?

visual stag
#

to the objects you create, the children

snow pebble
#

oh okay

#

hm seems to be working

#

not sure why that fixes it though

astral oar
#

are there any examples how to make element like this in uitoolkit? and also tree view

snow pebble
#

like what ? thats the default ui isn't it?

astral oar
#

I just have hard time finding good documentation on ui toolkit for 2019

peak bloom
#

2019 ffs.. can't you just upgrade?

waxen sandal
#

Lol don't bother in 2019

astral oar
#

ok, is it then possible to make a fast working tree view that can display thousands of elements with IMGUI?

#

I guess I'll have to sit in dnspy a lot more

patent pebble
#

does anybody know if there's a quick way to get this information in code?

#

kinda rusty on my editor extensions coding

#

making a tool that needs to know the current Visual Studio version

visual stag
patent pebble
#

thx

#
CodeEditor.Editor.CurrentInstallation.Name
#

that was it

gloomy chasm
patent pebble
#

all you have to do is cull whatever is not visible in the rendering area and it performs pretty well

#

if you don't do that it will slow down severely when you have a lot of rows and columns

worthy wyvern
#

What's the best way to draw a texture from an editor script?

waxen sandal
#

DrawTexture

worthy wyvern
#

both Graphics. and GUI. don't let me draw smaller than 1 unit

gloomy chasm
worthy wyvern
#

with new Rect(0, 0, 0.6, 0.6) the scale snaps back to 1 unit of size

#

and with smaller sizes it snaps to 0

gloomy chasm
worthy wyvern
#

by Units I mean Unity world units

#

which corresponds to Vector2.one

gloomy chasm
#

The rect takes pixels.

#

Where are you wanting to draw this texture?

worthy wyvern
#

to the scene

#

current scene

gloomy chasm
#

In GUI or world space?

worthy wyvern
#

in OnSceneGUI

gloomy chasm
#

You can use the scene.camera to convert GUI and world space

worthy wyvern
#

gotcha

worthy wyvern
#
GL.PushMatrix();
GL.LoadPixelMatrix();
Vector2 screenPosition = sceneCamera.WorldToScreenPoint(enemySpawnPosition);
GUI.DrawTexture(new Rect(
    screenPosition, enemySprite.rect.size),
    enemySprite.texture);
GL.PopMatrix();

I think this is somewhat correct, texture draws smaller than 1 world unit. The only thing is that it scales with the camera

gloomy chasm
worthy wyvern
worthy wyvern
#

moving the camera down moves the texture down instead of up

#

should be at that PositionHandle

#

the camera's center is currently under the world center

#

oh and I also should mention the sprite is rotated 180 degrees

#
GL.PushMatrix();
GL.LoadPixelMatrix();
Vector2 screenPosition = HandleUtility.WorldToGUIPoint(enemySpawnPosition);
GUI.DrawTexture(new Rect(
    screenPosition, enemySprite.rect.size),
    enemySprite.texture);
GL.PopMatrix();
gloomy chasm
#

Oh you might need to do
Handles.BeginGUI() and Handles.EndGUI around the GUI.DrawTexture call

worthy wyvern
#

thought those didn't do anything but they do
but still a problem with the scaling

gloomy chasm
#

What scaling issue?

worthy wyvern
#

zooming the camera zooms the texture with it

#

I want it to stay still in the world

gloomy chasm
#

Right now the texture isn't scaling. It is in screenspace. You want it to act like it is in world space

worthy wyvern
#

Yes

gloomy chasm
#

Er wait, you want the inverse of that

worthy wyvern
#

Worked with enemySprite.rect.size / HandleUtility.GetHandleSize(screenPosition)

gloomy chasm
#

Nice, so is it looking how you want now?

#

btw GetHandleSize is meant to take a position in 3D space, so it should be given the enemySpawnPosition

worthy wyvern
#

not in the center exactly

#

bottom right seems weird

#

huh, screenPosition - screenScale / 2 worked

gloomy chasm
#

Yeah the screenPosition is the exact position on the screen the point is. The GUI in unity has the top left of the window being (0, 0), while the bottom right is (width, height).

worthy wyvern
#

I mean before this the texture always drew with the bottom right at (0, 0)

gloomy chasm
#

You mean when you were using GL?

worthy wyvern
#

dammit I mean bottom left corner of the texture

#

so top right of 0

gloomy chasm
#

That is because screenspace and GUI space are different

#

The Game UI has the bottom left being (0, 0)

worthy wyvern
#

Alright

#

Thank you very much

gloomy chasm
#

You're welcome!

snow pebble
#

im creating a game object as a child to the prefab with editor code, when i assign it a mesh and save, the child is created as is the mesh but the child doesn't keep a refrence to the mesh even though i assigned it
child.GetComponent<MeshFilter>().sharedMesh = mesh;

why might that be ?

#

i have to manually drag the mesh file on to the mesh filter afterwards from the asset folder

#

not sure if im missing something

timid coyote
#

why do i have to reselect the gameobject in order for my value field to appear?

public override VisualElement CreatePropertyGUI(SerializedProperty property)
        {
            SetProperties(property);
            Initialize(); Compose();

            return _root;
        }

        private void SetProperties(SerializedProperty property)
        {
            _flagsDataProperty = property.FindPropertyRelative("data");
            _flagIDProperty = property.FindPropertyRelative("ID");
            _flagValueProperty = property.FindPropertyRelative("value");
        }

        private void Initialize()
        {
            _root = new VisualElement();
            
            _flagsDataField = new PropertyField(_flagsDataProperty);
            
            _flagsData = _flagsDataProperty.objectReferenceValue as FlagsData;
            if (_flagsData is null)
                return;
            
            SetFlagNames(_flagsData);
            //_popup = new PopupField();

            //_popup.Draw(_position, _flagIDProperty, label, _flagNames);

            _flagValueField = new PropertyField(_flagValueProperty);
        }

        private void Compose()
        {
            _root.AddChild(_flagsDataField)
                //.AddChild(_popup);
                .AddChild(_flagValueField);
        }```
astral oar
#

is there a way to send data to play mode from edit mode? I know editor prefs but what I want to send an object? I can probably serialize it into string and deserialize in play mode but is there a better way?

#

(unity's serialized fields won't work because it's not scriptableobject and it has fields that unity simply can't serialize)

snow pebble
#

when you update values in editor how do you get other scripts that are listening to changes to also change? i normally use Action OnChange but unity gives a warning not to send events in edit mode

#

plus that would require me to setup all the links anyway so actions don't really make sense

#

the only other way i can think of is the editor gets components from the scene and manually updates all the relevant scripts involved but that seems not very scalable

example: i change the values of my bezier spline via custom editor - another script in the scene needs to be aware of this change to update the data it has about it

peak bloom
#

whether it's scalable or not. depends on your impl

snow pebble
#

well i got it working after much hassle

#

just have to make the editor script do it all

#

not great if i ever change the design because then ill have to change the editor script too

gloomy chasm
snow pebble
#

which defeats the point when you doing editor scripts

#

ive got a weird issue with scene use in editor

#

i have this on my editor

#

and in OnScene i draw the mouse position but it only shows the mouse position when i stop moving the mouse

#

very laggy - i dont understand why

#

it only ever moves if i stop the mouse

#

all i have is
private void OnScene(SceneView view) => DrawMouse();

#

it should be following every frame but it doesn't

#

dear lord this is a pain

visual stag
#

Repaint the scene view

snow pebble
#

how come ive not needed that before 🤔

#

strange

#

So when does OnScene actually get called? when theres a new event on the stack ? i assumed it was on every repaint

real spindle
real spindle
snow pebble
#

ah i see

astral oar
#

EditorPrefs.GetString("EditorState.editorData", null) why does this return "" after I deleted key?

visual stag
#

https://docs.unity3d.com/2018.4/Documentation/Manual/script-Serialization.html

However, Unity actually makes more than a thousand allocations. The serializer does not support null. If it serializes an object, and a field is null, Unity instantiates a new object of that type, and serializes that. Obviously this could lead to infinite cycles, so there is a depth limit of seven levels. At that point Unity stops serializing fields that have types of custom classes, structs, lists, or arrays.

astral oar
#

why is unity serializer being shit as always facepalm

#

the thing is - in that case it doesn't even need to deserialize anything, since key doesn't exist in prefs I expect it to just return value that I gave

#

instead it instantiates empty string

#

wanted to avoid doing extra call to HasKey and do it in one call, I guess I'll have to call HasKey first

visual stag
#

I usually check strings with string.IsNullOrEmpty so I don't encounter this

#

Ah yeah, and HasKey

astral oar
#

also is there ANY reason why these foldouts are private

visual stag
#

If the value doesn't exist, it will return defaultValue. Note that EditorPrefs does not support null strings, so if defaultValue is null, an empty string is returned.
This was also documented btw

astral oar
#

well, not specifically these ones, since inspector ones can be used, but they can't be customized

astral oar
#

this seems stupid and just wastes cycles

visual stag
#

I agree, I'm not sure why it would work that way, I can only imagine there's some interaction with the serializer that causes it, why, cannot tell you lol

#

Also, no idea about the headers. What are you trying to do?

astral oar
#

I have DSL and I'm making IDE like experience in editor for another dev who isn't a programmer and I needed custom foldouts for objects in the DSL (unity's are not suitable because they don't support dictionaries and I need dictionaries) but the ones that are public work but they just look like plain tree items and I wanted to make them look like inspector ones

#

and they also made all styles private so I had to pull styles through reflection facepalm

visual stag
#

It is weird they haven't made the headers UITK yet

astral oar
#

and there is a public foldout but it seems bugged, despite taking GUIContent as a parameters it doesn't draw icon, I checked the code and the only reason it doesn't do that is because it removes icon from GUIContent, even though after I modified it to not do it - it works perfectly fine

#

that's basically where I took code, just took all private methods to my code and all calls to get styles I made through reflection and cached

#

they might've done, I need to check newer unity

#

for example in the one I use treeview is also private, but in newer ones it's public

visual stag
river galleon
#

hey guys I'm trying to make an editor window with which I may control my "actionEditor" script, however I'm having some trouble.
I'm quite new to editor scripts so sorry if this is silly but I can't see "transformEditor" in the inspector? (ignore the zeroes I'm doing some GUILayout nonsense)

visual stag
#

things aren't drawn automatically like in components

river galleon
visual stag
#

If it's serializable you can use a PropertyField

river galleon
#

would I need to do GUILayout.PropertyField?

visual stag
#

Yes

#

You can create a SerializedObject out of this in OnEnable and use that object to find your property

river galleon
visual stag
#

Both serializable, and either public or SerializeField

river galleon
#

much appreciated man you're a life saver for that

snow pebble
#

@visual stagby the way if you're curious..

#

i found a simpler way to open and saving prefabs

#

they have this method:
using (var editingScope = new PrefabUtility.EditPrefabContentsScope(AssetPath()))

#

found it by luck

warped sequoia
#

hi ! I have this bug when i try to build and Oculus Quest Build, i've used this graphic api with this settings for my previous build. I've import some packages from the assets store, is it possible that the few packages create this bug ?

waxen sandal
#

Wrong channel

#

Idk when your previous build was but sure packages can change the color space setting or render api (although unlikely bt depends what you imported)

warped sequoia
waxen sandal
#

🤷‍♂️ This channel is for writing extensions to the editor, not issues with the editor

warped sequoia
#

thanks !

livid bison
#

hello,is there a way find all the internal menuItems?

#

kind of stuck here

north sphinx
#

Is there a way to know whether executed code is inside of worker thread for builds?

#

I can't find a proper way to do so

#

BuildPipeline.IsBuildingPlayer returns false as well

waxen sandal
#

thread.getcurrentthread?

languid ether
#

I'm building a UIToolkit window for Editor use only, that uses UIElements.CurveField.

Is there any existing way to draw a vertical line over the curve, representing a "current value/position" within the curve?

I'm not seeing anything immediately, so my assumption is that I will have to draw my own VisualElement as a line (using border?) and just layer it on top with manual positioning. (?)

livid bison
languid ether
#

Huh, interesting; looks like I could use that Vector API to build a read-only curve without using CurveField/AnimationCurve. Maybe. If my first-glance is understanding this correctly. A useful API to be aware of regardless of this use case, thank you for bringing it to my attention.

Regardless, it still is a matter of drawing both the curve and the 'position' line independently; so, still the same outcome of sorts. If I understand correctly.

livid bison
#

yes.curve field doesnt has a bulit-in api for current value, but you can make you custom control inherit from cruvefield and save some code,

languid ether
#

Maybe, or just store a reference to a CurveField. My thought is I'd need a VisualElement container, CurveField, and a VisualElement for the 'line'.
The line would be absolute positioned, 1px wide, 1px left or right border... and just set it's position within the container.

Throw all that into class that extends VisualElement, instead of the CurveField.

#

Or would you extend the CurveField, and add the 'Line' VisualElement directly undernieth the curve? That.. hm. That would work better, wouldn't it?

#

(ie: Your suggestion does seem better than my initial thought, the more I think on it.)

livid bison
#

vector api is cheaper than a visual element i think

languid ether
#

Possibly. I'll look into it, too. For sure.
There may be a point later down the road I do want to allow editing the curve - but not when there's a value associated. [Different window state] -- So it may, just from a visual consistency stand point, be better to use the CurveField anyway. We'll see. It's good to have options at least.

#

Thank you, though. The real answer to the question I needed: Yes, do it manually. Bonus was learning about a new API. Heheh.

livid bison
#

yes,do it mannuly,painful,but can learn something,just another thought,maybe you can add a custome drawer for you cutom curve

languid ether
#

Don't think drawer's useful in this case, but yeah. I'm more backend dev, learning UI stuff... yes. Learning something. Lots of somethings. Heh. Thank you again.

full cedar
#

Hi, for some reason this script and it's editor script reset some of the values to 0 when I re-enter the prefab, why is that?
For example, I create a prefab like shown in the picture, add all the necessary components, play around with the values and it works flawlessly.
When I exit the prefab however, it just resets the _min to 0, _max to 1 and _value back to 0 but all the components are still properly referenced.
I can't figure this one out, can somebody please help me?

tawdry kraken
#

also: HideInInspector

#

_value also needs SerializeField

full cedar
#

interesting, will it appear twice if I call the base.OnGUI thing?

#

oh, so combine serialize with hide, that's smart, let me test it out!

#

oh wow, that actually worked, I don't know how I didn't make the connection between the serializefield and them being reset, thanks a lot!

#

I am pretty much a beginner when it comes to custom inspectors, if you have any advice on how to improve these scripts please, do let me know

tawdry kraken
tawdry kraken
# full cedar I am pretty much a beginner when it comes to custom inspectors, if you have any ...

If you run into any issues with using Reset() to get your components,
(in case an asset is removed or replaced)
then I recommend looking into this set of experimental solutions:
https://gist.github.com/Rovsau/5d06ff262679f9be6e2fbcb18c4eb74e
I have not used it in an actual game myself, but spent some time on finding ways to re-trigger the Getting of Components.
(This can be an issue if one assumes components will be fetched anew when entering Play mode)

full cedar
#

thanks!

snow pebble
#

when using ui elements how do we update the ui based on the data since the CreateInspector isn't called every repaint

#

i also can't bind

ocean geyser
#

Hello! Does anyone know how to preview a specific frame of clip on an object with an Animator at edit time?

I'm trying to iterate through the frames of an AnimationClip to get the world-space locations of some objects, in order to create a bounding box of all it's possible positions (probably later I'll want the actual path it took).
It's easy enough to do this with a PlayableDirector and it's Evaluate function, but I can't find an equivalent way to do this for Animators.

waxen sandal
#

With normalizedTime

ocean geyser
#

afaict this only works at runtime, I want to get these at edit time to cache the values

waxen sandal
#

Could try looking at the reference source for the animator and see what htey do there?

ocean geyser
#

yeah, my next step is to (find and) dig into that, because it's clearly possible! But I hoped someone would already know 😄

#

oho! I just discovered that if I call animator.Update(0) immediately after animator.Play(...) it does set the animation to that frame

#

🔥

waxen sandal
#

Nice

#

I was wondering whtehr update did something but I assumed no since you mentioned that play with normalized time doesn't 😅

ocean geyser
#

yeah, that's what I thought too 🙂

#

thanks for making question if I had really tried Play properly 😄

whole steppe
#

I got a class and property drawer. I want to override an Object Field's label by using a field. But the field returns null.

public class ClassX
{
    [SerializeField] private/public string field = "hehe";
}
[CustomPropertyDrawer(typeof(ClassX))]
public class ClassXDrawer: PropertyDrawer {
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUI.BeginProperty(position, label, property);
        
        // Null reference error
        var eventNameProperty = property.FindPropertyRelative("field");

        EditorGUILayout.ObjectField(property, new GUIContent(eventNameProperty.stringValue));
        
        EditorGUI.EndProperty();
    }
}
tawdry kraken
#

most notably: when changing field names

whole steppe
#

How can i make their size fit with the default Unity's one by using UI Toolkit Builder?
I was doing with Flex Grow and shrink but i see they use some sort of base unity classes. But when i put the classes to my custom field, it does not works.

This is the problem visualized:

#

The classes they use for the label:

#

My classes in label: unity-base-field__label is not affecting anything.

#

None of the inline style parameters is changed inside custom element.

visual stag
#

BaseField<int>.ussClassName + "__aligned" will do if you can't find it (I think it's exposed 2022.2 or newer)

north sphinx
#

Hmm. Is there any sort of postprocessor for builds where I can postprocess prefabs that got bundled?

#

Specifically: I want to remove components from game object prefabs which contain editor only monobehaviours

timid coyote
#

how can I re-render a property drawer if a field was chnaged? I tried in field.RegisterValueChangeCallback to call EditorApplication.update.Invoke();, but didnt work (ui toolkit)

north sphinx
#

because I don't want prefabs to be modified during build

#

Basically I have a monob X. This is editor only monob and it doesn't make it into build. It's all ok if I just don't do anything, but I get a warning about Missing component on my prefab

#

So what I want - remove it just for this build

whole steppe
# visual stag Do you mean the label alignment? Add the `alignedFieldUssClassName` class that's...

This thing works fine on unity's auto-generated property visual elements but not works in mine. Right now, i realize something. when there is a .unity-base-field__aligned class inside the element named #unity-input-etc, the label's width in Unity's label gets overriden. But even tho i put in mine, label's width does not gets overriden.
Even tho i delete .unity-object-field__label or another thing that is not base field, it does not affects the editor in unity's one.

An addition, .unity-base-field__aligned is working with default visual elements like Radio button inside UI Builder. I put them next to eachother vertically and tried to match the class names.
The radio button worked but mine wasnt working as usual. Is it a bug or is it my mistake?

#

Any ideas?

whole steppe
# whole steppe This thing works fine on unity's auto-generated property visual elements but not...

I am still trying to find solution to this, and realized another beautiful thing. My public string gets undo record at every char which is i dont want ._.
I cant find in google. How it can be possible?
It seems it is normal. All of the MonoBehaviours act like that but its actually anormal how do people living with this?
Okey i think the only way literally doing a focus-in focus-out undo system for every fucking thing that has string, int or whatever
Sent as bug report.

short tiger
#

I believe EditorGUI.DelayedTextField (and isDelayed property in UI Toolkit) is the solution to this. If a custom editor or drawer neglects to use it, this is the result. If you're seeing it everywhere, then either Unity messed up and made the default drawer not delayed, or maybe you have a custom editor for MonoBehaviour that doesn't use it.

astral oar
#

does anyone know to make "height: 100%" not break in USS?

#

I'm trying to make header, footer and scrollbable area between them

#

but having 100% height on scroll area in the middle breaks layout

#

regardless if I set height of footer/header to fixed value or auto

astral oar
#

it seems like the answer is I have to manually calculate height and put it into min-height after hours of search I couldn't come up with better solution, it just keeps breaking otherwise

naive thorn
#

Is it normal behaviour for a GUI label to update its text to the int value after using it to create an int field?

visual stag
#

No

naive thorn
#

Some weird things are happening, for whatever reason this triggers the gui content label to change its text to the int value:

#

property.intValue = EditorGUI.IntField(amountRect, label, property.intValue);

visual stag
#

how do you define label

naive thorn
#

I just use the one that OnGUI provides

#

i never modify it, but when i comment out this line specifically the label text stops changing

visual stag
#

the label text is drawn by this line though

#

you wouldn't have a label if not for this line

naive thorn
#

yeah, but the label text is the int value rather than what the actual provided label text is

visual stag
#

Is this in a PropertyDrawer?

naive thorn
#

yeah

visual stag
#

Can you send the whole drawer?

naive thorn
#

sure

#

also here:

#

these are the results

visual stag
#

What Unity version is this?

naive thorn
#

2021.3.21f1

#

also forgot to say, even if i dont provide the label itll still be modified

visual stag
#

quite old, so it's probably fixed if it is an issue

naive thorn
#

makes sense

#

ill scroll through the fix list and see if i can find something similar, seems specific to the int field too

visual stag
#
// Make a text field for entering integers.
internal static int IntFieldInternal(Rect position, GUIContent label, int value, GUIStyle style)
{
    int id = GUIUtility.GetControlID(s_FloatFieldHash, FocusType.Keyboard, position);
    Rect position2 = PrefixLabel(position, id, label);
    position.xMax = position2.x;
    return DoIntField(s_RecycledEditor, position2, position, id, value, kIntFieldFormatString, style, true, NumericFieldDraggerUtility.CalculateIntDragSensitivity(value));
}

I don't really see how PrefixLabel could modify your label, it doesn't even get passed the property

naive thorn
#

Weird?

#

hold on, ill send the full thing in case im missing anything

#

that creates this

#

The 25 on the left should show "Default reward" (the field name)

visual stag
#

Can you write EditorGUI.BeginProperty(position, null, property); instead

naive thorn
#

sure

#

cant pass null, but GuiContent.none is the same result

visual stag
#

Weird, GUIContent is a class, and it says

label Optional label in front of the slider. Use null to use the name from the SerializedProperty. Use GUIContent.none to not display a label.
in the docs

naive thorn
#

oh? weird

#

doing this threw this:

visual stag
#

Don't pass null to that

#

pass null to BeginProperty. I don't think it will change anything though... I'm just narrowing things down

naive thorn
#

ahh to begin property

#

sure

#

yeah no change

visual stag
#

Can you use the debugger and step into the IntField call to see when it gets changed

naive thorn
#

can i do that with IL code?

#

o wait, got it

#

stacktrace

visual stag
#

Interesting, so your GUIContent for the label is the TempContent one... which is never updated before the property is drawn? 🤔

naive thorn
#

yeah, and also another thing, when i select the int field the label gets properly drawn

#

presumably from this:
string str2 = !editor.IsEditingControl(id) ? (!EditorGUI.showMixedValue ? (passwordField ? "".PadRight(text.Length, '*') : text) : EditorGUI.s_MixedValueContent.text) : (!EditorGUI.showMixedValue || !(editor.text == "<>") ? (passwordField ? "".PadRight(editor.text.Length, '*') : editor.text) : string.Empty);

#

one of the monster lines in EditorGUI line 772

#

and editor.text seems to be where its fetching that number from

#

err no, could also just be passed down from EditorGUI.DoTextField?

visual stag
#

Regardless of all this though, I don't really understand why you are using the label in the int field at all. If you're drawing these elements side by side, it's surely not going to be enough space

naive thorn
#

the problem is that even if i specify no guicontent itll still draw the label lol

visual stag
#

I presume you're not doing anything whacky and calling this drawer yourself... is that the top of the stacktrace above?

naive thorn
#

property.intValue = EditorGUI.IntField(amountRect, property.intValue);
this still draws the label

#

yeah

visual stag
#

It's Unity calling it, not some random custom editor

#

As far as I'm aware you're really meant to do:

label = BeginProperty(position, label, property);
position = EditorGUI.PrefixLabel(position, label);
...

If you want to draw a prefix label for a property drawer

#

and every other element you don't pass a label (or pass GUIContent.none)

naive thorn
#

well

#

that fixed it lol

#

i didnt even know EditorGUI.BeginProperty returns a guicontent, but setting it to that fixed the issue somehow

visual stag
#

Yeah, it returns its own temp value

#

I have no idea why it's all so convoluted, I usually have no problems. I have moved to UITK exclusively now though 😄

naive thorn
#

the correct answer lol

whole steppe
short tiger
whole steppe
short tiger
#

@whole steppe Yeah, I see the same thing. Looks like Unity messed up. You were right to report it as a bug.

whole steppe
#

Could you possibly test the UI toolkit too?

#

unity-base-field__aligned this thing

short tiger
patent pebble
#

is there an easy way of changing the labels on a list that's drawn in a PropertyField?
(in IMGUI)

short tiger
#

Besides that, you can make a property drawer for the elements in the array that draws a different prefix label, or you can replace the entire editor for the parent type and draw the ReorderableList yourself.

patent pebble
#

yeah i've done in the past the remaking the ReorderableList from scratch and making drawers for the class
i was just wondering if there was a quick way of doing it for basic arrays

#

guess i'll make a property drawer then

#

thx anyways! 🙏

tawdry kraken
# patent pebble

If the elements are to be more complex, all it needs is the first property/field to be a string, and it will take that string value.
But it won't work if it's a single text field, like what you have there.

#
[Serializable]
public class Example {
    public string ElementName;
    // Other fields. 
}
patent pebble
#

yeah instead of "Element X" i just wanted to name them "Namespace X"
i just made a property drawer and get the array index for the name

tawdry kraken
#

that's a better solution then

patent pebble
#

yeah i don't like the weird workaround with extra fields because then i come back to the code a year later and i get confused

#
[CustomPropertyDrawer(typeof(ImportElement))]
public class ImportElementDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        bool isPropertyAnArrayElement = property.propertyPath.EndsWith("]");

        if (isPropertyAnArrayElement == false) // Draw the property normally
        {
            EditorGUI.PropertyField(position, property, label);
        }
        else // Draw the property with a custom label for its array entry
        {
            // Set the label to Namespace + index in array
            int index = -1;
            int openingBracketIndex = property.propertyPath.LastIndexOf("[");
            int closingBracketIndex = property.propertyPath.LastIndexOf("]");
            int numberCharacterLength = closingBracketIndex - openingBracketIndex - 1;
            string indexAsString = property.propertyPath.Substring(openingBracketIndex + 1, numberCharacterLength);
            Int32.TryParse(indexAsString, out index);
            label.text = $"Namespace {index}";

            // Adjust the rect to leave the correct space inbetween array elements
            Rect fieldRect = position;
            fieldRect.height = EditorGUIUtility.singleLineHeight;
            
            // Draw only the string property to avoid getting the foldout
            EditorGUI.PropertyField(fieldRect, property.FindPropertyRelative("_namespace"), label);
        }
    }
}
tawdry kraken
patent pebble
#

i need to check if the property is an element inside an array
not if the property is an array itself

tawdry kraken
#

ah

patent pebble
#

hehe

#

pretty weird how Unity doesn't expose that for the user

tawdry kraken
#

Pretty sure I was doing something similar not too long ago

#

I think that one can more easily work for you

#

though that doesn't give you the index xD

#

actually, your solution might be better

patent pebble
#

i remember seeing that depth property but never actually implementing in anything

#

so i wonder if i just ignored it or if it had some issues

astral oar
#

why are both UITK and imgui so god damn terrible

patent pebble
#

if i wanted to check which ones of those are array elements i would have to keep track of depth as i go down the nesting tree
and then try to keep track of the parents, and check if the parent is an array

#

seems just easier to check for [] brackets instead

#

(gotta be careful with strings tho because they are technically arrays of chars)

tawdry kraken
tawdry kraken
patent pebble
#

yeah probably

remote narwhal
#

dear asset store devs, consider making your libraries cross-engine to e.g. Godot:

gloomy chasm
remote narwhal
gloomy chasm
glad cliff
#

I saw some editor extension on asset store where you could have selected visual element in UI Builder window and press a button on a custom Behaviour inspector to create a GO which holds reference to that Visual Element (propably not actuall reference as it isnt serializable, but some data for a later Querry) and Im VERY intrested in how that was achieved, anyone has an idea? Selection class doesnt seem helpful here and UI Builder window itself isnt accessable cause of Unity.UI namespace

glad cliff
#

Ive checked to what assembly UI Builder window belongs to to try add assembly reference to get access to it, but cant even find corresponding assembly def file... so it is still a riddle for me

glad cliff
#

Ok i see guy must have done some custom wrapper window for UI Builder itself, ill leave it, it seems too intrusive

gloomy chasm
gloomy chasm
# glad cliff I saw some editor extension on asset store where you could have selected visual ...

Oh, and to answer your question. The answer is Reflection. Probably not that hard even.
Basically you would get the Assembly for it, then get the BuilderWindow Type. You can use Resources.FindObjectsOfType(builderWindowType) to get the window instance. Then you just have to look at the source code to figure out where it stores selection. Then I would assume it walks up the tree to make a build a string query or something like you had thought.

astral oar
#

how do I use EditorGUI.showMixedValue ?

#

I can set it but I can only pass 2 values to toggle - either true or false

glad cliff
glad cliff
glad cliff
#

Although after some thinking Ill propably implement some search window for my pourpose instead of this UI Builder selection, but knowing how to do it will still help, perhaps I will experiment with it

whole steppe
#

The whatever class has a normal property drawer. But something weird happens in arrays... Its gonna be used a lot so i dont want this to happen...

patent pebble
short tiger
whole steppe
short tiger
whole steppe
#

Okei

short tiger
#

You could also override CanCacheInspectorGUI to return false instead.

#

Or if you'd like to cache them, then you can save the data in a Dictionary instead, so you can save separate data for each property.

whole steppe
whole steppe
short tiger
# whole steppe

Okay, you can't save container, because it will be overwritten by the most recent property each time. Unity will only create one instance of WhateverDrawer and then call CreatePropertyGUI for each property it needs a GUI for.

#

You can get the element from the changeEvent parameter, so you don't need to save it.

whole steppe
#

😮

#

What the hell never thought the problem was the container okey i will try now

whole steppe
astral oar
#

I needed to have toggle that can show mixed value depending on some other values and clicking it would change all these other values

#

I just set showmixedvalue to true and call toggle with true value and I get what I need

supple willow
short tiger
supple willow
#

all I know is it's not related to Unity serialization. it's a domain reload thing from .net I presume

short tiger
#

If it's a static field and you have domain reload disabled, then sure, it would persist until the next domain reload. But [NonSerialized] doesn't affect that. It's not getting serialized, just never cleared out of memory because the domain isn't being reloaded.

supple willow
#

static or Instanced, editor data remains throughout domain reload unless marked as NonSerialized. that includes ScriptableObjects too

peak bloom
#

wait, no? statics get cleared

#

even in Editor

supple willow
#

Ah gotta say, I don't remember it being in my problem back when facing this, so yeah (the statics)

#

anyways, was just a side note to always mark these stuff NonSerialized for a clean flush after each domain reload (perhaps not statics)

short tiger
#

But I'm not sure it affects PropertyDrawers, since they don't inherit UnityEngine.Object, and so aren't serializable.

#

And I still don't see how it could also serialize Dictionary. That would mean Unity can serialize dictionaries but chooses not to during runtime, which doesn't make sense.

supple willow
#

right. my bad. just tested and yeah dics don't persist. only Unity serializable data types do

worthy wyvern
#

I have one editor in which I edit a List from the base class, and accessing it through a SerializedProperty correctly sets up undo and redo.
I have another editor for which the base class has a List of objects, which in turn have a List like the one from the first editor base class. This time I have to access the second list by using FindPropertyRelative(). This seems to break the undo and redo system, because I can't undo/redo the elements in that list. Is there something I need to add?

whole steppe
#

My Stylesheet is not working in editor but it is showing as working in UI Builder.
The stylesheet and UXML's are inside of Editor folder.
Stylesheet is created inside UI Builder.
Stylesheet edited inside UI Builder.
Stylesheet can be seen in Matching Selectors in element's class. But it is not showing when i use debugger in inspector.

Solved it. Do not use visualTree.Clone().ElementAt() when you creating a container ._.

pastel estuary
#

question, anyone else having an issue with VIM theme making it so you cant type...

#

it was working fine yesterday

gloomy chasm
#

I have a PropertyDrawer using UITK, but I am not getting the context menu for the field label (Copy Property Path, Copy Value, Paste Value).

There is a generic internal method I can grab to add it myself, but that feels dirty, and would prefer a nicer way of doing it, it feels like there should be something simple. Anyone know if there is?

glad cliff
#

What is happening here? I feel safe to do it cause my script (for which this custom editor is for) requires UI Document, but Unity screams for some reason.

    private UIDocument document;

    private void OnEnable()
    {
        document = (target as MonoBehaviour).GetComponent<UIDocument>(); 
        Debug.Log(new SerializedObject(document).FindProperty("sourceAsset"));
    }
gloomy chasm
#

Look at #854851968446365696 for post large blocks of code/errors. But all that error is if from the MoveTool, the one use you use change the position of the selected GameObject

#

I would comment out your code to check, but there is no reason it should be causing that error. If it persists I would make sure to restart Unity.

glad cliff
#

gosh... Unity likes to throw a jump scare from time to time for some reason lol...
with commented error does not accure, uncommented and shows again, but yeah, I restarted Unity and its gone like it was never there 😅
sorry im overreacting sometimes XD

whole steppe
glad cliff
#

while im here...
anyone has a better idea how to detect if certain .uxml has changed?
Unfortunatelly AssetModificationProcessor does not work for visual tree assets -,-

    private UIDocument document;
    private SerializedProperty visualTreeProperty;
    private VisualTreeAsset visualTreeAsset;
    private string visualTreePath;
    private string lastModified;

    private void OnEnable()
    {
        document = (target as MonoBehaviour).GetComponent<UIDocument>();
        visualTreeProperty = new SerializedObject(document).FindProperty("sourceAsset");
        visualTreeAsset = visualTreeProperty.objectReferenceValue as VisualTreeAsset;
        visualTreePath = AssetDatabase.GetAssetPath(visualTreeAsset);
        lastModified = File.GetLastWriteTime(visualTreePath).ToString();
        EditorApplication.update += CheckVisualTreeAssetChange;
    }
    private void OnDisable()
    {
        EditorApplication.update -= CheckVisualTreeAssetChange;
    }

    private void CheckVisualTreeAssetChange()
    {
        if(File.GetLastWriteTime(visualTreePath).ToString() != lastModified)
        {
            Debug.Log("Tree changed");
            lastModified = File.GetLastWriteTime(visualTreePath).ToString();
        }
    }
unreal light
#

making a custom property drawer for this using IMGUI

#

stumbled upon this cursed thing using a nested collection

#

how could i fix it?

glad cliff
#

seen worse XD I still didnt fix my tool after half year ago nested collections started disco every frame for some reason... almost got epilepsy attack XD

#

but this looks like something doesnt have specified Rect properly, but I havent used IMGUI for a while so propably wont be able to pin point exactly

astral oar
#

is there a way to get if editor window actually has open instances?

#

because HasOpenInstances lies if you maximize some window

#

and getwindow creates new instance

#

I want to force window to not have more than 1 instance but I can't find a way

#

static variables are erased when entering play mode

#

hasopeninstances doesn't do what it's supposed to do

peak bloom
dawn hull
peak bloom
#

just ignore that

glad cliff
#

1st of all GetWindow<> should give you instance of that window if it is already opened so I dont get it, but if you really want to save a static refference to it you can consider using ScriptableSingleton

visual stag
# dawn hull

Upgrade/downgrade the version of the post processing package using the Package Manager until the error goes away

dawn hull
#

how ican upgrad it?

visual stag
dawn hull
#

thanks itts working now

whole steppe
#

Man i got a dumb question. How can i find serialized getter setter property from FindProperty?
I see someone said this in forums:

In order to find a serialised property you have to run serializedObject.FindProperty("<propertyName>k__BackingField"). Note that it’s two underlines between the k and BackingField.

visual stag
whole steppe
#

I thought getter setter also had backing field

#

I have no idea how will i reach that tho

visual stag
#

It must be an autoproperty

[field: SerializeField]
public float Value { get; private set; }
#

They you use <PropertyName>k__BackingField, where in this case PropertyName is replaced with Value

#

If you have implemented the getter or setter then there is no backing field

glad cliff
#

maybe reflections trickery will work? Idk its jsut a blind shot
tagerObject.GeType().GetField("fieldPath").GetValue(targetObject)

#

ohhh you want to access methods themselfves? Ok im confused so dont listen to me

whole steppe
#

Thank you guys i will create a custom backing field instead of this thing.

When a property is specified like this, a backing field will automatically be generated for the property, and the accessors will be implemented to read from and write to that backing field. The name of the backing field is compiler generated and inaccessible to the user.

rancid kraken
#

Hey
Does anyone know how can I run a method from a different script when I click on a button in my custom editor?

#
[CreateAssetMenu(menuName = "PieceFactory")]
public class PieceFactory : ScriptableObject {
    public void OnButtonClick() {
        ...
    }
}

[CustomEditor(typeof(PieceFactory))]
public class PieceFactoryEditor : Editor {
    public override void OnInspectorGUI() {
        base.OnInspectorGUI();
        if (GUILayout.Button("Run method")) {
            // I want to call OnButtonClick from the PieceFactory here
        }

        serializedObject.ApplyModifiedProperties();
    }
}
worthy wyvern
glad cliff
#

Anyone knows if it is possible to force a pseudo-class on a visual element? I want a button to appear active, but dont want to specify custom styling for it

rancid kraken
astral oar
astral oar
astral oar
# glad cliff 1st of all GetWindow<> should give you instance of that window if it is already ...

scriptablesingleton seems like pain to setup because a lot of the data is not serializable by unity and it seems overkill for what should be built-in functionality, I just need some way to know if window instance already exists (I want window to open when I enter play mode but I don't want multiple instances and if I enter play mode in maximized window it still creates instance even though one already exists)

glad cliff
#

when you mentioned that static variables are areased when entering play mode you meant variables in Editor script? Cause I would guess they should stay intact hmmm

astral oar
#

no I meant that I can't just store window reference in a static variable because it'll get erased when I start play mode (entering play mode state of all objects, including editor scripts gets reset), so it wouldn't work as a solution and I can't find any solution to actually know if instance exists

#

singleton wouldn't work because a lot of the fields aren't serializable (by unity serializer, they can be serialized by other serializers), I already manually serialize some data from editor into game with a different serializer because the one unity uses is kinda garbage

glad cliff
#

use Resource.FindObjectsOfType<YourEditorWindowType> and check if ti finds at least one

astral oar
#

hm, that might work

#

ty

glad cliff
#

Can someone teach me a bit about assemblies?
Can I have some internal classes in MyCustomToolRuntime assembly and have access to it in MyCustomToolEditor assembly through some specific configuration?

robust spire
glad cliff
#

this is a class attribute or what is the usage of it?

robust spire
#

it's an assembly attribute, as the assembly: part indicates

#

so you don't need anything below it

glad cliff
#

oh so I just put it anywhere in any .cs file inside of MyCustomToolRuntime assembly and it makes all internals visable?

#

to specified assembly

robust spire
#

yup

glad cliff
#

great! Thanks man!

unreal light
#

you can serialize C# properties??

stark geyser
#

It's just an automatic backing field getting serialized.

astral oar
#

you can't serialize properties but when you create property like this it creates hidden backing field and that's what gets serialized

rough phoenix
#

Does anyone know why this is happening?
[Error - 10:31:33 AM] [LanguageServerProjectSystem] Exception thrown while loading c:\Users\User\Visual Studio Code Projects\Game Development Implementations\Groundwork\Assembly-CSharp.csproj StreamJsonRpc.RemoteInvocationException: Sequence contains no elements

nova creek
#

I'm having a heck of a time figuring out the test runner.

#

I followed the tutorial on the Unity website and it worked just fine. But trying to implement tests in my project is going nowhere.

#

I'm trying to load a scene in setup and it's telling me that this can only be done during play mode, but this is a test that I'm running in play mode

#
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using NUnit.Framework.Internal;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.TestTools;
using UnityEngine.SceneManagement;

[TestFixture]
public class SimpleTesting : IPrebuildSetup
{
    public void Setup()
    {
        Debug.Log("This is being set up!");
        SceneManager.LoadScene("TestARDesktop");
    }

    [UnityTest]
    public void MyFirstTest()
    {
        string testString = "Test string!";
        Debug.Log(testString);
        Assert.That(testString, Is.EqualTo("Test string!"));
    }
}```
#

This is in unity 2022.3.9f1, my boss has me implementing testing in our project.

#

I've been googling for solutions, someone said to chang a value in projectsettings, but that didn't help.

#

Anyone know what may be causing this?

snow pebble
#

can we use ui elements for custom inspectors on materials? will the binding property still auto bind ?

#

not entirely sure how to correctly find the values since they wont be from c# scripts

snow pebble
#

😢

#

so what are my options to make a more useful inspector

#

its getting complicated in the material

snow pebble
#

i see

#

hope they support it one day then

glad cliff
#

you can still use IMGUI container within your inspector alongside uitk if you dont want to sacrifice everything it offers. I would deffinitely do so (never going back to IMGUI lol)

snow pebble
#

wdym by container

glad cliff
#

i dont remember what the element is actually called but there is one allowing you to put a visual element which content is built with IMGUI

gloomy chasm
#

Doesn't help for making custom shader GUIs

glad cliff
#

propably, im just saying that if I had whole editor window made with uitk and then met the bottleneck forcing me to use IMGUI, I definitely wouldnt rewrite whole window to IMGUI

timid coyote
#

why nor popupfield or dropdownfield wont be in line with the other fields? (ui toolkit)

_popupField = new PopupField<TValue>(property.displayName, elements, oldIndex)
                .AddBind(property);

a = new DropdownField("ceva", _flagNames, 0);```
timid coyote
visual stag
timid coyote
#

oh and if i dont have it, i have to do it like this BaseField<int>.alignedFieldUssClassName" ?

#

it worked, but do u know any cleaner way of doing this?

visual stag
timid coyote
#

oki thanks

timid coyote
#

in ui toolkit how can i invoke an Callback in a custom visual element?

dawn hull
#

how i can get this?

visual stag
glad cliff
#

very minor thing but wtf is happening with my cursor over this textField? it drives me crazy...

#

styling for that TextField is simple

#search-field{
    flex-grow: 1;
    cursor: text;
}
#search-field > #unity-text-input{
    border-radius:7px;
    padding-left: 10px;
    padding-right: 10px;
}
.unity-text-field__placeholder > .unity-base-text-field__input {
    color: #969696
}
#

nvm, apparently there is one more element nested inside which for some reason got its cursor style overriden (no idea why)

glad cliff
#

I have a text field which i Bind to some property and im registering a value change callback to it, but this callback fires instantly because binding changes the value from a git go. I tried to SetValueWithoutNotify and THEN bind it, but for some reason it gives opposite effect than I hoped for, callback fires twice lol... Any idea what to do with it?

peak bloom
#

SetValueWithoutNotify should do the trick even, if not, that looks like a bug

timid coyote
#

are these 2 the same?

using var pooled = ChangeEvent<bool>.GetPooled(false, true)
                        .SetTarget(this)
                        .SendEvent();```
```cpp
ChangeEvent<bool>.GetPooled(false, true)
                        .SetTarget(this)
                        .SendEvent()
                        .Dispose();```
short tiger
timid coyote
#

thanks so much :DD

cobalt sphinx
#

I have Unity extension, unity code snippets, and C# extensions installed and I get this. I download the framework and it still wont get detected. All project setting deetects is the .net framework. I don't know how to switch it to 6.0

#

Im just trying to get intellisense to work...

glad cliff
cobalt sphinx
#

nvm it is solved I had an older version of .net framework and it was only detecting that

glad cliff
atomic sable
#

why won't the visual tree asset show as a default reference field?

#

right now im doing this bc it won't let me do it the way above:

private static readonly VisualTreeAsset m_VisualTreeAsset;

static BakePathDataOverlay()
{
  m_VisualTreeAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/Pathfinding/Editor/BakePathDataVisualTree.uxml");
}
``` which would break if it's moved at all. overall just seems like the UI Toolkit is missing features. I shouldn't have to load my visual tree asset at an exact path like that.
glad cliff
#

UIEventsSearchProvider eventsPopup = ScriptableObject.CreateInstance(typeof(UIEventsSearchProvider)) as UIEventsSearchProvider;
Do I need to dispose/destroy it manualy in OnDisable() of my custom Editor? It is created in CreateInspectorGUI() and idk if it behaves like local variable and GC will handle it or not.

full badge
atomic sable
#

in the screenshot I have it as [SerilizeField] public VisualTreeAsset m_VisualTreeAsset;

full badge
#

ah I see now

atomic sable
#

yea sorry. I meant to say that i'm loading the direct path right now because I can't do it the other way for some reason. Even though it's a mono script.

void night
#

Hey, im trying to work with the kiwicoder behavior tree, and im running into an issue where it wont accept public / serialized properties from the inspector. I dont know if anyone can provide some advise or if I'm just going to have to pony up for a real BT asset.
The issue is a little tough to but into writing but in short, its just like making a public or serialized property in a normal script, where it appears in the inspector and you can select an object of a specific type from the field. Except when you select an object from that field it errors out and says that there is a type mismatch, when you literally can't select an object of the wrong type

heres a video of it as well
https://cdn.discordapp.com/attachments/1146187317502029917/1154870484362612736/20230922-2002-19.6366722.mp4
ignore the poor naming, I did this in a different project to double check it wasnt a bug caused by a bad library

glad cliff
#

idk the inner workings of this tool, but is this behaviour tree saved as an asset in projects, or does it live directly in a scene?

#

if architecture is lets say similiar to Animator, where you give an "Animator" component to GO, but actual "Controller" that you assign to it lives as an asset in project then it is a ScriptableObject, which can not have any direct references to something from a scene, cause it doesnt have any information about scene itself at compilation time.

#

I might be wrong tho, didnt drink my coffee yet

glad cliff
glad cliff
#

My structure looks like this: my root visual element has one more visual element in it acting as a container for everything, when I press "Add element" root visual element is cleared and populated with newly created container, but as you see for some reason property isnt drawn in this cenerio and I dont know why. It is created and it shows in hierarchy, but it is empty. Any idea on what is happening?

#

button:

inspectorContent.Add(new Button(() =>
            {
                (target as UIEventsSelector).events.Add(new UIEventsPair());
                serializedObject.ApplyModifiedProperties();
                root.Clear();
                root.Add(GenerateInspectorContent());
            }) 

property:

var eventField = new PropertyField(mainListProperty.GetArrayElementAtIndex(i).FindPropertyRelative("UIEvents").GetArrayElementAtIndex(j).FindPropertyRelative("Event"));
foldout.Add(eventField);
glad cliff
#

creating a property field and then using BindProperty(), instead of passing property in the constructor, resolved the issue... partially

#

cause I still need to access it after it bounds itself, for which I use scheduler

#

but simple schedule.Execute() doesnt work as it may try to access it before it is properly bound

#

and ExecuteLater() with lets say 10ms works great... but it doesnt feel safe

#

I need to know when PropertyField builds itself after binding and then access it, unfortunatelly no matter what I try to check it it fails

#
var eventField = new PropertyField();
                    eventField.BindProperty(mainListProperty.GetArrayElementAtIndex(i).FindPropertyRelative("UIEvents").GetArrayElementAtIndex(j).FindPropertyRelative("Event"));
                    foldout.Add(eventField);
                    bool isBound = false;
                    foldout.schedule.Execute(() =>
                    {
                        Debug.Log(eventField.IsBound());
                        if (eventField.IsBound())
                        {
                            eventField.Q<Label>().text = "TESTING"; //Dummy access test for now
                            isBound = true;
                        }
                    }).Until(()=>isBound);

IsBound() always returns false for some reason -,- despite it being bound (field is already rendered and adding and removing events works so it must be bound)

#

eventField.binding always is null like it has no bounding at all, despite eventField.bindingPath having proper path assigned

gloomy chasm
glad cliff
#

well... I was putting every possible method there at this point to see if it changes the result even if it unlogical to do so XD

#

hammer sometimes works u know

gloomy chasm
#

Sometimes it doesn't 😛

glad cliff
#

anyway now the problem seems to lie somewhere else :/

gloomy chasm
#

I assume this is in a inspector an UIEventsSelector is a MonoBeaviour? Instead of adding directly to the events, you should use SerializedObject. Using ApplyModifiedProperties() after directly setting a value like that will clear the value you just set most of the time

glad cliff
#

didnt know that, but apparently it doesnt in this case, newly created UIEventsPair is right where it should be

gloomy chasm
#

What is it that the issue is exactly? It is a little hard to follow

glad cliff
#

but for some reason IsBound() always returns false despite it CLEARLY being aleady bound

gloomy chasm
#

I see, really it is best to not access PropertyFields like that. If you need to access the contents of a field, it is best to not use a propertyField.

glad cliff
#

I love how in the industry we say "thats quite an edge case u know?" instead of calling it directly a bug or smth XD clearly something doesnt work here as it supposed to. IsBound() method seems useless in my scenerio

gloomy chasm
glad cliff
#

god damn it... I need to use a bigger hammer

gloomy chasm
#

What are you actually trying to do?

glad cliff
#

Exactly that

#

but this is using a cheat code in form of ExecuteLater()

whole steppe
#
public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
{
    base.Init(ve, bag, cc);
    ((INotifyValueChanged<string>)ve).SetValueWithoutNotify(m_String.GetValueFromBag(bag, cc));
}

What is that (INotifyValueChanged<string>)ve)? Why do we need to convert that?
I didnt understand how INotifyValueChanged works tho
I see there is no implementation for INotifyValueChanged in VisualElement. But would like to know how this one works.

waxen sandal
#

So this is probably some string field right

#

So VisualElement has an abstract/virtual Init, so it can only pass a VisualElement and a visual element could something that whose value can't be cahgned

#

So the derived type (StringField or whatever) implements that interface

#

And has whatever code required for it to update the value

whole steppe
glad cliff
# glad cliff god damn it... I need to use a bigger hammer

I used a bigger hammer with jagged edges and prickly handle

                    bool safeCheck = false;
                    foldout.schedule.Execute(() =>
                    {
                        try
                        {
                            eventField.Q<Label>().text = "";
                            eventField.Q<Label>().Add(eventType);
                            safeCheck = true;
                        }catch (Exception) { }
                    }).Until(()=>safeCheck);
#

caution: user may end up with no fingers

vivid cedar
#

Hey, how do you target the transform in editor? Can't seem to grab it and not seeing much info on the subject

      if (GUILayout.Button("Reset All"))
        {
            TransformToolBox myComponent = target as TransformToolBox;
            GameObject t = myComponent.GameObject;

            t.transform.transform.localScale = Vector3.one;
            t.transform.transform.localRotation = Quaternion.identity;
            t.transform.transform.position = Vector3.one;
        }
#

No errors in this version. but log error says "InvalidCastException: Specified cast is not valid."

        if (GUILayout.Button("Reset All"))
        {
            GameObject t = (GameObject)target;

            t.transform.transform.localScale = Vector3.one;
            t.transform.transform.localRotation = Quaternion.identity;
            t.transform.transform.position = Vector3.one;

        }
naive holly
#

How could I get this to automatically set the base name to the name of whatever prefab I drag into Prefab To Spawn?

fringe turtle
#

is there a way to filter the results that get returned from the selection target button in a property drawer for a field?

glad cliff
#

or simply (target as Component).gameObject

glad cliff
glad cliff
north sphinx
#

How can I get prefab overrides from game object in a scene?
I want to know whether component added/removed or values tweaked

#

like this Impact Authoring

#

as well as Position and Rotation

north sphinx
#

var overrides = PrefabUtility.GetObjectOverrides(gameObject); is count of 0

waxen sandal
#

Has a bunch of helpers to find the changed properties, added components etc...

north sphinx
#

something I used before asking, should have mentioned

#

hmm

north sphinx
#

ooh

#

I see

#

yeah, that works. Thanks

whole steppe
#

How can i disable paste

north sphinx
#

ExecuteAlways doesn't seem to work on prefabs?
Can't get an OnUpdate callback when inspecting a prefab asset

glad cliff
#

cause it is an asset. Update is called only on objects that are in a scene

#

unless you meant that you are inspecting prefab INSTANCE?

gloomy chasm
#

Anyone have any idea why a window with just a ListView UITK element bounds to a List of UnityEngine.Object on a component would result in this?
Solve: Issue was the SerializedObject had a list with over 45k entries.

whole steppe
#

Wow why my EditorLoop is not like that? It is empty.

gloomy chasm
whole steppe
#

-- Title to Search for Discord Users
How can i override global classes? (USS)

--Solution
I want to override a global behaviour of prefab values.
When a prefab instance's value gets overriden, the property's label becomes bold. Of course i want that but i would like to customize that globally.
Okey i think i need to override some of the classes from provided default USS
How the hell am i gonna override this shit?
https://forum.unity.com/threads/unity-why-have-you-made-your-entire-gui-look-like-garbage-now.709037/#post-4747730 he says like "it works" but no bro it not works.
Okey, i see it is not an official thing but they gave us a trick to do that. Thank you unity atleast now i know i can customize something!
We need to literally do what he says. The path and USS file name must match. But does not matters where you put the Editor/StyleSheets/Extension/dark.common.light.uss

-- Desadvantages
Cant edit UI Toolkit Element's classes.

Some asset publisher say:

Please also note that it could potentially interfere with UIs from third-party assets! Use at your own risk. Should you encounter any anomalies, consider uninstalling it and discontinue further use. Do not bother Unity Technologies or developers of third-party assets with any bug reports - **customizing the Editor this way isn't officially supported (and likely will never be)**.

timid coyote
#

in ui toolkit can i change the color of a PopupField?, and also why do DisplayStyle.None VisualElements still are calculated in flex?

visual stag
#

I also don't believe they are calculated? They're not part of layout when display is none

near wigeon
#

Any straightforward way to override the script's title bar in the inspector based on the value of a property? Can't use AddComponentMenu as it isn't a constant string.

whole steppe
#

Is there a way to edit default classes globally? like unity-text-field__input class

timid coyote
#

why do i get null?

glad cliff
glad cliff
timid coyote
#

oh, thanks :DD

whole steppe
#

I think i read something like if height is set to zero, it calculates by its content

timid coyote
glad cliff
#

you mean that Debug.Log says its 15 but UI debugger says its 18?

timid coyote
#

in log shows NaN, but in debugger shows 15

#

when i set the height of another element

#

but the _popupField's height is 18 in debugger

glad cliff
#

ahhh right XD im also always forgetting that style properties arent actual ints and floats hah

#

resolvedstyle.height.value or something like that