#↕️┃editor-extensions
1 messages · Page 114 of 1
just finished following Brackeys custom inspector video but my buttons are going out of view when i have the inspector window to its smallest width, is there a way to make it so if there isnt enough room for all the buttons it starts to wrap?
doesnt seem to work, it just pushed it to the side and is now fully hidden
can u shows the code ?
i put it right after the Set Default Color button
it needs to be before GUILayout.BeginHorizontal();
seems to have just put some spacing above the buttons now
GUILayout.MaxWidth(Screen.width - offset)
looking for a way to delete multiple components from objects but I don't know what objects have them exactly, so selecting multiple objects doesn't show the component
if you want to delete all you could do
FindObjectsOfType<ScriptName>();
then DestroyImmediate() while reverse looping through the results
uhh. wut. I know nothing about that. I am just looking to do it in the editor, not through a script
you can run scripts in the editor as well
one way is the [ContextMenu()] attribute:
[ContextMenu("Run Method")]
public void AnyMethod()
{
}```
i already have visual studio 2022, its prompting me to install 2019
what can i do
oh nvm, i had a pending download in VS installer
Hey, this is a LONG shot, I am very new to writing editor things. I created a class to contain all my generic variables which is then turned into a list.
Now when I try to display the fields, it fails to show anything in the inspector. If I then take out all these variables from the class and call them, it works without any issues and the variables display in the inspector.
Anyone know why?
Really going to need to post code
You can look in #854851968446365696 for how to share the code.
I have an audio editor extension and it works just fine in the editor but for some reason when its built its just completely absent?
it doesn't appear on android or pc help
Shooow code
Sooo what's missing..?
Also, this is not a support channel for any editor tools you download into your project
This is discussion about developing custom editor extensions
oh I got redirected here last time from code beginner and then someone helped out
Is there any help channel for that then @waxen sandal ? on a deadline and I can't find anything online
If the developer does not provide support channels then you don't have many options, #archived-code-general might work, I suppose technically this channel could also work since you'll kind of be developing it but you'll have to provide a lot more context
Could you help out? and what kinda context would be helpful for this?
What's missing, how do you know it's missing, do you get errors?
Where is the code that's supposed to be included
Do you have a link.xml setup?
Are you building il2cpp or mono
This extension should add an audio clip when I press a specified button or when the player triggers a collection animation.
This sound is played in the editor but in the build these actions are silent.
No visible errors and think it is mono:
It looks like (from your screenshots) you have runtime code in the editor assembly, which means it won't get included at runtime
but that could also just be confusing namespaces by the developer
Its referring to a Runtime Assembly definition asset which is in a seperate Runtime folder Under the Editor folder?
That PlayCondition code is in BrightLib.Animator.Editor
? Sorry could you explain a bit more
Surely it should not be in there?
It's in there because that's the assembly definition it's closest beneath
So should I move the Play condition script into the runtime folder?
thats where the runtime definition is in
Any code that you want to work in the build needs to not be in an editor assembly
So I imagine a lot of this is in the editor assembly and is just stripped, and null when built
all the scripts seem to use the "BrightLib.Animation.Runtime" hmm
also the runtime folder is inside the editor folder is that okay?
No
is there a specified place I should put the runtime folder or just anywhere outside the editor? @waxen sandal
Folders don't matter, assembly definitions do
The assembly definition this code is below is an editor assembly
Presumably you have no runtime asmdef
No idea
I don't trust Unity enough to property support nested structures tbh
ok i've moved them and now they seem to be under runtime
Should work fine then
should I move the other scripts in the runtime just in case?
As long as they don't reference editor code
Presumably you've broken some assembly references
hm they need to be in the editor folder to work, could I have a duplicate of them under the runtime maybe?
Ok i have the playaudioclip and Playcondition in both runtime and editor no errors so far
also just quick question why does one assembly asset have "Include Platforms" and other "Exclude?"
If they're both editor, one isn't correct
https://help.vertx.xyz/building/assembly-definitions is how to set up an editor asmdef
The runtime one should be referencing all, it doesn't need to exclude the editor (and shouldn't)
Yeah this one is wrong. Don't exclude the editor. You want code to work in the editor!
after some errors I have pretty much all the scripts duplicated in both runtime and the editor as they both require it seems
sounds still workss
no full on errors at the moment
Duplicated 🤔
its either the editor is mad its not in the same file or the runtime ;/
having both folders have all scripts seems to be only way to have no errors hm
Well... I doubt that's correct. See if you can build
yeah ill go test it
k its built moment of truth
damn no sound 
weirdly having them duplicated didn't error just didn't work either rip
would it be good to try seperating the runtime folder outside the editor folder?
If it makes it make more sense to you
nope still nothing :( man
You just need one editor and one runtime assembly. The runtime one builds for all assemblies, the editor-just the editor. Only the editor scripts go in the editor assembly, and that assembly can reference the runtime one. The runtime scripts are objects you use in the build.
That's it
ok it seems to work just editor assembly in editor folder and all the scripts inside runtime with the runtime assembly
so the editor seems to reference them in the runtime now
ill try building now with that setup
:O
Success!
sorry for having to deal with me im absolute toddler at this @visual stag 
Is it possible to serialize something in a ScriptableObject, but editor only? I know I can use #if UNITY_EDITOR but Unity doesn't like when serialized properties suddenly disappear in builds. I know ScriptedImporter can serialize editor-only import settings for an asset, but this is just for a regular ScriptableObject, nothing imported.
I guess I could make a proxy ScriptableObject with my editor-only properties and have a way to map the real assets to the editor proxies.
But it would be cool if I could serialize something in the .meta file, like how import settings does it.
I think they allowed us to #if Unity_Editor since 2021.2.x .. I saw this mentioned in a changelog awhile back
even the example shows how to do it https://docs.unity3d.com/2021.2/Documentation/Manual/script-Serialization.html
Does that not cause this error to be thrown?
oh dayum...
It's an old screenshot, maybe they've changed it like you said
I'm on 2021.3 LTS, you think the fix is included in that?
also, I found this https://forum.unity.com/threads/serialize-fields-only-in-editor.433422/
Looking at the history of this page, I can see the section about #if UNITY_EDITOR was added in 2021.2, so yeah they must have fixed it.
Alright, I'll go that route then. Thanks!
goodluck!
just taking a another quick look, and yeah, the docs clearly says it should...
if not, oh well.
greetings, the latest substance plugin seems to only work with 2021, is there a way to find the 2019.2 version?
im just trying to import spp files
Looks like it is deprecated and can no longer be gotten
What a predicament
So weird they deprecated such a recent version
Yeah... not sure why they would deprecate it...
Sabotaged my plans
is there a way to edit a game objects transform (or a transform in general) as if you have selected it in the hierarchy without actually selecting it in the hierarchy? This selection will be triggered through a custom inspector btw.
Does GUILayout.Button not support Rich text ?
It does with GUIStyle but I got the width and height look of the button fucked.
Edit:
Used GUISkin.button to copy the default configurations and modified required ones(richText = true)
If they are yours there is as there is a priority parameter in the MenuItem constructor. Otherwise no (without a bunch of work)
How does what work? The priority parameter?
It just orders the menu items in their priority order from the smallest number at the top of the menu and the largest number at the bottom. I don't remember how it works with nested items exactly.
Wondering
It is possible to extend the animation events, to for example, add a custom parameter to be send?
I am creating a custom FMOD integration and I would love to be able to skip using event paths directly
i have a SO that gets created and its _name variable gets assgined by a editor script, but after 1 or 2 unity project's restarts the value clears itself and i dont understand why
Ya never set it dirty
dirty = LoadAssetAtPath?
EditorUtility.SetDirty(scritpableObject);
do i have to call another function when im done modifying it?
No
All SetDirty does is basically tell Unity that the object has changed and needs to be saved. So next time Unity does save, the object will also be saved
this is the SO that i modify and it has others SO as children, but now i cant assign the children to a field
I don't get what you're asking
i can assgin the child SO to an array but i cant assign it to a field
Hmm, should work just fine
ok so, I want to be able to build a node graph visually in the editor by having little spheres I can move around and visual lines I can see, like the light probe thing. How do I go about doing that?
how can i see a bigger error message, it's cutting off
and how can i write shader code in VS?
intellisense isnt working
Only Rider has intellisense for shaders afaik
you may be able to find a plugin for other IDEs, but 🤷
ok, ill look into this. there is an extension on the market place that i downloaded, it did not solver the issues. I believe the error code might give me the hint, but i cant figure out how to see all of it
In addition, I have these errors
Trying to create a section of a plugin for Render Textures. a SerializedObject of a camera cannot access targetTexture for modifying Render Textures. Anyone know why this is? (Unity Version 2020.3.29f1)
Ok, so I have a list containing points that I want to draw position handles on. How do I select which one I draw handlkes on without manually setting the index
Hello, I'm trying to make a test script save a list of transforms.
Base script:
{
[SerializeField]public List<Transform> transformList;
}
and it's editor:
using UnityEditor;
using System.Collections.Generic;
[CustomEditor(typeof(TestingScript)), CanEditMultipleObjects]
public class TestScriptInspector : Editor
{
TestingScript testingScript;
SerializedProperty transformListSer;
private void OnEnable()
{
testingScript = (TestingScript)target;
var serializedObject = new SerializedObject(target);
transformListSer = serializedObject.FindProperty("transformList");
}
public override void OnInspectorGUI()
{
var serializedObject = new SerializedObject(target);
serializedObject.Update();
EditorGUILayout.PropertyField(transformListSer);
serializedObject.ApplyModifiedProperties();
}
}
What am I doing wrong? (it's not saving the list when I modify it)
Don't create your own SerializedObject, there's already one in the base class
Thank you 🙏
Hello guys! 🙂 If I create a OnPreprocessPrefab(GameObject g) g is the is the scene object that just got dragged into the project to make a prfab or is it already the prefab itself?
Probably the prefab
Yeah, I thought so too but I am getting weird behaviours... I am doing weird dangerous things though 🙂 (Removing child objects....)
Yeah, that's what I wanted.... but no luck.... I think that does not exist for prefabs
I'm trying AssetPostprocessor
There's the OnPostProcessAllAssets as well
[Unity 2018.3]
anybody here has experience extending the tilemap GridPaintPaletteWindow ?
i am trying to implement a hotkey for the arrow buttons to select the tile to the up/down/left/right of the current selection
i managed to move this selection box (eg. to the left when i press left arrow) through reflections, but it doesnt actually change update my brush's tile
Hey guys 🙂 Noob question: I've written a custom field for a texture and I would like the changes made during playmode to be saved permanently, i.e. the texture stays the same in the inspector after changing back to editor mode. How can I achieve this?
i think u need to record the changes made separately somehow, and then when playmode switches back to editormode, reapply that change
Has anyone ever used
Microsoft Unity Analyzer https://github.com/microsoft/Microsoft.Unity.Analyzers before ?
If yes, how do you install and set rules?
I have a custom [Serializable] class with an associated property drawer. I'd like to re-define how some of those are drawn with a custom property attribute in the field declaration, like [Custom(params)]. This, so far, appears to be overriding the editor GUI but I'm worried it's just luck / order of operations. Anyone know if drawers from property attributes always have preference over property drawers, or a way to guarantee as such?
A property can only have a single property drawer attribute, but can have multiple decorator drawer attributes.
hi guys hope you doing well . i just want to Ask a question have . I download the 2020.3.30f1 unity version before and it worked fine but when i tried to install the New Lts version 2021.3.2f1 it fully download but didn't install
Right, ok, it must be dumb luck then that the type's default property drawer is being superceded by the property attribute's property drawer.
No, property attribute drawers take precedents over just plain property drawers
Ah, perfect! Thank you.
Permissions issue maybe? There's an editor log file that might have more helpful information if there's no popups or anything: https://docs.unity3d.com/2020.2/Documentation/Manual/LogFiles.html
Isn't like because i have Windows 11
No idea, it could be anything. Check the logs and look for an explicit reason for why it failed to install.
Is there any way of refreshing the Asset Database without triggering a Domain Reload?
I'm calling AssetDatabase.Refresh from a Script and I was expecting it NOT TO trigger a Domain Reload
https://docs.unity3d.com/Manual/AssetDatabaseRefreshing.html
This documentation page says this:
Unity performs the following steps during an Asset Database refresh:
1. It looks for changes to the Asset files, and then updates the source Asset Database
2. It imports and compiles code-related files such as .dll, .asmdef, .asmref, .rsp, and .cs files.
3. It then reloads the domain, if Refresh was not invoked from a script. <------------- ?????
4. It post-processes all of the Assets for the imported code-related files
5. It then imports non-code-related Assets and post-processes all the remaining imported Assets
6. It then hot reloads the Assets
step number three seems to be inaccurate?
my code triggers a Domain Reload when it shouldn't (according to the documentation)
If a code asset changed, it will trigger a domain reload. Is it doing it even when no code changes happen?
It only happens whenever I change any script
so I guess the documentation is just poorly worded?
You are talking about 3.? If you remove the comma it reads properly I think
according to 3, it shouldn't trigger a domain reload if I'm calling Refresh from my script
I'm now assuming that anything that triggers a recompilation will also do a Domain Reload and reset the scripting state?
if that's the case, 3. is just wrong, because Domain Reloads happen regardless
Yeah it seems to be worded poorly/incorrectly. I think it means it will force a domain reload regardless of changes when refresh is not invoked from a script.
Maybe...?
Or maybe it is just straight up wrong
Regardless, it should only cause a domain reload when a code asset changes
this seems to be accurate
I think it means it will force a domain reload regardless of changes when refresh is not invoked from a script.
hmmmm you may be right, for example like entering Play Mode always triggers a Domain Reload
Really wish the docs were on github and accepted PRs. They could be improved so much by the community. Even if just fixing small things like this.
yeah
I think further down in the docs they somewhat clarify on this
When you change and save a script, Unity hot-reloads all of the project’s script data. It first stores all serializable variable values in all loaded scripts, reloads the scripts, then restores the values. All of the data stored in non-serializable variables is lost during a hot reload.
I've always had trouble reading their docs on these topics (script compilation, serialization, domain reloading, etc)
they include a lot of information but it's a little bit all over the place
and there's many places where information seems contradictory if you don't have hands-on experience with the particular topic
😓 eh
I'm trying to figure out a way to draw the Texture of the sprite the player selected (for no other reason than the fact I think it looks good lol), yet I'm struggling to figure out a way to reference what texture the user chose
if there's an object selected you can possibly pull the value of the Property value you've set & create a GUILabel using the texture as the GUIContent parameter.
I'll give that a try, thanks!
If you're using PropertyField, use FindProperty(propertyname).objectReferenceValue
can cast to the Texture value.
I know how much of a pain Editor Extensions can be
been ground-up rewriting my camera management system from my uni group's project. Had to solve a lot of hiccups and it's not been fun.
also you're probably gonna want to clamp the values of GUILayout.Width() and GUILayout.Height() to fit in the editor window if you're pulling a texture, otherwise you'll pull the full resolution texture and mess your editor window's sizing.
yeah it took me like 3 hours of tutorials and documentation diving just to get to where that screenshot is lol
yea it's quite... un-fun.
wish more people knew how they worked so more tutorials would be out there lol
and then you have to deal with asmdefs or asm files if you're doing a package.
I haven't even scene a file with that extension sounds super fun lol
I'm making a dialog manager thingy for my main project & to have something to do over the summer
asmdef (Assembly Definitions) are files used for plugins
they're usually within a package and not often seen solo
There's Game Dev Guide, Brackeys and Code Monkey that are usually starters to elements of an Editor Window.
but it's a fairly obscure part of unity compared to what many use unity for.
I'm the only one in my uni course to do an extensive custom editor window. In the history of the course.
The only reliable documentation
as far as I'm aware my uni doesn't have a class about tools/editor extensions
Neither does ours.
We barely even touch custom inspector changes
Level 5s and 6s don't exactly touch Editor Windows either.
I'm curious on what you're doing with your editor window.
e.g. how you're tackling styles
my plugin rewrite creates style files and style-related background textures if they're missing.
https://misterparakeet.itch.io/
I just started yesterday basically off of the name lol
my old version used constantly recreated GUIStyles every refresh.
I haven't had to make any style files yet
I just followed gamedevguide's vid
and got here lol
Unity does allow for some default GUIStyles.
custom styles give you more ability to change the contrasting sections
Oh I see, I'll have to look into that once the basic functionally is done
I save the source texture backgrounds as texture files encoded to PNGs then rebind them when necessary if ever the styles lose the texture binding.
(which happens occasionally)
the GUIStyle format can just be saved as a JSON file because that's what it pretty much is. A giant JSON file that the unity devs had a chuckle implementing.
GUISkins are also an option but I prefer the extra agility I can get from separate styles that can be pulled independently and extended or modified.
Yeah I really like what you have so far, looks very professional
a lot of my current rewrite has been just background additions and extra stuff
I added Multi-Camera support which is still being actively worked on and rewritten
I am curious as to why you would need to write a custom editor script for camera management, I've only ever used cinemachine as a crutch lol
because I'm not using what CineMachine does
nor do I exactly need it.
I'm adding in a system that lets people test various types of camera movement
e.g. focus events, follow object, linear track, cutscene track
and has systems that can work between different types of cameras - 2D, 3D, Cinematic being the main ones.
I'm also working on Scene Renderer slaving for cameras that can be attached to a main camera so you can do extra render techniques such as shaders.
and Camera Presets that you can save and load, provided you have extensions for any third-party custom camera systems added to obscura.
Obscura is also fairly decently integrated into Unity's general shortcuts and hierarchy.
currently it only filters for cameras but it's going to get more efficient over time.
Idk what to say besides "that sounds so cool" lol
there'll also be scriptable cameras using exposed Obscura functions
so you can disable runtime altogether and just do what you want
it'll be entirely open-source
oh and setting up a camera will be in two separate stages
Developer Setup using a full-fat script that contains every function
then a Compiled Setup which takes the specifically used modules and creates the separated component versions of the modules for efficiency.
Developer Setup being so you can just change anything and have it take less time than the compiled setup, which should really be for when you've decided on what that level should have camera wise.
I know for certain others have their own ideas of what to use for cameras
CineMachine, Pro Camera 2.5D, etc.
but they just don't fill the specific needs
the original Obscura I was working on only ever worked on one camera system
and it would break if more than one camera was in a scene.
A handful of people have been constantly been giving me QA feedback for both versions too
and so I've built the rewrite around the lessons I learnt for spending the first 3 months on the uni project version
There's a relatively new api for that but I forgot what it's called
Update:
Public build is now available:
https://forum.unity.com/threads/overlays-public-build-available.1018858/
Also, for devs, a quick-start guide...
omg thank you so much!!
is there a way to get the PropertyDrawer that corresponds to a PropertyAttribute?
TagAttribute --> I have this
TagDrawer --> I want to get this type
ah nevermind, I went for a different approach
I used reflection to get the drawer directly from the SerializedProperty
which leads me to another question, a field can only use a single PropertyDrawer? correct?
and it seems if you try to use multiple drawers on a single field, it will use the first you provide?
[Tag] [ReadOnly] [SerializeField] private string _someTag; --> uses Tag attribute
[ReadOnly] [Tag] [SerializeField] private string _someTag; --> uses ReadOnly attribute
in 2020.3 it only had a list of DecoratorDrawers
in 2021.1 they seem to have added another list for PropertyDrawers
If I modify the Handles.matrix do I need to manually reset it once done?
Yup it’s kinda permanent. You have to restore it to what it used to be before
My fav way of doing this is to make it a disposable scope
tried to use Handles.DoPositionHandle in EditorWindow and unity returned me NullReferenceException in UnityEditor.Handles.GetCameraViewFrom :(
Pain. Is there any extentions that allow to use this sorts of handles in GUI?
hey so i've came across this video (https://www.youtube.com/watch?v=WtcnuaWrKOQ) and i was wondering how did they draw this pink wire cylinder gizmos, any idea?
i dont recall seeing any DrawCylinder in the Gizmos class and i was thinking maybe it was drawn using Handles?
Handles are the only thing i can think of right now
you can draw a cylinder using two circles and four lines
using Handles?
yes
though nothing stopping you from using gizmos
just have to draw the circle using lines
Is there a way to wait for AssetDatabase.ImportAsset() to finish before proceeding with the build? I call ImportAsset() from IPreprocessBuildWithReport.OnPreprocessBuild() and it imports the asset just fine in the editor but the imported asset does not exist in the built exe
alright thanks!
@round blade you can try this https://docs.unity3d.com/ScriptReference/BuildPlayerWindow.RegisterBuildPlayerHandler.html
ok thanks
ok i seem to have identified the problem incorrectly, the file does get added in the build, it is just using the wrong extension
thanks for the answer tho
gtk
Unity forum post for discussion:
https://forum.unity.com/threads/scene-tooling-2021-preview-extended-overlays.993494/
Hello! Welcome to a preview of our new Extended Overlays solution! As a reminder, this is only in planning, we can't guarantee anything, but we really do want your feedback and thoughts, early in the process, so thanks for w...
how can I do this?
I can't seem to find any tutorials
oh ok thanks
What does plugin.cs and Effect.shader do? https://helpx.adobe.com/animate/using/create-sprite-sheet.html
I'm using ObjectField to let the end-user assign a RenderTexture to a camera's TargetTexture but it's marked as obsolete. Creating a SerializedObject version of the Camera and attempting to use PropertyField for targetTexture does not work. Is there any alternative? - Unity 2020.3.29f1
Does anybody know how to get the type or reference to a deleted asset? I’m building a tool that should refresh when certain data-containing scriptable objects are deleted from the project
Any help is appreciated
I created a ScriptableObject instance through CreateAssetMenu. Then I modify this scriptable object using Resources.Load. I save the changes using EditorUtility.SetDirty and AssetDatabase.SaveAssets.
During play mode, I load this scriptable object and then unload it using Resources.UnloadAsset. The problem is the scriptable object resets to its default state when I do this (in this case, the serialized List inside it becomes empty). This doesn't happen when I don't use Resources.UnloadAsset.
I am not using any Editor scripts during Play Mode.
Figured it out. You can't use Resources.Load and then modify the asset. You have to use AssetDatabase.LoadAssetAtPath which is difficult since I want the user to be able to put the asset in any resources folder, not just Assets/Resources.
do I have to make something like this myself or is there an official way of doing it?
a menu like this I mean
where it prompts you with settings and you have a button to fix all as well
Hello, I did a custom editor for a ScriptableObject, I used
EditorGUILayout.PropertyField for most fields and I have a changeCheck that applies the changes to the serializedObject.
Howerver, when I do CTRL-Z to Undo the editor is not being repainted. If I switch selection and go back I have the undo-ed value.
I tried calling Repaint manually but it didn't work. I also tried overriding RequiresConstantRepaint but it did nothing.
is there a way I can detect when a script is added to an object?
like, kind of like a Start() on the script that just checks for that
If the script has execute always attribute then it will call awake
But otherwise I don't believe so
alright thanks!
Are there naming convention guide somewhere for editor stuffs?
Eg what to name classes for windows, custom editors, menu items, etc.
It's fine I figured out a way
Not officially, but there are common ones.
- For windows, end the name with the
Windowsuffix (e.g.ProjectBrowserWindow). - For custom editors, end with the
Editorsuffix (e.g.MeshRendererEditor) - For property drawers, end with the
DrawerorPropertyDrawersuffix (e.g.RectDrawer, orRectPropertyDrawer)
Everything else is basically whatever. The general rule of thumb is to end the name with what it is.
Generally those are in a class with other things and not in their own.
But if you want them in their own class, I would do something like MenuItems or AssetMenuItems(as an example, of course if it is not related to assets then don't use that)
I'm making a CustomEditor for a class that has an array of an interface marked with SerializeReference. Use case is picking an implementation of that interface in the inspector and adding an instance of that implementation to the array. Works fine until I try to actually access the array in my CustomEditor to add the new instance. I have a SerializedProperty for that array (and drawing it works fine with EditorGUILayout.PropertyField), but accessing managedReferenceValue throws the error "managedReferenceValue is only available on fields with the [SerializeReference] attribute". The array is definitely marked with SerializeReference, so I'm assuming this is the wrong way to do this. So how do I access that array (and write to the property after)?
Can you share the array code? and the relevant editor code?
I had an idea and actually made it work haha. In case you are interested, the trick was that SerializeReference applies to the elements in the array, not the array itself, but my SerializedProperty is the array. That's why managedReferenceValue didn't work. It works by adding an element to the property with InsertArrayElementAtIndex, getting the SerializedProperty for that new index with GetArrayElementAtIndex and then setting managedReferenceValue on that one instead of the whole array.
Ah, yup yup. All Unity attributes only apply to the elements in arrays/lists and not the arrays/lists themselves
what's the ratio that defines when unity shifts elements down and tries to put them on a new line? Trying to support it with my custom property drawer
This is what happens when I make the inspector thinner. playing around with some values and two monitors makes it seem like it's ~3/10 of the screen height but that feels a bit weird
so everything works fine on my other pc, but i just got this laptop up and running. when i try to play the game on it some things don't show up in the scene or look kind of weird a tiny bit? mostly just that one of my projectiles doesn't show up when its instantiated, it's still hitting things and doing damage and im not getting any errors
i just cant see it
and its on the right layer
like certain animations don't play and some sprites just dont show up
Heyas,
I ran into an issue using the [SerializeReference] in a ScriptableObject's custom inspector. I want the field to be nullable, but be drawn and edited in the inspector when not null. This is done through the code below:
if (GUILayout.Button ("Add Stat Modifier")) buff.statModifiers = new ObjectStatisticsCollection ();
} else {
GUILayout.BeginHorizontal ();
content = new GUIContent ("Statistic Modifier", "A collection of statistical bonusses that will be applied to a unit while the buff is active.");
EditorGUILayout.PropertyField (serializedObject.FindProperty ("statModifiers"), content, GUILayout.Width (EditorGUIUtility.labelWidth + 300));
if (GUILayout.Button ("X")) buff.statModifiers = null;
GUILayout.EndHorizontal ();
}```
Now, without the [SerializeReference] tag on the statModifiers everything gets drawn as intended, but as soon as I do add the [SerializeReference] tag to that field it will only draw the name and a little expand arrow, but nothing else (see image below).
So, how would I get the custom inspector to draw this class (preferably without having to do so manually)?
That is because it has nothing to draw. Unity serializes things by value by default. That means that the the fields have a default value of a newly created instances of whatever class the field is and are never null. However, when you add the [SerializeReference] attribute, it means that Unity serializes the field by reference, which in turn means the default value is null instead.
I have a question about editor coding, i'm not that advanced but i wrote some Editor/Inspector scripts already... i was wondering if there would be a way to generate a object which act as a folder in the scene hierachy but monobehavior would not see them as a game object (so if this "folder" is a parent of a go, the child go would not see itself under the folder, it would think its directly in the scene)
hope i managed to explain whats in my brain
this would come very handy in some networking solutions as they dont like the nested objects in some cases and i use empty go's for structuring my scene
I have an EditorWindow which has 2 reorderable lists in, If it's open when exiting play mode or discarding changes to a scene, then the SerializedObject is destroyed and I get type mismatch in the reorderable lists.
public class BuilderLists : ScriptableObject
{
public List<VehicleAudioData> audioData = new List<VehicleAudioData>();
public List<CollisionEffectsData> collisionData = new List<CollisionEffectsData>();
}
private BuilderLists _dataObject;
private SerializedObject _serializedObject;
private ReorderableList _reorderableAudioDataList;
private void OnEnable()
{
_dataObject = CreateInstance<BuilderLists>();
_serializedObject = new SerializedObject(_dataObject);
FindVehicleBuilderSettings();
SetupReorderable();
}
private void SetupReorderable()
{
_serializedObject = new SerializedObject(_dataObject);
_reorderableAudioDataList =
new ReorderableList(_serializedObject, _serializedObject.FindProperty("audioData"), true, true, true, true)
{
drawHeaderCallback = rect => { EditorGUI.LabelField(rect, "Audio Data"); },
drawElementCallback = (rect, index, active, focused) =>
{
var element = _reorderableAudioDataList.serializedProperty.GetArrayElementAtIndex(index);
rect.y += 2;
EditorGUI.PropertyField(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), element, GUIContent.none);
},
onAddCallback = addList =>
{
var index = addList.serializedProperty.arraySize;
addList.serializedProperty.arraySize++;
addList.index = index;
var element = addList.serializedProperty.GetArrayElementAtIndex(index);
element.objectReferenceValue = null;
}
};
}
private void OnGUI()
{
_serializedObject.Update();
_reorderableAudioDataList.DoLayoutList();
_serializedObject.ApplyModifiedProperties();
}```
Where are you calling SetupReorderable?
Just calling it in OnEnable should fix your problem
It's already in there
edited the above code to how it actually is
it appears the _dataObject is the thing that's getting destroyed
Adding this at the top of OnGUI() has sorted it
if (_dataObject == null)
{
_dataObject = CreateInstance<BuilderLists>();
_serializedObject = new SerializedObject(_dataObject); LoadPrefabSetup(); SetupReorderable();
}```
It isn't getting destroyed, you are just losing the reference to it
the error says it got destroyed
No, the error is that the SerializedObject is destroyed
Putting a log in OnDestroy() is logged out too
it's not. the error says the target for SerializeObejct was destroyed
Wait, is this for entering playmode or for a domain reload, or both?
exiting play mode, or a discard of scene changes
Ahh
I guess that's a domain reload ?
Before creating a new one, try doing Resources.FindObjectsOfTypeAll<BuilderLists>() and see if you get any.
doesn't find any
Ooh, I know why duh
So what is happening when exiting play mode is that Unity cleans up all the resources and resetting things. This includes GCing all of the loose UnityEngine.Objects
You can prevent this from happening by using the HideFlags.DontSave
Doing so means though that you need to make sure to clean it up via DestroyImmediate(..) or it will create a memory leak
Thanks for the reply; that makes a lot of sense.
I'm still kinda stumped, though. I don't know how to get from this reference to the actual (StatModifier) object that I'd like to draw. I attempted to just make my own draw function inside of StatModifier object, and simply call that from it's instance (bypassing the SerializedProperty). This works perfectly fine for base types (bool, int, etc), but to draw the classes within I'd use PropertyField() which takes a SerializedProperty; I don't know how to bridge that either. SerializedProperty's are a pain, is what I'm saying.
How do I get from this SerializedProperty containing the pointer/reference to a SerializedProperty containing the actual object to be drawn?
You are still misunderstanding I think. Your issue is that it doesn't have anything to draw in the first place.
You can do serializedProperty.managedReferenceValue = new YourClass(); to set the value of the property so it will have something that it can draw
This is the best I could come up with.
SerializedProperty abc = serializedObject.FindProperty ("statModifiers");
abc.managedReferenceValue = new ObjectStatisticsCollection ();
EditorGUILayout.PropertyField (abc);```
I doesn't draw anything still and I don't get it.
I have been using visual studio code for the longest time and it felt wrong to use visual studio 2019 for my unity related work
today i tried switching and failed miserably
unity fails to load intelisense
my error is as follows:
[fail]: OmniSharp.MSBuild.ProjectLoader
The reference assemblies for .NETFramework,Version=v4.7.1 were not found. To resolve this, install the Developer Pack (SDK/Targeting Pack) for this framework version or retarget your application. You can download .NET Framework Developer Packs at https://aka.ms/msbuild/developerpacks```
i have installed this version, uninstalled it and repaired it to no avail
if anyone could help me that would be great
The developer pack? https://dotnet.microsoft.com/en-us/download/dotnet-framework/net471
yep
installed and reinstalled
aswell as the .net sdk 6.0.3
ive fiddled with path variables
ive fucked about in the file explorer
what would the normal path variable be?
please help im still struggling
Have you changed editor preferences
and installed the Unity Extension for VS 2019
It's also available through Visual Studio Installer and you can install Unity from there too.
Have you checked to make sure that the SDK is not installed in both x64 and x86?
i did have the extension installed and up to date and i deleted all dotnet related stuff and re-installed
is there a way to configure the path for omnisharp
help needed, why does the debug ray only render properly if my cursor is moving, and when my cursor is stationary the debug ray is rendered infront every object?
private void OnSceneGUI()
{
Debug.DrawRay(CalculateStartingVector(point), -_detailPatch.transform.up * _height);
}
My guess would be that the scene view only repaints when the mouse moves (and other times), and the Debug.DrawRay is being called after it.
It is best to use the Handles API for drawing in the sceneView
ahh alright
one more thing, how can i make the red Handles go "darker" when it is below an object? currently using Handles.zTest = UnityEngine.Rendering.CompareFunction.Less; but it's not drawing the Handles that are below an object?
show code please
Please direct your question to the #💻┃unity-talk channel. This channel is for programming related discussion (like creating custom windows).
Don't forget to remove this message first since posting the same thing in multiple channels is not allowed. Best of luck 🙂
ok thanks
ah my bad, here's the code
private void OnSceneGUI()
{
Handles.zTest = UnityEngine.Rendering.CompareFunction.Less;
Handles.color = Color.red;
// Draw top and bottom disc
Handles.DrawWireDisc(_detailPatch.transform.position + (_detailPatch.transform.up * (_height / 2)), _detailPatch.transform.up, _radius);
Handles.DrawWireDisc(_detailPatch.transform.position + (-_detailPatch.transform.up * (_height / 2)), _detailPatch.transform.up, _radius);
// Draw 4 corners lines
Handles.DrawLine(_detailPatch.transform.position + (_detailPatch.transform.up * (_height / 2)) + (_detailPatch.transform.forward * _radius), _detailPatch.transform.position + (-_detailPatch.transform.up * (_height / 2)) + (_detailPatch.transform.forward * _radius));
Handles.DrawLine(_detailPatch.transform.position + (_detailPatch.transform.up * (_height / 2)) + (-_detailPatch.transform.forward * _radius), _detailPatch.transform.position + (-_detailPatch.transform.up * (_height / 2)) + (-_detailPatch.transform.forward * _radius));
Handles.DrawLine(_detailPatch.transform.position + (_detailPatch.transform.up * (_height / 2)) + (_detailPatch.transform.right * _radius), _detailPatch.transform.position + (-_detailPatch.transform.up * (_height / 2)) + (_detailPatch.transform.right * _radius));
Handles.DrawLine(_detailPatch.transform.position + (_detailPatch.transform.up * (_height / 2)) + (-_detailPatch.transform.right * _radius), _detailPatch.transform.position + (-_detailPatch.transform.up * (_height / 2)) + (-_detailPatch.transform.right * _radius));
}
extremely messy
You are never setting the 'other' color
Did you look at the example in the documentation?
Er, I misspoke, it is not another color, you basically just draw the same thing a second time but with a different color and zTest
alright will give it a try
Hi. I have editor tool that loads prefab with PrefabUtility.LoadPrefabContents, edit it, then save with PrefabUtility.SaveAsPrefabAsset. How can i record this changes to 'Undo'? Or there is some other way if i want to go back to previous prefab wersion?
Are you talking about edit an existing prefab or creating a new prefab? If you are just editing it, then you just Undo.RegisterCompleteObjectUndo(prefabAsset);
I have a slider in a GUI class but always when I start the game its reseting its values, what could be the problem?
I assume you are probably not using SerializedProperty, and since you aren't that means you are setting the value without dirtying the object.
Got this annoying bug where if i have a protected var and i add SerializeField and my custom HideInSubClass attribute, it gives me an error saying NullReferenceException: Object reference not set to an instance of an object. HideInSubClassAttributeDrawer.ShouldShow (UnityEditor.SerializedProperty property) (at Assets/Scripts/Property/HideInSubClassAttributeDrawer.cs:13) Any ideas?
using System;
using System.Reflection;
using UnityEditor;
using UnityEngine;
[CustomPropertyDrawer(typeof(HideInSubClassAttribute))]
public class HideInSubClassAttributeDrawer : PropertyDrawer
{
private bool ShouldShow(SerializedProperty property)
{
Type type = property.serializedObject.targetObject.GetType();
FieldInfo field = type.GetField(property.name);
Type declaringType = field.DeclaringType;
return type == declaringType;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
if (ShouldShow(property))
EditorGUI.PropertyField(position, property, label); //fun fact: base.OnGUI doesn't work! Check for yourself!
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
if (ShouldShow(property))
return base.GetPropertyHeight(property, label);
else
return 0;
}
}```
it works if i only have a public var using the custom atr (i guess that is the original idea, but still)
also line 13 is the Type declaringType = field.DeclaringType; line
@carmine basalt
Type.GetField(String)
that only works for public fields
you need to use the overload that takes in a BindingFlags parameter
check the Microsoft docs for that method
ah, forgot about this one
you can probably also just do
Type declaringType = fieldInfo.DeclaringType;
question: does anyone know how to create modifications to the existing unity tab views, like console specifically
i've seen other packages that create custom consoles with log channels and i wanted to make something similar, but i have no clue how to create an editor that will override or subclass the existing one
iirc you need to reimplement those windows and add your changes on top of that.... but that might have changed
There are two options. Either you create your own window from scratch (which a lot do) or use a patching library (like Harmony) to inject your own code in to Unity's code for the specific window.
oh ok. is there any reference on how to create one of those windows from scratch? because the editor window code for the console window is on the github. i assume i could copy pasta most of the core functionality
but constructing a class with the same format didn't seem to work
There are pinned messages for getting started with creating custom windows in general. And you cannot copy paste from the console window code from github both because it uses a number of internal APIs and because the code is reference only, meaning you cannot redistribute it.
i didn't copy paste the whole code i was just trying to construct a window that overrode the console, so i copied the class inheritence and the window name attribute
and did a base implementation of the specified interface
i don't see any of the pinned messages regarding creating a custom window. I make custom inspector views all the time but there's still a gap of knowledge there in creating a window that overrides the console output
i checked code beginner/general/advanced, her, i'm not sure where its' supposed to be
My bad I thought there was one. https://docs.unity3d.com/Manual/editor-EditorWindows.html
Quick question. I'm using AssetDatabase.RenameAsset to rename a scriptable object used by my editor extension through code, however when it does this it reimports the object and loses all of its variable values that have been assigned in the inspector. Is there any way to keep the values?
You are probably setting the values without dirtying the object
After setting dirty do I have to save them or does that happen automatically?
That is the whole point of dirtying 😛
It tells Unity that the object is dirty and next time it does a save, that object is one of the ones that needs to be saved.
But setting something dirty itself doesnt save anything tho. You have to then click Ctrl + S etc. to actually save all dirty objects
@patent pebble I'll check these out, thanks! Also I'll highly likely return with some more questions since im relatively new to this
should i use SerializedProperty when making custom inspectors?
or does it depend on my use case?
Got an example?
public class DetailPatch : MonoBehaviour
{
public DetailPalette detailPalette;
}
public class DetailPatchInspector : Editor
{
SerializedProperty _propDetailPalette;
private void OnEnable()
{
_propDetailPalette = serializedObject.FindProperty("detailPalette");
}
private void Test()
{
_propDetailPalette.???
}
}
like
how can i get my dedtailPalette value?
You can't get the instance, but you can find properties in detailPalette using FindPropertyRelative
oh?
_propDetailPalette.FindPropertyRelative("something")
so if my DetailPalette is something like
public class DetailPalette : ScriptableObject
{
public Mesh[] meshes;
public Material material;
}
i can get the material value like this: _propDetailPalette.FindPropertyRelative("material")?
There's also a bunch of ...Value fields on a SerializedProperty for Unity object types and most basic types
Yes
so to get the value of material you can do _propDetailPalette.FindPropertyRelative("material").objectReferenceValue as Material
i see i see
Arrays are GetArrayElementAtIndex or something similar
ahhh yea it's GetArrayElementAtIndex
so i guess for the array it's _propDetailPalette.FindPropertyRelative("meshes").GetArrayElementAtIndex(0) huh?
what if i wanna check if _propDetailPalette is null or not?
ehhhh?
.objectRefernceValue
_propDetailPalette is never null since it's serialized by unity
Or rather it shouldn't be
I think there's some edge cases where it is but you shouldn't be able to draw a propertydrawer/editor for it anyways then
i see i see
can i just do a null check using _detailPatch.detailPalette?
if (_detailPatch.detailPalette != null)
{
//do something
}
hmmmm why is it null?
public class DetailPalette : ScriptableObject
{
public Mesh[] meshes;
public Material material;
}
Hey everyone, been a while since I did editor scripts. Im trying to create a custom editor for a scriptableObject. Made a CustomEditor script, which works for monobehaviours but it does not seem to work for scriptableObject assets, Am i missing something? Should the GUI calls be in the SO script itself?
Nevermind, im an idiot. typeof was wrong
Hey @patent pebble iirc you were working on a PropertyDrawer who's height depended on the width. Did you ever find a good solution to that?
Hi all! I am trying to make an editor script that duplicates an existing prefab at new location. I am using AssetDatabase.CopyAsset however the issue is, if a prefab already exist at the new location, I'd like the GUID of the duplicate prefab to remain the same. With CopyAsset, Unity creates an entire new asset and assigns it a new GUID.
I found EditorUtility.CopySerialized but it doesn't seem to be working. If I try to copy a prefab with a Terrain component, the new prefab does not have a Terrain component attached. Has anyone worked with this method and know if it should be copying the Terrain correctly (maybe I have a bug somewhere). Or do you know of another way to make a copy of an asset while preserving the GUID of any existing assets being overwritten?
I can't remember exactly which one, I've been prototyping a bunch of different PropertyDrawers lately that do a bunch of stuff based on height/width
maybe this one?
what exactly are you looking for?
Yeah that looks like it! How did you calc the height?
I think I treat is as a "grid", iirc my code was not very optimized
brb, i'll share it
and also this extension method
using UnityEngine;
public static class GUIStyleExtensions
{
/// <summary>
/// Calculate the size of an IMGUI control with a constrained width.
/// </summary>
public static Vector2 CalcSizeWrapped(this GUIStyle style, GUIContent content, float maxWidth)
{
Vector2 size = style.CalcSize(content);
if (size.x > maxWidth)
{
size.x = maxWidth;
size.y = style.CalcHeight(content, maxWidth);
}
return size;
}
}
@gloomy chasm i think that's all the relevant code
if you need anything else I can dig further
I just came from vacation so I've lost track of a lot of stuff 😅
in that PropertyDrawer i use the code like this (pseudocode-ish)
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
// Calculate error box size
Vector2 errorBoxSize = PropertyDrawerErrors.GetErrorBoxSize(_propertyRect, linesAmount: 2);
// Calculate combined height of all valid types boxes
float validTypesBoxesHeights = CalculateValidTypesBoxesCombinedHeight(errorBoxSize.x);
return Mathf.Round(errorBoxSize.y) + PropertyDrawerStyling.SpacingY + Mathf.Round(validTypesBoxesHeights);
}
private float CalculateValidTypesBoxesCombinedHeight(float errorBoxWidth)
{
return IMGUIUtility.GetVariableRectsGridHeight(_typesContents, PropertyDrawerErrors.TypeBoxStyle, errorBoxWidth, PropertyDrawerStyling.TypeBoxLineHeight);
}
it's still a bit wonky
so the height calculations may not be 100% solid
don't know if that's caused by GUIStyles, by my height/width calculation or what
i still need to iron out a bunch of small bugs
I see what you do. Thanks.
so, my property drawer looks like this:
What do I need to fix it?
(current problem: the size of the property not extending to contain the entire property)
I think I need to edit GetPropertyHeight but I don't know how: public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return base.GetPropertyHeight(property, label); }
also to clarify, this is a property drawer for a class, not a monobehavior or etc.
@wild dragon try this
https://docs.unity3d.com/ScriptReference/EditorGUI.GetPropertyHeight.html
probably with includeChildren set to true
{
return base.GetPropertyHeight(property, label, true);
}``` This doesn't work. How do I get it to set includeChildren to true without getting the red squiggles?
base.GetPropertyHeight
v
v
v
EditorGUI.GetPropertyHeight
@wild dragon
well, that did something
but not quite what I intended
it seems like it's affecting the formatting of the properties' height as well
hard to tell without seeing the code you use to draw
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
probably they way you are calculating the rects
I did pull it straight out of a tutorial video, with slight modifications for the lines (as I couldn't tell how to make a new line in the drawer otherwise)
I'm willing to bet I need a new method for new lines and that will fix it
debug the rects individually with this
https://docs.unity3d.com/ScriptReference/EditorGUI.DrawRect.html
use different colors for each
green is position, red blue and yellow are min/mirrored/maxrect
what I need to know is how to make the element's window larger
You have to calculate the height of the elements you are rendering, easiest is to just go through the same ones you are rendering and sum them with EditorGUI.GetPropertyHeight
and set what variable/run what function to make it so that only the background changes size, not the properties?
I've been trying to look at examples but it's unclear what sets the drawer's background's size without changing each individual property's size in the process
OnGUI gets the size of the total area it's allowed to draw it
How you use that space is up to you
Overriding GetPropertyHeight lets you change the height of that area
You're really not giving information so I can't tell you how to fix it, if you're calling PropertyField (or any other GUI draw method) with the rect you get as parameter then that's the problem
You need to calculate the right size for your field and only draw in that area
this is my code for the entire drawer
is it EditorGUI.PrefixLabel that sets the backdrop's size?
@wild dragon without seeing the class you are drawing with your PropertyDrawer it's hard to tell
EditorGUI.GetPropertyHeight() will give you a height for the entire drawer, based on all the properties it has to draw
so for example if you have SomeDrawer to draw the class SomeClass and there's 3 string variables in that class
you will get from EditorGUI.GetPropertyHeight() a height of 3 rows
You're using position.height directly, this is always the height of the whole area that you are allowed to draw in
Not the height of a single element
^
There's a single element height field in EditorGUIUtility.SingleLineHeight
Or, you can use EditorGUI.GetPropertyHeight(SerializedProperty) to get the height that is needed for a given PropertyField
Alright, we'll do this a different way since I'm not understanding. I have this example property drawer that only draws 3 labels:
public class TestPropertyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginProperty(position, label, property);
Rect minRect = new Rect(position.x,
position.y,
position.width * 0.4f - 5,
position.height);
EditorGUI.LabelField(minRect, "Line 1");
EditorGUI.LabelField(minRect, "Line 2");
EditorGUI.LabelField(minRect, "Line 3");
EditorGUI.EndProperty();
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
//return EditorGUI.GetPropertyHeight(property, label, true);
return base.GetPropertyHeight(property, label);
}
}```
the problem is you are using the position
position.height should be EditorGUIUtility.SingleLineHeight in that case
it should be clear how the drawer should look, but it looks like this:
@wild dragon read this documentation carefully
https://docs.unity3d.com/ScriptReference/EditorGUI.GetPropertyHeight.html
it tells you it will calculate the height of your property, including all the children
I have tried that, but when I managed to get the backdrop to change size, it also changed the spacing of the properties, effectively not fixing the issue
Yes because your math is wrong
if you have this class
public class SomeClass
{
public string a;
public string b;
public string c;
}
that method will tell your drawer the height for the entire thing will need 3 lines (for A, B and C)
so then yourpublic override void OnGUI(Rect position, SerializedProperty property, GUIContent label) will receive that height
Rect position has now a height of 3 lines
as you can imagine, you don't want to use the full 3-line height for every single sub-property
or you will end up with a total height of 9 lines
for a simple class with 3 strings like that one doing this will take care of the 3 strings automatically
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.PropertyField(position, property, GUIContent.none, true);
}
because it's drawing the entire class using the 3-line height, so everything is fine
if you on the other hand, wanted to draw every sub-property manually, you would do like so
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
Rect r1 = new Rect(position.x,
position.y + (EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing) * 1, //Line 1
position.width,
EditorGUIUtility.singleLineHeight);
Rect r2 = new Rect(position.x,
position.y + (EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing) * 2, //Line 2
position.width,
EditorGUIUtility.singleLineHeight);
Rect r3 = new Rect(position.x,
position.y + (EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing) * 3, //Line 3
position.width,
EditorGUIUtility.singleLineHeight);
EditorGUI.PropertyField(r1, property.FindPropertyRelative("a"));
EditorGUI.PropertyField(r2, property.FindPropertyRelative("b"));
EditorGUI.PropertyField(r3, property.FindPropertyRelative("c"));
}
Let me explain my line of thinking right now, so you can help me understand: You are saying that the reason the backdrop and the elements are changing size at the same time is because of a math problem. But as I am trying to just change the size of the backdrop alone, I do not see what you mean or why that is. If I'm approaching this the wrong way, then let me ask another way: What's the right way to make an element get drawn on a new line instead of the same line?
Because the method I used draws the extra elements off of the backdrop.
what it sounds like you're saying is that position will automatically adjust to what the height of all of the properties should be, and that the issue is that I'm using position to calculate the rect. Okay. I understand that.
So how do I draw an element on a new line?
aka, how do I draw all three labels from this in sequence from top to bottom, instead of layered over each other?
just ignoring property fields right now
Rect element1 = new Rect(position.x,
position.y,
position.width,
EditorGUIUtility.SingleLineHeight);
Rect element2 = new Rect(position.x,
position.y + (EditorGUIUtility.SingleLineHeight + EditorGUIUtility.standardVerticalSpacing),
position.width,
EditorGUIUtility.SingleLineHeight);
Rect element3 = new Rect(position.x,
position.y + (EditorGUIUtility.SingleLineHeight + EditorGUIUtility.standardVerticalSpacing) * 2,
position.width,
EditorGUIUtility.SingleLineHeight);
so you have to have a new rect for each element ...
Or in the case of PropertyFields
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var p1 = property.FindPropertyRelative("s1");
var p2 = property.FindPropertyRelative("s2");
var p3 = property.FindPropertyRelative("s3");
Rect r1 = new Rect(position.x,
position.y, //Line 1
position.width,
EditorGUI.GetPropertyHeight(p1));
Rect r2 = new Rect(position.x,
position.y + (r1.height * 2), //Line 2
position.width,
EditorGUI.GetPropertyHeight(p2));
Rect r3 = new Rect(position.x,
position.y + r2.height, //Line 3
position.width,
EditorGUI.GetPropertyHeight(p2));
EditorGUI.PropertyField(r1, p1);
EditorGUI.PropertyField(r2, p2);
EditorGUI.PropertyField(r3, p3);
}```
Creating an instance of an rect is not drawing it, it's just math. Calling PropertyField or w/e method is the actual drawing
immediate guess is that the rect code goes in GetPropertyHeight(), but unless I'm overthinking it, I don't see how that works
(because it's not recognizing SingleLineHeight)
singleLineHeight
Not working with an IDE here 😛
In that example, your height that you return in GetPropertyHeight is EditorGUIUtility.singleLineHeight * 3 + EditorGUIUtility.standardVerticalSpacing * 2
GetPropertyHeight() is just the way of telling the system what height it needs to allocate for the ENTIRE property
public class TestPropertyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginProperty(position, label, property);
Rect element1 = new Rect(position.x,
position.y,
position.width,
EditorGUIUtility.singleLineHeight);
Rect element2 = new Rect(position.x,
position.y + (EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing),
position.width,
EditorGUIUtility.singleLineHeight);
Rect element3 = new Rect(position.x,
position.y + (EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing) * 2,
position.width,
EditorGUIUtility.singleLineHeight);
EditorGUI.LabelField(element1, "Line 1");
EditorGUI.LabelField(element2, "Line 2");
EditorGUI.LabelField(element3, "Line 3");
EditorGUI.EndProperty();
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return EditorGUI.GetPropertyHeight(property, label, true);
//return base.GetPropertyHeight(property, label);
}
}``` where's the extra space coming from?
return EditorGUI.GetPropertyHeight(property, label, true);
and return base.GetPropertyHeight(property, label); makes the backdrop one-line-tall again ...
Either return base.GetPropertyHeight(property, label); which is always one line
Like I said here, you need to calculate the height
🤔
@wild dragon can you share your FloorEvent class?
what variables does it have that are being serialized?
several "parameter classes" that I would need to make property drawers for as well
so I want to get this example done first
plus it's actually 2:11 AM here and I really shouldn't be up this late because I have class in the afternoon (late afternoon but still)
I didn't expect this to take as long as it did, simply put
EditorGUI.GetPropertyHeight(property, label, true) will just get the combined height of ALL the variables
if you want to have manual control over the height you have to do the calculations yourself
like i said
public class SomeClass
{
public string a;
public string b;
public string c;
}
doing EditorGUI.GetPropertyHeight(property, label, true) for that small class gives me the height I want, 3 lines
but if I had a bunch more vectors and floats and ints, it would get all of them even if I just wanted a height for the 3 strings
in that case i would do something like
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return (EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing) * 3
}
that worked for the line example!
it's the problem with following tutorials online
they give you all the code, condense the entire concept in a 10 minute video
and you miss all the actual meat of the topic
experimenting with very small, self-contained tests is way better to learn this stuff
written tutorials are usually better for editor stuff
I should be able to reverse engineer this to at least get started on properly implementing it for the FloorEvent class ... after sleep. I will most likely have some questions still since the class I'm making this propertydrawer for is ... packed, but I think I can at least get started now. Thanks.
(I work best with examples, which is why I figured it would be best to figure out a simpler "3 line" layout than trying to make the whole FloorEvent class support it when that's going to be more complicated than just "making a new line")
Gotta sleep now. Thanks for the help, truly!
You got an extra space here tho
Good night
@waxen sandal 💀 rip, my reputation as a professional Unity discord helper has been tarnished
crawls away in shame
Time to remove that role
rip
Hi I am trying to debug my code with visual studio code on an M1 Macbook
I've followed all these steps
but I'm not really sure what this step is asking me to do:
Anyone knows how to change the background color in PreviewSceneStage?
There's a "Background for Prefabs" in Preferences > Colors, so clearly it can be changed, just now sure how prefabs do it.
@patent pebble PropertyDrawers.cs is the main script I'm working on, FloorEvent is the class the drawer is for, the rest are just included because of references in FloorEvent requiring they be included (and because they too will need to be in the property drawer by extension).
What is the proper way to launch a Modal window from a custom inspector editor window? Everytime I try I get an error message saying "GUI Window tried to begin rendering while something else had not finished rendering! Either you have a recursive OnGUI rendering, or the previous OnGUI did not clean up properly."
my modal window is being shown with ShowModalUtility
How can I make sure the custom inspector stops rendering before the modal editor window starts rendering?
I've tried throwing an ExitGUIException from the OnInspectorGUI code of my insepctor, when I open the modal window.
I've tried only opening the window when the current event type is Repaint or Layout
Well nevermind, I changed out ShowModalUtility for ShowModal and it now works fine, so I guess there is a bug with ShowModalUtility
UITK people, Is there some way to do a binding template? I.e. I'm binding to a string and want it to show {Value} is something something normal text
how can i change my gui button colour if a boolean is true? i wanna set the "Edit" button background to like black or something when _inEditMode is true
public class DetailPatchInspector : Editor
{
private bool _inEditMode;
public override void OnInspectorGUI()
{
if (GUILayout.Button("Edit"))
{
_inEditMode = !_inEditMode;
Debug.Log(_inEditMode);
}
}
}
You mean for SerializedProperty binding? NOPE
Well... actually yes. You register a ValueChanged event and use SetValueWithoutNotify to then set the value to what you want
Yeah, the binding in UITK is a bit scuff still
Yeah I've always complained about it
GUI.color, GUI.backgroundColor
Tbh I think it is it's 'only' real place it is lacking in
alright will read the documentation
Hello. I'm having trouble with LabelField() => https://gdl.space/ejozufujes.cs
I'm trying to show text from a string, which has been changed by a function.
Rewritten it a bunch of times to test different approaches, and googled a lot, but so far I don't get this.
It's one of the major problems still, it's gotten better
What is the actual trouble you are having? 😛
hmmm does it affect all buttons?
Ah 😅
The text from the string variable isn't displaying.
Well.. are you sure there is text to show?
I assume that s is empty
My guess would be that the path is not finding any \\ to split at
Yup
what if i want it to be specific on only one button?
Huh, somehow this isn't returning my path. It's the function that is in error.
I've been running in circles 😅
You change it back after you've called your button
Reset the color after drawing your button
ah i see
wait am i doing it correctly
public class DetailPatchInspector : Editor
{
private bool _inEditMode;
public override void OnInspectorGUI()
{
if (GUILayout.Button("Edit"))
{
_inEditMode = !_inEditMode;
if (_inEditMode)
{
GUI.backgroundColor = Color.white;
}
}
}
}
No, you should set the color before you draw the button, and reset it afterwards
ah
like this??
public class DetailPatchInspector : Editor
{
private bool _inEditMode;
public override void OnInspectorGUI()
{
if (_inEditMode)
{
GUI.backgroundColor = Color.white;
}
if (GUILayout.Button("Edit"))
{
_inEditMode = !_inEditMode;
}
}
}
Yeah, however white iirc is the 'default' color that resets it.
Is it possible for a Button to change the value of a variable in a LabelField?
Fixed: I was setting the variable inside OnGUI (overriding any changes).
Has anyone made an editor script so you can use the scroll wheel to navigate in the inspector while you are currently dragging something?
One thing I need confirmation on before I continue my independent study essay
Is it true that any folder named "Editor" is not compiled into the runtime application? (regardless of placement in the folder hierarchy inside Assets)
@earnest talon yes
thanks, I've been running around documenting all sorts
Does anyone know how to recreate or access the default GUILayout button texture? I'm trying to disable button hover by assigning button.nornal.background to button.hover.background (or any of the other button states) does not work, because button.normal.background is actually null. So behind the scenes Unity must detect the null background and auto create a texture for it. Anyone know how to do the same? I want to capture the rounded corners of the texture.
It is in the button.normal.scaledBackground
Or it is something like that
Bump, still looking.
Fun fact, all Editor UITK elements are created for every target change of any inspector. So even Property windows will rebuild if the target of an inspector changes.
Hi, I don't think so but I'll take a look. When you query the value of even button.normal.background you see that it is null, however Unity is drawing something, so obviously it is creating the texture or retrieving it at some point. I'll look in the source code however it's likely behind the c++ wall.
No, it is using the texture from button.normal.scaledBackgrounds[0]. The "or something like that" was in reference to the name of the property. I couldn't remember the exact name at the time.
Thanks, exactly what I'm looking for, but it's internal hmm.
Reflection
Well since all it's doing is just:
m_Camera.backgroundColor = StageNavigationManager.instance.currentStage.GetBackgroundColor();
I tried grabbing the current camera and changing the background color directly or every frame, doesn't seem to do anything though.
@gloomy chasm I've got a listview with a bunch of buttons, when I click that button I want to get the item in the list. Obviously you can do that by just doing a lambda and capturing the index when subscribing, however you can't really unsubscribe in that situation anymore. How do you handle this?
Apparently you can set clickable to null which seems coutnerintuitive but okay
Also using icons results in shit quality, any ideas?
Also ScrollTo doesn't always bring the item into view
you need to execute it next frame
and yeah, thats the thing with ListView
someThing.schedule.Execute(()=> {}).ExecuteLater(0)
I don't think that matters?
funny thing is, if you're adding the element via .showAddRemoveFooter it would work flawlessly
that's what I've been doing, if it's not working I don't know tbh... ListView is powerful but buggy at the same time
thus, buggy as said above 😃 ...
@waxen sandal have you tried adding it via .showAddRemoveFooter ? it's flawless, and the ScrollTois toggled on by default
oh, then why not just ScrollView?
wdym
you can do the same with your own dragManipulator
Right but effort
but yeah, it will bloat a bit
without executing it the next frame it is almost impossible to ScrollTo, and this is after Rebinding then do ScrollTo the next frame
@waxen sandal try to rebind the List first, then srollto the next frame
ListView is a cool feature, but sorta broken...
Yeah my list is a 1000 items, scrollTo does work but it's just off by a few rows
that is weird... proly report it as a bug
do you put a custom margin for each element or nah?
proly check if the VisualElement's height displayed the correct value
Yeah that's fine
You mean UITK? Set the userData of the button to be the index, then you have no need to unsub the lambda.
Yeah, user data feels so hacky though
Anyways fixed that already
Now stuck making my own insert line in a list view
But will continue tomorrow
It seems Unity unloads the visual part of editor windows (like their UITK elements) after being hidden (in another tab) for a while. Anyone know a way to force this?
Is there like a end of update cycle event/callback, or for ever a repaint or after al IMGUI code is run or something...?
I'm probably doing something wrong but after dragging the object I want into the inspector field, if I run the game it changes to None again
You need to dirty the target object. However you should be using SerializedProperty instead of setting the values like that.
Sorry I'm still learning about the editor, can you explain what do you mean by dirty and SerializedProperty?
Dirty, tells Unity that the object has changed and needs to be saved. https://docs.unity3d.com/ScriptReference/EditorUtility.SetDirty.html
SerializedObject and SerializedProperty are a way to interact with the actual serialized data of UnityEngine.Objects. Using them will let your editor automatically support undo/redo, no need to dirty the object, and will support multi editing and prefab overrides
https://docs.unity3d.com/ScriptReference/SerializedObject.html
question, if centerPoint is already a member of CameraTrigger, why are you trying to jam its value into another member?
like someone else said you can just serialize the member
hi there, i wrote some custom inspector code
these use PropertyField(FindProperty(..)) to be drawn
and then at the end of my inspector function i call serializedObject.ApplyModifiedProperties();
this functions normally for 'path' and 'path length'
but I can't get the values to update for those fields with '3' in them
the two text fields are within DrawNode, sub function
that looks like this
void DrawNode(int nodeIndex) {
Road.Node node = road.nodes[nodeIndex];
EditorGUILayout.HelpBox($"{Screen.width}", MessageType.Info);
EditorGUILayout.BeginHorizontal();
for (int i = 0; i < node.columns.Count; i++) {
EditorGUILayout.PropertyField(serializedObject.FindProperty($"nodes.Array.data[{nodeIndex}].columns.Array.data[{i}].width"),GUIContent.none);
}```
it comes from Road.nodes[i].columns[j] (which is of type Node.Lane) .width
and the value it's displaying is correct but it just isn't getting written back i suppose and i'm not sure why that is
so what can i do to make this property update correctly?
is there a way to make a list<> (for use in a scriptableobject) that doesn't expose the add/remove button to the user in the inspector?
using a ReorderableList
it's a little bit of boiler plate, but it gives you a lot of control over the appearance and behavior
i think it's undocumented, but the API is public
Google should give you a bunch of tutorials
Is there any way to access the mesh names that are inside an FBX? I can see them in the inspector but I would like to verify if they are named correctly when I import them into the database
not the mesh asset itself, I mean the subMeshes
oh, nevermind. I can just use the transform cuz they are technically prefabs
Anyone here use NaughtyAttributes? is there a way i can have an infobox in the inspector, not tied to a property? i want it to act just like a Readme. a brief overview of what the class does.
Don't use Naugghty, but no there isn't. The only way to do that is if it was a attribute on the class.
Also, Naughty is really unoptimized and does a bunch of reflection every frame.
Only apparent in editor though right?
Yeah yeah
How can I use GUILayout and BeginArea to set out a custom block in between other inspector fields?
for example i have a couple of EditorGUILayout.PropertyField here
and then afterwards i guess I want to grab a rect beginning at the next available layout space, can I do that?
GUILayoutUtility.GetRect iirc
ooh ok :) i'll check it, thanks
Does anyone know if its possible to get the position and height/width of the Game window relative to the whole screen?
Screen.width etc maybe?
@tawdry kraken I ended up running in a circle on this one. Yes Screen.width should do it, but I also need the position of the window as well. I'm looking at EditorWindow.focusedWindow at the moment for all of that
I'm not sure I can help, but first: Why do you need the position?
Hey guys i don't know if this technically qualifies as an editor extension or not, but there is a code file within an Editor subfolder that defines helper 'build' menu items. I think this is common to do. So it has a using statement referencing unity editor, which makes sense....however the build itself is failing because i guess this code file is referencing the unity editor and doing that from within the player code isn't allowed? Ok.... then how do i not 'include' this code file? It is already within a folder named Editor if that has any effect.
EditorWindow.focusedWindow.position perhaps
I have some hardware that is giving me an absolute position of the mouse cursor on my screen and I'm having trouble getting it to scale and position properly in the editor (standalone build is not an issue, this is just a development annoyance). This is a very particular problem in which I cannot use Input.mousePosition for.
Resources.FindObjectsOfType<EditorWindow> should find it, just check for the name
And then just use position
GUILayout.BeginHorizontal();
GUILayout.Label("");
GUILayout.Label("");
GUILayout.Label("");
GUILayout.EndHorizontal();
GUILayout.FlexibleSpace() can be used instead of a Label or similar, to provide space between
well the block itself will be manually laid out with rects
ah, then you have the correct solution, it seems
ty anyway :)
@tawdry kraken @waxen sandal EditorWindow.position got me what I needed. Thanks!
hey guys! anyone can give me tips on tracking when an object was renamed in the hierarchy?
i don't want to subscribe to EditorApplication.update
or onHierarchyChange
I want something like OnValidate, but for renaming
I use OnValidate with a bool that executes in Update
using UnityEngine;
[ExecuteAlways]
public class OnValidateWorkaround : MonoBehaviour
{
private bool validate;
private void OnValidate()
{
validate = true;
}
private void Update()
{
if (Application.isPlaying)
{
// Play Mode
}
else if (validate)
{
validate = false;
// Editor
}
}
}
Why?
ooh thanks I might have a few good ideas with this
you mean why I don't wanna use onHierachyChange? is there a good option with onHierachyChange?
hey @tawdry kraken what's the use of this, though? I don't understand why you'd execute OnValidate in Update with a bool... isn't that kinda the same as just having OnValidaote? Is there something obvious I'm missing
For reasons I read about over a year ago, executing code inside OnValidate often returns various warnings.
This approach works around that, and is practically no different.
oh ok cool thanks
actually, you know what, you are probably right, "why" is a good question here. i might have to use it actually
I'm writing my own PropertyDrawer and I made a selection popup
The propertydrawer is for a class with two fields (int, and another c# class)
After getting the returned int from the selection popup, I need to set the fields of said class
How do I do that?
https://docs.unity3d.com/ScriptReference/PropertyDrawer.html
This doesn't seem to explain how user inputs can be written back into the original serialized field
basically I somehow need a reference back to the field being edited
Anybody knows why probuilder is not snapping to the grid in Unity 2021?
Any help is appreciated
good afternoon, how do I make something similar to this with OnInspectorGUI? When a condition is true, it plays a smooth animation showing the hidden property
Source code has the answers
https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/Inspector/CanvasEditor.cs#L267
thank you!
Try to ask on #🛠️┃probuilder. This is channel about coding your own editor extensions
property.intValue = yourValue
get the properties by name relative to the property you're given in OnGUI (I'm assuming you're doing imgui)
i just worked around it but I basically needed to set a field whose type is not one of those
it's not an int/float/string/ whatever
if it's a class, you need to reset the fields individually
same thing with structs
as in like the field isn't anywhere near something that had primitive typed fields lol
what is it?
it's a c# object which I absolutely needed to pass around by reference
if it's not one of those, or a struct/class with those fields, then it's not serializable
do a serializable class?
object?
like object?
an instance of what is this object?
if it's just object, you can't serialize that
Ok, awesome! When I get back to my computer I'll be able to get things working then. Thanks!
I'm going mad trying to make a simple editor window that has a single serialized property
Can anyone give me a hand or shoot me a good tutorial on this?
@opal tapir ?
I just did some code restructuring so I didn’t need that any more
that didnt work sadly, the field is completely gone now
BindingFlags.NonPublic or BindingFlags.FlattenHierarchy makes no difference tho (when using the overload)
yes i've read that, didn't help
i'll just make it not inherit instead, solves the problem quicker tbh
not like it needs to inherit anyway
Hey fellas!! A quick one that maybe you can spot me on or point me on the right direction. If I want to populate an AssetReference (Addressables) on the editor from path (working from a custom drawer). Do I load the object on the editor with LoadAssetAtPath and then assign the objectReference or is there a different method for AssetReferences?
I guess there is another trick cause it doesn't work....
it has a constructor that takes the guid
@jovial zealot Good point, let me try it out
I can create it but I cannot assign it:
string guid = AssetDatabase.AssetPathToGUID(path);
AssetReference ar = new AssetReference(guid);
int index = collection.arraySize;
collection.InsertArrayElementAtIndex(index);
collection.GetArrayElementAtIndex(index).objectReferenceValue = ar; // ERROR HERE: cause AssetReference does not inherit from Object.
You are going to need to take a peek at the source code to find what the field is called that stores the reference to the asset
@gloomy chasm Thanks a lot... on it....
I will look into SerializedProperty see if I can find something. But I guess SerializedProperty should be agnostic to Addressables... no? There is no dependency.
Haaa wait... you mean in AssetReference
Sorry for my slowness....
Yeah I mean look at the source for AssetReference so you can see what field stores the guid (or whatever it stores) so you can then get that field with SerializedProperty and set it.
Alllllmost got it!! 🙂 I feel I am getting close:
collection.GetArrayElementAtIndex(index).objectReferenceValue = ar.Asset;
No compiler errors but I get empty references
Is it a list of AssetReferences?
yes, an array
huuuu nice!!
collection.GetArrayElementAtIndex(index).FindRelativeProperty("m_AssetGUID").stringValue = AssetDatabase.AssetPathToGUID(yourAssetPath);
Holy crap..... It works perfect
You are the freaking god of reflection @gloomy chasm!!
Hahaha, well thanks! Glad to help.
https://github.com/needle-mirror/com.unity.addressables
But what is nice about Unity moving to packages, if you have added the package, you can just look in the "Packages" section of your Project Browser window and see all the source code for any given package 🙂
What do you mean?
Hooooo ofcourrrrrse!!! duhhh
Gotta use reflection
how can i link a GUILayout.Toggle to a boolean in a script?
hahahha here we go!!! 😂
Iirc it is EditorUtility.SetObjectIcon(object, texture)
Use a SerializedProperty. You can look in the pinned messages for more info
You can just assign the value that it returns if you have access to it I guess:
myBoolValue = GUILayout.Toggle(myBoolValue, "Toggle me!!");
Of course, like @gloomy chasm said, myBoolValue should probably be a SerializedProperty.
Also you will need to dirty the object that the bool is on or it will not save when entering playmode, saving scene, recompiling scripts etc.
Or just use SerializedProperty like you should haha.
You're totally right....
Basically there is almost never any reason you should not be using SerializedProperty.
But it basically works the same way right? I should have written:
myBoolValue.boolValue = GUILayout.Toggle(myBoolValue.boolValue, "Toggle me!!");
Right?
Yup, exactly!
Ha... ufff... Thought I had to re-write my life for a moment there... 
But really you don't even need to do that.
EditorGUILayout.Toggle(myBoolProperty, "Toggle me!!")
That is enough!
Oops, fixed it
All the EditorGUI(Layout) methods that take a value have a override for just taking a SerializedProperty
Of course you can also just use the EditorGUIlayout.PropertyField(anyProperty)
Yes, of course 🙂
Great to know... saves time! But doesn't work with GUILayout then?
EditorGUILayout and GUILayout are exactly the same. The only difference is that EditorGUILayout has editor specific overrides and methods. Such as ones that take SerializedProperties
So you can use them indiscriminately?
Because GUI and GUILayout were originally made to work at runtime and not just in the editor.
Yeah, I always found that strange indeed
Yup
Smarter every day! Thanks @gloomy chasm
iirc EditorGUILayout actually inherits from GUILayout. But don't quote me on that.
😉 Trying to verify that but not easy with the partial class definitions... Seems not to inherit but could be anywhere else...
https://github.com/Unity-Technologies/UnityCsReference/search?q="partial+class+EditorGUILayout+%3A"
Yeah, guess it doesn't. I must be thinking of a different class
I am trying to make an editor drag and drop field so I can drop several sprites at once rather than having to drag and drop every single one. The Error it is giving me in the editor as soon as I drop my 8 frames is: "InvalidCastException: Specified cast is not valid."
Whats wrong??
You can't cast arrays like that
You have to cast each item in the array. Think of it this way, you have a public class Object__Array { } and a public class Sprite__Array { }
As you can see, they don't have any relation so they cannot be cast from one to the other.
(Note that this is an imperfect explanation, but I hope helps a bit to get the basic idea)
so the only way to create a dropfield for an array is to drop every item one by one?
No, you just iterate over the array and cast each one
List<Sprite> sprites = new List<Sprite>();
foreach (Object obj in DragAndDrop.objects)
{
if (obj is Sprite sprite)
sprites.Add(sprite);
}
return sprites.ToArray();
thank you, I think I got it
Hi Anton, thanks for the response. Unfortunately that is for custom inspectors, not EditorWindow (which doesn't appear to have the serializedObject property).
Ok, I figured it out. Needed to create a scriptable object asset to save the window data in.
is there a way to have a button show a scriptable object in the inspector when i click it?
is there a tool out there somewhere that will analyze my code and give me a visual graphing / mapping like in visio? Like a block diagram. All the results for mapping and visualizing tend to be related to something different code wize.
There's a SelectObject function
Don't remember which class
Selection class
Hi, how can I catch the "Save" action in its Editor (i.e. custom Inspector)?
https://docs.unity3d.com/ScriptReference/PrefabUtility.SaveAsPrefabAsset.html this might help. you could override the old prefab with the new save
I have an array of rects that should be "pressable" I am currently trying it like that. The function creates the buttons but when I click one of them there is no feedback. what do I have to change? or is there even a method to click directly on the rects without having to lay a transparent button on top?
Hey all! Just wanted to post this here in case anyone finds it useful, I wrote a quick editor script that implements a hotkey to automate the process of building and running two local copies of your current open scene (for the purpose of local multiplayer client testing)
https://github.com/andrueandersoncs/unity-editor-scripts
*currently supports macOS specifically, but welcome to PRs to expand the functionality
No one has a solution to this?
i tried to install the cinemachine package to my project and i got this error
i dont know what it means
Is there a way that I can create a field that accepts multiple completely seperate types but limited to accepting these specific types? Secondly if you want to do validation on a custom type are there any other alternatives to EditorGUILayout.ObjectField since that is deprecated?
Hi! when I want to create clickable areas I do not use buttons (because they could be areas with multiple elements). I catch the MouseDown event and check if it intersects the Rect.
like:
//Draw your clickable area here.... and then:
if (Event.current.type == EventType.MouseDown)
{
Rect rect = GUILayoutUtility.GetLastRect(); //If you have that info (or if you are in a CustomDrawer you can use the Rect that you used to render the clickable box directly)
if (rect.Contains(m_Event.mousePosition))
{
//Area was clicked, do stuff here...
}
}
repeat ☝🏻 for each of your areas.
you can do Rect.Contains instead https://docs.unity3d.com/ScriptReference/Rect.Contains.html
hi there
working with custom inspectors
i have a normal reference type here
if the reference is not null i want to also display the inspector that referenced instance would have
how could i do this?
the HDRP does this
it displays the contents of the referenced volume and that's what i'd like to do too
What constants
Like there's a CONTEXT/Component that adds a context menu item to the context menu that appears when you right click a component
So the /stuff part constants
What do you mean there is none if there is CONTEXT/Component?
I want a list
Of these
Not necessarily literal constants in code
Component is just the type afaik
There's no premade list
https://docs.unity3d.com/ScriptReference/MenuCommand-context.html see the example here
How to add buttons to hierarchy context menu?
Like when you click an object in hierarcy
It's just GameObject/something
is there any trivial way to inject extra command to this button?
I'm guessing most would just make their own build dialog anyway
I'm currently running editor script for connecting Quest 2 via wifi with adb command and I need to hit that refresh (if I want to visually see the quest on the list) after that command is done, would be nice to get it all done with single click
I guess the easiest alternative would be to use editor coroutine to keep the quest wifi link connected always, it's just not as elegant
Hi, someone can tell me if there is some easy way to inspect a ScriptableObject instance?
Select it in the inspector?
i have only a reference in a component
it shows only the property field
not the content
Double click it and it'll probably select it in the inspector
You can also make a custom property drawer for it if you want
oh yes! double click worked! thank you!
I have already created a CustomEditor for this ScriptableObject because I needed some extra-editing functionalities. If I try to create a CustomPropertyDrawer I get an error in the inspector
"No GUI Implemented"
Well you gotta implement a gui lol
I already created several property drawers in my project and they works. I don't understand what's the problem now
(I implemented a gui anyway 😄 )
You should post the code, I don't have much time to check it btu someone else might
btw is it ok to have a CustomEditor and a CustomPropertyDrawer for the same class?
I've downloaded 2021.3.3f1. First element of a custom class in a list isn't drawn correctly. Anyone else seen this behavior?
Brand new project, no custom drawers or editors.
Hi, I am making a custom inspector for my script and I've found a useful thing called Foldout, however it needs to be done for every script individualy since it works like this example:
ExampleScript es = target;
isFoldedOut = EditorGUILayout.Foldout(isFoldedOut, "Name");
if(isFoldedOut)
show stuff like es.Something
so I was wondering, is it possible to make a custom attribute that you could use like this:
[Foldout]
{
var 1;
var 2;
var 3;
}
sounds to me like you want a propertydrawer instead of a editor script
this way, you can serialize any class or struct, and simply show them like how you're used to
https://docs.unity3d.com/ScriptReference/PropertyDrawer.html
just don't mind the pictures, they're from the unityscript days it seems 💀
nope that's not what I want
what I want is to be able to serialize all my variables but show them in groups
so have foldable:
[Foldout("Movement")]
{
float speed;
float jumpHeight;
}
[Foldout("Combat")]
{
float health;
float damage;
}
Nope
wym nope
I mean you can't. You would use what is called a DecoratorDrawer for doing this, however that only works on a single property at a time. So the bet you could do is to have a foldout for a single property.
The solution to this to write a custom base attribute and a custom default object editor where you manually resolve the custom attribute for drawing.
Additionally, there is no way to get the contents between { } as they 'don't exist'
That would be kind of an ugly solution. But yes that would be the easiest. There are free packages that have grouping like what you want (except for the { })
doesn't need to use {}
I just want them to be grouped and be able to expand and collapse them {} just helped explain what I want
I am making this game as an open source project so that I can share it w everyone so I'd like to make an attribute my self
but I am kind of confused with what I should do and I couldn't find anything online on how to make a "foldable" attribute in unity
Well you can include the package I just linked, or since it is MIT you can just include it in your project.
Or rip the code that you want out
I just told you how to do it...
ok, I'll take a look at it and thanks!
Guys how do I get a reference of what port another port is connected to (in relation to the node/graph view)
(while in editorGUILayout)
uhhh
i made the font larger with the GUI style
now it exceeds the box
but i can't find any way to make the reserved area larger?
im very confused? this is a blind spot?
the GUIStyle has a property for font size, so?
i cant use a property drawer to affect the height because EditorGUI.PropertyField doesn't take a gui style
Code?
@waxen sandal i was able to solve this eventually but i do have an outstanding question above at #↕️┃editor-extensions message
Idk how hdrp does that but it might just be a extra component that looks at the same profile and then draws its properties
ok so i made some progress but i got stuck again and i need some help
so i made this property called lod levels, you can see the GUI for it here
this gui is being made in a usual way, through OnInspectorGUI
the properties are sourced from serializedObject.FindProperty in the usual way. this works
i have one quirk, that I pass it through a function first, like this
but when it's running in the editor loop it works fine
ApplyModifiedProperties there at the bottom
so next: I have this property LodLevels also exposed in another object
and the way i'm doing this is by constructiong a new SerializableObject during the GUI function based on the object that roadNetworkAssets is referring to
and this ?sort of works? in the sense that the object represented is the correct object
if i make the reference null, then there's nothing to display.
so the object is correct
as you may expect this is done by calling that exposed Draw function with the new target and serializeableObject