#↕️┃editor-extensions
1 messages · Page 18 of 1
well I don't seem to get any errors or anything, it just doesn't reflect in game at all
let me quickly write a script and see how it behaves on my end
I wrote custom editor extension that compiles game scripts in my own language and checks for errors when I change them and if they compiled successfully call method if editor is in play mode to force game load new scripts
I can do that manually, just would be nice if I could do that automatically so when I make changes to scripts (not the C# ones) it'd immediately reflect in game
i can access GameObjects at runtime through an Editor Script without problems
[MenuItem("VoxelMMOnsters/Helper/Help a Stranger")]
public static void HelpAStranger()
{
foreach (var monsterStatus in Object.FindObjectsOfType<MonsterStatus>())
{
if (monsterStatus.gameObject.activeInHierarchy)
{
Debug.LogError(monsterStatus.gameObject.name + " Stamina: " + monsterStatus.CurrentStamina);
}
}
}
this is the script i used. Maybe it helps oyu figure out your pitfall 🙂
sorry, it was the dumbest thing possible, I just forgot to set a flag on my game controller that allows reloading scripts at runtime
this is all disabled for normal builds, I just forgot to turn it on
haha. glad you figured it out : )
with Odin you can simply append [NestedScriptableObject] onto the SO field
[InlineEditor] also helps in a similar way
oh wow, im already in bed but i need to try this tomorrow!
Hey y'all. I'm writing a custom Project Settings page that's backed by a ScriptableObject. So far it's going well but I'd like to clean the code up a lil. Right now I have this in the backing SO
public void OnValidate()
{
if (this.themeSettings == null)
{
EditorGUILayout.HelpBox("Please create and assign a Theme Settings asset to enable UI component theming.", MessageType.Error);
}
}
That way my SettingsProvider's guiHandler can call OnValidate on the object instance. (Otherwise it never gets called by Unity because it's not being viewed in the Inspector)
That way I can display help boxes to the user to make sure they don't leave mandatory fields blank
I'm wondering if there's a way to get Unity to call OnValidate automatically instead of exposing it as public
I'd also like to refactor this. It's based on the SettingsProvider example in Unity's docs.
public static AcidicGUISettings FindSettings()
{
var settings = AssetDatabase.LoadAssetAtPath<AcidicGUISettings>(settingsPath);
if (settings != null)
return settings;
settings = CreateInstance<AcidicGUISettings>();
AssetDatabase.CreateAsset(settings, settingsPath);
AssetDatabase.SaveAssets();
return settings;
}
I'd like to refactor it such that, instead of finding/creating the asset in a hardcoded path like in the example, I'd like to have the user create a settings asset themselves wherever they want it and then assign it in a field in their Project Settings.
Just like how you would with URP and HDRP settings (I'm aware those packages create their settings assets for you but you know what I mean, you can move them around)
Only 50% of what your looking for but this is what I currently have. This code is a modified version of some example code Odin provides in regards to it's ValueDropdown atrribute
public static ScriptableManagerSettings GetScriptableManager()
{
List<ValueDropdownItem> newScriptableObjects = new List<ValueDropdownItem>();
IEnumerable<ValueDropdownItem> scriptableObjects;
scriptableObjects = UnityEditor.AssetDatabase.FindAssets("t:ScriptableObject")
.Select(x => UnityEditor.AssetDatabase.GUIDToAssetPath(x))
.Select(x => new ValueDropdownItem(x, UnityEditor.AssetDatabase.LoadAssetAtPath<ScriptableObject>(x)));
foreach (ValueDropdownItem item in scriptableObjects)
{
if (item.Value.GetType() == typeof(ScriptableManagerSettings))
return ((ScriptableManagerSettings)item.Value);
}
return (null);
}
[SerializeField] public ScriptableManagerSettings scriptableManagerSettings
{
get
{
if (_scriptableManagerSettings == null && Application.isPlaying == false)
{
OnGetScriptableManager();
_scriptableManagerSettings = HelperFunctions.GetScriptableManager();
}
return (_scriptableManagerSettings);
}
}
What's that meant to do?
Basically when scriptableManagerSettings is null and the game isn't running it will run GetScriptableManager which gets every ScriptableObject in the project and checks if any are of the scriptableManager type and returns that
Doesn't solve your issue in regards to having it hooked up to the project settings but means it's not hardcoded
Ah.
Was hard for me to tell, I was reading it through text-to-speech
I love being blind
But... I could see a way to make that code a lil more efficient. Instead of querying AssetDatabase for all ScriptableObjects, you could tell it to query only for the type of ScriptableObject you're working for (there should be a filter parameter that takes a string of the format "t: MyDesiredTypeName")
That narrows down the amount of GUIDs you have to look up asset paths for
Unless I misread the code and it's already doing that
Yeahh it's not the best cook aha. Been putting off refactoring it since it's run very infrequently. Just figured might be some good food for thought for your problem but you might be a couple steps ahead of me 😛
I guess the only way to solve my issue is to figure out how to store something in the ProjectSettings directory
Maybe a JSON file that just holds the asset GUID of the user's desired settings asset
Then I can just use an object field inside the guiHandler to give the user a UI for setting this GUID
Only package i've seen add stuff to Project Settings so far is Bakery
TextMeshPro, URP, and HDRP all do
ScriptableSingleton + [FilePath] or using InternalEditorUtility.SerializeAndForget()
I got it all working the way I want
- I struggle to find any information on how to undo
AssetDatabase.CreateAsset. So far i've been trying to useUndo.RegisterCreatedObjectUndo(AssetDatabase.LoadAssetAtPath<...>(...), ...), but it leaves a ghost asset behind that disappears only after the project is saved. Is there any way to handle it better?
I don't have much experience with Undo, but maybe you can try Undo.undoRedoPerformed to handle the behind the scenes of an Undo CreateAsset
I am looking into modifying my prefabs with code (some refactoring).
After I set some serialized fields to that object. How do I record changes to disk?
Will that do?
Undo.RecordObjects(recordedObjects.ToArray(), "Convert inlined materials to templates.");
This will only create a Undo command and add it to the undo history.
If you want to apply modified data on your properties,you should look for serializedObject.ApplyModifiedProperties()
I access them as raw types
how do I serialize it?
foreach (var prefabGuid in prefabs)
{
var path = AssetDatabase.GUIDToAssetPath(prefabGuid);
var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(path);
if (prefab == null)
{
continue;
}
shapeList.Clear();
prefab.GetComponentsInChildren(shapeList);
if (shapeList.Count == 0)
{
continue;
}
here's what I mean
What are you actually modifying on the prefab ?
MonoBehaviour fields
Maybe AssetDatabase.SavesAssets() will be more suited to what you're doing
Undo.RecordObjects(recordedObjects.ToArray(), "Convert inlined materials to templates.");
AssetDatabase.SaveAssets();
So, like this?
After your modifications, but yes
hmm
doesn't seem to work
git does not pick it up, meaning it will be gone on reimport
Can you show the actual modification code ? The fragment you shared earlier only show that you're loading an asset
You can't load a prefab using any of the AssetDatabase stuff since it could be used inside other prefabs, prefab variants and such. To edit a prefab use an EditPrefabContentsScope and it should handle everything for you
shape.MaterialTemplate = template; where template is SO
and MaterialTemplate is property setting serialized field
PeppeJ's answer will probably more helpful than mine. I forgot that prefab were handled differently than other assets
Is it possible to modify a .meta file from a script?
I'd like to make some tooling for stuff that is too tedious with the FBX importer
Just open it like a text file?
Yeah that works but I want to make UI for it inside Unity
For example, copying curves & events from on anim to another
Or did you mean opening it like a text asset, via script?
Yes
Oh well if that works then great. I will try when I get home
I have a editor window that is referencing a ScriptableObject instance that lives in the scene. Is there a way to get the window to keep the reference when closing and opening Unity?
I was thinking GlobalObjectId, but it can't create one for the ScriptableObject, I assume because it isn't really 'in the scene' like a GO or Component is.
Yeah I was trying to think if there was a way to 'attach' it to the scene 'properly' so it would.
How would you make your own reference type?
You probably need some component in the scene to keep track of it
Which oyu can then ask for the reference
So the reference struct will mostly just contain the scene ref and some unique id
Oh got it, like that. Yeah I was hoping for a more generic solution since the object maybe not be mine. The window is showing the contents of a field. Sort of like how the AnimationCurve opens a window to edit it, but the window is dockable.
Ah not sure you can do that
when i install the 'Unity for VSC' extension and try to open a project it says smt along the lines of 'this project needs to be updated to the new SDK style'
been tryna fix my ide cuz intellisense randomly stopped working
none of these work for me by the way
i still lose the data
im updating the data by editing the target object values
so i use set dirty
is there a way to set LocalizedString with script? i'm making a dialogue editor and i want to add localization editing to it. it seems LocalizationString or StringTable only has getter methods. any hints?
Just create one
It has a constructor
I have a prefab inside hierarchy of other prefab.
How can I identify that current MonoBehavior I am inspecting is part of external prefab?
Basically, I only want to modify game objects that are part of currently opened Prefab, skipping if game object is part of other prefab (because I want to modify that nested prefab instead)
figured it out myself:
[InitializeOnLoad]
public static class EditorUtil
{
private static readonly MethodInfo logEntriesFlagsGet;
private static readonly MethodInfo logEntriesFlagsSet;
private const int CLEAR_ON_BUILD = 2048;
static EditorUtil()
{
var assembly = Assembly.GetAssembly(typeof(Editor));
var logEntries = assembly.GetType("UnityEditor.LogEntries");
var logEntriesFlags = logEntries.GetProperty("consoleFlags");
logEntriesFlagsGet = logEntriesFlags.GetGetMethod();
logEntriesFlagsSet = logEntriesFlags.GetSetMethod();
}
public static bool ClearOnBuild
{
get
{
var flags = (int)logEntriesFlagsGet.Invoke(null, null);
return (flags & CLEAR_ON_BUILD) != 0;
}
set
{
var flags = (int)logEntriesFlagsGet.Invoke(null, null);
if (value)
flags |= CLEAR_ON_BUILD;
else
flags &= ~CLEAR_ON_BUILD;
logEntriesFlagsSet.Invoke(null, new object[] { flags });
}
}
}
i am working an a event system for my game to make level design easy for my non coder friend, but am running into a editor script GUI issue, #archived-code-general message here is the message, i was recommended to ask it here and i still cant figure it out so i figured ide ask here like i was told lol
should have posted it here in the first place, but i did not put 2 and 2 together on this channels name
I don't really have a clear grasp of exactly the setup. Not sure if you can try breaking it donw a little simpler what and where the issue is. If you are on 2022, I would highly recommend just switching to UIToolkit for this as the IMGUI ReorderableList is a pain to use
im not i said a few msgs after the linked one im on 2021
and i dont know where the issue is, only what it is.
i mean, its in EventTriggerEditor.cs in case CommandType.SendEvent
but i dont know why its not displaying right as its the same as the main ReorderableList, just as one whole case
other than people saying its just messy to work with and that it could be a unity bug for my version of 2021.3.23f1
Ahh too bad. So what line is it that the nested list and "Target" foldout is being drawn at?
79 of EventTriggerEditor if im correct,,
sendEvent is just meant to store a list of commands inside of the command to send to another eventhandler like the commandList does, so i made a almost 1:1 copy of the main ReorderableList but just, inside of the case CommandType.SendEvent on line 60
Hmmm, for line 79, try using EditorGUIUtility.GetPropertyHeight instead of SingleLineHeight
(I think that is the class, might be EditorGUI)
says
Assets\Editor\EventTriggerEditor.cs(79,78): error CS1503: Argument 4: cannot convert from 'method group' to 'float'
changed it to
EditorGUI.PropertyField(new Rect(rect.x, rect.y, 60, EditorGUI.GetPropertyHeight),
nestedElement.FindPropertyRelative("commandType"), GUIContent.none);
No I meant EditorGUI.GetPropertyHeight(nestedElement.FindPropertyRelative("commandType"))
The method returns the height needed to render the property passed in to it
Also, I would recommend just making a custom PropertyDrawer for Command, it should make this easier for you
No problem
lets you make custom editors for normal C# scripts basically
i changed line 79 to what you recommended and same result
So any time the normal C# class is drawn in the inspector as a field, it will draw how you tell it to in your PropertyDrawer
Hmm, just for fun, try changing line 112, to have a height of like 150
i just want a list with the + and - to add to that looks the main gui
okay
same result
but hey, it says send event now in the commandType box
👍
if you want context #archived-code-general message
oh @lapis sonnet Part of the issue might be because you are nesting Commands. Is that not throwing a serialization warning in the console...?
it is
2 all the time
Serialization depth limit 10 exceeded at 'Command.commandArguments'. There may be an object composition cycle in one or more of your serialized classes.
Serialization hierarchy:
11: Command.commandArguments
10: Command.nestedCommands
9: Command.nestedCommands
8: Command.nestedCommands
7: Command.nestedCommands
6: Command.nestedCommands
5: Command.nestedCommands
4: Command.nestedCommands
3: Command.nestedCommands
2: Command.nestedCommands
1: Command.nestedCommands
0: EventTrigger.commands
Yuuup
i was not sure what it ment, and also did not know if it related to my issue
i mean, ig reading it it makes sense
sorta
is it like a GUI feedback loop?
Unity serializes things as values. Meaning that there can be no null value. As such, if you have a class that has a field of the same type, it creates a infinit loop
so how do i fix that?
(also gonna ask phind to break down what you said in my dumb brains language lol)
Either change your design or use https://docs.unity3d.com/ScriptReference/SerializeReference.html
(Please note that I specifically liked to the documentation because it is important to read and understand what it does)
public class MyClass
{
public float myValue;
public MyClass myField;
}
When Unity goes to serialize MyClass, it will first see the myValue field and initialize it to 0 as a default value.
It will then go to the next field, which is 'myField', and because it serializes things by value and not reference, it will create a new MyClass instance, and assign it to myField.
Unity now needs to go in to the instance it just assigned to myField, and serialize all the fields in it.
Go back to top of this message.
This is the issue you are having with the serialization depth warning.
and that is the core issue with my GUI being broken?
I don't know, but it isn't helping things at all haha
okay, ill work on fixing it then report back
when i click on the warning it brings me to command.cs and highlights nestedCommands
so it is something to do with the use of public List<Command> nestedCommands;
Did ya read the message I just wrote with the code block in it that explains the issue you are having?
i know, i did just figuring out stuff in the only way i can understand
Yeah the issue is public List<Command> nestedCommands;
U still using Reorderable Array?
if i can yes
:P
if i cant then ill firgure something else out
i feel like im super close to fixing this, but this is my last try
i asked here again as i wanted a responce from the correct channel, as i posted wrong in the first place last night
Structs + property drawers pretty much deal with most of the formatting stuff u need to do. :0
To modify the list itself (like element count limiting stuff like that), just make a property drawer or editor script of the one that has the field. :P
a
wanted to see if maybe it would work once fixed
moving onto this now
just,, need to figure out why its not showing the command as a dropdown list like it should

its doing the same thing that the list did with the non working dropdown, this time though it says nested command and looks better GUI wise
i want it to be a dropdown for the command types i add like the one at the top left corner, then once the command is selected show its inputs under it like how the command as a whole looks
okay, i return for more help, i want to be able to use a sendEvent inside of a sendEvent, but the nested list for sendEvent doesnt have a case for itself as that would need another layer for each layer i want to be able to nest and thats just not an option as i want to be able to use as many layered sendEvents as i want for bouncing commands back and forth, how would i do this? i normally would make it into a method but i cant add the case and add the method into the case as that would not work due to unity loop stuff, so how can i do this? https://pastebin.com/AFcuLFCi
so this ^ but working. and yea ik there is no gui code for it just giving an idea of what i want to achieve
Hi, I have been trying to make a data profiler editor window to be able to follow more effectively what happens at runtime in my game. Problem is, I can't get it to be a scrolling window if needed. It either doesn't fill the whole window or overflows too much horizontally, as the horizontal scroll bar fits the content, and not the containing window. I tried using a rect to make them fit but then the content got pushed out. I can share the code but it is quite long already
My editor window is not sticking around when I close and reopen Unity. A built-in windows doesn't disappear when I do that.
Do I need to do something special to make this happen?
here's the code, in case it matters
public class GameConfigWindow : EditorWindow
{
[MenuItem("Pursuit/Game Config")]
public static void ShowWindow()
{
GetWindow(typeof(GameConfigWindow));
}
void OnGUI()
{
GUILayout.Label("Game Config");
GameConfig.instance.Mode = (GameManager.GameMode) EditorGUILayout.EnumPopup(GameConfig.instance.Mode);
}
}
It doesn't get saved in layouts either. I do not see any messages in the console when saving or loading the layout. This is in 2023.1.6f1
Ah! The file name did not match.
Of course. EditorWindow derives from ScriptableObject
This only came up just now because I renamed it from GameConfig to GameConfigWindow
why doesn't my hover effector on the class detect any applicable elements
been trying to figure out why my buttons are non responsive and this appears to be why
looks like there is a space between unity-button and :hover
np 🙂
how do you subscribe to button clicks
button.clicked...
Yeah you would want to use MouseDownEvent
which is all the button is doing
Actually, it is using a Clickable which inherits from Manipulator and all that does is let you subscribe to multiple callbacks in a clean way if you want to add/remove them all at once
starting to really like using ui builder for editor ui now
shame the performance of it is quite slow to use at the moment
Yeah it is great for it! And don't don't worry! It is so much worse in 2023!
https://streamable.com/x3lqfz
i am using 2023 😢
Nice! So you already know!
yeh i noticed when you drag an element in and you want to make it a child even if you hover over the element it doesn't make it a child half the time
god knows how they managed to make it so slow
They are aware and are working on it
https://forum.unity.com/threads/the-uibuilder-lags-horribly-when-interacting-with-visualelements.1446733/
they consider ui builder to be in beta phase?
This is for the 2023 beta
Ahh, yeah
that will make things much quicker
For sure
Idk why they went with the nested class approach to start with
2023.2 has the new binding system in it which is cool
Haven't really gotten to use it much yet though
with unity editors for the new ui toolkit is there a way to still get the default inspector but then add ui elements after it ?
or must it require us to replace the whole thing with our ui document
surely the default inspector comes with a default ui toolkit version too?
how do we use that though its not an override
do we just call it and pass in the root with the serialized object
Yes
okay, will give it a try
thanks
weird its a static and not just using the same setup as the old editor function did by calling the base method
Means you can call it anywhere
why/when would you want to call it in a different location though
So show an editor nested in another location
I just added a comment on DrawDefaultInspector to help those looking
wdym
Using my notes extension https://notes.vertx.xyz
oh wow thats a neat idea
It's existed for a while, and previously as a different extension before chrome changed their requirements. Sorry for assuming you knew about it 😅
hadn't heard of it before
was it stickied or something
unity should adopt this idea of user comments/notes as a feature
I thought it was... but it doesn't seem to be
They have considered it in the past I think, but the docs team is understaffed
fair enough
that would explain why documentation is sometimes non existent for some things 😄
dammit
what the heck were you writing
Updating the pins, the top one is at capacity it seems
maybe an external wiki would be better and then just pin the wiki
is there a way to know if the serialized object for the editor is a prefab or an instanced version in the scene
since i want different editor ui depending on the situation
I guess you can get the targetobject and then use PrefabUtility?
Is there anything that fires off if I stop moving the selected gameobject via its gizmos and/or inspector?
There is but I'm on phone.
hmmm. I have an abstract GameObject reference. I need to know whether this is a prefab or whether this is a instance instantiated from prefab.
All done in Edit-Time (not PlayMode).
Basically, I need to get source GUID of game object. Any tip how can I do so?
hey folks, does anyone know how to add Version History to my own custom github packages? I can't find any documentation on it.
my packages are using Tags and Releases with MAJOR.MINOR.PATCH formatting and release notes, but they don't show up here.
PrefabUtility.GetPrefabParent(theGO)
you may want to add another check whether the prefab is disconnected or not
just calling AssetDatabase.GetAssetPath seems to work
I might need to test it further though
is there a way to get current folder in Project tab ?
got it :
var path = (string)typeof(ProjectWindowUtil).GetMethod("GetActiveFolderPath", BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, null)
hi im writed a code like this:
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(GameObject))]
public class ApplyChangesToPrefab : Editor
{
public override void OnInspectorGUI()
{
GameObject go = (GameObject)target;
if (!PrefabUtility.IsPartOfPrefabInstance(go) || !PrefabUtility.HasPrefabInstanceAnyOverrides(go, false))
{
DrawDefaultInspector();
return;
}
EditorGUILayout.HelpBox("This object is a prefab instance with changes.", MessageType.Info);
if (GUILayout.Button("Apply Changes to Prefab"))
{
PrefabUtility.ApplyPrefabInstance(go, InteractionMode.UserAction);
}
}
}
but whenever I open this script it happens like this:
what is the reason of this?
I want to write a script that does some modifications to gradle project before building, is it possible to do that? I know I can export gradle project but it still builds it, I can rebuild it I guess but it takes nearly twice as much time
wait, nevermind
it only exports
for ui elements how do we restrict the object field to be a specific scriptable object type
right now it lets me choose any object which i dont want
set the objectType
objField.objectType = typeOf(T)
doesnt seem to work though
it has restricted to that type
but it wont load my scriptable objects to select one
oh it works now
unity must've just had a brainfart
thanks!
PrefabUtility.IsPartOfPrefabAsset(target) this doesn't seem to work for me for a prefab
was hoping to show different ui when i open the prefab
but it doesn't seem to be returning true when i open a prefab
seems theres no actual way to do it
if (PrefabStageUtility.GetCurrentPrefabStage() != null)
this turns out to be the way to test if you're in prefab editor scene or game scene
finally worked it out
PrefabUtility has no method for it either
i tried one but it turns out to be deprecated
wtf
that seems like a stupid limitation
I'm not really sure what the context of that quote is
turns out the post is from 2015 so was likely in the early days of prefab feature
var transform = target.GameObject().transform;
int count = _data.Points.Count / 3;
for (int i = 0; i < count; i++)
Instantiate(new GameObject("ID: " + i), transform);
this technically works
but it also adds gameobjects to the main scene aswell
kinda weird
they dont end up attached to anything either
There's a talk pinned to this channel with info on how to do some things with the prefab system
PrefabUtility methods is how to do everything
The one that says
Talks
Prefab System
weird i didnt see it the first time
There are more APIs and things have changed since then, but it's got the basics
Instantiate(new GameObject("ID: " + i), transform);
wait would the new part be creating a gameobject in the scene then instantiate is cloning it ?
maybe that would explain why im getting random ones appearing the scene aswell as my prefab
ok the slide seems to suggest i can do it
though it doesn't actually show any api on how
though it says "edit prefab assets" doesnt necessarily mean i can instantiate child elements to it
when i tried i get Cannot instantiate objects with a parent which is persistent. New object will be created without a parent.
which explains why it spawns them in scene
Yes
Whatever you're trying to do, if you're just wanting to modify the prefab asset I think you can use the method on slide 60
i tried that earlier with :
var assetRoot = PrefabUtility.LoadPrefabContents(PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(target.GameObject()));
Debug.Log(assetRoot.name);
but it seems to return null
target.GameObject() is the prefab since the editor only runs in prefab mode
but its not a prefab in a scene its the actual selected prefab in asset folder opened up
So what's being returned by GetPrefabAssetPathOfNearestInstanceRoot?
Because I would try to keep it simple and tackle one thing at a time, if that's not returning the prefab asset then that's where to start
appears the path is empty or null
Then I doubt you are dealing with a prefab instance
Then why are you using that method?
AssetDatabase.GetAssetPath
Show what object that GameObject is
so when i click regenerate tank the idea is it will create child objects based on the layout data
debug log of target.GameObject() gives Tank (UnityEngine.GameObject) UnityEngine.Debug:Log (object)
If you're getting the asset path of something opened in a stage you may need to use PrefabStageUtility.GetCurrentPrefabStage ().prefabAssetPath
I am unsure if there's a consistent way to handle it in all cases
not sure what a "stage" means in unity
I have not set something up like this
When you have a prefab opened it's opened in the prefab stage
which is the temporary view for staging prefab changes before they are saved
Assets/Prefabs/Tank.prefab
ah that seems to be it
ok so thats the word im looking for is stage not scene 😄
I don't think you should generally allow editing the prefab asset directly when the stage is open, because I think you may have to reload the contents of the stage
or, if you do, only support that
it'll be annoying to handle all cases otherwise. But you can make your own decisions, just be aware that the stage is a temporary representation loaded from your asset
so when i do this:
var assetRoot = PrefabUtility.LoadPrefabContents(path);
and add what i need, i then need to save it to the asset path as a prefab again ?
and overwrite basically
Yes, you need to save and unload it
seems simple enough theres a save prefab asset function
the steps are in slide 60
I'm trying to use it but it never gets called
hm it's called after restart
nevermind I guess
After getting a Sprite from my prefab's Sprite Renderer, how do I draw it in the current scene correctly? I'm using GUI.DrawTexture, but I don't know how to set the Rect correctly.
any one know why I keep losing the reference value in my object field here? the object is serialized:
[SerializeField]
TankLayout _data;
yet it becomes null
im using ui elements for my object field
cant I root.Bind(serilizeObject) and right after i added a new element to an array, make it be shown without deselecting and selecting again the scriptable object?, because it doesnt seem to work (for ui toolkit)
@visual stag so after some playing around it seems this:
PrefabUtility.SaveAsPrefabAsset(asset, path);
PrefabUtility.UnloadPrefabContents(asset);
doesn't actually seem to save to my prefab
it shows it in the stage, but then i drag the prefab to the scene and its all gone
It's surprising it would even show it in the stage for me
but 🤷 you'll have to figure it out, it should save just fine. I imagine it's having the stage open that's causing the issues
it seems odd they wouldnt make it simple enough to edit prefabs in stage from editor code
less hassle than dragging into the scene then saving it to a prefab
because the code instantiates child gameobjects. selecting it in the project window only shows the inspector
not the visuals of it
The code loads the prefab into a temporary scene, does it's work, and saves the prefab. You don't need to open the stage to do that.
But yeah, I'm sure you can make it work with the stage, I just am not familiar with it and it would take too long to test it for you
I am very surprised the API adds children to the prefab in the stage
if we can do it manually with a mouse i dont see why we can't with code
I suspect you have done something different to what was on that slide 60
and are actually editing the thing in the prefab stage, and in that case you will just need to dirty it
using Undo.RegisterCreatedObject or whatever should do it
this is basically the summary of it:
void Load(out GameObject asset)
{
var path = PrefabStageUtility.GetCurrentPrefabStage().assetPath;
asset = PrefabUtility.LoadPrefabContents(path);
}
void Save(GameObject asset)
{
var path = PrefabStageUtility.GetCurrentPrefabStage().assetPath;
PrefabUtility.SaveAsPrefabAsset(asset, path);
PrefabUtility.UnloadPrefabContents(asset);
}
private void Regenerate()
{
Load(out var asset);
ClearChildTransforms(asset);
for (int i = 0; i < _data.BiArcs.Count; i++)
{
var segment = Instantiate(_segmentPrefab, target.GameObject().transform);
segment.name = "ID : " + i;
segment.GetComponent<WallSegment>().Set(_data.BiArcs[i]);
}
Save(asset);
}
Regenerate called when i hit the button
weird it randomly worked this time 🤔
unity is being a bit glitchy with it
where do i try that to ?
to the objects you create, the children
are there any examples how to make element like this in uitoolkit? and also tree view
like what ? thats the default ui isn't it?
I just have hard time finding good documentation on ui toolkit for 2019
2019 ffs.. can't you just upgrade?
Lol don't bother in 2019
ok, is it then possible to make a fast working tree view that can display thousands of elements with IMGUI?
I guess I'll have to sit in dnspy a lot more
does anybody know if there's a quick way to get this information in code?
kinda rusty on my editor extensions coding
making a tool that needs to know the current Visual Studio version
I imagine CodeEditor.Editor.CurrentCodeEditor, just looking at the source
ah there's an exposed class for that, perfect
thx
CodeEditor.Editor.CurrentInstallation.Name
that was it
Yeah it is possible, you would just have to write it yourself.
And why would you need to sit in dnspy? The C# source code of Unity is avaliable on github (for viewing only)
there's public API for doing tree views with IMGUI and UITK
all you have to do is cull whatever is not visible in the rendering area and it performs pretty well
if you don't do that it will slow down severely when you have a lot of rows and columns
What's the best way to draw a texture from an editor script?
DrawTexture
both Graphics. and GUI. don't let me draw smaller than 1 unit
What do you mean smaller than 1 unit? You mean like GUI.DrawTexture(new Rect(0, 0, 1, 1), myTexture);?
with new Rect(0, 0, 0.6, 0.6) the scale snaps back to 1 unit of size
and with smaller sizes it snaps to 0
So you want to display a texture that is 6/10ths of a pixel in size...?
In GUI or world space?
in OnSceneGUI
You can use the scene.camera to convert GUI and world space
gotcha
GL.PushMatrix();
GL.LoadPixelMatrix();
Vector2 screenPosition = sceneCamera.WorldToScreenPoint(enemySpawnPosition);
GUI.DrawTexture(new Rect(
screenPosition, enemySprite.rect.size),
enemySprite.texture);
GL.PopMatrix();
I think this is somewhat correct, texture draws smaller than 1 world unit. The only thing is that it scales with the camera
What...
My bad I forgot Handles has stuff for this already
Vector2 screenPosition = HandlesUtility.WorldToGUIPoint(enemySpawnPosition);
GUI.DrawTexture(new Rect(
screenPosition, enemySprite.rect.size),
enemySprite.texture);
unfortunately that moves the texture on the Y axis in addition to the scaling
What do you mean?
moving the camera down moves the texture down instead of up
should be at that PositionHandle
the camera's center is currently under the world center
oh and I also should mention the sprite is rotated 180 degrees
GL.PushMatrix();
GL.LoadPixelMatrix();
Vector2 screenPosition = HandleUtility.WorldToGUIPoint(enemySpawnPosition);
GUI.DrawTexture(new Rect(
screenPosition, enemySprite.rect.size),
enemySprite.texture);
GL.PopMatrix();
Oh you might need to do
Handles.BeginGUI() and Handles.EndGUI around the GUI.DrawTexture call
thought those didn't do anything but they do
but still a problem with the scaling
What scaling issue?
Right now the texture isn't scaling. It is in screenspace. You want it to act like it is in world space
Yes
Worked with enemySprite.rect.size / HandleUtility.GetHandleSize(screenPosition)
Nice, so is it looking how you want now?
btw GetHandleSize is meant to take a position in 3D space, so it should be given the enemySpawnPosition
not in the center exactly
bottom right seems weird
huh, screenPosition - screenScale / 2 worked
Yeah the screenPosition is the exact position on the screen the point is. The GUI in unity has the top left of the window being (0, 0), while the bottom right is (width, height).
I mean before this the texture always drew with the bottom right at (0, 0)
You mean when you were using GL?
That is because screenspace and GUI space are different
The Game UI has the bottom left being (0, 0)
You're welcome!
im creating a game object as a child to the prefab with editor code, when i assign it a mesh and save, the child is created as is the mesh but the child doesn't keep a refrence to the mesh even though i assigned it
child.GetComponent<MeshFilter>().sharedMesh = mesh;
why might that be ?
i have to manually drag the mesh file on to the mesh filter afterwards from the asset folder
not sure if im missing something
why do i have to reselect the gameobject in order for my value field to appear?
public override VisualElement CreatePropertyGUI(SerializedProperty property)
{
SetProperties(property);
Initialize(); Compose();
return _root;
}
private void SetProperties(SerializedProperty property)
{
_flagsDataProperty = property.FindPropertyRelative("data");
_flagIDProperty = property.FindPropertyRelative("ID");
_flagValueProperty = property.FindPropertyRelative("value");
}
private void Initialize()
{
_root = new VisualElement();
_flagsDataField = new PropertyField(_flagsDataProperty);
_flagsData = _flagsDataProperty.objectReferenceValue as FlagsData;
if (_flagsData is null)
return;
SetFlagNames(_flagsData);
//_popup = new PopupField();
//_popup.Draw(_position, _flagIDProperty, label, _flagNames);
_flagValueField = new PropertyField(_flagValueProperty);
}
private void Compose()
{
_root.AddChild(_flagsDataField)
//.AddChild(_popup);
.AddChild(_flagValueField);
}```
is there a way to send data to play mode from edit mode? I know editor prefs but what I want to send an object? I can probably serialize it into string and deserialize in play mode but is there a better way?
(unity's serialized fields won't work because it's not scriptableobject and it has fields that unity simply can't serialize)
when you update values in editor how do you get other scripts that are listening to changes to also change? i normally use Action OnChange but unity gives a warning not to send events in edit mode
plus that would require me to setup all the links anyway so actions don't really make sense
the only other way i can think of is the editor gets components from the scene and manually updates all the relevant scripts involved but that seems not very scalable
example: i change the values of my bezier spline via custom editor - another script in the scene needs to be aware of this change to update the data it has about it
that's what I'd do, or I'd just make those components subscribe to static event when 1st instantiated to the scene
whether it's scalable or not. depends on your impl
well i got it working after much hassle
just have to make the editor script do it all
not great if i ever change the design because then ill have to change the editor script too
Just a normal System.Action? that should work just fine without any issues...
yeh but you have to press play to get your classes to register to them first
which defeats the point when you doing editor scripts
ive got a weird issue with scene use in editor
i have this on my editor
and in OnScene i draw the mouse position but it only shows the mouse position when i stop moving the mouse
very laggy - i dont understand why
it only ever moves if i stop the mouse
all i have is
private void OnScene(SceneView view) => DrawMouse();
it should be following every frame but it doesn't
dear lord this is a pain
Repaint the scene view
how come ive not needed that before 🤔
strange
So when does OnScene actually get called? when theres a new event on the stack ? i assumed it was on every repaint
It might depend on if you have "Always Refresh" enabled in the scene view settings
Meant to reply to this
ah i see
EditorPrefs.GetString("EditorState.editorData", null) why does this return "" after I deleted key?
Unity's serializer never serializes null. I presume EditorPrefs is just using Unity's serializer
https://docs.unity3d.com/2018.4/Documentation/Manual/script-Serialization.html
However, Unity actually makes more than a thousand allocations. The serializer does not support null. If it serializes an object, and a field is null, Unity instantiates a new object of that type, and serializes that. Obviously this could lead to infinite cycles, so there is a depth limit of seven levels. At that point Unity stops serializing fields that have types of custom classes, structs, lists, or arrays.
why is unity serializer being shit as always 
the thing is - in that case it doesn't even need to deserialize anything, since key doesn't exist in prefs I expect it to just return value that I gave
instead it instantiates empty string

wanted to avoid doing extra call to HasKey and do it in one call, I guess I'll have to call HasKey first
I usually check strings with string.IsNullOrEmpty so I don't encounter this
Ah yeah, and HasKey
also is there ANY reason why these foldouts are private
If the value doesn't exist, it will return defaultValue. Note that EditorPrefs does not support null strings, so if defaultValue is null, an empty string is returned.
This was also documented btw
well, not specifically these ones, since inspector ones can be used, but they can't be customized
even if documented it's completely unintuitive behaviour, no other code behaves like this, why would Prefs need to check default value I provided myself?...
this seems stupid and just wastes cycles
I agree, I'm not sure why it would work that way, I can only imagine there's some interaction with the serializer that causes it, why, cannot tell you lol
Also, no idea about the headers. What are you trying to do?
I have DSL and I'm making IDE like experience in editor for another dev who isn't a programmer and I needed custom foldouts for objects in the DSL (unity's are not suitable because they don't support dictionaries and I need dictionaries) but the ones that are public work but they just look like plain tree items and I wanted to make them look like inspector ones
and they also made all styles private so I had to pull styles through reflection 
It is weird they haven't made the headers UITK yet
and there is a public foldout but it seems bugged, despite taking GUIContent as a parameters it doesn't draw icon, I checked the code and the only reason it doesn't do that is because it removes icon from GUIContent, even though after I modified it to not do it - it works perfectly fine
that's basically where I took code, just took all private methods to my code and all calls to get styles I made through reflection and cached
they might've done, I need to check newer unity
for example in the one I use treeview is also private, but in newer ones it's public
They haven't
hey guys I'm trying to make an editor window with which I may control my "actionEditor" script, however I'm having some trouble.
I'm quite new to editor scripts so sorry if this is silly but I can't see "transformEditor" in the inspector? (ignore the zeroes I'm doing some GUILayout nonsense)
Serializing something in an EditorWindow won't make it appear there, it's just serialized
things aren't drawn automatically like in components
so what would be the syntax to show it?
If it's serializable you can use a PropertyField
would I need to do GUILayout.PropertyField?
Yes
You can create a SerializedObject out of this in OnEnable and use that object to find your property
so uhhh wait do I just have a serialized object variable in my script that I can show in onGUI?
Data has to be serialized
Both serializable, and either public or SerializeField
oh thank you so much
much appreciated man you're a life saver for that
@visual stagby the way if you're curious..
i found a simpler way to open and saving prefabs
they have this method:
using (var editingScope = new PrefabUtility.EditPrefabContentsScope(AssetPath()))
found it by luck
hi ! I have this bug when i try to build and Oculus Quest Build, i've used this graphic api with this settings for my previous build. I've import some packages from the assets store, is it possible that the few packages create this bug ?
Wrong channel
Idk when your previous build was but sure packages can change the color space setting or render api (although unlikely bt depends what you imported)
my bad, what channel should i have ask ?
🤷♂️ This channel is for writing extensions to the editor, not issues with the editor
Maybe #💻┃unity-talk works
thanks !
Is there a way to know whether executed code is inside of worker thread for builds?
I can't find a proper way to do so
BuildPipeline.IsBuildingPlayer returns false as well
thread.getcurrentthread?
I'm building a UIToolkit window for Editor use only, that uses UIElements.CurveField.
Is there any existing way to draw a vertical line over the curve, representing a "current value/position" within the curve?
I'm not seeing anything immediately, so my assumption is that I will have to draw my own VisualElement as a line (using border?) and just layer it on top with manual positioning. (?)
you can create a cutom control and use vector api
I'm not familiar with that API, looking it up now.
For note, the curve (and 'position') are not intended to be editable. They're read-only, just for visual reference. If that changes anything.
Huh, interesting; looks like I could use that Vector API to build a read-only curve without using CurveField/AnimationCurve. Maybe. If my first-glance is understanding this correctly. A useful API to be aware of regardless of this use case, thank you for bringing it to my attention.
Regardless, it still is a matter of drawing both the curve and the 'position' line independently; so, still the same outcome of sorts. If I understand correctly.
yes.curve field doesnt has a bulit-in api for current value, but you can make you custom control inherit from cruvefield and save some code,
Maybe, or just store a reference to a CurveField. My thought is I'd need a VisualElement container, CurveField, and a VisualElement for the 'line'.
The line would be absolute positioned, 1px wide, 1px left or right border... and just set it's position within the container.
Throw all that into class that extends VisualElement, instead of the CurveField.
Or would you extend the CurveField, and add the 'Line' VisualElement directly undernieth the curve? That.. hm. That would work better, wouldn't it?
(ie: Your suggestion does seem better than my initial thought, the more I think on it.)
vector api is cheaper than a visual element i think
Possibly. I'll look into it, too. For sure.
There may be a point later down the road I do want to allow editing the curve - but not when there's a value associated. [Different window state] -- So it may, just from a visual consistency stand point, be better to use the CurveField anyway. We'll see. It's good to have options at least.
Thank you, though. The real answer to the question I needed: Yes, do it manually. Bonus was learning about a new API. Heheh.
yes,do it mannuly,painful,but can learn something,just another thought,maybe you can add a custome drawer for you cutom curve
Don't think drawer's useful in this case, but yeah. I'm more backend dev, learning UI stuff... yes. Learning something. Lots of somethings. Heh. Thank you again.
Hi, for some reason this script and it's editor script reset some of the values to 0 when I re-enter the prefab, why is that?
For example, I create a prefab like shown in the picture, add all the necessary components, play around with the values and it works flawlessly.
When I exit the prefab however, it just resets the _min to 0, _max to 1 and _value back to 0 but all the components are still properly referenced.
I can't figure this one out, can somebody please help me?
_min and _max are lacking SerializeField
also: HideInInspector
_value also needs SerializeField
interesting, will it appear twice if I call the base.OnGUI thing?
oh, so combine serialize with hide, that's smart, let me test it out!
oh wow, that actually worked, I don't know how I didn't make the connection between the serializefield and them being reset, thanks a lot!
I am pretty much a beginner when it comes to custom inspectors, if you have any advice on how to improve these scripts please, do let me know
It's a lot of logic to juggle 😅
You're welcome.
If you run into any issues with using Reset() to get your components,
(in case an asset is removed or replaced)
then I recommend looking into this set of experimental solutions:
https://gist.github.com/Rovsau/5d06ff262679f9be6e2fbcb18c4eb74e
I have not used it in an actual game myself, but spent some time on finding ways to re-trigger the Getting of Components.
(This can be an issue if one assumes components will be fetched anew when entering Play mode)
thanks!
when using ui elements how do we update the ui based on the data since the CreateInspector isn't called every repaint
i also can't bind
Hello! Does anyone know how to preview a specific frame of clip on an object with an Animator at edit time?
I'm trying to iterate through the frames of an AnimationClip to get the world-space locations of some objects, in order to create a bounding box of all it's possible positions (probably later I'll want the actual path it took).
It's easy enough to do this with a PlayableDirector and it's Evaluate function, but I can't find an equivalent way to do this for Animators.
afaict this only works at runtime, I want to get these at edit time to cache the values
Could try looking at the reference source for the animator and see what htey do there?
yeah, my next step is to (find and) dig into that, because it's clearly possible! But I hoped someone would already know 😄
oho! I just discovered that if I call animator.Update(0) immediately after animator.Play(...) it does set the animation to that frame
🔥
Nice
I was wondering whtehr update did something but I assumed no since you mentioned that play with normalized time doesn't 😅
yeah, that's what I thought too 🙂
thanks for making question if I had really tried Play properly 😄
I got a class and property drawer. I want to override an Object Field's label by using a field. But the field returns null.
public class ClassX
{
[SerializeField] private/public string field = "hehe";
}
[CustomPropertyDrawer(typeof(ClassX))]
public class ClassXDrawer: PropertyDrawer {
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginProperty(position, label, property);
// Null reference error
var eventNameProperty = property.FindPropertyRelative("field");
EditorGUILayout.ObjectField(property, new GUIContent(eventNameProperty.stringValue));
EditorGUI.EndProperty();
}
}
I think i found my answer
Note: When changing the structure of a serialized object, like adding new fields, the asset might need to be reimported.
most notably: when changing field names
How can i make their size fit with the default Unity's one by using UI Toolkit Builder?
I was doing with Flex Grow and shrink but i see they use some sort of base unity classes. But when i put the classes to my custom field, it does not works.
This is the problem visualized:
The classes they use for the label:
My classes in label: unity-base-field__label is not affecting anything.
None of the inline style parameters is changed inside custom element.
Do you mean the label alignment? Add the alignedFieldUssClassName class that's exposed on anything that inherits from BaseField
BaseField<int>.ussClassName + "__aligned" will do if you can't find it (I think it's exposed 2022.2 or newer)
Hmm. Is there any sort of postprocessor for builds where I can postprocess prefabs that got bundled?
Specifically: I want to remove components from game object prefabs which contain editor only monobehaviours
how can I re-render a property drawer if a field was chnaged? I tried in field.RegisterValueChangeCallback to call EditorApplication.update.Invoke();, but didnt work (ui toolkit)
Like before building?
no, just for a build
because I don't want prefabs to be modified during build
Basically I have a monob X. This is editor only monob and it doesn't make it into build. It's all ok if I just don't do anything, but I get a warning about Missing component on my prefab
So what I want - remove it just for this build
This thing works fine on unity's auto-generated property visual elements but not works in mine. Right now, i realize something. when there is a .unity-base-field__aligned class inside the element named #unity-input-etc, the label's width in Unity's label gets overriden. But even tho i put in mine, label's width does not gets overriden.
Even tho i delete .unity-object-field__label or another thing that is not base field, it does not affects the editor in unity's one.
An addition, .unity-base-field__aligned is working with default visual elements like Radio button inside UI Builder. I put them next to eachother vertically and tried to match the class names.
The radio button worked but mine wasnt working as usual. Is it a bug or is it my mistake?
Any ideas?
I am still trying to find solution to this, and realized another beautiful thing. My public string gets undo record at every char which is i dont want ._.
I cant find in google. How it can be possible?
It seems it is normal. All of the MonoBehaviours act like that but its actually anormal how do people living with this?
Okey i think the only way literally doing a focus-in focus-out undo system for every fucking thing that has string, int or whatever
Sent as bug report.
Which Unity version are you seeing this in?
I believe EditorGUI.DelayedTextField (and isDelayed property in UI Toolkit) is the solution to this. If a custom editor or drawer neglects to use it, this is the result. If you're seeing it everywhere, then either Unity messed up and made the default drawer not delayed, or maybe you have a custom editor for MonoBehaviour that doesn't use it.
does anyone know to make "height: 100%" not break in USS?
I'm trying to make header, footer and scrollbable area between them
but having 100% height on scroll area in the middle breaks layout
regardless if I set height of footer/header to fixed value or auto
it seems like the answer is I have to manually calculate height and put it into min-height after hours of search I couldn't come up with better solution, it just keeps breaking otherwise
Is it normal behaviour for a GUI label to update its text to the int value after using it to create an int field?
No
Some weird things are happening, for whatever reason this triggers the gui content label to change its text to the int value:
property.intValue = EditorGUI.IntField(amountRect, label, property.intValue);
how do you define label
I just use the one that OnGUI provides
i never modify it, but when i comment out this line specifically the label text stops changing
the label text is drawn by this line though
you wouldn't have a label if not for this line
yeah, but the label text is the int value rather than what the actual provided label text is
Is this in a PropertyDrawer?
yeah
Can you send the whole drawer?
What Unity version is this?
2021.3.21f1
also forgot to say, even if i dont provide the label itll still be modified
quite old, so it's probably fixed if it is an issue
makes sense
ill scroll through the fix list and see if i can find something similar, seems specific to the int field too
// Make a text field for entering integers.
internal static int IntFieldInternal(Rect position, GUIContent label, int value, GUIStyle style)
{
int id = GUIUtility.GetControlID(s_FloatFieldHash, FocusType.Keyboard, position);
Rect position2 = PrefixLabel(position, id, label);
position.xMax = position2.x;
return DoIntField(s_RecycledEditor, position2, position, id, value, kIntFieldFormatString, style, true, NumericFieldDraggerUtility.CalculateIntDragSensitivity(value));
}
I don't really see how PrefixLabel could modify your label, it doesn't even get passed the property
Weird?
hold on, ill send the full thing in case im missing anything
that creates this
The 25 on the left should show "Default reward" (the field name)
Can you write EditorGUI.BeginProperty(position, null, property); instead
Weird, GUIContent is a class, and it says
label Optional label in front of the slider. Use null to use the name from the SerializedProperty. Use GUIContent.none to not display a label.
in the docs
Don't pass null to that
pass null to BeginProperty. I don't think it will change anything though... I'm just narrowing things down
Can you use the debugger and step into the IntField call to see when it gets changed
Interesting, so your GUIContent for the label is the TempContent one... which is never updated before the property is drawn? 🤔
yeah, and also another thing, when i select the int field the label gets properly drawn
presumably from this:
string str2 = !editor.IsEditingControl(id) ? (!EditorGUI.showMixedValue ? (passwordField ? "".PadRight(text.Length, '*') : text) : EditorGUI.s_MixedValueContent.text) : (!EditorGUI.showMixedValue || !(editor.text == "<>") ? (passwordField ? "".PadRight(editor.text.Length, '*') : editor.text) : string.Empty);
one of the monster lines in EditorGUI line 772
and editor.text seems to be where its fetching that number from
err no, could also just be passed down from EditorGUI.DoTextField?
Regardless of all this though, I don't really understand why you are using the label in the int field at all. If you're drawing these elements side by side, it's surely not going to be enough space
the problem is that even if i specify no guicontent itll still draw the label lol
I presume you're not doing anything whacky and calling this drawer yourself... is that the top of the stacktrace above?
property.intValue = EditorGUI.IntField(amountRect, property.intValue);
this still draws the label
yeah
It's Unity calling it, not some random custom editor
As far as I'm aware you're really meant to do:
label = BeginProperty(position, label, property);
position = EditorGUI.PrefixLabel(position, label);
...
If you want to draw a prefix label for a property drawer
and every other element you don't pass a label (or pass GUIContent.none)
well
that fixed it lol
i didnt even know EditorGUI.BeginProperty returns a guicontent, but setting it to that fixed the issue somehow
Yeah, it returns its own temp value
I have no idea why it's all so convoluted, I usually have no problems. I have moved to UITK exclusively now though 😄
the correct answer lol
Does someone know?
Thank you. The custom editor with DrawDefaultInspector() in OnInspectorGUI() works but as you said "default drawer not delayed" how can i do that? (2022.3.7.1f)
So all MonoBehaviours have this issue, except for ones where you've created a custom editor that uses DrawDefaultInspector()? That sounds a lot like you have some custom editor that overrides all MonoBehaviours unless there's some other more specific editor. Something like Odin Inspector or Naughty Attributes.
Yes DrawDefaultInspector() has no issue.
No sir i had no custom editor before this problem. This thing also happens in empty projects so.
I'm installing the latest 2022 LTS (2022.3.9f1) to see if I find the same behavior in an empty project. It's possible that Unity messed up the default UITK drawer by not using delayed fields. Calling DrawDefaultInspector() in OnInspectorGUI() will use the old GUI system, which likely doesn't have that same issue.
@whole steppe Yeah, I see the same thing. Looks like Unity messed up. You were right to report it as a bug.
I haven't made custom field elements in UITK before. If the thing vertx said doesn't work, then maybe there has been some recent change that broke it and you need to do some extra step to get the right alignment.
is there an easy way of changing the labels on a list that's drawn in a PropertyField?
(in IMGUI)
The "Element N" name comes from SerializedProperty.displayName. The native part of the editor chooses that display name for array element properties. The only way it can be overridden is if the element is a class/struct with a string field matching one of the recognized names, like "name", "title", probably some other ones.
Besides that, you can make a property drawer for the elements in the array that draws a different prefix label, or you can replace the entire editor for the parent type and draw the ReorderableList yourself.
yeah i've done in the past the remaking the ReorderableList from scratch and making drawers for the class
i was just wondering if there was a quick way of doing it for basic arrays
guess i'll make a property drawer then
thx anyways! 🙏
If the elements are to be more complex, all it needs is the first property/field to be a string, and it will take that string value.
But it won't work if it's a single text field, like what you have there.
[Serializable]
public class Example {
public string ElementName;
// Other fields.
}
yeah instead of "Element X" i just wanted to name them "Namespace X"
i just made a property drawer and get the array index for the name
that's a better solution then
yeah i don't like the weird workaround with extra fields because then i come back to the code a year later and i get confused
[CustomPropertyDrawer(typeof(ImportElement))]
public class ImportElementDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
bool isPropertyAnArrayElement = property.propertyPath.EndsWith("]");
if (isPropertyAnArrayElement == false) // Draw the property normally
{
EditorGUI.PropertyField(position, property, label);
}
else // Draw the property with a custom label for its array entry
{
// Set the label to Namespace + index in array
int index = -1;
int openingBracketIndex = property.propertyPath.LastIndexOf("[");
int closingBracketIndex = property.propertyPath.LastIndexOf("]");
int numberCharacterLength = closingBracketIndex - openingBracketIndex - 1;
string indexAsString = property.propertyPath.Substring(openingBracketIndex + 1, numberCharacterLength);
Int32.TryParse(indexAsString, out index);
label.text = $"Namespace {index}";
// Adjust the rect to leave the correct space inbetween array elements
Rect fieldRect = position;
fieldRect.height = EditorGUIUtility.singleLineHeight;
// Draw only the string property to avoid getting the foldout
EditorGUI.PropertyField(fieldRect, property.FindPropertyRelative("_namespace"), label);
}
}
}
There is an isArray property of SerializedProperty btw
i need to check if the property is an element inside an array
not if the property is an array itself
ah
Pretty sure I was doing something similar not too long ago
I think that one can more easily work for you
though that doesn't give you the index xD
actually, your solution might be better
i remember seeing that depth property but never actually implementing in anything
so i wonder if i just ignored it or if it had some issues
why are both UITK and imgui so god damn terrible
yeah i was just checking my tests and it just seems like a lot more convoluted to check if something is an array element with the .depth property
if i wanted to check which ones of those are array elements i would have to keep track of depth as i go down the nesting tree
and then try to keep track of the parents, and check if the parent is an array
seems just easier to check for [] brackets instead
(gotta be careful with strings tho because they are technically arrays of chars)
noticed that 😆
Yep. I agree.
it might help with coding visual indentation
yeah probably
dear asset store devs, consider making your libraries cross-engine to e.g. Godot:
That is a nice idea, but for probably +90% of asset store assets it is not practice or even possible. And all of the editor code is engine specific by nature.
The only things this really works for a 'back end' type of systems and libraries that already don't really touch engine specific APIs.
true, but one can dream.
I imagine it might be useful for things like save/load, navigation, ai, where you can limit the surface area to the engine. But yeah.
Yeah, and even then they end up touching quite a bit of engine specific stuff.
I saw some editor extension on asset store where you could have selected visual element in UI Builder window and press a button on a custom Behaviour inspector to create a GO which holds reference to that Visual Element (propably not actuall reference as it isnt serializable, but some data for a later Querry) and Im VERY intrested in how that was achieved, anyone has an idea? Selection class doesnt seem helpful here and UI Builder window itself isnt accessable cause of Unity.UI namespace
Ive checked to what assembly UI Builder window belongs to to try add assembly reference to get access to it, but cant even find corresponding assembly def file... so it is still a riddle for me
Ok i see guy must have done some custom wrapper window for UI Builder itself, ill leave it, it seems too intrusive
Could you link it out of my own curiosity?
(You can surround the link with < > like <https://mylink.com> to about it showing a large preview)
Oh, and to answer your question. The answer is Reflection. Probably not that hard even.
Basically you would get the Assembly for it, then get the BuilderWindow Type. You can use Resources.FindObjectsOfType(builderWindowType) to get the window instance. Then you just have to look at the source code to figure out where it stores selection. Then I would assume it walks up the tree to make a build a string query or something like you had thought.
how do I use EditorGUI.showMixedValue ?
I can set it but I can only pass 2 values to toggle - either true or false
https://assetstore.unity.com/packages/tools/gui/ui-toolkit-script-components-248976
here you have it. I checked what files it contains and there is this wrapper class I talked about, also manual tries to explait a bit how it works but honestly I dont get it
I would need an example cause some parts of reflections are still like a magicto me
Although after some thinking Ill propably implement some search window for my pourpose instead of this UI Builder selection, but knowing how to do it will still help, perhaps I will experiment with it
The whatever class has a normal property drawer. But something weird happens in arrays... Its gonna be used a lot so i dont want this to happen...
what do you want to use it for?
setting it to true makes GUI elements draw a line "--" to signify there's multiple different values
Property drawers are cached and reused. It looks like you might be saving some data in the drawer class, which is then used for other properties.
Hm i was creating the whatever label inside property drawer. Maybe that is causing the issue you mean?
You can create it there, you just can't save it and reuse it. Can you share the property drawer code?
Okei
You could also override CanCacheInspectorGUI to return false instead.
Or if you'd like to cache them, then you can save the data in a Dictionary instead, so you can save separate data for each property.
I have no idea what it does but let me try
Okay, you can't save container, because it will be overwritten by the most recent property each time. Unity will only create one instance of WhateverDrawer and then call CreatePropertyGUI for each property it needs a GUI for.
You can get the element from the changeEvent parameter, so you don't need to save it.
Thank you so much! It fixed the issue
I figured it out, it makes true act as mixed value
I needed to have toggle that can show mixed value depending on some other values and clicking it would change all these other values
I just set showmixedvalue to true and call toggle with true value and I get what I need
(just a reminder as a side note to mark the dictionary as NonSerialized, otherwise it'd persist across domain reload with invalid data all over it)
Unity can't serialize a Dictionary though, and for a field to be serialized it must be public or have [SerializeField].
all I know is it's not related to Unity serialization. it's a domain reload thing from .net I presume
If it's a static field and you have domain reload disabled, then sure, it would persist until the next domain reload. But [NonSerialized] doesn't affect that. It's not getting serialized, just never cleared out of memory because the domain isn't being reloaded.
static or Instanced, editor data remains throughout domain reload unless marked as NonSerialized. that includes ScriptableObjects too
Ah gotta say, I don't remember it being in my problem back when facing this, so yeah (the statics)
anyways, was just a side note to always mark these stuff NonSerialized for a clean flush after each domain reload (perhaps not statics)
Oh okay, I didn't know this about NonSerialized. It's mentioned here in the documentation:
https://docs.unity3d.com/ScriptReference/NonSerialized.html
Apply to a private field to stop the field being serialized during a hot reload operation, such as after an assembly is recompiled, or during a domain reload operation before entering Play mode.
But I'm not sure it affects PropertyDrawers, since they don't inherit UnityEngine.Object, and so aren't serializable.
And I still don't see how it could also serialize Dictionary. That would mean Unity can serialize dictionaries but chooses not to during runtime, which doesn't make sense.
right. my bad. just tested and yeah dics don't persist. only Unity serializable data types do
I have one editor in which I edit a List from the base class, and accessing it through a SerializedProperty correctly sets up undo and redo.
I have another editor for which the base class has a List of objects, which in turn have a List like the one from the first editor base class. This time I have to access the second list by using FindPropertyRelative(). This seems to break the undo and redo system, because I can't undo/redo the elements in that list. Is there something I need to add?
My Stylesheet is not working in editor but it is showing as working in UI Builder.
The stylesheet and UXML's are inside of Editor folder.
Stylesheet is created inside UI Builder.
Stylesheet edited inside UI Builder.
Stylesheet can be seen in Matching Selectors in element's class. But it is not showing when i use debugger in inspector.
Solved it. Do not use visualTree.Clone().ElementAt() when you creating a container ._.
question, anyone else having an issue with VIM theme making it so you cant type...
it was working fine yesterday
I have a PropertyDrawer using UITK, but I am not getting the context menu for the field label (Copy Property Path, Copy Value, Paste Value).
There is a generic internal method I can grab to add it myself, but that feels dirty, and would prefer a nicer way of doing it, it feels like there should be something simple. Anyone know if there is?
What is happening here? I feel safe to do it cause my script (for which this custom editor is for) requires UI Document, but Unity screams for some reason.
private UIDocument document;
private void OnEnable()
{
document = (target as MonoBehaviour).GetComponent<UIDocument>();
Debug.Log(new SerializedObject(document).FindProperty("sourceAsset"));
}
Look at #854851968446365696 for post large blocks of code/errors. But all that error is if from the MoveTool, the one use you use change the position of the selected GameObject
I would comment out your code to check, but there is no reason it should be causing that error. If it persists I would make sure to restart Unity.
gosh... Unity likes to throw a jump scare from time to time for some reason lol...
with commented error does not accure, uncommented and shows again, but yeah, I restarted Unity and its gone like it was never there 😅
sorry im overreacting sometimes XD
What the hell unity has a leak detector thats cute
while im here...
anyone has a better idea how to detect if certain .uxml has changed?
Unfortunatelly AssetModificationProcessor does not work for visual tree assets -,-
private UIDocument document;
private SerializedProperty visualTreeProperty;
private VisualTreeAsset visualTreeAsset;
private string visualTreePath;
private string lastModified;
private void OnEnable()
{
document = (target as MonoBehaviour).GetComponent<UIDocument>();
visualTreeProperty = new SerializedObject(document).FindProperty("sourceAsset");
visualTreeAsset = visualTreeProperty.objectReferenceValue as VisualTreeAsset;
visualTreePath = AssetDatabase.GetAssetPath(visualTreeAsset);
lastModified = File.GetLastWriteTime(visualTreePath).ToString();
EditorApplication.update += CheckVisualTreeAssetChange;
}
private void OnDisable()
{
EditorApplication.update -= CheckVisualTreeAssetChange;
}
private void CheckVisualTreeAssetChange()
{
if(File.GetLastWriteTime(visualTreePath).ToString() != lastModified)
{
Debug.Log("Tree changed");
lastModified = File.GetLastWriteTime(visualTreePath).ToString();
}
}
making a custom property drawer for this using IMGUI
stumbled upon this cursed thing using a nested collection
how could i fix it?
seen worse XD I still didnt fix my tool after half year ago nested collections started disco every frame for some reason... almost got epilepsy attack XD
but this looks like something doesnt have specified Rect properly, but I havent used IMGUI for a while so propably wont be able to pin point exactly
is there a way to get if editor window actually has open instances?
because HasOpenInstances lies if you maximize some window
and getwindow creates new instance
I want to force window to not have more than 1 instance but I can't find a way
static variables are erased when entering play mode
hasopeninstances doesn't do what it's supposed to do
You want CreateInstance instead var window = EditorWindow.CreateInstance<T>();
wdym?
Oh! I misread your question, apparently you don't want multiple windows 🤣
just ignore that
1st of all GetWindow<> should give you instance of that window if it is already opened so I dont get it, but if you really want to save a static refference to it you can consider using ScriptableSingleton
Upgrade/downgrade the version of the post processing package using the Package Manager until the error goes away
oh i download unity particals and i ignore the upgrade
how ican upgrad it?
thanks itts working now
Man i got a dumb question. How can i find serialized getter setter property from FindProperty?
I see someone said this in forums:
In order to find a serialised property you have to run serializedObject.FindProperty("<propertyName>k__BackingField"). Note that it’s two underlines between the k and BackingField.
You can't. You can only get the backing field if you serialized it, like they are doing there
I thought getter setter also had backing field
I have no idea how will i reach that tho
It must be an autoproperty
[field: SerializeField]
public float Value { get; private set; }
They you use <PropertyName>k__BackingField, where in this case PropertyName is replaced with Value
If you have implemented the getter or setter then there is no backing field
maybe reflections trickery will work? Idk its jsut a blind shot
tagerObject.GeType().GetField("fieldPath").GetValue(targetObject)
ohhh you want to access methods themselfves? Ok im confused so dont listen to me
Thank you guys i will create a custom backing field instead of this thing.
When a property is specified like this, a backing field will automatically be generated for the property, and the accessors will be implemented to read from and write to that backing field. The name of the backing field is compiler generated and inaccessible to the user.
Hey
Does anyone know how can I run a method from a different script when I click on a button in my custom editor?
[CreateAssetMenu(menuName = "PieceFactory")]
public class PieceFactory : ScriptableObject {
public void OnButtonClick() {
...
}
}
[CustomEditor(typeof(PieceFactory))]
public class PieceFactoryEditor : Editor {
public override void OnInspectorGUI() {
base.OnInspectorGUI();
if (GUILayout.Button("Run method")) {
// I want to call OnButtonClick from the PieceFactory here
}
serializedObject.ApplyModifiedProperties();
}
}
turns out this was a Unity bug that is fixed in the latest versions of 2021.3
Either use a massage or reflections (although idk if massages work on SO), but it shouldnt be tricky to acces this method with reflections
Anyone knows if it is possible to force a pseudo-class on a visual element? I want a button to appear active, but dont want to specify custom styling for it
Ty. managed to implement my solution in a different way tho
it gives instance if it's already open but not if it's hidden when one of the windows is maximized - even though it exists getwindow creates new instance
exactly, I want to force SINGLE window and getwindow doesn't do that, even hasopeninstances lies
scriptablesingleton seems like pain to setup because a lot of the data is not serializable by unity and it seems overkill for what should be built-in functionality, I just need some way to know if window instance already exists (I want window to open when I enter play mode but I don't want multiple instances and if I enter play mode in maximized window it still creates instance even though one already exists)
when you mentioned that static variables are areased when entering play mode you meant variables in Editor script? Cause I would guess they should stay intact hmmm
no I meant that I can't just store window reference in a static variable because it'll get erased when I start play mode (entering play mode state of all objects, including editor scripts gets reset), so it wouldn't work as a solution and I can't find any solution to actually know if instance exists
singleton wouldn't work because a lot of the fields aren't serializable (by unity serializer, they can be serialized by other serializers), I already manually serialize some data from editor into game with a different serializer because the one unity uses is kinda garbage
use Resource.FindObjectsOfType<YourEditorWindowType> and check if ti finds at least one
Can someone teach me a bit about assemblies?
Can I have some internal classes in MyCustomToolRuntime assembly and have access to it in MyCustomToolEditor assembly through some specific configuration?
yeah, you can put a [assembly: InternalsVisibleTo("MyCustomToolEditor")] somewhere within your MyCustomToolRuntime assembly and it should work
this is a class attribute or what is the usage of it?
it's an assembly attribute, as the assembly: part indicates
so you don't need anything below it
oh so I just put it anywhere in any .cs file inside of MyCustomToolRuntime assembly and it makes all internals visable?
to specified assembly
yup
great! Thanks man!
what the fuck?
you can serialize C# properties??

It's just an automatic backing field getting serialized.
you can't serialize properties but when you create property like this it creates hidden backing field and that's what gets serialized
Does anyone know why this is happening?
[Error - 10:31:33 AM] [LanguageServerProjectSystem] Exception thrown while loading c:\Users\User\Visual Studio Code Projects\Game Development Implementations\Groundwork\Assembly-CSharp.csproj StreamJsonRpc.RemoteInvocationException: Sequence contains no elements
I'm having a heck of a time figuring out the test runner.
I followed the tutorial on the Unity website and it worked just fine. But trying to implement tests in my project is going nowhere.
I'm trying to load a scene in setup and it's telling me that this can only be done during play mode, but this is a test that I'm running in play mode
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using NUnit.Framework.Internal;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.TestTools;
using UnityEngine.SceneManagement;
[TestFixture]
public class SimpleTesting : IPrebuildSetup
{
public void Setup()
{
Debug.Log("This is being set up!");
SceneManager.LoadScene("TestARDesktop");
}
[UnityTest]
public void MyFirstTest()
{
string testString = "Test string!";
Debug.Log(testString);
Assert.That(testString, Is.EqualTo("Test string!"));
}
}```
This is in unity 2022.3.9f1, my boss has me implementing testing in our project.
I've been googling for solutions, someone said to chang a value in projectsettings, but that didn't help.
Anyone know what may be causing this?
can we use ui elements for custom inspectors on materials? will the binding property still auto bind ?
not entirely sure how to correctly find the values since they wont be from c# scripts
Nope
😢
so what are my options to make a more useful inspector
its getting complicated in the material
Gotta use IMGUI https://docs.unity3d.com/ScriptReference/ShaderGUI.html
you can still use IMGUI container within your inspector alongside uitk if you dont want to sacrifice everything it offers. I would deffinitely do so (never going back to IMGUI lol)
wdym by container
i dont remember what the element is actually called but there is one allowing you to put a visual element which content is built with IMGUI
Doesn't help for making custom shader GUIs
propably, im just saying that if I had whole editor window made with uitk and then met the bottleneck forcing me to use IMGUI, I definitely wouldnt rewrite whole window to IMGUI
why nor popupfield or dropdownfield wont be in line with the other fields? (ui toolkit)
_popupField = new PopupField<TValue>(property.displayName, elements, oldIndex)
.AddBind(property);
a = new DropdownField("ceva", _flagNames, 0);```
_popupField = new PopupField<TValue>(property.displayName, elements, oldIndex)
.AddClass("alignedFieldUssClassName")
.AddBind(property); ``` and still the same
That's not the class name, that's the name of the constant variable
oh and if i dont have it, i have to do it like this BaseField<int>.alignedFieldUssClassName" ?
it worked, but do u know any cleaner way of doing this?
No, that's how it works, there is no cleaner way afaik
oki thanks
in ui toolkit how can i invoke an Callback in a custom visual element?
SendEvent
how i can get this?
If you mean the items in that list, you don't, they existed many many many many years ago
oh 👀
very minor thing but wtf is happening with my cursor over this textField? it drives me crazy...
styling for that TextField is simple
#search-field{
flex-grow: 1;
cursor: text;
}
#search-field > #unity-text-input{
border-radius:7px;
padding-left: 10px;
padding-right: 10px;
}
.unity-text-field__placeholder > .unity-base-text-field__input {
color: #969696
}
nvm, apparently there is one more element nested inside which for some reason got its cursor style overriden (no idea why)
I have a text field which i Bind to some property and im registering a value change callback to it, but this callback fires instantly because binding changes the value from a git go. I tried to SetValueWithoutNotify and THEN bind it, but for some reason it gives opposite effect than I hoped for, callback fires twice lol... Any idea what to do with it?
SetValueWithoutNotify should do the trick even, if not, that looks like a bug
are these 2 the same?
using var pooled = ChangeEvent<bool>.GetPooled(false, true)
.SetTarget(this)
.SendEvent();```
```cpp
ChangeEvent<bool>.GetPooled(false, true)
.SetTarget(this)
.SendEvent()
.Dispose();```
using will generate a try-finally block to ensure that the resource is disposed, even if there's an exception. If SetTarget or SendEvent causes an exception in the second example, Dispose will not be called.
thanks so much :DD
I have Unity extension, unity code snippets, and C# extensions installed and I get this. I download the framework and it still wont get detected. All project setting deetects is the .net framework. I don't know how to switch it to 6.0
Im just trying to get intellisense to work...
it makes callback fire one additional time which clearly looks like WITH notify lol... for now I added additional check in a callback to not run the logic in this particular scenerio
nvm it is solved I had an older version of .net framework and it was only detecting that
its always the .net version issue... I bet that installing newer version of .net can cure cancer as well
why won't the visual tree asset show as a default reference field?
right now im doing this bc it won't let me do it the way above:
private static readonly VisualTreeAsset m_VisualTreeAsset;
static BakePathDataOverlay()
{
m_VisualTreeAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/Pathfinding/Editor/BakePathDataVisualTree.uxml");
}
``` which would break if it's moved at all. overall just seems like the UI Toolkit is missing features. I shouldn't have to load my visual tree asset at an exact path like that.
UIEventsSearchProvider eventsPopup = ScriptableObject.CreateInstance(typeof(UIEventsSearchProvider)) as UIEventsSearchProvider;
Do I need to dispose/destroy it manualy in OnDisable() of my custom Editor? It is created in CreateInspectorGUI() and idk if it behaves like local variable and GC will handle it or not.
If you mark it with [SerializeField] and remove static and readonly it should show up
yea I did that
in the screenshot I have it as [SerilizeField] public VisualTreeAsset m_VisualTreeAsset;
ah I see now
yea sorry. I meant to say that i'm loading the direct path right now because I can't do it the other way for some reason. Even though it's a mono script.
Hey, im trying to work with the kiwicoder behavior tree, and im running into an issue where it wont accept public / serialized properties from the inspector. I dont know if anyone can provide some advise or if I'm just going to have to pony up for a real BT asset.
The issue is a little tough to but into writing but in short, its just like making a public or serialized property in a normal script, where it appears in the inspector and you can select an object of a specific type from the field. Except when you select an object from that field it errors out and says that there is a type mismatch, when you literally can't select an object of the wrong type
heres a video of it as well
https://cdn.discordapp.com/attachments/1146187317502029917/1154870484362612736/20230922-2002-19.6366722.mp4
ignore the poor naming, I did this in a different project to double check it wasnt a bug caused by a bad library
idk the inner workings of this tool, but is this behaviour tree saved as an asset in projects, or does it live directly in a scene?
if architecture is lets say similiar to Animator, where you give an "Animator" component to GO, but actual "Controller" that you assign to it lives as an asset in project then it is a ScriptableObject, which can not have any direct references to something from a scene, cause it doesnt have any information about scene itself at compilation time.
I might be wrong tho, didnt drink my coffee yet
I have no idea but you are better out looking for anwer at #🎥┃cinemachine propably
my bad, thx
yeah I just looked at it and Behaviour Tree is an asset so just as I said, you can not select anything from a scene, consider some DI or Singleton (like Victim manager that holds references to all Victims in a scene). Another option (not the best one) is if your node class have a reference to anything that manages this controller from a scene, you can use Find method on it.
My structure looks like this: my root visual element has one more visual element in it acting as a container for everything, when I press "Add element" root visual element is cleared and populated with newly created container, but as you see for some reason property isnt drawn in this cenerio and I dont know why. It is created and it shows in hierarchy, but it is empty. Any idea on what is happening?
button:
inspectorContent.Add(new Button(() =>
{
(target as UIEventsSelector).events.Add(new UIEventsPair());
serializedObject.ApplyModifiedProperties();
root.Clear();
root.Add(GenerateInspectorContent());
})
property:
var eventField = new PropertyField(mainListProperty.GetArrayElementAtIndex(i).FindPropertyRelative("UIEvents").GetArrayElementAtIndex(j).FindPropertyRelative("Event"));
foldout.Add(eventField);
creating a property field and then using BindProperty(), instead of passing property in the constructor, resolved the issue... partially
cause I still need to access it after it bounds itself, for which I use scheduler
but simple schedule.Execute() doesnt work as it may try to access it before it is properly bound
and ExecuteLater() with lets say 10ms works great... but it doesnt feel safe
I need to know when PropertyField builds itself after binding and then access it, unfortunatelly no matter what I try to check it it fails
var eventField = new PropertyField();
eventField.BindProperty(mainListProperty.GetArrayElementAtIndex(i).FindPropertyRelative("UIEvents").GetArrayElementAtIndex(j).FindPropertyRelative("Event"));
foldout.Add(eventField);
bool isBound = false;
foldout.schedule.Execute(() =>
{
Debug.Log(eventField.IsBound());
if (eventField.IsBound())
{
eventField.Q<Label>().text = "TESTING"; //Dummy access test for now
isBound = true;
}
}).Until(()=>isBound);
IsBound() always returns false for some reason -,- despite it being bound (field is already rendered and adding and removing events works so it must be bound)
eventField.binding always is null like it has no bounding at all, despite eventField.bindingPath having proper path assigned
What's this? You'r applying modifications, but you don't ever modify the serialized object?
(target as UIEventsSelector).events.Add(new UIEventsPair());
serializedObject.ApplyModifiedProperties();
well... I was putting every possible method there at this point to see if it changes the result even if it unlogical to do so XD
hammer sometimes works u know
Sometimes it doesn't 😛
anyway now the problem seems to lie somewhere else :/
I assume this is in a inspector an UIEventsSelector is a MonoBeaviour? Instead of adding directly to the events, you should use SerializedObject. Using ApplyModifiedProperties() after directly setting a value like that will clear the value you just set most of the time
didnt know that, but apparently it doesnt in this case, newly created UIEventsPair is right where it should be
What is it that the issue is exactly? It is a little hard to follow
scheduling this lambda expression throws nullreference exception, like eventField wasnt populated yet. Understandable, as PropertyField takes some time to bind and build itself and does not so exactly at the frame of creation. So I need to check IF it is already bound and then try to access its guts
but for some reason IsBound() always returns false despite it CLEARLY being aleady bound
I see, really it is best to not access PropertyFields like that. If you need to access the contents of a field, it is best to not use a propertyField.
I love how in the industry we say "thats quite an edge case u know?" instead of calling it directly a bug or smth XD clearly something doesnt work here as it supposed to. IsBound() method seems useless in my scenerio
Btw IsBound() is literally just field.binding != null. I don't remember off the top of my head, but binding might be only set for the root binding. The one that element.Bind(serializedObject) is called on....
god damn it... I need to use a bigger hammer
What are you actually trying to do?
public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
{
base.Init(ve, bag, cc);
((INotifyValueChanged<string>)ve).SetValueWithoutNotify(m_String.GetValueFromBag(bag, cc));
}
What is that (INotifyValueChanged<string>)ve)? Why do we need to convert that?
I didnt understand how INotifyValueChanged works tho
I see there is no implementation for INotifyValueChanged in VisualElement. But would like to know how this one works.
So this is probably some string field right
So VisualElement has an abstract/virtual Init, so it can only pass a VisualElement and a visual element could something that whose value can't be cahgned
So the derived type (StringField or whatever) implements that interface
And has whatever code required for it to update the value
((INotifyValueChanged<string>)ve).SetValueWithoutNotify(m_String.GetValueFromBag(bag, cc));
If i understood correctly, this thing tells "ve" to that the value changed only once? And the value is m_String.GetValueFromBag(bag, cc)
Thank you so much!
I used a bigger hammer with jagged edges and prickly handle
bool safeCheck = false;
foldout.schedule.Execute(() =>
{
try
{
eventField.Q<Label>().text = "";
eventField.Q<Label>().Add(eventType);
safeCheck = true;
}catch (Exception) { }
}).Until(()=>safeCheck);
caution: user may end up with no fingers
Hey, how do you target the transform in editor? Can't seem to grab it and not seeing much info on the subject
if (GUILayout.Button("Reset All"))
{
TransformToolBox myComponent = target as TransformToolBox;
GameObject t = myComponent.GameObject;
t.transform.transform.localScale = Vector3.one;
t.transform.transform.localRotation = Quaternion.identity;
t.transform.transform.position = Vector3.one;
}
No errors in this version. but log error says "InvalidCastException: Specified cast is not valid."
if (GUILayout.Button("Reset All"))
{
GameObject t = (GameObject)target;
t.transform.transform.localScale = Vector3.one;
t.transform.transform.localRotation = Quaternion.identity;
t.transform.transform.position = Vector3.one;
}
How could I get this to automatically set the base name to the name of whatever prefab I drag into Prefab To Spawn?
is there a way to filter the results that get returned from the selection target button in a property drawer for a field?
target is a component and not a game object. (target as YourComponentType).gameObject
or simply (target as Component).gameObject
serializedObject.FindProperty("BaseName").stringValue = (serializedObject.FindPropert("PrefabToSpawn").objectReferenceValue as GameObject).Name
idk but you can use SearchWindowProvider instead and get way more freedom with it (its practically the same search window that opens up when "Add component" is pressed, you can sort results in groups etc.)
Thanks, I'll take a look.
How can I get prefab overrides from game object in a scene?
I want to know whether component added/removed or values tweaked
like this Impact Authoring
as well as Position and Rotation
var overrides = PrefabUtility.GetObjectOverrides(gameObject); is count of 0
Has a bunch of helpers to find the changed properties, added components etc...
How can i disable paste
ExecuteAlways doesn't seem to work on prefabs?
Can't get an OnUpdate callback when inspecting a prefab asset
cause it is an asset. Update is called only on objects that are in a scene
unless you meant that you are inspecting prefab INSTANCE?
Anyone have any idea why a window with just a ListView UITK element bounds to a List of UnityEngine.Object on a component would result in this?
Solve: Issue was the SerializedObject had a list with over 45k entries.
Wow why my EditorLoop is not like that? It is empty.
DeepProfile is on in this screenshot
-- Title to Search for Discord Users
How can i override global classes? (USS)
--Solution
I want to override a global behaviour of prefab values.
When a prefab instance's value gets overriden, the property's label becomes bold. Of course i want that but i would like to customize that globally.
Okey i think i need to override some of the classes from provided default USS
How the hell am i gonna override this shit?
https://forum.unity.com/threads/unity-why-have-you-made-your-entire-gui-look-like-garbage-now.709037/#post-4747730 he says like "it works" but no bro it not works.
Okey, i see it is not an official thing but they gave us a trick to do that. Thank you unity atleast now i know i can customize something!
We need to literally do what he says. The path and USS file name must match. But does not matters where you put the Editor/StyleSheets/Extension/dark.common.light.uss
-- Desadvantages
Cant edit UI Toolkit Element's classes.
Some asset publisher say:
Please also note that it could potentially interfere with UIs from third-party assets! Use at your own risk. Should you encounter any anomalies, consider uninstalling it and discontinue further use. Do not bother Unity Technologies or developers of third-party assets with any bug reports - **customizing the Editor this way isn't officially supported (and likely will never be)**.
in ui toolkit can i change the color of a PopupField?, and also why do DisplayStyle.None VisualElements still are calculated in flex?
I also don't believe they are calculated? They're not part of layout when display is none
Any straightforward way to override the script's title bar in the inspector based on the value of a property? Can't use AddComponentMenu as it isn't a constant string.
Is there a way to edit default classes globally? like unity-text-field__input class
why do i get null?
I believe there are plenty of reasons for it not to be possible
propably because you havent set any height to it. Use _popupField.resolvedStyle.height instead
oh, thanks :DD
I think i read something like if height is set to zero, it calculates by its content
it sets my element height to 15 instead of 18 that is showed in debugger of the _popupField
you mean that Debug.Log says its 15 but UI debugger says its 18?