#↕️┃editor-extensions

1 messages · Page 21 of 1

real spindle
#

Sure, was just providing one solution

full cedar
#

oh, I took a slightly different approach(which might be wrong because my logic is usually very flawed), what I do is just get a sum and then just Random.Range(0, sum+1) and then choose an element that has the WeightRange that includes this number

short tiger
# full cedar oh, I took a slightly different approach(which might be wrong because my logic i...

The method I use is to calculate the sum weight, generate a random value between 0 and the sum weight, then loop over every item and check if its weight is greater than the random weight. If it isn't, I subtract the weight of the item from the random weight and keep iterating until I find an item. Looks something like this:

int sumWeight = ...;

float randomWeight = Random.value * sumWeight;

foreach (var weightedItem in weightedItems)
{
    if (weightedItem.Weight > randomWeight)
        return weightedItem.Item;

    randomWeight -= weightedItem.Weight;
}

I got this algorithm from somewhere online.

full cedar
#

I have to be honest, I am quite disappointed by the way unity is handling property drawers, it's missing so many useful features.
It's just common to use events to update the UI values and the other way around, how didn't they think of that when implementing other features :/

snow pebble
#

how would you draw a grid in scene window from an editor script

#

i usually like to use a 2D plane mesh with a shader for run time grids

#

but for an editor tool - not sure how to go about making a grid

real spindle
#

Though handles are a bit expensive so another option is to draw it with a repeating GUI texture

#

OnSceneGui + Handles.BeginGUI/EndGUI + GUI.DrawTexture

snow pebble
#

oh didnt realise we could draw textures like that

#

ill try it

native prawn
#

hey,
I want to delete some textures from the assetdatabase when the editor quits.

i found the EditorApplication.quitting.
and it works on a MonoBehaviour script.
but i want to use it on a editor script.
does anyone have any idea how i can do it?

waxen sandal
#

Use initialize on load to register

#

But you're probably not allowed to do asset manipulation in that callback

nova pecan
#

how do i create a panel like this that appears in the scene view when selecting a custom tool? can't find any documentation about how to make something like that

cerulean creek
#

I have a state like this

using UnityEngine;

public class HumanRunState : HumanBaseState
{
    [SerializeField] float RunMultiplier = 3.5f;
    public HumanRunState(HumanStateMachine currentContext, HumanStateRepository playerStateFactory) : base(currentContext, playerStateFactory)
    {
        IsRootState = false;
        StateEnum = HumanStates.Run;
    }

    public override void CheckSwitchStates()
    {
        if (!Ctx.IsMovementPressed)
        {
            SwitchState(Factory.GetState(HumanStates.Idle));
        }
        else if (Ctx.IsMovementPressed && !Ctx.IsRunPressed)
        {
            SwitchState(Factory.GetState(HumanStates.Walk));
        }
    }

    public override void EnterState()
    {
        Ctx.Animator.SetFloat("VelocityX", Ctx.AppliedMovementX);
        Ctx.Animator.SetFloat("VelocityZ", Ctx.AppliedMovementZ);
    }

    public override void ExitState()
    {

    }

    public override void InitializeSubState()
    {

    }

    public override void UpdateState()
    {
        Ctx.AppliedMovementX = Ctx.CurrentMovementX * RunMultiplier;
        Ctx.AppliedMovementZ = Ctx.CurrentMovementZ * RunMultiplier;
        Ctx.Animator.SetFloat("VelocityX", Ctx.AppliedMovementX);
        Ctx.Animator.SetFloat("VelocityZ", Ctx.AppliedMovementZ);
        CheckSwitchStates();
    }
}
#

I wanna make an editor extension that lets me personalize that RunMultiplier directly from the Inspector. Is the solution only SOs?

#

The RepositoryClass and the BaseState are not monobehaviours

cerulean creek
#

This method is soooo ugly

real spindle
#

In this case you also want to recreate the embedded SO editor when you change the SO instance

#

Not sure how you want it to be displayed since it's a list, though.

#

You can also right click the object field and click properties to open it in a new window

cerulean creek
#

I don't need a list, it was just for testing i can change the code around initializing them

#

I would love like all the state showing and an easy way to set for example the speed on the run state

real spindle
#

Yes, check the answer in the link I provided

cerulean creek
#

Looking at it

glad cliff
#

guys I have made custom bindable visual element that my editor uses to bind some ScriptableObject to it. Despite everything working I constantly get warning in my console that this field type is not compatible with PPtr<$ConditionSetup> property (where ConditionSetup is my SO), and I cant surpress this warning no matter what I do... Any ideas?

#

I guess it is designed to make BindableElements for objects that are not type of Unity Object, but I made it work anyway, however Unity thinks it shouldnt so it spits warnings at me when binding

snow pebble
#

unity has added a right click context menu in the scene which, i used right click for undo in my custom editor now the context menu pops up every time its a pain how do i stop that

waxen sandal
#

Haha

#

You can try using the event but chances are they're using some other method to detect it

#

There might be a shortcut to override?

snow pebble
#

yeah i am using the event

#

still does it 😦

waxen sandal
#

Rip

#

Unity giveth, Unity taketh

snow pebble
#

i wish i could find a way to disable selecting anything in the scene too

#

its a pain if i select an object when i just want to click in world space to get a position and then i lose focus on the editor

waxen sandal
snow pebble
#

no

#

im using an event from the scene view

waxen sandal
#

Ah

snow pebble
#

shouldn't make a difference though which way i do it

#

duringSeneGui event is the one i use

waxen sandal
#

Wonder if it makes a difference if you consume in beforeSceneGui?

#

Not sure if input works there though

north sphinx
#

I need a way to have editor asset references

#

I know I can attach it to just Editor instance

#

but how can I access it without actually having any custom editor UI?

#

this is what I mean

snow pebble
#

is there a way to hide mouse cursor in scene view from editor code

#

since im snapping to grid i want to use a handle so hiding the mouse would make more sense

nova pecan
nova pecan
nova pecan
#

woops

real spindle
#

You access it like any other field
And you can draw with ObjectField

shrewd parrot
#

System.IO.File.WriteAllText($"{scriptsFolder}O_{scriptName}.cs", scriptTemplate);

AssetDatabase.Refresh();

Type scriptType = Type.GetType($"O_{scriptName}, Assembly-CSharp");

if (scriptType != null)
{
    gameObject.AddComponent(scriptType);
}
else
{
    Debug.LogError($"Failed to get the type for script: {scriptName}");
}

heya guys. so i'm not quite sure how to proceed forward. it appears that the code running after AssetDatabase.Refresh() can't really find my newly created script since it still needs time to actually refresh and i confirmed that fetching existing scripts works. So I'd like to know if there's a way to await the database refresh (yes I know its not async but I want to know how to wait for the database to refresh so I can fetch this newly created script)

north sphinx
#

but I already figured that I can serialize to EditorWindow

surreal flume
#

Anybody knows how to discard changes from SerializedObject.ApplyModifiedProperties and reload asset from values on disk. I have tried "AssetDatabase.LoadAssetAtPath" but I think it's caching the already loaded asset because the object values are not the one written to disk but the "applied" one

crude silo
#

For some reason my Unity Editor is creating a ton of lag in play mode and takes my frame rate randomly down to below 7 frames even on a simple opening screen. I was using the profiler and all that I see causing it is the Editor Loop. I have no idea what is causing it. I tried updating to a newer unity version in 2022 but that actually somehow made it worse.

In my console for the profiler it is telling me a ton of times, "Internal: deleting an allocation that is older than its permitted lifetime of 4 frames (age = 15)" (and various other ages) which might be related?

What are things I can do to figure out what is causing the lag spikes? I tried deleting all my editor related stuff but that did not work.

surreal flume
#

Though the allocation thing is probably the root cause of it and I'd have no idea on how to debug that

surreal flume
# keen pumice not quite what you asked for best I got for you is: https://docs.unity3d.com/Sc...

Thanks, I think it'll be difficult to get this to work with using the Undo system but I'll try it out if I can't find a better solution. I did just find this forum thread with a couple of promising suggestions that I'll also try: https://forum.unity.com/threads/discard-unsaved-changes-done-to-scriptableobject-in-editor.1163249/

surreal flume
# surreal flume Thanks, I think it'll be difficult to get this to work with using the Undo syste...

Actually I ended up coming up with a great way to do this with the following:

// Call this on editor initialization
snapshot = ScriptableObject.CreateInstance(target.GetType());
EditorUtility.CopySerialized(target, snapshot);

// On save changes
serializedObject.ApplyModifiedProperties();
EditorUtility.CopySerialized(target, snapshot);

// On discard changes
EditorUtility.CopySerialized(snapshot, target);
serializedObject.Update();
nimble jolt
#

Hi 👋 ,
Don't really know if that's the place or not, but i'll try it here.

We just updated to latest unity 2022 lts : 2022.3.14f
And our CI&CD isn't capable of running Unity anymore to perform builds.
Issue is related to the thing with unity as administrator, so far we have been using many many things but didn't manage to fix it.
If anyone has an idea on how to fix that, would be very helpfull....
We were on 2022.3.7f before it was running ok.

We are actually starting it via powershell here is the script if that can help anyone.

param (
    [string]$branchName = $(throw "-branchName is required.")
)

# Stop script execution on error
$PSNativeCommandUseErrorActionPreference = $true
$ErrorActionPreference = "Stop"

$UNITY_VERSION="2022.3.14f1"
$UNITY_DIR="$PSScriptRoot\..\"
$UNITY_LOG=Join-Path -Path $UNITY_DIR -ChildPath 'Builds\build-logs.txt'
$UNITY_EXECUTABLE="C:\Program Files\Unity\Hub\Editor\$($UNITY_VERSION)\Editor\Unity.exe"
#-nographics -wwiseEnableWithNoGraphics # nographics causes issue SIGSEGV during build
#If ($branchName.Equals("/Playtest")) {
#    $cmdargs="-projectPath `"$($UNITY_DIR)`" -batchmode -executeMethod EditorBuildSystem.Builder.PerformCIBuildPlaytest -logFile `"$($UNITY_LOG)`""
#} Else {
    $cmdargs="-projectPath `"$($UNITY_DIR)`" -batchmode -automated -executeMethod EditorBuildSystem.Builder.PerformCIBuild -logFile `"$($UNITY_LOG)`""
#}

echo "Build started for branch $branchName"
$process = (Start-Process $UNITY_EXECUTABLE -ArgumentList $cmdargs -PassThru -Wait)
Get-Content -Path $UNITY_LOG

If ($process.ExitCode -eq 0) {
  echo "Run succeeded, no failures occurred"
}  ElseIf ($process.ExitCode -eq 2) {
  echo "Run succeeded, some tests failed"
}  ElseIf ($process.ExitCode -eq 3) {
  echo "Run failure (other failure)"
}  Else  {
  echo "Unexpected exit code $($process.ExitCode)"
}

If ($process.ExitCode -ne 0) {
  throw  "Build for target $($BUILD_TARGET) failure"
}

We have done many many changes, tries many different start / launch option, we just seems to not be able to run it via ou PS script anymore.

waxen sandal
#

Don't run your build as admin..?

#

Which means dont run your build pipeline as admin

glad cliff
#

https://forum.unity.com/threads/listview-remove-button-in-footer-serialized-property-disappears.1207432/
I have the same issue, seems like a bug cause I cant find anything wrong with my approach pretty much, but as I see it exists for a long time now, so maybe anyone found some solution or workaround?

nimble jolt
surreal flume
minor cloud
#

How can I ensure that the value of my property isn't updated unless it is changed? For other types of fields it can be done like this:

EditorGUI.BeginChangeCheck();
var tempInt = EditorGUILayout.IntField(someInt);
if (EditorGUI.EndChangeCheck())
  someInt = tempInt;

However I don't know how to handle it with PropertyFields.

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

Context: I'm trying to get rid of an issue that automatically duplicates one value to all GameObjects if multiple GameObjects are selected.

surreal flume
glad cliff
# surreal flume Try calling serializedObject.ApplyModifiedProperties() before calling Bind(). I ...

nah I tried this, eventually I just had to implement removing by myself without calling view controller and then rebuilding the list. For some reason removing items through view controller doesnt seem stable since 2020 lol... As I analyzed stack trace (only briefly so I might be wrong) it seems like between removing item from source and removing item from view, something tries to rebind that view item. Why and when exactly? No idea

#

tbh Unity could give us a bit more freedom in terms of binding. For example I see no point of making custom BindableElement without reflections to access binding event itself...

minor cloud
pure coral
#

Any idea how to handle Undo with static variables?

#

i cant find any info on the subject thats why im curious

waxen sandal
#

You don't

#

It only supports serializable objects

pure coral
# waxen sandal It only supports serializable objects

okay help me change my logic flow then, i keep a static reference to a class to avoid having my components conflicting one another (only 1 can be active in my "settings mode")
by pressing a button that static variable is set then, how can i still achieve something similar?

