#↕️┃editor-extensions
1 messages · Page 21 of 1
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
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.
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 :/
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
You could use OnSceneGUI and Handles.DrawLine
Though handles are a bit expensive so another option is to draw it with a repeating GUI texture
OnSceneGui + Handles.BeginGUI/EndGUI + GUI.DrawTexture
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?
Use initialize on load to register
But you're probably not allowed to do asset manipulation in that callback
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
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
This method is soooo ugly
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
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
Yes, check the answer in the link I provided
Looking at it
rn doing this
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
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
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?
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
You using htis? https://docs.unity3d.com/ScriptReference/Editor.OnSceneGUI.html
Ah
shouldn't make a difference though which way i do it
duringSeneGui event is the one i use
Wonder if it makes a difference if you consume in beforeSceneGui?
Not sure if input works there though
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
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
thank you :)
not sure if this is 100% what you were looking for but it might be helpful https://docs.unity3d.com/ScriptReference/AssetPostprocessor.html
absolutely not it
woops
Really unsure what you mean here
You access it like any other field
And you can draw with ObjectField
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)
I mean, outside of it's context
but I already figured that I can serialize to EditorWindow
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
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.
I am not sure if this would help you, but I had low frame rate in editor when running in VR, and closing opened probuilder windows and setting the play mode to "Maximize On Play" increased frame rate a bit for me
Though the allocation thing is probably the root cause of it and I'd have no idea on how to debug that
not quite what you asked for best I got for you is: https://docs.unity3d.com/ScriptReference/Undo.html
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/
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();
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.
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?
That is likely not the solution at all.
Solution is simple someone from Unity messed the arguments, now -batchmode need to be the first argument now.
Try calling serializedObject.ApplyModifiedProperties() before calling Bind(). I don't know how binding works internally but this is something I started doing to avoid those invalid data errors
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.
Maybe you could do the same thing like var tempInt = processedProperty.intValue (or whatever value type you're using). I don't know if that's what you're looking for or if that would solve your problem though
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...
After some testing, it turned out SerializedProperties already has some sort of protection built in (looks like my problem was caused by something else). The problem solved itself. But thanks for the reply.
I was trying to achieve protection similar to the trick from the following video:
https://youtu.be/zkr6LU3kHE4?feature=shared&t=485
Any idea how to handle Undo with static variables?
i cant find any info on the subject thats why im curious
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)
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.
Maybe try visualElement.layout, I don't know if it's more or less accurate than contentRect though
it's still giving me 300
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
What's the (x,y) of visualElement.layout btw? Is it (0, 0) as expected?
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
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!
nice, glad you fixed it, and np
Is there any way to stop EditorGUI.Popup from interpreting slashes as sub-menus?
Use different slashes
the slashes are part of the values
oh, could I just use UITK instead?
it's a property drawer
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);
I don't know why I get an error here when I put the c# extension
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;`
Thanks. 🙇♂️
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
Looking through Unity Cs Reference, I'm seeing some scripts do this check:
evt.keyCode == KeyCode.Tab || evt.character == '\t'
Maybe sometimes keyCode is assigned, while other times character is assigned instead.
oh boy, now it triggers consistently, but twice every time instead, lol
😨 are you also still checking if it's EventType.KeyDown?
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
scary
maybe consuming the tab character allows you to trigger it again
What if you just check character then?
yeah, that works consistently

yep, as long as I consume the event as well, it works perfectly
Maybe something to keep in mind, in case you start getting bug reports from people on Linux:
https://github.com/Unity-Technologies/UnityCsReference/blob/b7836efd9f4a79fdb74565f599cfce5fd7b5c984/Modules/UIElements/Core/Controls/InputField/KeyboardTextEditor.cs#L97
neat
Does this not prevent text fields from reading the tab character?
depends on who eats it first I suppose
in my case it's for scene view interaction input, not for proper GUI
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
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?
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?
I'm not using unity version control
It's not just for Unity's version control
I've used some of these with perforce before iirc
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.
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
Meaning it can't have [Range(...), Postfix(...)] for example?
Yeah
(You can theoretically build a system that allows it, but it's hard to define the edge cases)
Alright, thank you
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?
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);
});
is there any way to show an error state in a property drawer?
Like, a HelpBox?
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?
ok I figured it out, not great but it will do
there's still a problem - I don't want to just blindly revert changes to file, I want to store its state before I start build and then restore it after build is done
you can give the box custom heights, if you want some custom error box you will have to make a GUIstyle yourself
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?
it might have something to do with the order of the attribute
something from your script might override the other attribute logic
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 
I've ran into this before, but I just accepted it being a little fucked
how to open a properties window if i have the asset as a variable ?
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 } );
}
}
}
Is there a way to make a separate workspace? Like when you open a prefab.
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
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?
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
Nope, not possible (well, you might be able to using a ViewContainer, and some injection. But would be unstable and may as well just use a editor window at that point)
If you just want a custom tooltip, you can just use a EditorWindow for that. It is what the normal tooltip is if memory serves
good to know thanks! im assuming an editor window can be styled without a border and stuff?
Yeah, you can use window.ShowAsDropdown or window.ShowPopup
Once they change the underlying api or method name in this case your code will fail
if you're looking for reliability(like you said), then don't do reflection.
Based on my experience, they rarely changed editor apis and it makes sense to use reflection for custom editors if there's no better alternatives
the thing is it's more resilient to internal API changes because if they add another method with same name but different parameters this will also fail
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
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?
Any way to get odin inspector attributes working on NetworkBehaviour?
Ask in the odin discord?
ok?
People here are mostly writing their own editors instead of using odin, thus likely do not know
No to mention, the developers are very active in that server.
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
Why cant you use a PropertyDrawer ?
https://docs.unity3d.com/ScriptReference/PropertyDrawer.html
Also, I know it is only and example, by you might want to use an enum with the flags attribute to enable multiselection.
[Flags]
public enum Layer
{
Layer1 = 1,
Layer2 = 2,
Layer3 = 4,
Layer4 = 8,
}
https://vintay.medium.com/enum-flags-in-unity-and-c-e8af3fee3fc0
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?
That woudld be pretty easy to test it out.
i know but im kinda in hurry and was hoping someone already knew the answer :V
You probably took as much time to write that to try it.
Oh you mean have the PropertyDrawer target the Struct directly rather than using PropertyDrawer with PropertyAtrribute. Damn yeah i guess i've just been creating so many custom attributes lately that i forgot you don't have to use PropertyDrawer only for attributes. Thanks @willow jackal i'll try it out
Haha yeah, works. i was waaay overcomplicating it. Thanks again!
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);
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
it looks like for some reason it isnt bound at all, so I would investigate this firstly
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
How are you initializing the PropertyField? I do "new PropertyField(SerializedProperty)" and then call propField.BindProperty(SerializedObject), and this works for me
I've tried both ways, but I'm creating it empty right now:
private readonly PropertyField _portField = new();
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?
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);
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)
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
So just throwing an idea out there, what are the values for message and output by checking the target object of serialized object?
They're both null
I wonder if it's not showing because it's null, idk
Oh, could you try settng it to empty?
Yeah
They are strings, so it's weird that it works for prefix when I use it through InspectorElement
OMG
Oh, it works for prefix but not the others?
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();
}
}
lol
The thing is, I want them to show up outside of InspectorElement, so I was hiding them
But this also impacts PropertyField
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
Yes, thank you for the help!
tbh yeah it was too obvious to think about XD its always the case haha
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
}
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
@surreal delta I didn't think reflection knew anything about comments? I need to extract comment strings from the source file itself
oh, i tought you were using some kind of reflection
Hmm, that is tricky. An idea that is a bit funky and not sure if it will work. You could try using [CallerFilePath] in the constructor of your CommentAttribute class. And in the constructor, cache the path in a property?
More importantly, how did you get your custom tooltip editor window to be transparent?? Or is that an artifact of the gif?
Good idea, thanks!
i think it's a gif artifact? looks opaque on my end 👀
Another option is to basically make a database of all the files. here is one implementation https://discussions.unity.com/t/c-find-class-file-path-for-any-class/81357/3
Dang, I was really hoping that you had a transparent editor window 😦
haha that would be sick 
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 :/
damn!
[CallerFilePath] works great! super cool
Oh sweet!
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");
}
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
@surreal flume Yep!
Right on the dot too! I was going based of the Docs themselves.. https://docs.unity3d.com/ScriptReference/PrefabUtility.InstantiatePrefab.html
Thanks alot! 
Nice, glad to help
Does DOtween count as editor extension or is this the wrong channel to ask doubt about it here
This channel is about developing extensions, not for help with someone elses extensions
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?
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
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
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.
Why are you not using SerializedProperty/SerializedObject, but instead bypassing them and using SetDirty?
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
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;
}
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?
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
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
Im 100% sure SerializeReference doesnt work with structs at all
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
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.
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.
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. 🤔
@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.
Or instead of path, a guid
Or use SessionState/EditorPrefs
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 
Serialized data in EditorWindows does persist across closing and reopening the editor
They just won't survive closing the window itself
Oh my god, I had it force clearing the data when CreateGUI ran since I was using test data 
Cool, I've been wondering if he's on this server and apparently he already promoted his video
well, thanks!
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 ?
[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
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...)
What is the state of GraphTool foundation? It doesn't even compile for me in the latest Unity in an empty project.
it's being developed internally, the latest package available to download won't work with recent unity versions
The answer is no by the way
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)
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 🥹 ?
.text?
Read the page and look for information. Text file in the editor needs to be TextAsset
it also says:
Text Assets are not intended to be used for text file generation at runtime.
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);
You are not using them at run time
This constructor creates a TextAsset, which is not the same as a plain text file. When saved to disk using the AssetDatabase class, the TextAsset should be saved with the .asset extension.
doing so doesn't yield the so-called plain text I want... 🥹
Because you must not used it correctly. But whatever, you found an alternative.
(plz, stop to use emoticon...)
yeah! I did! xd
(and plz, don't tell to not use emoticon emojis...)
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.
I'm guessing, just like animator states, UITK doesn't work for those
Ha ha, no
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
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;
}
}
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
AssetDatabase.OpenAsset(..) https://docs.unity3d.com/ScriptReference/AssetDatabase.OpenAsset.html
Unity automatically takes the first string field and puts it as the name of the element in the array.
Instead of changing the indent, try changing the position.x directly maybe?
I've tried that too but had no luck unfortunately.
hmm, what version of Unity?
2022.3.14
Might be a UITk thing messing with the IMGUI stuff 🤷♂️
Roger. I'll see about just creating the drawer with uitk
That would be my suggestion if you don't need to support IMGUI editors.
Just as a heads up, there is a bit of a bug still in regards to binding that you might run in to https://forum.unity.com/threads/child-inotifyvaluechanged-raises-parents-change-event-if-same-value-type.1459042/
Ok good to know. thanks for the callout 🙇
You're welcome, it caused me much pain haha
is SerializedProperty.FindPropertyRelative capable of finding non-public members?
It finds any serializable members
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")); // ... } }
Dictionaries are not serializable
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
oh! alright!
thanks for the info!
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?
thanks, alot....why i didnt realize that
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...
Thank you for not answering my question. I am perfectly capable of searching for tutorials myself.
ywc
GraphView obviously, the GTF solution isn't ready yet and trust me, GrapView will still be in Unity for years to come
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
It's like people saying imgui will disappear
But then they realize that animator doesn't support UITK at all
I see some ppl using UI builder with the graph view . . .
Ok based on this input GraphView it is 😀
Which is nice because now I can use this I think https://github.com/alelievr/NodeGraphProcessor
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:
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&
someone said something about it not being seralized, but i dont know what that means
int toolbarSelection = 0;
string[] toolbarStrings = { "Main Panel", "Build Panel" };
public override void OnInspectorGUI()
{
toolbarSelection = GUILayout.Toolbar(toolbarSelection, toolbarStrings);
switch (toolbarSelection)
{
case 0:
MainPanel();
break;
case 1:
BuildPanel();
break;
}
}
This is all I do on mine but it's been a while since I touched this project
What's this a custom editor of? You have that cropped out
not a custom editor, just an editor
okay, so the first line in OnInspectorGui is the the same as mine, and i dont need the switch statement, i just set a value, so it should work
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
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
i put [SerializeField] [HideInInspector] before my properties and it was still reverting
i guess i didnt need need [hideinispector] but whatever
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)
i also tried this but it was still resetting(asked ai)
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.)
Oh no no, just to clear up any miss understanding, they really don't. [SerializeField] makes it so the value of a field can be saved when it is changed. And [HideInInspector] simply notes whether a serialized field should be shown in the inspector.
First guess would be there is a custom editor for all MonoBeavhoiurs/ScriptableObjects.
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
it resulted in a bunch of errors and the ui breaking
Is there a place I can breakpoint to see the editor type?
Try using the IMGUIDebugger and pick a element that is drawn and look at the callstack
ughhh. NetworkBehaviourEditor is the culprit. not sure how much i can do about that 😭
Who is that from?
Ah, right, I guess by similar I mean you still serialize it regardless but having the ability to hide it from view is the bonus
Unity's NetcodeForGameObjects package
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
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
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
#↕️┃editor-extensions message
evrey discussion i find online on this matter is on a custom editor, with a target game object, but i dont have that.
Yeah, I would take a look to see how hard it would be, depending on what it is they are doing. You could maybe just copy paste it in to a IMGUIContainer and have the rest be UITk stuff
That looks fine to me 🤔
Are you setting the int anywhere else in the script?
i dont think so beacuse this isnt a customeditor with a target component, as ive said i did not make this, im trying to fix a unity package
see? no requiredcomponent
can i use EditorPrefs to store the value?
like playerPrefs
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
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.
in the unity docs?
alr
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
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
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)
No they should work, it is possible they broke it when they switched to UITK or they made some minor change to the backend which did this.
Good to know. I'll file a bug report
That is probably the best thing to do, though I don't think they will fix it. IMGUI is on the way out.
ill tell you the results as soon as unity is done with "loading domain(busy for 5:03)"
the debug.log is running whenever i press the "global" button
is it set to what you'd expect?
nope, look at the console
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" });
}
}
LOOK
[CustomEditor(typeof(Test))]
my editor is not attached to a component* like yours is
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?
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?
i cant find an editor window class in this script, maybe thats the reason?
this only has a class deriving from Editor
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
Can you share the callstack from OnInspectorGUI to see where it's being called from? how do i do that?
sorry im not familiar with custom editors
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" });
}
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
this script
@wispy delta sorry forgot to ping
line 316
the node editor isnt an editor window...
let me see where its refranced
I just downloaded the Schema asset and the toolbar works fine for me. For context, I'm curious what needed fixing?
xd
what unity version are you using?
2022.3.15
can you create and select things with the plus icon on the top?
and remove them with the minus?
ya 👍
im using 2022.3.12f1
bro this is so weird
ill re import the scripts and see if it gets fixed
i that doesnt work, id update the editor and reinstall the asset
mother fu
ever since i tried to fix this my editor has become super slow
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
it works for this fella but for some reason it dosnt work for me
the code for the editor : https://gdl.space/eyitiqojug.cs
new project fixed it
for some reason
what is a Handles.DoPositionHandle and how does it differ from the regular Handles.PositionHandle?
Hey there
Any ideas why compute shaders behaves weird in editor?
But works in playmode
afaik the methods starting with Do are internals and barely made it to public. the latter will probably call into the first one somewhere inside it. do take a look at the sources for ensuring though, that part is open source
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
Nope, basically what I would do is to use reflection to create a instance of the default GameObject editor, and then call its methods from the ones in your editor
I just ended up using SceneView.duringSceneGui event to toogle the labels instead
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?
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?
I think I use ApplyModifiedProperties inside of OnInspectorGUI()
I mean I've done that as well but it doesn't do anything?
I mean, that what updates my GUI so it must be doing anything
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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.
So when you update variables in like OnSceneGUI you don't have to do anything else to save them
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
also I add base.OnInspectorGUI and immediately it just duplicates it
im not editing the values in the inspector
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
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
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
In your script you assign a serializeproperty but you dont use it
yet in your OnSceneGui you make another property
That property is inside of the points property
bc points is an array
See, it's used.
Told ya it makes no sense.
ah, I see. I work on the editor stuff once in a while but I try to avoid it for the most part so perhaps someone else has an idea.
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
It isn't.
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
probably need to repaint the scene
yeah if you're drawing stuff into the scene you need to update the handle and to call a repaint
something like that
is it just this.Repaint()
HandleUtility.Repaint
does nothing
sorry when do i call this
Oh my god duide it works thank you so much that took WAY too long
<33
Oh nice
I think SceneView.Draw / DrawAll works too I forget
honestly it's something you take a day to read into
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)
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;
give the inspectorDefaultMargins or inspectorFullWidthMargins editor style to your object field, see how that looks
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
oh, i missunderstood the problem, i think the problem had something to do with the width position
no problem, I think my REAL problem is described in that thread, I need to use EditorGUI.ObjectField instead of EditorGUILayout.ObjectField
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
Can I use Import Package dialog window from code?
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
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.
^^^
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.
If you are setting them in the editor without using SerializedProperties and without dirtying the target object, the changes will not be saved when you enter playmode. So if they were null to start with, even after setting them, they will still be null. Unless you mean a public variable in the custom editor class itself?
I want to apply arcgui similar to Platform effector 2 editor to my Hook script, what can I do?
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
Thank you. I'll give it a try.
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)
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 
only way, adjust from normal vector?
Yeah adjust your start vector
// 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.
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?
I only know FormerlySerializedAs
Would be neat to have that for types
I'm really open to any 3rd party things for that
Would make me have to write less code, but eh...
Nope nothing. But you can provide feedback on the potential feature here which increases the chances that we might get it in the future.
https://portal.productboard.com/z8pw2ms6jxytyez9chlmm4kr/c/578-c-serialized-data-migration?utm_medium=social&utm_source=portal_share
@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
How did ya bind/populate the list?
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
try setting the bool for showing the array size to false
I have done that already
If you are on a LTS make sure you are on the latest too.
Hmm... try simplifying it and not do any custom binding or MakeItem callbacks?
just listview.bindingPath and let it automatically handle it
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
What? No, no, I just me temporarily commenting out the lines to see if they are what is causing the issue
// listView.bindItem += BindItem
As it could be some way you are accessing the SerializedProperties from there
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)
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.
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
yea thats a good idea
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
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?
You looking for paid or free?
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)
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.
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
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?
@twin dawn Basicially I'm logging all of the contents of an assetbundle and looking to sort them a little bit
https://paste.gg/p/anonymous/2faa6b0739d745d180b3319c3416655a
and which objects/types is this failing for?
im dumb nevermind
i did not realise component and monobehaviour where seperate
my bbbbbb
tyvm
Is there a function to open an asset, similarly to if you double clicked it in the project view?
Ah nice, found it here. https://github.com/Developer-Notes-Extension/Unity-Notes/discussions/165#discussioncomment-3412685
ScriptReference/EditorUtility https://docs.unity3d.com/ScriptReference/EditorUtility.html
Sounds like you might want a serializedreference?
i was messing around with it for a while but couldnt quite get it to work
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)
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)
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)?
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
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)

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
unity unfinished packages
but it does look pretty cool, ill def see whats going on with it
I should test this
I'm serializedRef abuser but never realized this. Does it only happen on PropertyDrawers?
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
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!
when you open the color selector there are 3 dots that open this menu, it shows you the folder location
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?
If you are using IMGUI then EditorGUI.PropertyField(..)
If you are using UIToolkit then new PropertyFIeld(..)
mhh I get property is null exception on this line:
EditorGUI.PropertyField(positionRect, property.FindPropertyRelative("upgradeChange"));
---- // How it is declared
[SerializeField] private ValueChange upgradeChange = new ValueChange();
Does ValueChange have the [Serializable] attribute?
ah jesus I had an enum between that and the class name
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):
- 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?
Do you mean you need to draw the UnityEditor.Editor for a UnityEngine.Object from inside of a PropertyDrawer?
- Yes, exactly
Are you using IMGUI or UITK. If it is UITK then you can use a InspectorElement (I think?)
- 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
Then you are going to have to use Editor.CreateCachedEditor and then draw it's OnInspector method
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
🤔
You never dirty it....?
Also you are setting the asset to reference a instance of NewAnimationPlayable
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)
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
Need to remove it yourself
@gloomy chasm ty for the help
How to reproduce: 1. Open the attached “serializedlist_issue“ project 2. Open the SampleScene 3. Select the “Example” GameObject in ...
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
Yeah they rewrote the ListView in 2022, so not surprising.
But why does that not happen in 2023? purely curiosity
Cause they refactored it again 😂
Basically every major version of Unity that has the ListView in it has seen a mid to very large refactor to the ListView
i wish ugui wasnt chinese to my eyes so i would avoid this
but ui toolkit allows me to make so much cleaner stuff
Yeah UIToolkit is so much nicer. Especially when doing any type of styling.
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?
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!");
}
}```
Not sure I follow, maybe you want the [HideInInspector] attribute?
wont work, because it does not cooperate with:
SerializedObject serializedObject = new SerializedObject(this);
SerializedProperty property = serializedObject.FindProperty("PublicField");
EditorGUILayout.PropertyField(property);
That is cause you need to draw the field type yourself. The other option is to have a custom editor/property draw and simply not draw it there instead
would be easier if there was not already ScriptableWizard with 2000 lines of code...
but i get it 😛
Hmm, does Time.realtimeSinceStartup work properly in the editor outside of playmode?
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...
Hmm, so it should be able to work. I might try doing EditorApplication.update += () => Debug.Log($"Time: {Time.realtimeSinceStartup}");
Just to see if the time is incrementing how you would expect. My only other idea is that after trying to move to the next you might need to wait until the next update call to check again...?
I'd put this in the Update method yeah?
[InitializeOnLoad]
public static class TimeEditorTest
{
static TimeEditorTest()
{
EditorApplication.update += () => Debug.Log($"Time: {Time.realtimeSinceStartup}");
}
}
oh honey... you didn't need to do that just for me, aww... 😳
Haha, seemed easier than trying to explain it. Does the time properly update?
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 🤵♂️
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
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 ❤️
Haha, well good luck. And let use know what it was, if you manage to figure it out!
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?
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
have you tried Selection.GetFiltered<YourType>() ?
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
how about AssetDatabase.FindAssets($"t:{nameof(YourType)}, {nameof(OtherType)}");
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;
}
}```
does this mean you already know their paths?
I have objects already
Just need user to select one
Via some ui
@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!
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
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
@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
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?
why saving the whole scene instead of saving the dirtied asset itself?
oh misread
thought it was asset
I guess EditorUtility.SetDirty would be enough, wouldn't it?
like... once set dirty, the change won't be lost right?
as long as you're saving your scene before closing it should be fine
yeah! and Unity will warn about wanting to save the changes when closing anyway... XD
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
agreed! and talking about unwanted changes, I might also need to record the change for an undo operation in any case, right?
You can just:
- Undo.RecordObject
- Change the data
- SetDirty
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
this is the wrapper
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
I had the same issue, it's annoying that you can't customize what new object is created
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
how did u solve it?
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
And I think someone was asking about something similar a few days ago.
#↕️┃editor-extensions message
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
goddamit, i guess the data is lost
Maybe not necessarily, you can manually do a conversion and create a new asset?
mmmm, yeah I guess I could do that, manually copying it
I have the project before commit so lets see
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
Thanks and no problem!
I made a lot of changes to it, if anyone ever wants to use it, at least have the right one :=)
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
Not possible without SerializeReference. If you're not serializing the same object instances somewhere else on the same Unity object, then each "reference" will be a separate, individual object.
The problem is when having a list and pressing the option, Duplicate element, where it ends up with the same object twice
Draw your own list and duplicate the item when duplicate is called
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
if (propertyOne.managedReferenceValue == propertyTwo.managedReferenceValue)
Also, I think there is a managedReferenceId property or something like that you could also use. But I could be misremembering
Hmmm, I can't remove component that on which other components depend via RequireComponent
is there a way to recursively destroy all of them?
No? Other components require them, so...
yeah, so I want other components first
remove them
and then until original one is destroyed as well
Ahh, gotta do it manually
via checking attribute you mean?
yup

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?
don't care for order
just want them all removed
if X components requires Y, then I want them both destroyed
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
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



Do you mean a different type of 'depend on' than the attribute?
no
just multiple components
X depends on Y
Y depends on Z
Z depends on A
and etc
Ahh, justt gotta call the method recrusivly instead
Just updated the code to be recursive I think
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
😅
Then not really better is it 😛
wish I could supress
it is better, because it avoids reflection
and keeps code much simpler
but you know
stuped native errors
Can you not get them with try/catch?
Ahh it is a Debug.Error
and they are also inside of c++ side
Yeah
so even if I wanted, I wouldn't be able to just copy paste code
I don't get how this code gets rid of the RequiredComponents...
it just keeps looping
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
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!
Yes yes, that's what I said I'm doing. Now the issue is getting a new reference id for the item
I mean, I wouldn't use it only because of errors
someone can help me with a code
otherwise it's much cleaner than going into reflection zone yourself
check #archived-code-general
Why are you needing the reference id? Or do you mean you want to keep the copied data, but have it be assigned to a new instance?
Your issue is not a editor one so this is the wrong channel, and asking in multiple channels is not allowed on this server. You can look in the #📖┃code-of-conduct channel for what is and is not allowed.
oh
There isn't anything wrong with using reflection, especially when you are using attributes. That is what it is there for. It only gets messy when you start using it to access members of a class.
Exactly, same data but different instance
the problem is that code gets much more complicated. not because of reflection
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
That's what i was looking at beforehand, but is there a method to get a new id generated by unity?
That is the first link 🙂
(I think. Never used it my self)
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)
Also, how does this id thing work? Because there's this https://docs.unity3d.com/ScriptReference/Serialization.ManagedReferenceUtility.GetManagedReferenceIdForObject.html and i don't know how it would find an id if two objects have the same data
bruh, I don't know even know how to do it
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
I am confused... what is wrong with my implementation?
it will error
When?
when it tries to remove component that depends on something else
What? So if A has a RequiredComponent(B). And you remove A first. Does it error?
Or does it error if you remove B first and then A?
Yeah my code doesn't have that issue
oh wait
The parent is removed first
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...
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
The easiest way is to make it a package instead of having it in the assets folder.
yeah but I don't want it to be a package
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
how would I assign it in a script?
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.
I'm, not finding that icon property
Hmm, let me check my code...
I think EditorWindows have a property like that, but not tool contexts it seems
Hmm, looks like I was wrong and hard coded it using the attribute too. The attribute uses the EditorGUIUtility.IconContent
With that said, if you want to use some good old reflection, looks like you can add your texture to this internal dictionary https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/Tools/EditorToolUtility.cs#L22
I can't remember, IconContent might be able to get stuff from a Resources folder...
ah gosh okay ;-;
that dictionary might be the way to go
I just wish the Icon attribute let me use a GUID lol
Haha yeah, that would be nice.
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 );
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
oh right I just needed the full type name
Type edToolUtil = typeof(Handles).Assembly.GetType( "UnityEditor.EditorTools.EditorToolUtility" );
works too
Type.GetType("UnityEditor.EditorTools.EditorToolUtility, UnityEditor") or something like that prob works too
well, got it all to call now but it doesn't work 
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
Is there an API to get source of prefab variant?
Do you mean the original prefab? https://docs.unity3d.com/ScriptReference/PrefabUtility.GetCorrespondingObjectFromOriginalSource.html
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
AssetDatabase.SaveAssets
need to call afterwards
thank you but it still doesnt work, i think it doesnt get the Right refrence to the lit shader cause debug.log gave me this
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
Is there a way to get asset hash? Checksum for example
so when asset changes, I want this value to change as well
looks like it
I think SerializedObject has one, I know SerializedProperty does. But Navi's looks better haha
They don't
Unless I'm blind
Ah, maybe I was just thinking of the SerializedProperty one then
Yeah the contentHash is what I was thinking of. Though for SerializedObject there is an internal uint objectVersion property
Probably serialization version though
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
how would I get userData from .meta file if I know guid/assetPath only?
via the asset importer
how do I get one
thanks
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
Uhh, you could maybe try getting the last modified time before editing the meta file and then set to that time after you are done editing it? https://learn.microsoft.com/en-us/dotnet/api/system.io.file.setlastwritetime?view=net-8.0
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
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.
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