#

(basically im trying to ensure if my user presses undo when he presses the button, that variable can be unset in this example)

rustic parcel
#

Is there any way to get an accurate rect size for a VisualElement?
I'm using the Vector API to draw the blue circles at (0,0) and (contentRect.width, contentRect.height). These show as (463.2, 300) when I have it in the Editor.
However, in my OnMouseDown that just prints out the localMousePosition, it shows (462.4, 314.4) when I click around the bottom right corner. This difference gets bigger if I add anything else above this element in the UI builder.

surreal flume
rustic parcel
#

it's still giving me 300

surreal flume
#

I am guessing than the element is being scaled or something, the 300 must be the accurate size of the element and localMousePosition is in some other scaled space. Idk

surreal flume
rustic parcel
#

yes, it's (0,0)

surreal flume
# rustic parcel yes, it's (0,0)

Well if localMousePosition is (0, 0) at top-left then I would definitely assumed something is scaled but either way localMousePosition should give you the position relative to element space so that's weird. Maybe the evt.target from the mouse event value is not the element you're getting the size of. Also, have you tried inspecting with the UI Toolkit Debugger? That could possible help

rustic parcel
#

Ok, think I solved it after some rearranging of USS and UXML.
What I think was happening was that the localMousePosition counts the tab at the top of the window as well, but returns positions relative to that rather than from within the element itself.
The element itself wasn't ever scaled, just that there my USS was probably doing some weird things with flex and height.
I found it by looking through the debugger and finding that "World Bound" had (x:0, y: 20.80), which is the amount that my mouse click position was off by. So the solution is to store this as an offset, and subtract it from every time I use a localMousePosition.

#

Thanks!

surreal flume
tall bloom
#

Is there any way to stop EditorGUI.Popup from interpreting slashes as sub-menus?

waxen sandal
#

Use different slashes

tall bloom
#

the slashes are part of the values

#

oh, could I just use UITK instead?

#

it's a property drawer

minor cloud
#

I've noticed that both EditorGUILayout.PropertyField and EditorGUI.PropertyField inside mu attribute property drawer draw UnityEvent differently than it is being drawn usually. On the top of the screenshot, you can see how UnityEvent is being drawn by my Property Drawer, and on the bottom of the screenshot you can see how UnityEvent is being drawn by default. Is there any way to draw it normally?

public override void OnGUI(Rect position, SerializedProperty processedProperty, GUIContent label)
{
    EditorGUILayout.PropertyField(processedProperty);
maiden urchin
#

I don't know why I get an error here when I put the c# extension

surreal delta
# minor cloud I've noticed that both `EditorGUILayout.PropertyField` and `EditorGUI.PropertyFi...
protected UnityEventDrawer eventDrawer;

protected virtual void DrawProperty(Rect position, SerializedProperty property, GUIContent label)
{
    eventDrawer ??= new UnityEventDrawer();

    try
    {
        eventDrawer.OnGUI(position, property, label);
    }
    catch (NullReferenceException)
    {
        EditorGUI.PropertyField(position, property, label, true);
    }
}
``` ive done this function to handle unity event cases and use this in every OnGUI drawer, make sure you add the `using UnityEditorInternal;`
blissful burrow
#

does anyone know if it's possible to use the tab key reliably for custom plugins?
Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Tab
seems to trigger very weirdly, ie: only once every second or so

#

it's not a repaint issue, and it doesn't seem to be a GUIUtility.hotControl issue either (since I presume tab cycles GUI element focus), I've tried overriding it as well

#

and so idk what else to try ;-;

#

or maybe it is a control issue actually, because it seems to be every nth press that toggles

#

but then I'm not sure why my overriding doesn't work

short tiger
#

Maybe sometimes keyCode is assigned, while other times character is assigned instead.

blissful burrow
#

oh boy, now it triggers consistently, but twice every time instead, lol

short tiger
blissful burrow
#

yeah

#

it triggers twice, one for the tab key, and one without the tab key, but with the character instead

#

I don't understand how it can be consistent now though

short tiger
#

scary

blissful burrow
#

maybe consuming the tab character allows you to trigger it again

short tiger
#

What if you just check character then?

blissful burrow
#

yeah, that works consistently

#

yep, as long as I consume the event as well, it works perfectly

blissful burrow
#

neat

short tiger
blissful burrow
#

depends on who eats it first I suppose

#

in my case it's for scene view interaction input, not for proper GUI

wanton arrow
#

Why wont intellisense work for scripts inside the editor folder? How to I tell it that they are part of my project??

#

inside editor folder

#

outside editor folder

#

ig I could put them outside it for now but thats annoying when I need to build

astral oar
#

I have a small problem - when I'm building for different platforms unity modifies GraphicsSettings.asset but all builds are completely automated for me and I want it to revert back to original state after build, is there a way to do that?

#

because currently I'm just asking non-programmers to do git reset after building so that they don't commit this file

#

and I would like to avoid that

#

all it does is modifying this field

#

(m_AlwaysIncludedShaders)

#

is there a way to record this specific change and undo this specific change?

potent yoke
#

hey.. I've got a strange question... I have few components on a GameObject and those have custom editors... is it possible to reach them from other custom editors?
I mean - I'm asking how can I get in custom component editor (inspector) reference to some other custom editor of a sibling component?

astral oar
#

I'm not using unity version control

waxen sandal
#

It's not just for Unity's version control

#

I've used some of these with perforce before iirc

tulip tulip
#

Hi, would it be difficult to simply make a float variable show up in the inspector with a postfix like s so it shows up as 0.5s etc. I kinda want to have a [Postfix("s")] attribute to make the field simply add an s to the end of a the value to the float whether it be a slider, a field etc.

waxen sandal
#

Yes

#

If it's in the input field that is

#

If you don't care that it's outside after the input field, then it's fairly easy

#

But you can't combine multiple propertydrawers

tulip tulip
#

Meaning it can't have [Range(...), Postfix(...)] for example?

waxen sandal
#

Yeah

#

(You can theoretically build a system that allows it, but it's hard to define the edge cases)

tulip tulip
#

Alright, thank you

surreal flume
#

I am running into this very weird issue where this DropdownField (UITK) doesn't expand on click after updating a serialized property. The dropdown is binded to a separate enum field and on using both field.TrackPropertyValue, I attempt to update another serialized property in the same object based on this updated value. The problem is after I set valueProp.stringValue = someString, the dropdown just doesn't expand anymore. If I comment the line where I set the valueProp.stringValue, the dropdown can be selected and updated multiple times.

#

Anybody has an idea on how this could possibly happen or how to debug?

surreal flume
#

Actually, I just figured it took out. I guess you shouldn't change property values within TrackPropertyValue so I scheduled the change instead

field.TrackPropertyValue(property, (_) =>
{
    trackCallback();
    field.schedule.Execute(changeCallback);
});
tall bloom
#

is there any way to show an error state in a property drawer?

visual stag
tall bloom
#

ideally I would like something like a red border but helpbox looks like it may be the only thing

#

can I give it it's own line or do I have to smoosh it all in on one line?

tall bloom
#

ok I figured it out, not great but it will do

astral oar
surreal delta
timber stump
#

I'm trying to draw all of the property fields of a script inside a custom node editor window (basically recreating the inspector for an item). I'm using

EditorGUI.PropertyField();

but it seems like it won't properly draw attributes, such as Range(). Is there a way of getting the attributes on a SerializedProperty and applying them when drawing them on custom GUI?

surreal delta
#

it might have something to do with the order of the attribute

#

something from your script might override the other attribute logic

blissful burrow
#

does anyone know why Handles.lighting = false; make my handles invisible? (and if there's a way to fix it?)

#

Handles.CubeHandleCap(...) is invisible if I use a Handles.Color with an alpha of 1, but if it's less than 1 it does render

#

and when I do draw it with a lower alpha, the color is, very off, it looks blown out

#

this yellow cube should be the same color as the orange here

#

uuuuh multiplying RGB with 0.5 made the colors match what is happening lol

#

well, it works now, thanks for listening henlo

waxen sandal
#

I've ran into this before, but I just accepted it being a little fucked

tough cairn
#

how to open a properties window if i have the asset as a variable ?

tough cairn
#

nvm i figured it out , looks like some reflection was needed

#
var methods = typeof(Editor).Assembly.GetType("UnityEditor.PropertyEditor")
    .GetMethods( System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic );
foreach( var m in methods )
{
    if( m.Name == "OpenPropertyEditor")
    {
        if( m.GetParameters().Length == 2 )
        {
            // OpenPropertyEditor( Object obj, bool showWindow = true ) -> PropertyEditor
            var _PropertyEditor = m.Invoke( null, new object[] { SaveData.file, true } );
        }
    }
}
plush mulch
#

Is there a way to make a separate workspace? Like when you open a prefab.

astral oar
# tough cairn ```cs var methods = typeof(Editor).Assembly.GetType("UnityEditor.PropertyEditor"...

wouldn't using GetMethod("OpenPropertyEditor", System.Reflection.BindingFlags.Static, null, new Type[] { typeof(UnityEngine.Object) /* or w/e the actual 1nd argument type is, my version of unity doesn't have this method */, typeof(bool) }, null) be a much more reliable way since you're getting a specific method; and also probably want to save method reference into a static variable, there is no need to constantly make a lookup via reflection

timber stump
#

When using EditorGUILayout.PropertyField on the left, the [Range()] attribute is rendered correctly, but on the nodes I am using EditorGUI.PropertyField, and it looks like it doesn't apply the attribute. Does anyone know why this is or how I fix it?

wispy delta
#

Is it possible to draw gui outside an editor window using either imgui or ui tookit?

#

I'm trying to make a custom tooltip for inspector fields that draws some ui on top of (and potentially outside) the inspector window

gloomy chasm
wispy delta
gloomy chasm
peak bloom
astral oar
#

but using full lookup with exact parameters will always give correct method reference as long as it exists

#

and lookup will likely be faster depending on how reflection is implemented although that shouldn't even matter if you just save method reference in some static variable instead of making a lookup on every call

#

I constantly use reflection to call unity internal APIs because they tend to make anything remotely useful private or internal

frozen roost
#

Question
I'm automating a process of creating spritesheets and assign them to a prefab.
for now I'm using the SpriteDataProviderFactories to convert a texture into the spritesheet, then load each sprite using AssetDatabase.LoadAllAssetsAtPath to get the sprites. But the problem is, I need to wait for the texture/sprite files to be ready before I can load the sprite. So the question is, is there a way to use/convert spriterect data from Factory.GetSpriteEditorDataProviderFromObject into sprite?

silk terrace
#

Any way to get odin inspector attributes working on NetworkBehaviour?

waxen sandal
#

Ask in the odin discord?

silk terrace
waxen sandal
#

People here are mostly writing their own editors instead of using odin, thus likely do not know

trail dawn
#

No to mention, the developers are very active in that server.

daring temple
#

Hey guys, Is it possible to have an editor for a non MonoBehaviour?

So as shown in the image i have a struct and then i am using that struct in the "TestLayerInfo" MonoBehaviour and i want to create an editor for LayerInfo so that every time it is used in an inspector it is displayed in the way that i specified in the editor.

Just some things first:
1.) If LayerInfo needs to be a class intead of a struct that's fine i can change it.
2.) This specific example having to do with layers is not important, it's more about the concept
3. I know i can just create an editor for TestLayerInfo, but it's kind of time-wasting to create an editor for everything that uses LayerInfo
4.) I can create an CustomAttribute which you use on LayerInfo fields so i know that's a backup if there isn't another solution but what i'm asking i feel should be possible if you look at how UnityEvent is displayed in the inspector

#

In the meantime i'm gonna start looking at the source code for UnityEvent and how the editor drawing is handled but if anyone already knows how it works and can point me in the right direction it would be greatly appretiated

willow jackal
glad cliff
#

A question regarding [SerializeReference] attribute:
SerializedPropertyChangeEvent is send whenever something in a serialized property changes, but how does it work with SerializeReference? Does it trigger when anything in referenced object changes, or only when reference itself changes? Does anyone know?

willow jackal
glad cliff
#

i know but im kinda in hurry and was hoping someone already knew the answer :V

willow jackal
#

You probably took as much time to write that to try it.

daring temple
daring temple
glad cliff
#

Ok this time less testable question from me XD
Im adding a button to Toggle element of foldout (the whole foldout acts as a toggle), but pressing the button doesnt invoke its action as event seems to be eaten by the toggle parent element. How do i make that pressing the button inside this toggle executes its onclick callback and not toggles callback? I tried registering additional callback for button to stop propagading the pointer down/up event, but still toggle eats this event

#
addButton.RegisterCallback<PointerDownEvent>(evt => { evt.StopPropagation(); });
addButton.RegisterCallback<PointerUpEvent>(evt => { evt.StopPropagation(); });
...
foldout.hierarchy[0].Add(buttonsContainer);
pine gale
#

Is PropertyField not working at all for anyone else in Unity 2022.3.15 or 2022.3.13? The space is plenty big, I'm binding a property with BindProperty and also using Bind with the SerializedObject. All of this was created with C# scripts - I'm not using XML files for layout. Any ideas why PropertyField refuses to render anything but a blank VisualElement?

#

Is this a known issue? I'm surprised that it doesn't work whatsoever regardless of the configuration I use

glad cliff
#

it looks like for some reason it isnt bound at all, so I would investigate this firstly

pine gale
#

I ran the debugger to be sure it hits those lines. This is the code:

var so = new SerializedObject(port.NodeMetadata.asset);
so.Update();
_portField.label = port.Reference.fieldName;
_portField.BindProperty(so.FindProperty(port.Reference.fieldName));
_portField.Bind(so);
#

I can see the PropertyField having its bindingPath set in the debugger too

surreal flume
pine gale
#

I've tried both ways, but I'm creating it empty right now:

private readonly PropertyField _portField = new();
surreal flume
#

I would double check and debug the "bindingPath" on the field and also what is the type of the property you are trying to bind?

pine gale
#

Same result making the field not-readonly and constructing it with the SerializedProperty with the following code:

if (_portField != null)
{
    Remove(_portField);
}
var so = new SerializedObject(port.NodeMetadata.asset);
_portField = new PropertyField(so.FindProperty(port.Reference.fieldName),
        port.Reference.fieldName);
_portField.Bind(so);
Add(_portField);
glad cliff
#

on my journey with editors iveencountered so many wierd cases that sometimes it seems like things that shouldnt matter make difference if something works or not...
for example:
-setting binding path manually instead of using BindPrperty and vice versa (i had issues where one worked and another didnt for some reason)
-the order in whch you bind to a property and bind to serialized object
-having reference to the field stored globaly in an instance or localy in a method (idk why but i had such issue where changing it to local made it work lol)

pine gale
#

This is what I'm trying to bind:

    public class LogNode : NodeAsset
    {
        [Port] public string message;
        [Port(PortDirection.Output)] public string output; 
        public string prefix;
    }

NodeAsset is just an empty class derived from ScriptableObject

#

Both of the [Port] fields pretty much. When I log the bindingPath I get "message" and "output"

#

I've tried practically every kind of meaningless transformation of my code

surreal flume
#

So just throwing an idea out there, what are the values for message and output by checking the target object of serialized object?

pine gale
#

They're both null

surreal flume
#

I wonder if it's not showing because it's null, idk

#

Oh, could you try settng it to empty?

pine gale
#

Yeah

#

They are strings, so it's weird that it works for prefix when I use it through InspectorElement

#

OMG

surreal flume
#

Oh, it works for prefix but not the others?

pine gale
#

I made them disappear intentionally didn't I

#

Haha

#

The culprit:

    [CustomPropertyDrawer(typeof(PortAttribute))]
    public class PortPropertyDrawer : PropertyDrawer
    {
        public override VisualElement CreatePropertyGUI(SerializedProperty property)
        {
            return new VisualElement();
        }
    }
surreal flume
#

lol

pine gale
#

The thing is, I want them to show up outside of InspectorElement, so I was hiding them

#

But this also impacts PropertyField

surreal flume
#

Yep that makes sense, I actually thought about asking if you had a property drawer for it by I just assumed you didn't haha

#

Well glad you found it out

pine gale
#

Yes, thank you for the help!

glad cliff
#

tbh yeah it was too obvious to think about XD its always the case haha

wispy delta
#

This one might be a stretch, but given an arbitrary class is it possible to find the source file that class is declared in?

#

I'm messing with a custom attribute that automatically displays comments as tooltips, but custom serialized classes where the comment is in a different file along with the declared field is tricky

public class SimpleExampleScript : MonoBehaviour
{
    // This is a tooltip for a single line comment
    [Comment] public float someSingleLineComment;
    ...
    // A struct declared in another file
    [Comment] public Test someNestedFieldComment; // <-- this is tricky
}
surreal delta
#

Since the struct its a separate thing from your class you will have to use relfection to go inside the struct and get the comment from there

#
public static Type GetSerializedObjectFieldType(SerializedProperty property, out object serializedObject)
{
    var targetObject = property.serializedObject.targetObject;
    var pathComponents = property.propertyPath.Split('.'); // Split the property path to get individual components
    var serializedObjectField = targetObject.GetType().GetField(pathComponents[0], BINDING_FLAGS);

    serializedObject = serializedObjectField.GetValue(targetObject);

    return serializedObject.GetType();
}
#

here is a function i made for my package to look for stuff inside custom serialized objects

#

then you can just call that function and it will return the type of the field and you can get stuff inside it via reflection @wispy delta

#

either that or just add your comment attribute to the fields inside that struct as well

wispy delta
surreal delta
#

oh, i tought you were using some kind of reflection

gloomy chasm
wispy delta
gloomy chasm
gloomy chasm
wispy delta
#

haha that would be sick sadcowboy

gloomy chasm
#

The annoying thing is that the API is actually there for it internally with a SetAlpha(float alpha) method. But on the C++ side they only check if it is 0 or 1 it seems :/

wispy delta
#

damn!

wispy delta
gloomy chasm
spark totem
#

Hey guys! I'm currently making a custom editor for my game
In a Button I have I'm trying to instansiate a new prefab and then move it to a specific position that is defined. However.. It instansiates the prefabs fine, but newPoint is null, so I'm never able to access the newly created gameObject and therefore can't move it
Any pointers?

GameObject newPoint = PrefabUtility.InstantiatePrefab(serializedObject.targetObject.GetPrefabDefinition()) as GameObject;
if (newPoint == null)
{
    Debug.Log("well shit");
}
surreal flume
# spark totem Hey guys! I'm currently making a custom editor for my game In a Button I have I'...

So I am guessing that InstntiatePrefab should always return a GameObject so maybe this check irrelevant but idk you can probably try this:

var newPoint = PrefabUtility.InstantiatePrefab(serializedObject.targetObject.GetPrefabDefinition());
var newPointGameObject = newPoint as GameObject;
if (newPointGameObject == null)
{
    Debug.Log("well shit");
}
if (newPoint == null)
{
    Debug.Log("well shit again");
}
#

The only reason I'm suggesting it is because the type definition says it returns an Object. So I'd assume this Object could possibly not be a GameObject in some calls. And in that case, the "as GameObject" would return null

spark totem
brisk ivy
#

Does DOtween count as editor extension or is this the wrong channel to ask doubt about it here

waxen sandal
#

This channel is about developing extensions, not for help with someone elses extensions

whole steppe
#
public static List<T> FindRegistryChildClasses()
{
    var types = Assembly.GetExecutingAssembly().ManifestModule.GetTypes().Where(type => type.BaseType == typeof(T)).ToArray();

   return types.Select(abilityType => (T)Activator.CreateInstance(abilityType)).Where(abilityInstance => abilityInstance is T).ToList();
}

So I recently learned how to scan for classes that derive from T, and Im wondering if it would be possible to create an enum/list for a dropdown in the editor with a similar technique.
Is it possible to scan for classes with editor scripts like this as well?

calm grail
#

so i have a function called DrawFieldOfViewLines and everything works, except when i increase the yVisionAngle from 0 to any value, the lines endpoints are getting calculated correctly, but the problem is that because the line is getting rotated, it looks like its shrinking, and i need it to touch the radius wire arc
https://hastebin.skyra.pw/abizemixop.java

#

here it works correctly

#

this is what i mean

#

its probably really simple

#

i just dont know the math

#

so at the moment, i have a radius wire arc being drawn, and also i have a yVisionAngle which is responsible for how far the enemy can see on the y axis so up and down, the problem i have at the moment is that it works when the yVisionAngle is set at 0, because each endpoint is alligned with the radius, but as i increase yVisionAngle the angle of the lines change, resulting in them going back away from the radius, making them look shorter, i need them to constantly be alligned with the radius, so that means you have to calculate the endpoints going from the radius and up depending on what the yVisionAngle is set to

short whale
#

I am not sure where to ask this question but whenever I attach code from Visual studio (2022) to unity it keeps debugging and i cant stop it I tried disabling debug mode on the bottom left but still it keeps trying to debug

#

if anyone answers ping me

daring temple
#

Hey guys so i have an attribute here and it works fine and sets the string value of the string it's on just fine, or at least it seems like that at first, until you try to use the attribute on a variables that is not directly in the MonoBehaviour.

So as you can see i the screenshots the value for DirectTag changes, but NestedTag that is inside of a serializable class doesn't change.

No errors and also property.serializaedObject.targetObject is the same for both when debugging.

Do i have to somehow check if the property is nested and handle the value settings and saving differently if it is?

#

Oh and the property.SetFieldValue that you see in the screenshots is just an extension that i created that works fine in other places that it's used. Even if i use property.stringValue the result is the same.

visual stag
daring temple
#

I'm not sure what you mean but i've never had any issues with SetDirty, what are you suggesting instead?

I tried ApplyModifiedProperties now and it doesn't solve the issue

daring temple
#

I think i may be misunderstanding so if you don't mind and have a minute here's the CreatePropertyGUI function as text 🙏

    public override VisualElement CreatePropertyGUI(SerializedProperty property)
    {
        string defaultValue = !string.IsNullOrEmpty(property.stringValue) ? property.stringValue : "Untagged";

        if (defaultValue == "Untagged")
        {
            property.SetFieldValue("Untagged");
            EditorUtility.SetDirty(property.serializedObject.targetObject);
        }

        TagField tagField = new TagField(property.displayName, defaultValue);
        tagField.RegisterValueChangedCallback((evt) =>
        {
            property.SetFieldValue(evt.newValue);
            EditorUtility.SetDirty(property.serializedObject.targetObject);
        });

        return tagField;
    }
daring temple
#

Oh it is working now with just ApplyModifiedProperties

sorry i read this: #↕️┃editor-extensions message

and thought you meant to do it in that order but i understand now they "override" each other, is that right?

glad cliff
# glad cliff A question regarding [SerializeReference] attribute: SerializedPropertyChangeEve...

just got to a point when I was forced to check it and my conclusion is:
Property field bound to serialized property with SerializeReference attribute sends ValueChange event on every change within referenced object. Tracking property directly doesnt send ProeprtyChangeEvent either on reference change nor any other change, so it seems useless, or I havent figured out its functionality yet.
Pretty useful information if I say so myself

elder wasp
#

Hi

#

What's the right way to modify a struct through editor?

#

trying to assign a value on initalize

#

but cannot find the right format

glad cliff
#

if you serialize it with normal SerializeField, then I guess you can modify it same way as you would any other property

#

unless you mean assigning some struct to a SerializeField, then it simply comes down to setting each relative property one by one

#

Guys can someone explain to me what is going on and where to even search for the problem?
When I enter playmode and one of my custom property drawers is visable in the editor in that moment, console throws this at me:

#
ArgumentNullException: Value cannot be null.
Parameter name: _unity_self
UnityEditor.SerializedObject.FindProperty (System.String propertyPath) (at <fe7039efe678478d9c83e73bc6a6566d>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindPropertyRelative (UnityEngine.UIElements.IBindable field, UnityEditor.SerializedProperty parentProperty) (at <c91a25f185b743118a39aafa100dff09>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindTree (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at <c91a25f185b743118a39aafa100dff09>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.ContinueBinding (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at <c91a25f185b743118a39aafa100dff09>:0)
UnityEditor.UIElements.Bindings.DefaultSerializedObjectBindingImplementation+BindingRequest.Bind (UnityEngine.UIElements.VisualElement element) (at <c91a25f185b743118a39aafa100dff09>:0)
UnityEngine.UIElements.VisualTreeBindingsUpdater.Update () (at <79c7b132c51745cbae03eebea8111c0e>:0)
UnityEngine.UIElements.VisualTreeUpdater.UpdateVisualTreePhase (UnityEngine.UIElements.VisualTreeUpdatePhase phase) (at <79c7b132c51745cbae03eebea8111c0e>:0)
UnityEngine.UIElements.Panel.UpdateBindings () (at <79c7b132c51745cbae03eebea8111c0e>:0)
UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.UpdateSchedulers () (at <79c7b132c51745cbae03eebea8111c0e>:0)
UnityEngine.UIElements.UIEventRegistration.UpdateSchedulers () (at <79c7b132c51745cbae03eebea8111c0e>:0)
UnityEditor.RetainedMode.UpdateSchedulers () (at <c91a25f185b743118a39aafa100dff09>:0)

#

property drawer hangs empty for a moment, but then draws itself properly after a while, so everything works fine, but clearly Unity wants me to know that something bad happens, but "_unity_self" tells me nothing from that error log O.o

proper raptor
#

Class: public sealed class Database : ScriptableObject
this works [CustomEditor(typeof(Database), editorForChildClasses: true)]
this does no work[CustomEditor(typeof(ScriptableObject), editorForChildClasses: true)]

for Monobehaviours, editorForChildClasses seems to work fine, for ScriptableObject it does not?
Edit/Solved: Because i'm a dummy.

glad cliff
#

I have a custom Visual Element in which constructors I have this:

public ParametersElement(SerializedProperty property)
{
    this.TrackPropertyValue(property);
}

When in my editor I remove list element, which uses a property drawer with this custom visual element I got an error that serialzied property dissapeared. After some testing I know for sure that this TrackProeprtyValue is what causes this error, but I have no idea how to fix it. I tried unregistering to SerializedPropertyChangeEvent in OnDeatachFromPanel event and in a destructor, both didnt change a thing, and there is no such thing as "UntrackProeprtyValue" or something.

plucky knot
#

Is there a straightforward way to persist instanced serialized EditorWindow fields across editor re-opening? I know there is ScriptableSingleton for a main instance of the window, but the window I have atm can be instanced with its own unique data.

I would just bundle all the data into a serialized array on the ScriptableSingleton, although that would bring to question how to even bind a persistent id to a window instance in the first place to then load the correct info back up. 🤔

surreal flume
#

@plucky knot I may be wrong but my guess is that re-opening just creates a new instance so there'd be no way to id these unless you identify instances by how they are opened. For example, if you open an editor instance via a scriptable asset you can use that path for an id.

I would either store field state within the scriptable asset itself or like you said, use some ScriptableSingleton or a custom ScriptableObject with id's that map to different editor states.

visual stag
#

Or use SessionState/EditorPrefs

plucky knot
#

I wonder how something like two locked Project window instances maintain their own unique data across an editor re-open then. Unless they do some internal shenanigans to maintain their own buffer of windows that are saved somewhere and somehow know which window to put the data into WAAAA

visual stag
#

They just won't survive closing the window itself

plucky knot
#

Oh my god, I had it force clearing the data when CreateGUI ran since I was using test data kermie_AAA

visual stag
fiery forum
timber fulcrum
#

Hello, I just installed Unity extension for VSCode and followed all the steps, but the "Projects: X" in the bar doesn't appear

#

In Output tab, I selected "Unity" and there is no message, any clues ?

hollow estuary
#
[CustomEditor(typeof(Health))]
public class HealthEditor : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();
        var script = (Health)target;

        script.isPlayer = EditorGUILayout.Toggle("Is Player", script.isPlayer);
        if (script.isPlayer == true)
        {
            script.EasterEggSound = EditorGUILayout.ObjectField("EasterEgg Sound", script.EasterEggSound, typeof(AudioSource), true) as AudioSource;
            script.textValue = EditorGUILayout.ObjectField("Text Value", script.textValue, typeof(TextMeshProUGUI), true) as TextMeshProUGUI;
        }
    }
}
#

I made this custom editor

#

Does someone know how to hide another booleans?

#

Lets say that I have another bool like isntPlayer

#

And if isPlayer is true then I want to hide bool isntPlayer because I dont need it in inspector

#

How could I do this if its even possible

waxen sandal
#

I got an editorwindow that creates an in-memory scriptable object, this does not survive editor restarts since scriptableobjects can't be serialized like that. Any ideas to do that anyways?

#

(Yeah I know scriptablesingleton or SerializeAndForget but don't really want to maintain a file...)

small oriole
#

What is the state of GraphTool foundation? It doesn't even compile for me in the latest Unity in an empty project.

peak bloom
#

it's being developed internally, the latest package available to download won't work with recent unity versions

twilit gazelle
#

is there a way to pass custom messages from a build back through the debugger connection (the one that passes debug logs, frame debugger, and profiler info back from a build)? I want to pass some state to an editor inspector so I can confirm some things, but I don't want to write a whole transport system for it when there appears to be a perfectly good one already set up (plus phones might not be on the same actual network but merely connected via adb)

whole steppe
#

I'd like to be able to both create an ping a file in the Editor, however!

I'm ending up with unpleasant results in these both cases:

var asset = new TextAsset("..."));

// NOTE: asset creation with a ".txt" extention results a console error
// saying the extension should instead be ".asset".
// and using the ".asset" extension creates a YAML-like file...

//AssetDatabase.CreateAsset(asset, "Assets/text.txt");
AssetDatabase.CreateAsset(asset, "Assets/text.asset");
        
EditorGUIUtility.PingObject(asset);
var text = "...";

File.WriteAllText("Assets/text.txt", text);
// NOTE: can't ping since `text` since it isn't a Unity object...
EditorGUIUtility.PingObject(text);

what should I do 🥹 ?

willow jackal
whole steppe
#

however!

#

I already found a workaround xd

const string TEXT_PATH = "Assets/text.txt";

var text = "...";

File.WriteAllText(TEXT_PATH, text);

AssetDatabase.Refresh();

var pingable = AssetDatabase.LoadAssetAtPath<TextAsset>(TEXT_PATH);

EditorGUIUtility.PingObject(pingable);
willow jackal
whole steppe
willow jackal
whole steppe
timid plume
#

Has anyone had the No GUI Implemented when trying to create UI TK propertydrawers for custom timline clips? Works for even=rything else in my project but not custom clip.

waxen sandal
#

I'm guessing, just like animator states, UITK doesn't work for those

timid plume
#

Damn that sucks.

#

Is there an official list of what is supported?

waxen sandal
flint garnet
#

so i want to create "tools" and there, i have button when i clicked if that a scripts, then open the scripts on current Text editor we used, if that a shader graph file, then its open shader graph window, if vfx, then open vfx...and so on, the thing is HOW, there must be a method somewhere, for opening a scripts right??, anyone know?, thanks in advanced

surreal delta
#

Does anyone know why does the array label changes to the value of the string field? it only happens to arrays and when the string field is the first field drawn, if the field is empty it just says Element 0 as it should

#
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
    if (property.propertyType != SerializedPropertyType.Generic)
    {
        EditorGUILayout.HelpBox("The RowAttribute can only be attached to collections and serialized structs or classes", MessageType.Error);
        return;
    }

    property.isExpanded = true;

    int childCount = property.Copy().CountInProperty() - 1;
    int initialDepth = property.depth;
    float currentX = position.x;

    var labelRect = new Rect(currentX, position.y, EditorGUIUtility.labelWidth, position.height);
    EditorGUI.LabelField(labelRect, label, EditorStyles.boldLabel);

    currentX += labelRect.width + EditorGUIUtility.standardVerticalSpacing;

    while (property.NextVisible(true) && property.depth > initialDepth)
    {
        float propertyFieldWidth = Mathf.Max((position.width - EditorGUIUtility.labelWidth) / childCount, EditorGUIUtility.fieldWidth);

        if (property.propertyType == SerializedPropertyType.Generic || property.propertyType == SerializedPropertyType.Vector4 || property.propertyType == SerializedPropertyType.ArraySize)
        {
            var helpBoxRect = new Rect(currentX, position.y, propertyFieldWidth, position.height);

            EditorGUI.HelpBox(helpBoxRect, "Collection, UnityEvent and Serialized object types are not supported", MessageType.Error);
            break;
        }

        var propertyLabelRect = new Rect(currentX - 20f, position.y, propertyFieldWidth, position.height / 2f);
        var propertyFieldRect = new Rect(currentX - 20f, position.y + position.height / 2f, propertyFieldWidth, position.height / 2f);

        EditorGUI.LabelField(propertyLabelRect, property.displayName);
        EditorGUI.PropertyField(propertyFieldRect, property, GUIContent.none);

        currentX += propertyFieldRect.width + EditorGUIUtility.standardVerticalSpacing;
    }
}
wispy delta
#

I'm running into a weird issue with foldouts in a custom property drawer. For some reason, clicking the caret does not expand the foldout when I position the foldout manually

If I just draw it at the property position it has an awkward indent, but clicking the foldout caret works

// This works!
[CustomPropertyDrawer(typeof(Sound.Layer))]
public class LayerPropertyDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUI.BeginProperty(position, label, property);
        position.height = EditorGUIUtility.singleLineHeight;
        property.isExpanded = EditorGUI.Foldout(position, property.isExpanded, "", true);
        ...
#

However if I unindent it, clicking the caret does nothing

// This does NOT work!
EditorGUI.indentLevel--;
property.isExpanded = EditorGUI.Foldout(position, property.isExpanded, "", true);
EditorGUI.indentLevel++;
#

My best guess is that the reorderable list is eating the input since I can reorder the element by dragging in that space, but it's only an issue with a custom property drawer. unity handles it correctly with the default drawer; however the caret still doesn't work when the property is drawn outside a list

gloomy chasm
gloomy chasm
wispy delta
gloomy chasm
wispy delta
#

2022.3.14

gloomy chasm
#

Might be a UITk thing messing with the IMGUI stuff 🤷‍♂️

wispy delta
#

Roger. I'll see about just creating the drawer with uitk

gloomy chasm
wispy delta
gloomy chasm
#

You're welcome, it caused me much pain haha

whole steppe
visual stag
whole steppe
#

I got a class that's marked with the System.Serializable attribute, which means that members become serializable, unless explicitly said to not be with the System.NonSerialized attribute.

[Serializable]
public class Class
{
    internal Dictionary<string, string> _values = new Dictionary<string, string>();
}```
however! when accessing the `_values` field using the `FindPropertyRelative` method from the `CreatePropertyGUI` `property` method parameter like so:```cs
public override VisualElement CreatePropertyGUI(SerializedProperty prop)
{
    // ...
    Debug.Log(prop.FindPropertyRelative("_values"));
    // ...
}```
it  returns `null`, even though the `_values` field doesn't have `System.NonSerialized` attribute on it...

would you happen to know why is that?
#

this is how the PropertyDrawer looks like:cs [CustomPropertyDrawer(typeof(Class))] public class ClassDrawerUIE : PropertyDrawer { public override VisualElement CreatePropertyGUI(SerializedProperty prop) { // ... Debug.Log(prop.FindPropertyRelative("_values")); // ... } }

visual stag
#

and nor are non-public fields not marked with [SerializeField]

#

It's the same rules as what appears in the inspector, SerializedObject/Property is a window into Unity's serializer, and isn't something general

whole steppe
ebon helm
#

So if I were to start a graph based tool today what should I use? Graph View? Graph Tools Foundation? Some open source implementation? Say fuck it and write my own with UIElements?

flint garnet
flint garnet
# ebon helm So if I were to start a graph based tool today what should I use? Graph View? Gr...

start with a tutorial buddy, here is one good example
https://youtu.be/nvELzBYMK1U?si=ZtUck2sQLcRPnxQZ
he explain very well

In this tutorial series we'll be making a node based dialogue system using the Unity Experimental GraphView API.

It will have a series of features that you can check out on this video or in the dialogue system features video.


Timestamps:

00:00 Introduction
00:50 Features
01:10 Referenc...

▶ Play video
ebon helm
flint garnet
#

ywc

peak bloom
#

it's just too many assets and internal tools rely on that api

#

there are some quirkiness with the api, but still the best graph api you can use in unity today I'd say

#

another plus with the graphview is that it uses uitk

waxen sandal
#

It's like people saying imgui will disappear

#

But then they realize that animator doesn't support UITK at all

past crane
ebon helm
#

Ok based on this input GraphView it is 😀

crimson cobalt
#

I'm a bit stumped. I have this class which serializes a key value pair for a dictionary for me.

[Serializable]
public class SerializableKeyValuePair<TKey, TValue>
{
    public TKey Key;
    public TValue Value;
}

How can I ensure that, if TValue is a string, I draw it using the [TextArea] attribute?
If I just add the attribute, then other types will break:

dusk bobcat
#

hey guys, i have set up a int that takes a GUILayout.Toolbar but every time i press a button on it, it reverts back to the old int value. what is causing this? the debug.log says the int toolbarIndex is zero, on every frame, but it only says that it is 1 only when i press the global button.
https://cdn.discordapp.com/attachments/497874004401586176/1184558338156003389/image.png?ex=658c68eb&is=6579f3eb&hm=885b5478fee0118acbe521cffa5f570c63e2b83778491145639e6f7dea812098&
https://cdn.discordapp.com/attachments/497874004401586176/1184558338449616968/image.png?ex=658c68eb&is=6579f3eb&hm=a7dd813b262975cc1c53934dcb0e03cb126f51cf55c57cc0bc2e9843affeadec&

dusk bobcat
#

someone said something about it not being seralized, but i dont know what that means

severe lance
#

What's this a custom editor of? You have that cropped out

dusk bobcat
dusk bobcat
severe lance
#

Hmm, so I think normally the values reset when you have your target script unfocused, but since yours is specifically to the editor there must be more to it

#

maybe it does matter if it's serialized

#

try that

#

because that should save the values when defocused

dusk bobcat
#

im using a unity package and it had this problem and now im trying to fix it because it is unusable, ive never made unity editors

dusk bobcat
#

i guess i didnt need need [hideinispector] but whatever

severe lance
#

Both do similar stuff (ah, brain fart but [HideInInspector] can be used on a public variable which itself would already be serialized and would hide similar to that of a private serialize field variable)

dusk bobcat
wispy delta
#

I'm using a uitk property drawer in my project, but it's not drawing because every editor is using imgui for some reason. Any idea why Unity would be making all the default editors use IMGUI when it should use UTIK by default?
(i'm using 2022.3.15 and "Use IMGUI Default Inspector" is toggled off in the Project Settings.)

gloomy chasm
gloomy chasm
wispy delta
#

I was thinking the same, but wasn't sure how to confirm. I haven't done that so it'd have to be an external asset. I'm not using anything like Odin or Naughty Attributes

dusk bobcat
wispy delta
gloomy chasm
wispy delta
severe lance
wispy delta
#

Unity's NetcodeForGameObjects package

gloomy chasm
#

WHY!?

wispy delta
#

yea. so it's not actually an editor for every base type like i thought, but it's an editor for LOTS of them since you derive from it for like any component thats networked lmao

#

oh unity why you gotta do this to me

gloomy chasm
#

Ooh, okay so it is just for their own components that you inherit from... thats better at least

#

Uhh... you could write your own maybe?

#

There is no good way around this sadly

wispy delta
#

i'll see about making my own that ports whatever they're doing in imgui to uitk. or I could just write my property drawer in imgui, but I switched to uitk specifically because of that foldout issue in imgui from the other day rip #↕️┃editor-extensions message

dusk bobcat
gloomy chasm
wispy delta
dusk bobcat
#

see? no requiredcomponent

#

can i use EditorPrefs to store the value?

#

like playerPrefs

wispy delta
#

can you share the entire file? you shouldn't need to use player prefs for the field to persist.

if the value is not persisting, and the editor is not for a specific component, the only thing i can think is that the editor is being used in an unorthodox way by unity. maybe log a message from OnEnable to see when it's being created. Idk why, but Unity might be making new instances

#

you could also make the toolbarIndex a property and log from the setter to see when it's being set and what the callstack is

severe lance
#

I actually see stuff about storing it in editorprefs since you don't have a target (mono) of the custom editor. No clue what that implies.

severe lance
#

nah just looking around the forums

#

more related to scriptable objects

dusk bobcat
#

alr, editor prefs is not a good solution beacuse i also need to save a custom class, that being public BlackboardEntry selectedEntry;

#

second property in blackboardeditor

wispy delta
#

Man, now I'm back to the weird imgui property drawer indent issue.
Seems like stuff can't be clicked if it's outside the property's rect; which is an issue for foldouts whose caret is typically drawn to the left of the content

The rect is visualized in red in the comparison images below. Seems like any clicks outside it don't register. Has this always been the way things worked?

Default behavior (looks wrong, but is interactable since the caret is in the rect)

// first image
public override void OnGUI(Rect rect, SerializedProperty property, GUIContent label)
{
    EditorGUI.PropertyField(rect, property, label, true);
    GUI.color = Color.red;
    GUI.Box(rect, "");
    GUI.color = Color.white;
}

Corrected behavior (looks correct, but is not interactable since the caret is outside the rect)

// second image
public override void OnGUI(Rect rect, SerializedProperty property, GUIContent label)
{
    // also doesnt work with rect.x -= 15
    EditorGUI.indentLevel--;
    EditorGUI.PropertyField(rect, property, label, true);
    GUI.color = Color.red;
    GUI.Box(rect, "");
    GUI.color = Color.white;
    EditorGUI.indentLevel++;
}
#

And this is how the foldout works with uitk, which works and looks correct

wispy delta
# dusk bobcat

From that script I still don't see why the index wouldn't persist. Can you try making it a property and logging a message from the setter to see when it's being set?

private int _toolbarIndex{
private int toolbarIndex{
  get => _toolbarIndex;
  set => {
    if (value == _toolbarIndex)
      return;
    Debug.Log($"Toolbar Index changed from {_toolbarIndex} to {value}")
    value = _toolbarIndex;
  }
}
#

(and comment out the editorprefs stuff)

gloomy chasm
wispy delta
gloomy chasm
dusk bobcat
dusk bobcat
wispy delta
#

is it set to what you'd expect?

dusk bobcat
dusk bobcat
wispy delta
#

so strange

#

this works fine for me 😕

[CustomEditor(typeof(Test))]
public class TestEditor : Editor
{
    private int _toolbarIndex = 0;
    
    public override void OnInspectorGUI()
    {
        _toolbarIndex = GUILayout.Toolbar(_toolbarIndex, new[] { "Local", "Global" });
    }
}
dusk bobcat
#

[CustomEditor(typeof(Test))]

#

my editor is not attached to a component* like yours is

#

i dont have customeditor(typeof)

wispy delta
# dusk bobcat i dont have customeditor(typeof)

Works fine for me without that attribute too

public class TestEditor : Editor
{
    private int _toolbarIndex = 0;
    
    public override void OnInspectorGUI()
    {
        _toolbarIndex = GUILayout.Toolbar(_toolbarIndex, new[] { "Local", "Global" });
    }
}
public class TestWindow : EditorWindow
{
    private TestEditor _editor;
    [MenuItem("Tools/Test Window")]
    private static void Open()
    {
        GetWindow<TestWindow>();
    }
    
    private void OnEnable() => _editor = CreateInstance<TestEditor>();
    private void OnDisable() => DestroyImmediate(_editor);
    private void OnGUI()
    {
        _editor.OnInspectorGUI();
    }
}

Tho idk how exactly Unity is using the BlackboardEditor in your context. Can you share the callstack from OnInspectorGUI to see where it's being called from?

dusk bobcat
#

i found a BlackBoard.cs script in the package

#

can i fix my issue by making that a required component?

#

and making it a custom editor?

dusk bobcat
dusk bobcat
wispy delta
# dusk bobcat i cant find an editor window class in this script, maybe thats the reason?

I was just using an editor window to show how an Editor can be drawn without the [CustomEditor] attribute. I don't know anything about the package you're using so I don't know the relationship between the BlackboardEditor and Blackboard classes, or if it even makes sense for the BlackboardEditor to be a custom editor for Blackboard. If you're changing Unity's packages you'll wanna have a good understanding of what their code is doing

dusk bobcat
#

sorry im not familiar with custom editors

wispy delta
#

to see the callstack you can just log a message from the gui function. The log will show the callstack in the Console window

public override void OnInspectorGUI()
{
    Debug.Log("This log has a callstack");
    _toolbarIndex = GUILayout.Toolbar(_toolbarIndex, new[] { "Local", "Global" });
}
dusk bobcat
#

wait, unity is reloading domain

#

still....

#

man what are these load times

#

!code

grave hingeBOT
dusk bobcat
#

this script

#

@wispy delta sorry forgot to ping

#

line 316

#

the node editor isnt an editor window...

#

let me see where its refranced

wispy delta
# dusk bobcat this script

I just downloaded the Schema asset and the toolbar works fine for me. For context, I'm curious what needed fixing?

dusk bobcat
#

what unity version are you using?

wispy delta
#

2022.3.15

dusk bobcat
#

can you create and select things with the plus icon on the top?

#

and remove them with the minus?

wispy delta
#

ya 👍

dusk bobcat
#

im using 2022.3.12f1

#

bro this is so weird

#

ill re import the scripts and see if it gets fixed

wispy delta
#

i that doesnt work, id update the editor and reinstall the asset

dusk bobcat
#

mother fu

dusk bobcat
#

ever since i tried to fix this my editor has become super slow

dusk bobcat
#

hey guys, ive downloaded an asset on my unity project but its having a problem. when clicking a button in a custom editor of the asset, that is a GUILayout.Toolbar, i get two errors and it dosnt function like it should. ive tried to fix them but i couldnt so i re installed the package, any info on how to fix this? the asset name is schema

dusk bobcat
# wispy delta

it works for this fella but for some reason it dosnt work for me

#

new project fixed it

#

for some reason

glad mica
#

what is a Handles.DoPositionHandle and how does it differ from the regular Handles.PositionHandle?

gentle forge
#

Hey there

#

Any ideas why compute shaders behaves weird in editor?

#

But works in playmode

supple willow
snow summit
#

Hello, I'm trying to add labels in the scene view when selecting GameObjects with a custom editor.
Calling a custom editor for a game object destroys the existing GUI in the inspector. Is there a way to prevent this?

public class RenderersGUIInfo : UnityEditor.Editor
gloomy chasm
snow summit
#

I just ended up using SceneView.duringSceneGui event to toogle the labels instead

wooden jasper
#

Howdy. I am working on custom editor stuff and have run into the issue of not being able to add an enum to the custom editor script. I have tried a couple variations I found online but I cant seem to get anything that works. Here is the line I am using
levelController.startingLvl = EditorGUILayout.EnumFlagsField("First Shed Door Close Trigger :", levelController.startingLvl, typeof(Enum), true);
levelController is the script I am making the editor for
startingLvl is the enum

Does anyone have a solution?

rancid ridge
#

How can I update the state of properties in a script, from an "Editor" script. When I use "serializedObject.ApplyModifiedProperties();" It works but errors the following:

How can I do the same thign without the error?

severe lance
rancid ridge
severe lance
#

I mean, that what updates my GUI so it must be doing anything

rancid ridge
severe lance
#
public override void OnInspectorGUI()
{
    base.OnInspectorGUI();
    serializedObject.Update();

    bool recalculateDimensions = false;

    EditorGUILayout.PropertyField(brushSize);

    EditorGUILayout.Space();
    EditorGUILayout.LabelField("Map Data", EditorStyles.boldLabel);
    EditorGUILayout.PropertyField(tilesPerChunk);

    EditorGUILayout.Space();
    EditorGUILayout.LabelField("Chunk Size", EditorStyles.boldLabel);
    EditorGUILayout.PropertyField(chunksPerMap);

    if (serializedObject.hasModifiedProperties)
    {

        if (brushSize.intValue <= 0)
        {
            brushSize.intValue = 1;
        }

        recalculateDimensions = true;
    }

    if(serializedObject.ApplyModifiedProperties())
    {

        if (recalculateDimensions == true)
        {   //
            map.CreateGridCollider(map.GridComposition);
            map.UpdateGridlines();
        }

    }
}

Simplified part of my script so maybe that'll give you an idea.

rancid ridge
severe lance
#

Been a while since I've done this stuff, but I'm pretty sure what happens is you edit the values on the GUI which you then check if the GUI has been modified in this loop. From there I think ApplyModifiedProperties does do the final confirmation that these values will now be serialized

rancid ridge
#

also I add base.OnInspectorGUI and immediately it just duplicates it

rancid ridge
#

I'm editing them in a script and they aren't saving to the inspector

#

As soon as i put applymodifiedproperties in the onscenegui it works, but i get that annoying error which there is no way to ignore

#

like how does something error if it works perfectly fine? just let me use serializedobject where i want to lmao

severe lance
#

I don't seem to be using serializeobject outside of UI element values

#

everything else is just serialized on the targeted script which I update

#

I could be doing it wrong though honestly

rancid ridge
#

does yours work

#

cuz if so that's all i care about

#

this makes no sense dude istg

#

Why does this genuinely have to be so impossible to do something so basic

severe lance
#

In your script you assign a serializeproperty but you dont use it

#

yet in your OnSceneGui you make another property

rancid ridge
#

bc points is an array

#

See, it's used.

#

Told ya it makes no sense.

severe lance
#

I do notice you don't target a specific object yet have the [CanEditMultiple] attribute which I think is a problem too but I don't think it's error related.

#

Actually it could be

rancid ridge
#

The issue is, is that stuff in OnInspectorGUI updates fine

#

i've tested it using a button

#

It doesn't save when i do it outside of oninspectorgui

#

such as in onscenegui

#

@severe lance

#

you can see this here.

#

Idk what i could use except for serializedObject.applymodifiedproperties here

#

if i just directly set the value to the target, OnDrawGizmos runs slowly for some odd reason.

#

Yeah i jujst tried setting directrly

severe lance
#

probably need to repaint the scene

rancid ridge
#

after everything?

#

lemme try

#

does nothing

severe lance
#

yeah if you're drawing stuff into the scene you need to update the handle and to call a repaint

#

something like that

rancid ridge
severe lance
#

HandleUtility.Repaint

rancid ridge
#

does nothing

severe lance
#

oh you're using OnDrawGizmos not handles

#

should still work

rancid ridge
#

sorry when do i call this

#

Oh my god duide it works thank you so much that took WAY too long

#

<33

severe lance
#

Oh nice

#

I think SceneView.Draw / DrawAll works too I forget

#

honestly it's something you take a day to read into

outer kraken
#

Hey,
is it possible to create an editor that appends a button inside the component headers?
(without caring about the component and without breaking existing builtin/custom inspectors)

in which direction do i have to research to find more about this?

(example, i'd like to have a "Quick Remove" button inside the header of any components, instead of crawling that context menu)

zenith oyster
#

Hello editor wizards,
I'm making a custom PropertyDrawer for strings that represent AssetGUIDs. The goal is that the user can drag an object reference into the field, and then it only serializes the AssetGUID as a string. Its extremely useful when passing around weak references to prefabs, assets, etc. and functionally it is working great!

However, my implementation puts an annoying extra space between fields in the inspector. Does anyone have any idea how this could be removed? My theory is that it's because I am using EditorGUILayout.ObjectField(... to draw the field to drop in the asset, and maybe the original rect to draw the property is being unused and creating that extra space.

Thanks in advance!

[AssetGuid(typeof(DeeeprTile)), SerializeField] private string _test; [AssetGuid(typeof(DeeeprTile)), SerializeField] private string _test3;

surreal delta
#

give the inspectorDefaultMargins or inspectorFullWidthMargins editor style to your object field, see how that looks

zenith oyster
# surreal delta give the inspectorDefaultMargins or inspectorFullWidthMargins editor style to yo...

I don't understand how to use EditorStyles in this context (or really at all, can't find any examples online either): https://docs.unity3d.com/ScriptReference/EditorStyles.html

This doesn't have any effect, regardless of which option you mentioned :

_obj = EditorGUILayout.ObjectField(label, _obj, assetGuidAttribute.Type, false);
EditorGUILayout.EndVertical();

EDIT found my issue, just need to override GetPropertyHeight:
public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return 0; }

https://discussions.unity.com/t/empty-space-at-the-top-of-a-custom-property-drawer-layout/175683

EDIT: I think my REAL problem is described in that thread, I need to use EditorGUI.ObjectField instead of EditorGUILayout.ObjectField

surreal delta
#

oh, i missunderstood the problem, i think the problem had something to do with the width position

zenith oyster
#

no problem, I think my REAL problem is described in that thread, I need to use EditorGUI.ObjectField instead of EditorGUILayout.ObjectField

plush spade
#

Are the node connections in the (Graph View) is only visual ?

Or from where can i get the input and output nodes of the connection like (Edge, Node Connector) which one of them should i look or which callbacks ?

Shortly I want to create node inner texts depending on input port connections

wide dock
#

Can I use Import Package dialog window from code?

rancid ridge
#

Anyone online to help?

#

I have a script with a custom editor, where a public variable randomly becomes null on runtime for some reason

#

How is this even theoretically possible? LOL

elfin gorge
#

Hi everyone, I've been implementing some custom editors for some of my components using handles and to make things look a bit clearer I was thinking of using images, for both the buttons and as labels.

The problem I am having is that I can't find anything that can do this with either Handles or Gizmos online. The closest I came to was this https://discussions.unity.com/t/is-there-a-way-to-draw-a-custom-image-to-a-handle-in-a-custom-editor-like-you-can-for-gizmos/152318 however trying this nothing appears.

Texture _image = Resources.Load<Texture>("Editor/Rail Dismount.png");
Handles.Label(curveStart, _image);

Simuarly with Handles.Button, from how I understand its the cap function that determins behaviour and visuals. However the documentation page on this is pretty much useless in terms of how you should go about actually using it to render graphics (or do anything custom really) https://docs.unity3d.com/ScriptReference/Handles.CapFunction.html.

Any help on this would be appriciated for both the buttons and the labels.

elfin gorge
# elfin gorge Hi everyone, I've been implementing some custom editors for some of my component...

^^^
Sorry, just replying to my previous post, I figured out how to do the label approach using

Vector3 screenPoint = sceneCamera.WorldToScreenPoint(position);
GUI.DrawTexture(new Rect(screenPoint.x - 50, sceneCamera.pixelHeight - screenPoint.y - 50, 100, 100), _targetScript._texture);

This doesnt' work with scaling the size of the image based on distance but that shouldn't be to hard to do now. If anyone knows how to do this in the intended way for the buttons I would still apreciate the help but for now I think I will just draw images below the buttons themselves using this method.

gloomy chasm
rugged atlas
#

I want to apply arcgui similar to Platform effector 2 editor to my Hook script, what can I do?

waxen sandal
rugged atlas
#

Thank you. I'll give it a try.

pure coral
#

Im trying to understand how to incorporate undo / redo with adding an list element that i bind to a ListView, the problem i am facing is that when i undo after adding an element then i get a SerializedProperty has disappeared exception

#

do you guys just avoid having undo on adding elements?

#

(i am atm using Undo.recordObject for my logic, cause applying the add through the serialized property doesnt allow for the listview to update on undo for some reason)

rugged atlas
#
using UnityEditor;
using UnityEngine;

namespace AlephStudio.AlongTheColorHorizon.Editor {
    #if UNITY_EDITOR
    [CustomEditor(typeof(Hook))]
    public class HookEditor : UnityEditor.Editor {
        private const float Radius = 3.0f;

        // 유니티 에디터 OnSceneGUI 콜백 메서드.
        private void OnSceneGUI() {
            Hook t = target as Hook;
            if (!t) return;
            
            Transform tTransform = t.transform;
            Handles.color = new Color(0f, 1f, 1f, 0.2f);
            Handles.DrawSolidArc(tTransform.position, tTransform.forward, tTransform.right, t.Angle, Radius);
        }
    }
    #endif
}

Like the second video, I want the arc to spread out widely, not clockwise or counterclockwise. What should I do UnityChanHuh

#

only way, adjust from normal vector?

waxen sandal
#

Yeah adjust your start vector

rugged atlas
#
// Copyright (c) AlephStudio. All rights reserved.

using UnityEditor;
using UnityEngine;

namespace AlephStudio.AlongTheColorHorizon.Editor {
    #if UNITY_EDITOR
    [CustomEditor(typeof(Hook))]
    public class HookEditor : UnityEditor.Editor {
        private const float Radius = 2.0f;
        private const float Thickness = 1.0f;

        // 유니티 에디터 OnSceneGUI 콜백 메서드.
        private void OnSceneGUI() {
            Hook t = target as Hook;
            if (!t) return;
            
            Transform tTransform = t.transform;
            float halfAngle = t.SurfaceArc * 0.5f;
            Vector3 center = tTransform.position;
            Vector3 normal = tTransform.forward;
            Vector3 from = tTransform.right;
            
            Handles.color = new Color(0f, 1f, 1f, 0.1f);
            Handles.DrawSolidArc(center, normal, from, halfAngle, Radius);
            Handles.DrawSolidArc(center, -normal, from, halfAngle, Radius);
            
            Handles.color = new Color(0f, 1f, 1f, 0.5f);
            Handles.DrawWireArc(center, normal, from, halfAngle, Radius, Thickness);
            Handles.DrawWireArc(center, -normal, from, halfAngle, Radius, Thickness);
        }
    }
    #endif
}

I tried many things, but as a result, I solved the problem by combining two arcs into one arc. I really appreciate your help.

lapis pendant
#

Is there something like a FormerlySerializedAsType attribute? Where I can define a new and old type, and maybe even pass in a callback for a conversion strategy if deemed necessary?

pure coral
real spindle
#

Would be neat to have that for types

lapis pendant
#

I'm really open to any 3rd party things for that

#

Would make me have to write less code, but eh...

gloomy chasm
pure coral
#

@gloomy chasm do you happen to know how to incorporate listview undo with serialized properties?
I keep getting on undo (through now only serialized property writing) a "serialized property has disappeared!" error on undo / redo

#

atm i just have a simple button that does

listProperty.arraySize++;
serializedObject.ApplyModifiedProperties();
#

On undo though for some reason i get that weird error so hm

gloomy chasm
pure coral
#

Bind is done through bindingPath for now, the error doesnt change if i use BindProperty() on the list property
And i define a bindItem / unbindItem callback that just handles visual bindings for children elements for each index

#

populate is done through the button i mentioned

gloomy chasm
pure coral
#

I have done that already

gloomy chasm
#

If you are on a LTS make sure you are on the latest too.

pure coral
#

2022.3 lts atm

#

latest release

#

(from unity hub)

gloomy chasm
#

Hmm... try simplifying it and not do any custom binding or MakeItem callbacks?

#

just listview.bindingPath and let it automatically handle it

pure coral
#

that is a lengthy process to solve this problem but it may be the only solution

#

ill consider it

#

but i would like to avoid spending half a week on it tbh with all the bugs that are bound to rise

#

ill make a post on unity forum o nit

gloomy chasm
#

As it could be some way you are accessing the SerializedProperties from there

pure coral
#

i am not talking about the process of removing bind item

#

i am talking about the process of carrying over my entire logic

#

from the BindItem callback

#

into a custom property drawer

#

binding into the root uxml asset doesnt work it seems

#

(i used binding paths on the uxml file to test)

gloomy chasm
#

I wasn't talking about doing that. I mean just trying to debug real quick to see if it is that part of the code that is causing the error on undo.

pure coral
#

oh

#

testing atm

gloomy chasm
#

It could be you are trying to access something 'incorrectly' or it could be a actual bug with the ListView. I am just trying to figure out which. So if we temporarily comment out your code, that can gives us a better idea of where the error is coming from as if it still happens we can rule out that it is coming from your binding code

pure coral
#

This doesnt occur with bind item commented out

#

This doesnt occur on lts 2021 either from testing (with bind item on)

#

this does occur consistently across 3 versions of 2022 though

#

its actually buffling that this error occurs and it seems that even if on unbindItem i remove the binding through either changing the path or using UnBind this error happens one step before in the stack trace (atleast rider breaks before unbind gets called)

#

but this only occurs on 2022 which is a target release platform for me

#

so maybe i should make a unity forum post after all

hoary grove
#

Does anyone have a Editor Extentsion that is sort of like... a window where I can have Prefabs, that can be easily viewed and dropped into a scene?

gloomy chasm
hoary grove
#

Preferably Free, but I'd take a peak at paid options as well.

#

(I can sort of fake it by legit just having a second project window open, with it set to Two Col + Scale up on it, but it looks ugly)

gloomy chasm
# hoary grove Preferably Free, but I'd take a peak at paid options as well.

Nothing comes to mind, you probably would want to look for "Favorite" or "bookmark" type of extension. I did a quick look on github but didn't see any recent ones. For a paid ones there is Smart Library on the asset store which lets you create collections of any type of asset (and drag prefabs in the scene). I am biased as it is mine though haha.
There is also a number of popular bookmark and favorite assets that are paid.

naive thorn
#

how would I draw all of the properties of a serializable class without providing a SerializedProperty?

#

in my case right now im trying to draw the propertydrawer of some type based on an enum value, sort of like this:

#

heres pretty much what im trying to do

#

not entirely sure if theres a better way to do this, where i want to serialize a different class based on some enum (objectiveType is the enum), so for now Im just serializing/deserializing the class as a json

bright raft
#

Hey I've got a plugin that won't run in the editor, it only runs on an android / iphone / apple device. I would like to have it run on the windows editor, is there any way for me to fake it so it thinks it's running on another device?

queen wharf
twin dawn
queen wharf
#

im dumb nevermind

#

i did not realise component and monobehaviour where seperate

#

my bbbbbb

#

tyvm

barren moat
#

Is there a function to open an asset, similarly to if you double clicked it in the project view?

waxen sandal
naive thorn
#

not sure if i was doing something wrong but i could never have the values actually display in the inspector (which according to online is intended? unless its part of a list or something)

waxen sandal
#

Yeah you should be able to do that

#

Might need custom drawing code though

#

It's a bit of a shame that the editor side of serializereference is basically undocumented

#

Basically, you should be able to set managedReferenceValue to your object then use FindPropertyRelative (or iterate over it's children to draw them)

naive thorn
#

hmm, i might try that after and see what happens

#

i ended up just brute forcing my way through and just manually grabbed all of the serializable fields, then drew their respective fields (sort of like how unity already does internally)

#

but also to use find property relative id have to read all of the serializable fields anyways right (if im using it with serialiereference)?

visual stag
#

SerializeReference fields draw themselves just fine when something's assigned, but their drawer shows nothing when null

#

so if you wanted to tie it to an enum it'd be as easy as assigning to managedReferenceValue and using a PropertyField on its property

naive thorn
#

ill try again after and post my results here, earlier i tried manually assigning the field (and confirmed it was assigned via the asset file) but it was still showing nothing for me

#

for now my solution is dirty but looks a bit like this:

#

which is drawn from here: (also parametersObject is serialize/deserialized from a json)

visual stag
naive thorn
#

i know how it looks

#

im literally just rewriting what unity does

visual stag
#

Just to answer the original question kinda badly lol: it's not really that well integrated yet, but the Properties API that used to be https://docs.unity3d.com/Packages/com.unity.properties.ui@1.1/manual/index.html but is now... half-integrated with the entities package...? I think will be a part of the editor core and will allow you to draw any class fairly easily. In my ECS project I pulled some of that code out to be accessible, and I can draw any C# object without it being serialized, and it's super cool 😎

#

It's a whole other nightmare to work out what's going on with the whole thing though, sadly it'll probably have to wait to unity 7 hahah

#

in the meantime just assigning it to a SerializeReference field and drawing that is the best way if you can do it

naive thorn
#

unity unfinished packages Sadge but it does look pretty cool, ill def see whats going on with it

peak bloom
visual stag
#

Not that I know of? I use my own drawer, but I am almost certain I didn't implement it to draw the property

#

Seeing as it's a decorator drawer

peak bloom
#

ah I see

#

I misunderstood the statement

tacit hearth
#

Hey everyone! I reset my computer and when I checked my Unity editor, I noticed that I lost my color swatches and play mode color, but my editor layout stayed the same. How do I get my swatches back? Thanks!

muted cave
#

How do I draw a custom drawer from inside another custom drawer?
I have a serializable class that contains another serializable class. How can I expose the fields of the contained class in the inspector?

gloomy chasm
muted cave
gloomy chasm
muted cave
#

ah jesus I had an enum between that and the class name

lyric garden
#

Hey guys, I have this really weird behavior when working with edges in the GraphView. My Graph gets rebuild/reloaded every time I select another scriptable Object. After a change in code or reopening the whole editor window, the edges are completely fine, even when they were broken before, but after the first reload, all the edges break and are no longer connected with the nodes.
But there is no difference when the graph gets generated for the first, second or X time. Do you have any idea what might cause this behavior?
I generate the Edges with:

private void CreateEdgeView(DialogueNodeView parentView, DialogueNodeView childView)
{
    Edge edgeView = parentView.OutputPort.ConnectTo(childView.InputPort);
    edgeView.output.Connect(edgeView);
    edgeView.input.Connect(edgeView);
    AddElement(edgeView);
}

Edit:
So after some further testing, I can say that the error is somewhere within the graphView itself. When I delete the graphElements with

graphViewChanged -= OnGraphViewChanged;
DeleteElements(graphElements);
graphViewChanged += OnGraphViewChanged;

the elements are deleted correctly, leaving me with 0 Elements in graphElements. But somewhere it keeps some data that causes my edges to freak out.
Because when I destroy and recreate the graphview component instead of just deleting its elements, it works.

So do you guys know what data might cause this or what I could be doing wrong? Recreating the graphview every time is a very sketchy solution to this. 😅

And an image showing the problem (I moved the nodes in the second image, they start in the same place shown in the first image):

errant shale
#
  • I find myself in a need to draw a type inspector in property drawer and struggle to find a way to do this. The inspector code is licensed and cannot be copy-pasted into my property drawer, so i have to work it around in this awful way. Any ideas?
gloomy chasm
errant shale
#
  • Yes, exactly
gloomy chasm
errant shale
#
  • It's imgui. Switching to uitk is an option, but i'd like to keep things the old way for consistency with the rest of the project
gloomy chasm
north sphinx
#

hmm. I'm trying to modify TimelineAsset in a way - replace some sub SOs referenced inside.

#
            foreach (var guid in AssetDatabase.FindAssets($"t:{nameof(TimelineAsset)}"))
            {
                var assetPath = AssetDatabase.GUIDToAssetPath(guid);
                var asset = AssetDatabase.LoadAssetAtPath<TimelineAsset>(assetPath);
                var dirty = false;
                foreach (var rootTrack in asset.GetRootTracks())
                {
                    if (rootTrack is not AnimationTrack animationTrack)
                    {
                        continue;
                    }

                    var clips = animationTrack.GetClips();
                    foreach (var timelineClip in clips)
                    {
                        if (timelineClip.asset is AnimationPlayableAsset playableAsset and not NewAnimationPlayable)
                        {
                            var newAnimationPlayable = CreateInstance<NewAnimationPlayable>();
                            newAnimationPlayable.clip = playableAsset.clip;
                            timelineClip.asset = newAnimationPlayable;

                            var prevPath = AssetDatabase.GetAssetPath(playableAsset);

                            dirty = true;
                        }
                    }
                }
                 AssetDatabase.SaveAssetIfDirty(asset);
            }
#

but nothing gets changed here

#

maybe I can make asset dirty manually somehow

#

or maybe CreateInstance<NewAnimationPlayable>(); this needs to be saved somehow differently?

#

or created?

#

actually, it does change

#

but to null

gloomy chasm
#

Also you are setting the asset to reference a instance of NewAnimationPlayable

north sphinx
#

yeah, so that's what I don't get - how to save it as asset

#

as part of timeline asset

#

(not as some hanging asset)

gloomy chasm
#

AssetDatabase.AddObject

#

Or AssetDatabase.AddSubAsset or something like that

north sphinx
#

oh, let's see

#

oh yeah

#

that works

#

nice

#

I guess I'd need to remove previous asset

#

or will unity remove it on it's own?

#

unreferenced hanging sub asset

gloomy chasm
#

Need to remove it yourself

pure coral
#

@gloomy chasm ty for the help

#

i managed to make it into a proper issue after a bug report

#

Its a 2022 regression only

#

2021 and 2023 dont have it iirc

gloomy chasm
#

Yeah they rewrote the ListView in 2022, so not surprising.

pure coral
#

But why does that not happen in 2023? purely curiosity

gloomy chasm
#

Basically every major version of Unity that has the ListView in it has seen a mid to very large refactor to the ListView

pure coral
#

i wish ugui wasnt chinese to my eyes so i would avoid this

#

but ui toolkit allows me to make so much cleaner stuff

gloomy chasm
#

Yeah UIToolkit is so much nicer. Especially when doing any type of styling.

rain depot
#

I want to hide the field from the ScriptableWizard GUI (no auto draw of public/[SerializeField] variables) whilst also allowing the field to be available for construction as a SerializedObject from code inside this wizard - is that possible at all?

whole steppe
#

trying to implement a coroutine handler that works in the Editor for the fun of it,
however, it's not so fun when I'm completely lost...

here's what the current implementation looks like:

public sealed class EditorCoroutine : IDisposable
{
    private readonly IEnumerator enumerator;

    private EditorCoroutine(IEnumerator enumerator) => this.enumerator = enumerator;

    public static EditorCoroutine Start(IEnumerator routine)
    {
        EditorCoroutine co = new(routine ?? throw new ArgumentNullException(nameof(routine)));
        EditorApplication.update += co.Update;
        return co;
    }

    private void Update()
    {
        Debug.Log("Aleph Call");
        if (MoveNext() is false) Stop();
    }

    public bool MoveNext()
    {
        return enumerator.Current switch
        {
            CustomYieldInstruction waitress => waitress.keepWaiting,
            AsyncOperation instruct => instruct.isDone is false,
            _ => enumerator.MoveNext()
        };
    }

    public void Stop() => EditorApplication.update -= Update;

    public void Dispose()
    {
        Stop();
        enumerator.Reset();
        GC.SuppressFinalize(this);
    }
}```
it runs, until it doesn't...

it never reaches this line:```
Debug.Log("Waiting For An Asynchronous Web GET Request Operation...");```
here```cs
internal static class Foo
{
    [MenuItem("Foo/Bar")]
    private static void Bar() => EditorCoroutine.Start(Baz());

    private static IEnumerator Baz()
    {
        Debug.Log("Coroutine Started!");

        Debug.Log("Waiting For 1,65 Seconds...");
        yield return new WaitForSecondsRealtime(1.65F);

        Debug.Log("Waiting For An Asynchronous Web GET Request Operation...");
        var client = UnityWebRequest.Get("https://docs.unity3d.com/Manual/com.unity.editorcoroutines.html");
        yield return client.SendWebRequest();
        Debug.Log($"Response Content: {client.downloadHandler.text}");

        Debug.Log("Coroutine Finished!");
    }
}```
gloomy chasm
rain depot
gloomy chasm
rain depot
#

would be easier if there was not already ScriptableWizard with 2000 lines of code...

#

but i get it 😛

gloomy chasm
whole steppe
# gloomy chasm Hmm, does `Time.realtimeSinceStartup` work properly in the editor outside of pla...

the docs:

The iterator functions passed to Editor Coroutines do not support yielding any of the instruction classes present inside the Unity Scripting API (e.g., WaitForSeconds, WaitForEndOfFrame), except for the CustomYieldInstruction derived classes with the MoveNext method implemented.

the src:

public class WaitForSecondsRealtime : CustomYieldInstruction

so I guess yeah?

I mean, it does work, the thing does wait, but does it work properly? that I can't answer unfortunately...

gloomy chasm
whole steppe
#

I'd put this in the Update method yeah?

gloomy chasm
whole steppe
#

oh honey... you didn't need to do that just for me, aww... 😳

gloomy chasm
#

Haha, seemed easier than trying to explain it. Does the time properly update?

whole steppe
#

does this answer your question?

#

I did this instead:cs [InitializeOnLoadMethod] private static void TimeEditorTest() => EditorApplication.update += () => Debug.Log($"Time: {Time.realtimeSinceStartup}");
'cause I'm neat 🤵‍♂️

gloomy chasm
#

Yeah that looks right. Not sure...

#

I guess I would say to copy-paste the WaitForSecondsRealtime source code and then use that instead so you can either set breakpoints and step through the code or put debug.logs in so you can see waht it is doing

#

Sorry, that is all I got now for ideas @whole steppe

whole steppe
#

I don't remember having an employee with such a username

what I'm saying is: what are you apologizing for ?!1 lol XD

#

you're all good honey ❤️

gloomy chasm
#

Haha, well good luck. And let use know what it was, if you manage to figure it out!

whole steppe
#

well, debugging the WaitForSecondsRealtime doesn't seem to be a good idea apparently,
as Time.realtimeSinceStartup doesn't have time, for us...

it keeps incrementing!1 in debug mode?!

dear Unity, what's wrong with you?

north sphinx
#

Is there a way to show choice between objects without implementing custom windows?

#

Basically, I want to do custom search and then open window with objects I specify

#

and then whatever is selected - I want returned in a callback of some sort or smth

whole steppe
north sphinx
#

not sure what it does even with docs tbf

#

oh

#

it's just selected objects

#

no

#

I need to search manually via AssetDatabase

#

and then call window

#

with results

#

while user just needs to select one

#

and once he does - I want to know which

whole steppe
#

something like this:```cs
var guids = AssetDatabase.FindAssets(@$"t:
{nameof(Texture2D)},
{nameof(AudioClip)}");

foreach (var guid in guids)
{
var path = AssetDatabase.GUIDToAssetPath(guid);
var type = AssetDatabase.GetMainAssetTypeAtPath(path);

switch (type.Name)
{
    case nameof(Texture2D):
        var texture = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
        /* TODO: ... */
        break;
    case nameof(AudioClip):
        var audio = AssetDatabase.LoadAssetAtPath<AudioClip>(path);
        /* TODO: ... */
        break;
}

}```

whole steppe
north sphinx
#

Just need user to select one

#

Via some ui

whole steppe
#

@north sphinx hmm, yeah... not sure how the pros do that in here...

however! I do be doing some reflection, therefore I know the existence of this little shy puppy UnityEditor.ObjectSelector!

with some reflection, you can set your chosen objects as the available ones in the window, then find out which one got selected fromt that class too!

gloomy chasm
# north sphinx Just need user to select one

If you just care about showing the user the names, you could just toss them in a dropdown menu.
If you are on 2022, you might be able to use the new Search based object picker window and have it do the search.
Those are basically your ownly options without going for a custom editor

snow pebble
#

any one know how unity draws grid lines in their scene view ?

#

dunno if their code for it is public or not

#

i want to override it and make my own

whole steppe
#

@snow pebble the SceneViewGrid.cs class seems promising?

I didn't really look deep into it, but from the nameof(It), I think we can infer something about it XD

whole steppe
#

I'd like to save a changed made to a Component, this is how I'm currently approaching that:

var component = Object.FindFirstObjectByType<ComponentType>();
component.field = value;

EditorUtility.SetDirty(component);
EditorSceneManager.SaveScene(component.gameObject.scene);

it works correctly, however! I find it annoying that Unity will keep asking whether the user would like to reload the scene or not due to saving...

is there a more straightforward method to do that? if not, is it possible to prevent Unity from showing the dialog box?

and... do I even need to worry about saving the change at all?

peak bloom
#

oh misread

#

thought it was asset

whole steppe
#

I guess EditorUtility.SetDirty would be enough, wouldn't it?

like... once set dirty, the change won't be lost right?

peak bloom
#

as long as you're saving your scene before closing it should be fine

whole steppe
peak bloom
#

I mean, that's what most of us want, no?

#

imagine saving without confirming but you've unwanted changes that can't be reverted, that would be hell

whole steppe
real spindle
elder wasp
#

How can I add support for transfering an object to be another type? For example, if you have a list field on a component, add items, and switch to array the data will not be lost

#

I have a wrapper of a list, and I would like that, when i switch from a list ot the wrapper, the data to be still accessible

#

actually this is to overwrite/overcome the property drawer that unity has for Lists, which is shit. When pressing + i would expect for a new object to be generated and the constructor to be called, but in unity for some reason, it duplicates the previous if any, otherwise creates one without anything

surreal flume
elder wasp
#

completely

#

If you want, that script with this that I made can replace the list with the new class and have the right functionality

#

Now I just want to have the right data and that would be it

surreal flume
#

I didn't really solve it, it sort of a hack I'm not proud of lol. Whenever the list changes I assign unique Ids and check them against some set so I know when something added was new. It's nasty

surreal flume
north sphinx
#

Hmmm. I'm looking for a pretty complicated functionality:
I need to create a prefab variant for ANY prefab with specific label, with a bunch of components removed via my script.
But at the same time I need it so variants get removed if original prefab is destroyed.

#

I was thinking about asset importer

#

but I'm lost on removing variant when original prefab gets destroyed

#

oh, removing variant should also happen if original prefab loses label

#

if it gets removed, I need to cleanup variant as well

elder wasp
surreal flume
elder wasp
#

mmmm, yeah I guess I could do that, manually copying it

#

I have the project before commit so lets see

surreal flume
# elder wasp mmmm, yeah I guess I could do that, manually copying it

And if that doesn't work there might be another option where you keep the value serialized as a list and either convert it manually whenever you need to access it. Or use ISerializationCallbackReceiver. But that might be too much. Either way hope you figure it out. And thanks for the property drawer source, I could probably use that

elder wasp
elder wasp
#

How can i make a list of abstract class serialized with [SerializedField]? I know of SerializeReference, but I don't want to transform that data into references, but individual objects

short tiger
elder wasp
#

The problem is when having a list and pressing the option, Duplicate element, where it ends up with the same object twice

waxen sandal
#

Draw your own list and duplicate the item when duplicate is called

elder wasp
#

Yup, but there's no duplicate call, or at least i cannot find the callback

#

There's a callback for on changed, and i can use it to check if two items have the same id

gloomy chasm
#

Also, I think there is a managedReferenceId property or something like that you could also use. But I could be misremembering

north sphinx
#

Hmmm, I can't remove component that on which other components depend via RequireComponent

#

is there a way to recursively destroy all of them?

gloomy chasm
north sphinx
#

remove them

#

and then until original one is destroyed as well

gloomy chasm
#

Ahh, gotta do it manually

north sphinx
#

via checking attribute you mean?

gloomy chasm
#

yup

north sphinx
gloomy chasm
#

I assume you mean you want to remove one component and then remove any other components that were added due to a [RequireComponent] attribute on the first component?

north sphinx
#

don't care for order

#

just want them all removed

#

if X components requires Y, then I want them both destroyed

gloomy chasm
#
public static void RemoveComponent(Component target)
{
  var requiredAtts= target.GetType.GetCustomAttributes<RequireComponentAttribute>();
  var components = new Component[requiredAtts.Length];

  for (.. components.Length .. )
  {
        components [i] = target.GetComponent(requiredAtts[i].type);
  }

   Object.Destroy(target);
   forr(.. components.Length ..)
   {
    RemoveComponent(components[i]);
    }
}
#

Something like that I think. Didn't fill in the for loops cause I am lazy

#

Wanna add some null checks too probably

north sphinx
#

it'll be even more complicated

#

because I have multiple layers of those

#

so first I need a pass where I collect all those

#

then I found out which are dependable

#

then I remove those that are not dependable first, but that on which others depend

#

and then do that in a while loop

#

until all such hierarchies are done

#

and only then I can clear the rest

gloomy chasm
#

Do you mean a different type of 'depend on' than the attribute?

north sphinx
#

no

#

just multiple components

#

X depends on Y

#

Y depends on Z

#

Z depends on A

#

and etc

gloomy chasm
#

Ahh, justt gotta call the method recrusivly instead

north sphinx
#

yep

#

hopefully not too slow

#

I don't want to cripple editor

gloomy chasm
#

Just updated the code to be recursive I think

north sphinx
#
                list.Clear();
                prefabVariant.GetComponentsInChildren(list);

                while (list.Count > 0)
                {
                    for (var index = list.Count - 1; index >= 0; index--)
                    {
                        var monoBehaviour = list[index];
                        if (monoBehaviour == null)
                        {
                            list.RemoveAt(index);
                            continue;
                        }

                        var fullName = monoBehaviour.GetType().FullName;
                        if (fullName != null && fullName.Contains("Authoring"))
                        {
                            Object.DestroyImmediate(monoBehaviour);
                            if (monoBehaviour == null)
                            {
                                list.RemoveAt(index);
                            }
                        }
                        else
                        {
                            list.RemoveAt(index);
                        }
                    }
                }
#

tbf

#

this works even better

#

but it errors

#

😅

gloomy chasm
#

Then not really better is it 😛

north sphinx
#

wish I could supress

north sphinx
#

and keeps code much simpler

#

but you know

#

stuped native errors

gloomy chasm
#

Can you not get them with try/catch?

north sphinx
#

nah

#

they are not exceptions

gloomy chasm
#

Ahh it is a Debug.Error

north sphinx
#

and they are also inside of c++ side

gloomy chasm
#

Yeah

north sphinx
#

so even if I wanted, I wouldn't be able to just copy paste code

gloomy chasm
north sphinx
#

until all of them are removed

#

if it wasn't removed

#

it's not null

#

so no matter how many hierarchies, I keep trying to remove each until I'm empty

gloomy chasm
#

oh I see... yeah I don't see how that is better. My implementation is explicit, and doesn't throw errors. But to each their own!

elder wasp
north sphinx
wheat tulip
#

someone can help me with a code

north sphinx
#

otherwise it's much cleaner than going into reflection zone yourself

wheat tulip
gloomy chasm
gloomy chasm
wheat tulip
#

oh

gloomy chasm
elder wasp
north sphinx
#

but because I need to make multiple passes

#

to ensure I remove something that nothing depends on

#

while this something doesn't even know what depends on it

elder wasp
#

That's what i was looking at beforehand, but is there a method to get a new id generated by unity?

gloomy chasm
#

(I think. Never used it my self)

elder wasp
#

That's to set it, but i still need the id, do i just pass the random value?

#

Like i can generate myself the int64 value, but maybe unity has a function that provides it

#

(i couldn't find it)

north sphinx
#
                var map = new Dictionary<Type, List<Type>>();
                for (var index = list.Count - 1; index >= 0; index--)
                {
                    var monoBehaviour = list[index];
                    if (monoBehaviour == null)
                    {
                        list.RemoveAt(index);
                        continue;
                    }

                    var type = monoBehaviour.GetType();
                    var attributes = type.GetCustomAttributes(typeof(RequireComponent), true);
                    if (attributes.Length == 0)
                    {
                        continue;
                    }

                    if (!map.TryGetValue(type, out var depends))
                    {
                        depends = new List<Type>();
                        map[type] = depends;
                    }

                    foreach (var attribute in attributes)
                    {
                        var requirement = (RequireComponent)attribute;
                        TryAdd(requirement.m_Type0);
                        TryAdd(requirement.m_Type1);
                        TryAdd(requirement.m_Type2);
                        continue;

                        void TryAdd(Type dependsOn)
                        {
                            if (dependsOn != null)
                            {
                                depends.Add(dependsOn);
                            }
                        }
                    }
                }
#

so what I have so far

#

is map of raw type -> dependencies list

#

so I guess I need to loop this dictionary lists and check them against dictionary, if there is nothing - destroy those

#

and remove from list

gloomy chasm
#

I am confused... what is wrong with my implementation?

north sphinx
#

it will error

gloomy chasm
#

When?

north sphinx
#

when it tries to remove component that depends on something else

gloomy chasm
#

Or does it error if you remove B first and then A?

north sphinx
#

yeah

#

atually

#

if I switch order

#

maybe it's ok

gloomy chasm
#

Yeah my code doesn't have that issue

north sphinx
#

oh wait

gloomy chasm
#

The parent is removed first

north sphinx
#

no

#

your code is faulty

#

because if first element you call RemoveComponent on

#

does not have requirements

#

it will be removed

#

and it will error

#

because that component while not having any requirements

#

is what other components rely on

#

even if it does have requirmenets

#

it will error, if it itself is dependency for some other components

#

ok, so I need inversed map...

blissful burrow
#

does anyone know if there's a way to set the icon of an EditorToolContext in a path-agnostic way?

#

the canonical way to set the icon is with an attribute on the type [Icon("Assets/Icon.png")], which means it's got a hardcoded path, which means users can't put my plugin wherever they want

gloomy chasm
#

The easiest way is to make it a package instead of having it in the assets folder.

blissful burrow
#

yeah but I don't want it to be a package

gloomy chasm
#

Fair enough. Then... no 😛
The only other option is to either load and assign it in the script or to convert it to a byte array and hard code the array in to a script

blissful burrow
#

how would I assign it in a script?

gloomy chasm
#

The way I do it is using a utility method where I use the [CallerFilePath] attribute and parse it to get the path to my asset/package folder and then from there get the icon
Texture2D LoadTexture(string pathRelativeToMypackage, [CallerFilePath] string pathToScript = "");

#

THe tool context has a icon property which you can assign it to.

blissful burrow
#

I'm, not finding that icon property

gloomy chasm
#

Hmm, let me check my code...

blissful burrow
#

I think EditorWindows have a property like that, but not tool contexts it seems

gloomy chasm
#

I can't remember, IconContent might be able to get stuff from a Resources folder...

blissful burrow
#

ah gosh okay ;-;

#

that dictionary might be the way to go

#

I just wish the Icon attribute let me use a GUID lol

gloomy chasm
#

Haha yeah, that would be nice.

blissful burrow
#

weh! I can't seem to be able to load EditorToolUtility using reflection

#

is it in some weird assembly?

#

I feel like these should be in the same one
Type edToolUtil = typeof(EditorTool).Assembly.GetType( "EditorToolUtility", true );

waxen sandal
#
    private static System.Reflection.Assembly editorAssembly = System.Reflection.Assembly.Load("UnityEditor");
    private static System.Type editorToolUtilityType = editorAssembly.GetType("UnityEditor.EditorTools.EditorToolUtility");```
Is apparently the trick
blissful burrow
#

oh right I just needed the full type name

#

Type edToolUtil = typeof(Handles).Assembly.GetType( "UnityEditor.EditorTools.EditorToolUtility" );
works too

waxen sandal
#

Type.GetType("UnityEditor.EditorTools.EditorToolUtility, UnityEditor") or something like that prob works too

blissful burrow
#

well, got it all to call now but it doesn't work tired

#

I'm guessing unity clears it with the force reload thing

#

its joever

#

last resort hack would be to tap into the toolbar GUI I guess lol

#

maybe I'll just leave it for now

north sphinx
#

Is there an API to get source of prefab variant?

tough sonnet
#

how can i get all materials with the default lit shader and replace it with my custom shader ? i tried it like this but nothing happens when i call that functions

north sphinx
#

need to call afterwards

tough sonnet
peak bloom
#

make sure you're not getting the default materials. You can't change their settings/properties if they're

#

test it by making your own Material, and get that material you just created and change it, see what'll happen

tough sonnet
#

i forgot spaces in the "Universal Render Pipeline/Lit"

#

and the e

north sphinx
#

Is there a way to get asset hash? Checksum for example

#

so when asset changes, I want this value to change as well

north sphinx
#

looks like it

gloomy chasm
#

I think SerializedObject has one, I know SerializedProperty does. But Navi's looks better haha

gloomy chasm
gloomy chasm
#

Yeah the contentHash is what I was thinking of. Though for SerializedObject there is an internal uint objectVersion property

#

Probably serialization version though

waxen sandal
#

I was looking at docs but I'm not sure objectVersion is what you're thinknig it is

#

Also there's probabyl a cache version hash somewhere

north sphinx
#

how would I get userData from .meta file if I know guid/assetPath only?

north sphinx
#

how do I get one

north sphinx
#

thanks

blissful burrow
#

okay so I may be doing illegal things but

#

is there a way to, not have this happen, after modifying an asset?

#

this is when selecting a scriptable object I just created from code

#

and after modifying its GUID from code

gloomy chasm
peak bloom
#

to get the last write time typically in plain c# you'd just do System.IO.File.GetLastWriteTime

#

but then again this is Unity, I'd not be surprised if they're doing internal caching for their stuff

#

wait, pretty sure they added last modified time in the meta file, or proly I'm just tripping here

floral tangle
#

is there a flag/filter or other mechanism in the editor to search only for all scripts that are referenced in the current hierarchy?

e.g. I'd like to find all scripts used by a particular prefab with several dozen objects.

north sphinx
#

I'm looking for a way to open custom hierarchy window just for a specific prefab. And potentially embed into my custom window (hierarchy + inspector for selected prefab via script, without actually affecting current selection). Is there a way to do with built in hierarchy or do I need custom solution for it?

#

I guess worst case - I just make tree view out of game object hierarchy