#↕️┃editor-extensions
1 messages · Page 98 of 1
Yes
Ok thanks guys, I guess I went down the wrong rabbit hole
😂 Ok not quite but getting somewhere - the dot is a GUILayout.Box in an editor [CustomEditor (typeof (TetrisShape))]
Ok got it working with GL! Thanks! My next issue is trying to figure out how to get the actual data out of SerializedProperty - type casting doesn't seem to be doing it
https://help.vertx.xyz/?page=programming/editor-issues/serialisation/serializedobject-how-to
Let me know if any of it is confusing
Thank you! I am reading now
Thank you! Oh that wasn't so bad. I have book marked your site
This is my full code if anyone ever stumbles across this
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomEditor (typeof (TetrisShape))]
[CanEditMultipleObjects]
public class TetrisShapeEditor : Editor {
Material mat;
public RenderTexture preview = null;
SerializedProperty pattern;
private void OnEnable() {
pattern = serializedObject.FindProperty("pattern");
var shader = Shader.Find("Hidden/Internal-Colored");
mat = new Material(shader);
}
private void OnDisable()
{
DestroyImmediate(mat);
}
private void DrawSquare(float x, float y)
{
GL.Begin(GL.QUADS);
GL.Vertex3(
x * 50,
y * 50,
0f
);
GL.Vertex3(
(x * 50) + 50,
(y * 50),
0f
);
GL.Vertex3(
(x * 50) + 50,
(y * 50) + 50,
0f
);
GL.Vertex3(
(x * 50),
(y * 50) + 50,
0f
);
GL.End();
}
public override void OnInspectorGUI() {
base.OnInspectorGUI();
GUILayout.BeginHorizontal(EditorStyles.helpBox);
Rect rect = GUILayoutUtility.GetRect(10, 1000, 200, 200);
if (Event.current.type == EventType.Repaint)
{
GUI.BeginClip(rect);
GL.PushMatrix();
GL.Clear(true, false, Color.black);
mat.SetPass(0);
for(int i = 0; i < pattern.arraySize; i++) {
var element = pattern.GetArrayElementAtIndex(i);
var vec = element.vector2Value;
DrawSquare(vec.x, vec.y);
}
GUI.EndClip();
GL.PopMatrix();
}
// End our horizontal
GUILayout.EndHorizontal();
}
}
THanks for the help good night
I'm not sure what I did, but, my GetWindow<T>() isn't creating an instance anymore if one doesn't exist. I've had to go to CreateWindow. I don't really have any code to share because that's it hehe
nvm, commented basically all of the window code out atm, and then did reset layout, and that worked
is there a way to tell when scene window focus is regained ?
EditorWindow.focusedWindow
I haven't fully finished this script yet to see, but, is there a specific purpose I would do
protected override bool OnOpenStage()
{
return base.OnOpenStage();
}
protected override void OnCloseStage()
{
base.OnCloseStage();
}
in a stage setup vs just using OnEnable and/or OnDisable?
what's that based on ?
It's for scenes
i got a script that creates materials OnEanbled and disposes them onDisable ,
added [ExecuteInEditMode] and subscribed to these events :
UnityEditor.SceneVisibilityManager.visibilityChanged += Refresh;
UnityEditor.EditorSceneManager.sceneSaved += SceneCallback1;
UnityEditor.EditorSceneManager.sceneOpened += SceneCallback2;
UnityEditor.EditorSceneManager.sceneDirtied += SceneCallback1;
but it won't always work , for example when editing a shader and switching back the scene tab it won't fire any of the events
that's isn't how OnEnable/OnDisable work, though they could for niche things
made a DynamicMaterial script that holds a reference to the original material and creates copies in play / edit mode on enable
so the idea is to not have 100's of different materials in the project folder and instead only store the properties in the script
I'm getting the mesh leaking warning - I cannot modify shared mesh though because every instance of the meshes need to be different - any suggestions? I set each object to destroy the mesh in OnDisable.
Also how would I be able to tell if I am leaking meshes?
You still use sharedMesh. You make a new mesh and copy the mesh data to it
I tried that but it modified every mesh in the scene with the exact same shape, and then actually saved it permanently to the model. I had to restore it from blender.
Maybe I need to get the sharedMesh and then set the mesh?
the way I do it, and I know you can shorten this, but, I do it on purpose
Mesh newMesh;
void CopyMesh(Mesh m)
{
//List or arrays of however you want to get the data from m
newMesh.SetWhatever(lists or arrays);
//or
newMesh.vertices = lists.ToArray();
//or
newMesh.vertices = arrays;
}
is the general idea
you could probably even just do something like newMesh.SetWhatever(m.GetWhatever())
basically though, if you just say newMesh = m, you basically still have a reference to the originalData. I forgot the phrase that is used
you have to do the same thing with materials if you are creating them in code also
Here's my code: https://paste.ofcode.org/ZqcnQBbrvdcWNxbKn6JQfx
Line 32 in that paste is where I tried changing it to sharedMesh and it broke everything
So anytime I call meshFilter.mesh, I'm effectively creating a copy of that mesh. And the old copy from the last time I called it doesn't get garbage collected. Does that sound right?
But if I use meshFilter.sharedMesh, I'm getting a reference, not a copy? But I need it to be a copy.
Having trouble wrapping my head around this lol
It's the way the data is stored. When you use mesh it makes a copy of every single thing in the mesh
Like a struct?
for example, mesh will give you a unique mesh object. If you have a mesh that is used more than once and you call .mesh instead of .sharedMesh, Unity will duplicate the mesh to return a unique reference. This will impact both memory usage and rendering cost.
check out http://nothkedev.blogspot.com/2018/08/procedurally-generated-meshes-in-unity.html imo is helps understand the mesh stuff more
As I have mentioned at the beginning, when we stop using objects, as in - we don't reference to them anymore, they will be deallocated from memory. But unlike normal objects, Unity Meshes are a special case in that Unity considers them as "assets" and keeps them in memory... FOREVER! (Well, ok, not technically forever as assets will be unloaded if loading another level for example
> and >>> to quote btw
lol apparently im bad
Needs a space only, and I'd use triple to continue until the end of the paragraph
oh there we go
thanks!
vertx always teaching me the discord tricks, among other things haha
Thanks, good read. It sounds like I maybe just need to grab a copy of the mesh in OnEnable or something and then just use that every update. I'll play around with it and watch for issues in the profiler.
I'm still really noob in Unity, learning everyday, so, there may be a lot of things I'm missing. Personally, I actually save mesh data on a scriptableobject and create a mesh from that when I need one
Well I really only need the mesh data once. Every time the terrain settings are changed in my editor window I call that InitiailizeTerrain method and all the vertices change immediately - I shouldn't need to grab a new reference to the mesh everytime. In fact, if you take the settings to the extreme and any of the vertices drop below the bottom layer of the model, suddenly it treats that as the bottom layer and starts messing up the other vertices. If I just grab one reference once, that won't happen.
Maybe solves two problems at once.
I have a sky box that would apply to the first scene but not the second , any idea why??
and what i can do to solve it
it would apply but when i switch scenes it just changes
and if i compile it is also gone
Hi, I'm trying to figure out the best approach to take to make a custom editor that tries to depict a restricted field of view in 3d. I'm not sure of a better way to describe it than firing arcs from from a ship.
if I create a custom editor window (or property drawer) for a serializable, will a list of that object be serializable too, the usual way?
okay, how do I even add a custom PropertyDrawer to my custom Editor in the first place?
You mean this? https://docs.unity3d.com/ScriptReference/PropertyDrawer.html
nah I want to draw a propertydrawen within an Editor subclass, but i let it go
i didn't really need a custom editor anyway
Ya just do EditorGUI.PropertyField(..)
nah, that doesn't work
Sure it does
...Well then I must not understand what you want. Because that is what you do to draw a serialized property with a custom property drawer. (Just so you know, the serialized property has to be the same type as what the property drawer is for, it can't be a list or some other serialized property)
I created a PropertyDrawer for a serializable, which worked, all great. Then I wanted to create a custom editor for an object that has this property. Propagating the drawing with PropertyField didn't work, and on google I could only find some ugly solution that loads PropertyDrawers and propagates from the custom Editor
tldr, doesn't really matter now, I didn't need the editor in the first place
If that didn't work then you either did something wrong or the whole editor is broken
I'm going to bet in the first
care to show me a source code that does that then?
okay 😄
what if cfg is not a usual Unity serializable like Vector3, but something with its own propertydrawer? Then PropertyField will not call the PropertyDrawer. Or I did sth wrong, an old forum post said otherwise 🤷♂️
[CustomEditor(typeof(MyClass))]
[CanEditMultipleObjects]
public class MyClassEditor : Editor
{
SerializedProperty cfg;
void OnEnable()
{
cfg = serializedObject.FindProperty("cfg");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
// etc...
EditorGUILayout.PropertyField(cfg);
}
}
That is exaclty how it works, it is the *only way in fact to use a custom propertydrawer.
hmm
Are you sure cfg is serializable? If so, then you can share your propertydrawer and I can look at it.
If it is long you can put it in hastebin or something.
yup, because when I added it to a MonoBehaviour without a custom editor, it worked percetly
gimme sec i'll recreate the issue
public class MyClass : MonoBehaviour
{
public int asd;
public MyProperty myprop;
}
[Serializable]
public class MyProperty
{
public int val;
}
[CustomPropertyDrawer(typeof(MyProperty))]
public class MyPropertyPropertyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginProperty(position, label, property);
//position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);
var indent = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
EditorGUI.LabelField(
new Rect(position.x, position.y, 100, 18),
"whatever"
);
EditorGUI.indentLevel = indent;
EditorGUI.EndProperty();
}
}
this works.
custom editor:
[CustomEditor(typeof(MyClass))]
[CanEditMultipleObjects]
public class MyClassEditor : Editor
{
SerializedProperty asd;
SerializedProperty myprop;
void OnEnable()
{
asd = serializedObject.FindProperty("asd");
myprop = serializedObject.FindProperty("myprop");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUILayout.PropertyField(asd);
EditorGUILayout.PropertyField(myprop);
serializedObject.ApplyModifiedProperties();
}
}
and indeed it works
so smh
no clue what i screwed up then
hey, i got a question
so I'm trying to get character spritesheets from MuseDash so i can use as references in Blender
but whenever I decompress the file that contains said spritesheets, I'm unable to open the streamed data asset in Unity Asset Bundle Extractor
plus this is all i see when i go to the folder in the game that has the (assumably) package file with the character spritesheets. can someone help me with this?
Yeah can't help you with that as it likely breaks discord tos
Likely breaks the TOS of that game
also i asked a mod in the MuseDash discord if i was allowed to extract the spritesheets and they said that i can, as long as i dont use them for making mods, which im not
*official MuseDash discord
also im not looking to make profit off of said models that are using the spritesheets as references since im doing all of this because i'm bored, and for personal use
but eh.
anyone knows how to force unity editor use dedicated GPU ?
tried setting in nvidia control panel but it still uses the integrated one
ah nvm just noticed that info bubble ...
is there an editor utility to make gizmos draw with constant size regardless of the scene view camera position ?
well it ain't pretty but this seems to do the trick :
private void OnDrawGizmosSelected()
{
float size = 1f;
#if UNITY_EDITOR
size = UnityEditor.HandleUtility.GetHandleSize( transform.position ) * 0.25f;
#endif
...
}
FYI I don't think the preprocessor directive is necessary since OnDrawGizmosSelected runs in the editor only anyway.
hello i wish to ask why is my FieldOfView class suddenly could not be found on my FieldOfViewEditor? i didnt change any code either of the two class. although it is still working, im bothered why is this happening
I'm not really sure what is going on, but I think it is because of the "Editor" folder.
I'm using visual studio code, regenerating project files (Editor -> Preferences/External Tools) and restarting the ide helped
thank you! it did work in my case too! very helpful
Learned something new today. In an editor window you can add the method which will be called when the window is opened or docked as a tab to another window.
private void OnAddedAsTab()
{
}
(It is called when the editor window is added as a tab to a DockArea if you are familiar with the internals)
Likewise there is also OnBeforeRemovedAsTab()
@opaque zenith About your question from #🧰┃ui-toolkit it is hard to answer since I really have no idea what you are doing or or trying to do.
I'm trying to replicate the avatar window, but, more complex than what is there. Essentially, making my own prefab altering window
It's actually going quite well as I've been learning to mix both UIElements and IMGUI elements together
but I'm trying to figure out if I can do something one way, if it is always better to do it that way? For example, if I want to have a sceneview that constantly updates, is it better to keep it as an IMGUI thing, or, still do is through the UITK
UITK should be fine since it doesn't have to regenerate any geometry.
So, what exactly am I doing different by using an IMGUIContainer and putting a sceneview into that, vs, using the EditorWindows default OnGUI? It seems to even run smoother, but, I don't actually know why?
So, I guess from here, do I continue to use handles, or, do I create UITK overlays?
Those are to different things.
You can use handles with overlays, but that is as far as that goes.
they are two different things, but, you can imitate handles with UITK
Like a couple, but not the majority.
hey folks, making a custom editor window. Wondering what I use to hide a bunch of settings behind a drop down, similar to the 3D sound settings on an audio source
You can either have the types serialized in a class/struct in the first place, which will automatically show as a foldout.
Or you can use https://docs.unity3d.com/ScriptReference/EditorGUILayout.Foldout.html
If you use Foldout, you can use SerializedProperty.IsExpanded to make it persist between instances
I can't find a way to check if the ObjectPreview window is open or closed in my editor script.. is there any way?
There isn't anything about it here:
https://docs.unity3d.com/ScriptReference/ObjectPreview.html
Check reference source
Can't find. can you link reference source?
I did check here but again, can't find
https://github.com/Unity-Technologies/UnityCsReference/blob/2020.2/Editor/Mono/Inspector/AudioClipInspector.cs
I mean, you should check the reference source whether there is something
As I'm not aware of anything else
Oh lol ok thanks I'll make a workaround with flags (OnPreviewGUI won't be called when the preview is closed) I just tried to avoid this 🥴
Adding onto what vertx said, you can also use ToggleGroup and FoldoutHeaderGroup to achieve similar results.
I like FoldoutHeaders better than regular foldouts because they highlight when you hover the mouse over them, the entire lable is clickable by default, and you can add a custom button on the right side that you can use with GenericMenu to call your own functions
Hi, wondering if anyone here knows a good primer on using the preview Windows (I'm trying to visualize some data inside a Scriptable object). Is there support for drawing shapes and the like, or should I just draw my data to a render texture and display that(through a compute shader maybe ?) ?
Reference source is your best bet
Hey,
Can anybody explain why I can't do this:
[SerializeField]
[Range(0.0f, 100.0f)]
[OnValueChanged("ApplyProperties")]
float mValue;
It seems attributes, or some attributes can't be combined. Is there a way of writing my own Range attribute that'd have the same effect and also fire off a callback?
Do I have to make my own custom property drawers for ranged floats as well?
I have no idea, just giving you a link to that if you want to make your own. IDK what native things might already exist for that. Uhhh I think if go to the scripting api under the left hand side there should be Attributes you can look at
FYI, I just found I can achieve what I was after using 'OnValidate()'. Bit clumsy and unrefined (it'd be nice if it could tell me what had changed, if anything) but better than nothing.
if it's an Editor Script I use EditorGUI.BeingChangeCheck()
nice, thanks!
is there a way for me to override things in a method if I call the base in an override?
Like, even if I get methodinfo is there a way for me to alter what is going on in that method if it is called
You want to edit the base method from a derived class?
well, I'm looking over SceneViewfor example, and see CreateSceneCameraAndLights(); in it which does GameObject cameraGO = EditorUtility.CreateGameObjectWithHideFlags("SceneCamera", HideFlags.HideAndDontSave, typeof(Camera)); and I wanted to alter that, but, I realized I can just get the m_Camera field through reflection and alter that, but, I guess to refresh the popup SceneView I'm trying to figure out if there is a methodInfo I can use to update that camera change basically without making my own method basically hehe
and was thinking if I could someone just change that line
so then I was thinking if I make my own CreateSceneCameraAndLights(); I didn't know if I could alter the base OnEnable to use mine, instead of that one, for example, or if I would then need to create me own OnEnable
might be better to just not inherit from SceneView and just copy all of SceneView out
idk
That is not possible in C#.
You can do private new void OnEnable() { }
Yeah, I just found that out. I'm instead finding other ways
yeah! Exactly, doing that now!
though I'm kinda confused, since, now I have mutiple scene cameras, and they all have different names, but seem to be linked hehe
What...?
Nothing. It might be easier to just do what some people have done and created editor scripts where they have the scene camera following a GameObject camera with align view, but hmm
I haven't learned how to do complex stuff with previews, but i remember this article being a very basic introduction
https://timaksu.com/post/126337219047/spruce-up-your-custom-unity-inspectors-with-a
from the very limited experience I have with that topic, it seems like the API is all over the place with the preview stuff
there is a bunch of undocumented stuff, so you're gonna have to dig through the source code
okay, nvm, I figured it all out, and now have the cameras culling mask set also
next step is to now is imitate the inspector window
because right now clicking the objects in this scene updates the inspector window
is there a way to get the "parent" of a SerializedProperty?
so if i have this property path
parentProperty.childProperty
how can I go up and get the parent if I don't know the name?
should I just cut the path string at the period and call it a day? (it seems like a hacky solution 😓 )
I just do SerializedProperty.serializedObject to get the parent
yes but my parent isn't always the serializedObject
i have multiple levels of SerializedProperties within SerializedProperties
SerializedProperty.serializedObject != .targetObject though it can be
my structure looks like this
SerializedObject.SerializedProperty.SerializedProperty.SerializedProperty, etc...
yes, I know what you are saying
the problem is I never know what a parent's name is. I only know the child's name
if you do SerializedProperty.serializedObject on the third SerializedProperty it will return the previous SerializedProperty
because it's all dynamic data
oh does it? I was under the asumption that .serializedObject returned the top level object all the properties belonged to
serializedProperty.name serializedProperty.displayName
Object is the basis of everything in Unity. All your fields are Objects also. This isn't always true, but, for the sake of this, just assume it like that
so, for example, you have a custom class, that is the SerializedObject which you can find SerializedProperties on, however, it can also be a SerializedProperty if used in that way
I'm still trying to separate it all also. It is confusing at times. I do know if you do something like, serializedProperty.serializedObject.targetObject it always returns the topmost object
no matter what depth I'm at, it always returns the top level object
this seems to be incorrect
no matter what depth I'm at, it always returns the top level object
how are you iterating through your properties?
because, if you aren't storing previous serialized properties as you iterate chances are it will return the top
they are nested lists
Right, but, how are you getting the properties? How are you storing the properties?
it's a custom implementation of ReorderableList
it's kinda hard to explain
each level iterates on it's own list of children
top level object won't be the top level object if the initial value isn't the serializedObject, for example
I mean it will be, but, depending on how you are caching the serializedProperties, it won't be what you assumed it would be
it's always the top level object
🤷
that's why I asked if there's a built-in way of iterating backwards to get the parent of a SerializedProperty
other than manually fiddling with the path
everything works fine, but recompilation breaks some stuff, and I can fix it by iterating backwards through the hierarchy chain
how are you getting the serializedProperties? For example, SerializedProperty.Next(true) goes down if there is a child property, but will go to next property at same depth if there isn't. SerializedProperty.Next(false) will go to next property at same depth
are you sure you aren't referencing a property that is only 1 depth down?
how are you getting the serializedProperties? that's handled internally by Unity's implementation of ReorderableList
i think so
I haven't used ReoderableList unfortunately :(, which may be the problem, just trying to help with what I know of serializedProperties
idk if ReorderableList is screwing anything up
yeah I'm trying to figure out how to fix this
everything works fine, but recompiling breaks the chain
I still have the data after it breaks, I just need to inject it again into the ReorderableList to make it render correctly
this is the inner workings of RedorderableList
internal struct PropertyCacheEntry
{
public SerializedProperty property;
public float height;
public float offset;
public PropertyCacheEntry(SerializedProperty property, float height, float offset)
{
this.property = property;
this.height = height;
this.offset = offset;
}
}
List<PropertyCacheEntry> m_PropertyCache = new List<PropertyCacheEntry>();
internal bool IsCacheClear => m_PropertyCache.Count == 0;
checking now to see if I can find more info for ya
yeah I'm also checking the source code
so, I think you can use
public int index { get; set; }
public IList list { get; set; }
to find what you are looking for
already tried that
that public IList is null always
internally they use a different IList, the one that's publicly exposed is always null
i don't know if that is because I'm using my own ReorderableListClass
internally they use this
private IList m_ElementList;
So you went to the index of the serialized property in the list and got its name and it returned null?
no, the list of the serializedProperty gets populated, but I can't use that to get the data out
// active element index accessor
public int index
{
// In order to always return a valid index to list element, we should
// return the last item if there are no active element
get { return m_ActiveElement >= 0 ? m_ActiveElement : count - 1; }
set { m_ActiveElement = value; }
}
if you aren't getting it that way
idk why
no, that's a whole different thing, I can access the data inside my ReorderableList class just fine
the issues is probably because I use a wrapper class
and I have some parallel data in that wrapper class that needs to match the data in the ReorderableList, but in the original Type rather than in SerializedProperty form
it's kinda tricky to explain, and my code is an unreadable mess right now, otherwise I'd share the entire thing
You can cast the serializedProperty as a type and if the field doesn't return null it is that type. You can cast the serializedObject as an object and do gettype, or you can reference with serializedProperty.type. SerializedProperty.GetType() will just return serializedproperty
yeah but then I have to account for all the built-in types and I have to update my implementation every time I make a new wrapper class
and that's a pain
I'm just trying to keep everything generic so dynamic data can be used without much hassle
@patent pebble Did you get it figured out or do you still need some help?
@gloomy chasm i ended up just cutting up the SerializedProperty path by figuring out the nested depth of the current element
but if you know a better way of getting the parent SerializedProperty of a child SerializedProperty let me know! 🙃
Yeah, afaik that is the only way. But it shouldn't be hard to get the parent from the path at all. So if it is complex you may be doing something in a more complex way than needed?
It's because I'm dealing with arrays and they are weird with SerializedProperties
particularly if they are procedurally generated because the names of the list elements are Element0, 1, 2 etc
as you can probably guess, trying to discern what is the parent/children relationship based on that gets kinda tricky
this is just for learning, i found a better implementation of ReorderableList online and it's open source
so I'll probably build on top of that
i just wanted to see how extendable was the default implementation that Unity provides
it has some bloat that I don't enjoy, like pagination, but it's pretty good overal
Not really...? You just split by . You can use regex to replace array element part of the path.
do I need to do anything special to load a subscene? Or do I just load it like a normal scene
Is there any way to get the object picker to show prefab assets with a specific monobehaviour attached?
There is not.
ah, too bad. Thanks for the info!
not sure fully on a picker, but, EditorGUILayout.ObjectField(new Object(), typeof(ModelManager), true); for example will only show me GameObjects with the MonoBehaviour script ModelManager on them
ah ok, if that's the case it's kind of surprising that doesn't happen with the default picker window. I suppose a ref wrapper and a custom property drawer should basically get the behavior I want. Thanks for the info!
There's no interface for finding components on prefabs - which I feel like is a massive flaw that I'm very surprised they haven't added support for over the years
I thought QuickSearch did this now but it seems not. At least with QS you can write your own provider so that it would support it and be integrated well in to the editor.
I take it back! It does support it if you index properties.
I have my main editor window show me all components on any prefab when selected just using Selection surely it can't be too difficult
What is 'it'?
That's a little different to finding and displaying all components of a type on the root of all prefabs in the project
Is it?
In reply to what Eliseus just said
yes
I have no idea what you mean by "It does support it if you index properties." though
Ah, I thought you were replying to what I said.
yeah, I mean, you can't do it through Selection, but, just use AssetDatabase to get all the assets, check if it is a GameObject, and if it is, check if it has components
Ya gotta toggle Properties on so it will index the components of prefabs.
to make it easier have AssetDatabase only search for gameobjects
or anything with .prefab
I'm a little confused, but sure. I'm assuming that it's not doing what Eliseus is saying, because using the asset database to load thousands of prefabs into memory and searching them doesn't sound feasible
How else do you populate an initial set of data?
You can't know something exists if you don't know it exists
With that toggled on, you can query components of prefabs
I presume how Rider does it by just looking at the raw files and never loading anything via Unity
ohh okay, yeah, I'm not that fluent yet to know those things, however, I do know using assetDatabase, at least over several thousands of files, has been able to do this
iirc the way Unity does it is to load it in to memory get the data then unload. But I can't remember exactly so maybe it only does that for some things.
It can do it, but it would definitely make unity pause.
I've been trying to learn how to read yaml from code, but don't really know much, just randomly read about yaml
If you want to find anything in Unity I can't recommend QuickSearch enough.
Everyday in Unity I learn a lot more, start to feel good. Move onto something new and realize I still don't know anything
I found it extremely irritating and practically broken when I first used it, so I imagine it's better since then
Now it's even built-in by default
The API or the window?
The window
Ah, it seems pretty good now. And I think the API is quite nice and powerful.
QuickSearch uses a ScriptedImporter to only create the search index when assets are changed / imported. The results are saved to files in the Library folder so they can be queried quickly
You can see some of the files in Library/Search
ScriptedImporter? I am pretty sure it uses the AssetPostprocessor's OnPostprocessAllAssets(..) method to do incremental index updates.
That is just for when the .index asset is imported.
Ah that makes total sense, my mistake. I presume the index is maintained by the OnPostprocessAllAssets step then
I love how Unity doesn't recommend using OnPostprocessAllAssets and yet they use it everywhere
So many comments in Unity code going "we'll change this when the engine changes"
They recommend not using it?
Yeah, I forget where I've seen comments about it though. I'm pretty sure there's one in URP somewhere
I was finding a bunch of negative comments in code when I was screwing around looking at source code to do material variants
Lol, well I've never had any problems with it. Except for when they changed how AssetDatabase.GetGUIDFromPath() worked to no longer give GUIDs for deleted assets. (They added an enum param so no big deal, but took a bit to track down)
I've been going through the source more and more all the time to help my learning... I laugh at some of the comments, ngl
Oh did I tell you I got ScriptableObject and material variants working? Ended up having to use Harmony for the Material inspector, but that's it.
(forgive me if I have, I can't remember)
You did, I wasn't willing to do it with harmony haha
Oh alright my bad. Yeah there just wasn't any other way to do it. I even looked in to doing using the data from the IMGUIDebugger but there was no way to get the MaterialProperty for the control 😦
Of course, I could if it used SerializedProperties.
Rewriting the material inspector lol
But then it wouldn't work with custom inspectors which a lot of assets use.
Wouldn't even work with the standard shader I think because it uses one too, haha.
Yeah, I understand why you went with Harmony. God Unity could make some things so much easier
Honestly the way the Material Editor works right now is so funky... It doesn't function like any other of the Editor stuff...
It certainly is. That's just typical Unity though. We need Unity 2 so they can just make one way to do things
Get rid of the old input system, built-in renderer, monobehaviours, etc
Hopefully that's what the DOTS hidey hole is coming out with
That is exactly what I have been saying recently! Honestly get rid of UGUI and IMGUI as well, just have UITK for UI, it would be so clean...
I mean, I know they never will do a Unity 2 though...
However if they had a DOTs + SRP + New Input system + UITK Unity 2... that would be amazing.
I'm vaguely holding out hope that's what they've figured they need to do to get DOTS support very integrated
It would be the equivalent of having to support 2 engines, and then people would complain about having to have their asset support both engines, etc.
It's what Epic does 🤷
Fair enough.
Seeing as UITK and these packages already exist in Unity the cross-compatibility would probably be better
Same, I have this teeny tiny sliver of hope...
though if it was completely DOTS based there might not be much that is the same
I do wish they'd start squashing the old though regardless, just release the next major version without support for some of the old things and force people to move on, force the Unity devs to make sure everything's properly supported
Yeah, I would like that too.
They just have to do it when the replacements actually exist though
so they don't do an Enlighten again
They are to hesitant to get rid of things. Like it is small, but there is still that stupid override for EditorGUI.ObjectField that is obsolete... like come one it has been like 5 years...
Being new, why is there support for legacy things to begin with? Is it really that hard to update your projects?
Sorry, I'm still trying to understand all of that stuff. I don't even know what things I use that are and aren't Unity or c#
I think because it's a whole huge ecosystem that there are a lot of people in it who really do find it difficult to upgrade
You can't switch to the new input system because something you built and use every day has a dependency on rewired, you can't switch to URP or HDRP because you're using all these legacy shader solutions, etc
but really, they should just make cutoffs in yearly unity versions, if someone needs a thing they can just not update
The ecosystem's hell right now because there are like 3 versions of everything
2 would be bad enough but why are there 3
The way I've trying to implement the things I do I should be able to always be able to update easily. The only thing that would hurt me is if Unity changed things like their winding order of vertices and stuff, but, I'm still in my infancy and hope to have more complex thing soon
Yeah they certainly won't do that
The rotation systems and winding order should be here to stay
I don't actually check atm what changes in different updates of Unity between the LTS versions. I'm hoping to eventually be fluent enough where when I read the changelogs I basically know everything they are talking about lol
Wrong channel
Umm, where am I supposed to report problems with Unity Hub?
#💻┃unity-talk for help probably, forums/bug reporter for bugs
trying to not have to deal with culling I make a NewPreviewScene and set the Camera.scene to that yet it is still rendering outside the scene?
Anyone got any good ideas on how to do network queries in editor code? Hitting a variety of issues... From httpclient disposing itself somehow to UnityWebRequest logging errors because the response is empty
Seems like I fixed it somehow, no idea how but I'm doing less requests now so that might influence it somehow
I want the play button to always load the first scene instead of currently loaded scene, is there a modern Unity version solution to this?
thank you, I'm still a Unity noob, should it be enough to just have a script in a folder or do I need to set it up somewhere for it to work?
seems just having it in folder is enough, thank you again
Just call the script, it doesn't matter where its being located in
so, kinda just an organizing question. I'm removing some of my callbacks into their own scripts just to make it easier to read, I have an enable like this
public void Enable(CallbackOptions options = CallbackOptions.All)
{
bool doHierarchyChanged = (options & CallbackOptions.HierarchyChanged) != 0;
bool doPauseStateChanged = (options & CallbackOptions.PauseStateChanged) != 0;
bool doPlayModeStateChanged = (options & CallbackOptions.PlayModeStateChanged) != 0;
bool doProjectChanged = (options & CallbackOptions.ProjectChanged) != 0;
bool doQuitting = (options & CallbackOptions.Quitting) != 0;
bool doUpdate = (options & CallbackOptions.Update) != 0;
bool doWantsToQuit = (options & CallbackOptions.WantsToQuit) != 0;
if (doHierarchyChanged) EditorApplication.hierarchyChanged += HierarchyChanged;
if (doPauseStateChanged) EditorApplication.pauseStateChanged += PauseStateChanged;
if (doPlayModeStateChanged) EditorApplication.playModeStateChanged += PlayModeStateChanged;
if (doProjectChanged) EditorApplication.projectChanged += ProjectChanged;
if (doQuitting) EditorApplication.quitting += Quitting;
if (doUpdate) EditorApplication.update += Update;
if (doWantsToQuit) EditorApplication.wantsToQuit += WantsToQuit;
}
Would it look better to just use a switch?
if you use a switch i don't think the All enum value would work , or any other enumerable that represents a collection of possible values
I think I would just have to do a switch based off the byte value
it should be fine to use enums but i mean if you would need to use break; and it will prevent from executing multiple choices ( i think )
from what i remember switch looks up the first matching line and starts going down line by line until it reaches a break or a closing bracket , so if you omit any breaks all other entries below the first match will get executed as well , i use to omit breaks if i do a return value , at least that's how i use switches
@opaque zenith i would organize it like that :
public void Enable( CallbackOptions o = CallbackOptions.All )
{
if (o.HasFlag(CallbackOptions.HierarchyChanged )) EditorApplication.hierarchyChanged += HierarchyChanged;
if (o.HasFlag(CallbackOptions.PauseStateChanged )) EditorApplication.pauseStateChanged += PauseStateChanged;
if (o.HasFlag(CallbackOptions.PlayModeStateChanged )) EditorApplication.playModeStateChanged += PlayModeStateChanged;
if (o.HasFlag(CallbackOptions.ProjectChanged )) EditorApplication.projectChanged += ProjectChanged;
if (o.HasFlag(CallbackOptions.Quitting )) EditorApplication.quitting += Quitting;
if (o.HasFlag(CallbackOptions.Update )) EditorApplication.update += Update;
if (o.HasFlag(CallbackOptions.WantsToQuit )) EditorApplication.wantsToQuit += WantsToQuit;
}
Hey, I'm using progrids, but the 'snap to grid' is a bit weird
This is the current position of this floor
If I snap to grid
it becomes this
Any idea what might cause this and how to fix it?
i think this is suitable for#archived-code-general editor extensions is for making custom editor tools
ye , that was my point
I don't see how this is code related
look in pro grid if you have any offset values
Oh wait I reread what you said
That makes sense
Still not code related tho so idk what other channel to put it in
Where do I find that?
Do you even know if there is an offset? XD
no lol
lmao
would make sense tho , it shouldn't snap to those weird values
what is your snapping step ?
yea idk
;-;
Are people really saying I'm not a moron?
so, in an effort to try and understand better, previewScene = EditorSceneManager.NewPreviewScene(); is creating a preview scene that no cameras outside of can see, however, EditorSceneManager.MoveGameObjectToScene(previewCamera.gameObject, previewScene); doesn't prevent cameras from in the scene not seeing outside of the scene. Easily fixed with previewCamera.scene = previewScene;, but, should I still be applying a cullingmask also?
I feel like I can never get EditorSceneManager.NewPreviewScene(); to work as well for what I'm doing vs just doing EditorSceneManager.NewScene()
Is there any way to know if any properties have been changed or if my custom editor window is "set dirty" basically? GUI.changed doesnt seem to fire, even when called from Update or OnGUI, and creating a copy of every single variable then checking it in Update seems tedious, so I assume there is a better way to approach this?
Got code?
hey can someone tell me how can i check what is sending this error?
Hi! Basically i have a folder with a bunch of prefab, and i want to load them into an array using like UnityEngine.Object[] possChars = AssetDatabase.LoadAllAssetsAtPath(path);
But it isn't made for that, is it?
No that's for subassets
Not folders
You just gotta findassets in that dir then load them manually
okay, i see! thanks :)
never used that though, it's searching in the whole data folders, right? Can i restrict the search..?
cuz there's that, okay but it's still going to be long
oh nvm
Grass Manager has a [RequireComponent(typeof(Terrain))] on it. You'll need to remove the grass manager before the terrain
is there a handy dandy function to de-select all selected objects in the scene?
Since i've got an annoying problem with it
public static class SelectionExtensions {
[MenuItem("Edit/Deselect All %`", priority = 301)]
static void DeselectAll() => Selection.objects = new Object[0];
}```
Didnt work, Thus i have zero idea whats going on here then
Sorry - here is basically what im trying to do:
void OnGUI()
{
settings.texture = GUILayout.TextField(settings.texture);
settings...;
if (GUI.changed) { Debug.Log("changed"); } //never gets called
}
void Update()
{
Debug.Log("update called");
if (GUI.changed) { Debug.Log("changed"); } //never gets called
}
Basically, if anything in "settings" is changed/if any of the GUI text fields, toggles, etc have changed, then in this case print something, but that just isnt getting fired, though Update is
They have to be selected, i dont get it
Update: here's my script, still not working... Am i missing something..?
public static List<Character> Characters() {
string path = "Assets/Game/Application/Misc/Characters/";
string[] possCharsGUIDs = AssetDatabase.FindAssets("t:Character",new[] { path });
List<Character> possChars=new List<Character>();
foreach (string guid in possCharsGUIDs) {
possChars.Add((Character)AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guid),typeof(Character)));
}
return possChars;
}```
Remove the last / in the path.
oh.
lmao
still not finding any objects though (character is a custom type of mine, problem?)
What is Character? Is it a scriptableobject?
Unity can't find components of prefabs.
Love when you realize you are causing a memory leak somewhere by the things you are messing around with in editor when your computer starts yelling at you to close apps from running out of memory
so I found out I was having issues because I wasn't calling RenderTexture.Release() if anyone can help me better understand all of this. Here is
public void Preview(Rect r)
{
PreviewCameraControl();
SetPreviewRenderTexture(r);
previewCamera.targetTexture = previewRenderTexture;
previewCamera.Render();
GUI.DrawTexture(r, previewCamera.targetTexture);
}
void SetPreviewRenderTexture(Rect r)
{
if (previewRenderTexture == null) previewRenderTexture = new RenderTexture((int)r.width, (int)r.height, 32, RenderTextureFormat.ARGB32);
previewRenderTexture.Release();
}
In this way, does Releasing right after creation not hurt because of GUI.DrawTexture since .Release isn't destroying the reference, only releasing it, I can still draw it? In my disable I was already destroying the RenderTexture, does this not do the same thing? When not releasing, while messing around with this, with the above code I sit at 1g memory usage in Unity, without the release, I jump up to about 8g before I close the window and restart Unity. I understand why I have the call the release due to the documented reasons. I just was hoping for a better understanding
if I'm doing GUI outside of the normal scope for GUI, do I need to include GUILayout.BeginArea(r); AND Handles.BeginGUI();? if I want to use handles also, or can I just do handles and put GUI stuff into it
BeginArea is a helper function, it does nothing but define a rect for the layout that is within it
Is there some way to addcomponents to a serializedObject?
I want to add components to certain objects in a scene via editor script
SerializedObject is only one object. If you have a GameObject as a serialized object, cast .target to GameObject and call AddComponent
Undo.AddComponent if appropriate
Do I need to mark the gameobject/scene dirty manually If I do that?
Undo does that automatically. I'm unsure what you'd have to do with normal AddComponent
Gotcha. Thanks.
Hello! i got something to ask about EditorGUILayout.
I'm trying to make a function where when i click the "Randomize" button it will set the value in "red square" as random number. but i'm having a problem where when i click the button it keeps on randomizing number whenever i hover mouse or do something else in the editor
You should post your code, there is no reason it would do that if it was implemented properly
and here is the script i do to make the GUI for reference..i'm not sure if i'm doing it correctly or not
do you ever set randomised_fIxed_square back to false?
You're constantly calling Randomize when it's enabled
if you want to only do that when the button is pressed, and want to keep the toggle, add another boolean that only is true when the button is pressed
bool randomise = false;
if(...Button...) {
randomise = true;
}
...
if(randomise)
k = Random(...);```
wait a min...somehow when i set the randomised_fIxed_square to false at the end of the script, the value just didnt change anything when i click "Randomize" button
That's because you set k back to 0 if it's false
hmm
i think i'm getting a better understanding here on what should i do... thank you again...i'll try test something out first...
How do you check if the MonoBehavior field behind a Serialized property is null? I'd like to show a warning if certain fields(ex: Rigidbody) is null in a property drawer.
.objectReferenceValue == null
Hey everybody! is there a quick method to just draw the outline of a rect (and not just the whole rect like this:)
so more like this (made in paint(tm))
Only in UIToolkit. In IMGUI you've either got to use textures in a style, similar to the "box" style, or you draw two rects, one slightly inset.
UIToolkit has borders (with border radius) built-in
Having the TimerOOPChild list in the inspector means it only exists in this editor, which is refreshed when you enter playmode or recompile.
If you look at another object (closing this editor) that will also clear the list.
If TimerOOPChild is Serializable then it will survive the transition into Play Mode
but it will not survive closing the editor/looking at another object
I wanna save the list of TimerOOPChild , Where should I write it?
Tests?
Yes
I'll try , Thx for your time ❤️
You may also need to use the functions in the Undo class to get them to save properly
I will ❤️
Btw Navi, if you see this, know that we might have something to show in... Lets say... 2.5 weeks 👀
(and by something, i mean a whole game)
i didn't even answer sorry:
Thanks! I'll say goodbye to my outline then lol, it's no big deal
It worked when I switch between inspectors but when I run the game still the same issue
hey. anyone knows why JsonUtility is not working on serializedobjects ?
when I log the count of the list in the start method , It says 0
the same happens with Debug.Log($"{JsonUtility.ToJson(property)}");
object is not monobehaviour. it's a simple C# default class
Show code @supple willow
Haha cool
Send me a link once you do
that's all the code inside property drawer. let me send u the full code just for sure
What's fieldInfo, what's property
public class BossWaveEditor : Wave.editor
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
Debug.Log(JsonUtility.ToJson(property));
}
}```
as u see, that's all
Yeah you can't save a SerializedProperty
I don't even know what you're trying to save there...
what are u talking about ...
I'm not saving. I'm simply serializing into Json. any object can be serialized
you see? even Vector2 (which is a struct) can be turned into json
but for some reason property and fieldinfo can't... and btw this is Unity specific. C#'s toJson is something else that we can't use inside Unity for some versioning reasons
No not any object can be serialized
What is your end goal
Why are you trying to serialize those objects
the end goal is to see what's inside property variable. and toJson should work on ALL objects...
at least that's what it's supposed to be
No it's not
It works on Unity serializable objects, which is actually very little compared to other things
Either way, SerializedProperty is not serializable and there's no way to make it serializable
maybe. let me test it real quick
nah, you're wrong man
Try a dictionary
ok
Or generics
dictionary won't wok
so I guess C# primitives + C# generics won't work
or in other words, it works with ***reflection ***?
No that's some stupid assumption you just made
Reflection supports with both of those
Also primitives do work
anyways. I ended up doing what i wanted to do though another way. but still it would be nice if I could get this toJson to show property
nope. u can't get a sub variable from an int struct, because there's no variable inside int. int is the most basic variable
I dont know if you've ever really worked with reflection, but reflection can acces childs and parents. and int doesnt have any child to return
yeah.
just as a dictionary doesn't have any childs to return I guess...
Again, you're making assumptions. Dictionary is a normal class, with children, with internal lists to keep track of the items
I'm just going to stop answering since this conversation is useless
dunno what's up with u right now ... like , really :?
does anybody know how to add buttons to an editor window's top bar?
similar to the "lock" button in the Inspector and Project tabs
apparently they don't have anything publicly exposed to add those buttons, if anyone knows otherwise, let me know
They do! Let me find it for you.
Finally found an answer online.
Apparently adding this method to an EditorWindow automatically handles the logic
private void ShowButton(Rect position)
{
//Your button or toggle or custom GUI here
}
is it the code I posted? or is there another way?
Yeah that's the one
it's so weird how they don't have that documented
There are quite a few like that
i was trying to weirdly draw textures outside the window clip area and detect the mouse position with external code before I knew that method existed 🙃
👀 got any more of those magic methods?
There is OnAddedAsTab and OnBeforeRemovedAsTab
nice, thanks, that one will come in handy too 😊
There is also OnTabDragging too
thx a bunch!
Sure thing!
Hi guys, mb someone can help me. I have EditorGUI.Popup with string array (1k+ elements) and i want to sort that in alphabet groups. I want to show in my Popup strings in groups but can i it or need to use genericMenu only?
yes Denis. You can Add "/" to string and it will be work )
There's also an interface you can implement for the tab right click menu
How do I destroy a previewScene if I accidentally created one? I'm not sure if it actually exists and it is just a bug with EditorSceneManager.previewSceneCount
I already do EditorSceneManager.ClosePreviewScene(previewScene); in the disable, but, this was after the fact I realized they might have not been closing the other way I was doing it, so reopened Unity to fix the EditorSceneManager.ClosePreviewScene(previewScene);
so got me wondering how you even find a preview scene that might be floating off into space
scene is a struct though
nvm, I think I figured it out, think I was writing it wrong how I would need to
nope, nvm, even though ide didn't catch it, still an error since scene doesn't derive from UnityEngine.Object
Hey everyone, I have been playing around with designing an editor window. I am a bit on a struggle bus.
I have a setup for preview windows to show a sprite and a 3D model (Prefab or Mesh). I am using Editor.OnPreviewGUI(rect, EditorStyles.objectField) which works initially however, it Collapses into an error over time or if you leave a Prefab/Mesh hovering over the ObjectField it is pulling from. It begins to give off a Unable to allocate new scene culling mask then shortly after it starts giving a notification there are more than 100 preview scenes.
I tried finding a way to stop the system from chronically creating multiple preview scenes but when I stop it, it cuts the preview completely.
Anyone have some tips or directions I could go look at to keep my preview of the 3D model without it spamming my session with multiple scene culling masks?
There isn't enough info here. I'm assuming you are using PreviewRenderUtility? If so, you have to do your own cleanup of it. When I use that I basically put if (previewRenderUtility != null) previewRenderUtility.Cleanup(); at all of my initalize and disable methods
depending on what you are using, you have to release it
it isn't done by itself
in terms of why sometimes your preview scene is blank, again, depends on where you are calling draws and updates
which I can't see with the above question
The ObjectField on top is being checked to see if it != null
if it isnt, it previews the image.
after about 40 seconds or so, or if I hover over the ObjectField with another mesh I begin to have this occur. I can't find a way to prevent it from spamming itself.
I wasn't able to figure out how to send my snippet of code so I sent it directly to you. (Not a good Discord user 😅 )
Is there a way to choose which blender installation Unity should use to process .blend files? I use 2.78 for modelling and 2.9 for video editing
hey , trying to use unity remote but whenever i test the game it doesnt do anything on my mobile phone any help?
how do I remove elements from a list without this happening?
I want a list of elements and a delete button for each that uses .DeleteArrayElementAtIndex() but it just errors out
im even using a reverse loop to draw them
Without a look at the code its difficult to see whats happening @wanton arrow
I working on an editor extension where i'd like to embed a hierarchy view inside a custom window. I see from the cs reference that there is the SceneHierarchyView class, but it's internal. Any way of doing this short of recreating the hierarchy by hand?
@near wigeon depends on what you want to do with it. If you want to just do a 1 to 1 replication you could maybe use something like this
however if you want your custom hierarchy to have its own scroll value, collapsed/expanded states, etc
you are probably gonna have to make it from scratch
Just 1:1 I think. Doesn't matter if it shares state with the "original"
I've actually tried that method, but not 100% sure how I'm supposed to use it. Like it's just a callback right? I don't get a base.OnGUI() with all the hierarchy GUI calls
one sec I did something similar with the Project Window, it has the same kind of callback
i'll share the code
@near wigeon https://hastebin.com/ogehukariw.csharp
that's a script that I made to display the type of prefab in the hierarchy
however I don't know if the hierarchyWindowItemOnGUI would be suitable to display an embedded hierarchy on a separate window
as far as I know you need the original hierarchy open to get the callbacks
and it only does on the currently visible items
ah so you still need to recreate the GUI elements? Does your Hierarchy behave like the built-in hierarchy? You click an item and it selects it in scene view?
or you just enumerating the items in the hierarchy?
if you add your method to the callback you can draw on top of them, the original GUI contents still get displayed
That is just adding things to the project/hierarchy window. Drod wants to embed the hierarchy window inside their own widnow.
yeah
so you lose the search bar, ability to drag and drop, re-ordering, re-parenting?
no, everything is the same, you just draw stuff on top
@near wigeon what exactly are your needs? why do you need to have a hierarchy on a separate Editor Window?
you mean you draw on top of the original hierarchy
yes
gotcha
mostly ux for a unity-based framework
so people without game-dev backgrounds can put together a 3D scene more easily
still within the unity editor, but with some more hand-holding
it sounds like you're gonna have to make it from scratch then
trying to make a tabbed interface that shows the hierarchy, project, alongside some custom editor windows
"#view" would switch between those views when you click each tab
sounds like I can't embed though, so I'll explore other options. Thank you both for your help.
yeah with that level of customization you are gonna have to get all the scene objects manually and draw your own hierarchy
the TreeView API can be useful for this, but it's a little bit overwhelming and the documentation is not the best
@near wigeon i had this example saved that makes a very simple hierarchy with the currently loaded hierarchy
https://hastebin.com/hacusatabe.csharp
https://hastebin.com/ugejoyodiw.csharp
Awesome, thanks @patent pebble
you can draw your trees however you want
Yeah, I've not used TreeView API before. It looks fairly straightforward. Was trying to avoid recreating views if I could help it, but looks like I should be able to get something going without too much trouble.
i had a bit of trouble learning how to use TreeViews correctly
but once you understand it, it's pretty easy to make them any way you want
the documentation and examples are atrocious in my opinion, that's why I had trouble at first
There is two ways to do this. You could either create the windows without showing them and then call their OnGUI/OnEnable methods your self. However you are going to have a bit of funky things to do to get it to serialize nicely.
The other option is to use reflection to get the actual Views and dock them together.
Thanks, @gloomy chasm. Good info.
is there a way to clear the editor image catch ?my thumbnails are mismatching with he actual image
Do you guys know how to make an editor window stay on top without being a utility? Do I just need to make some sort of wrapper is that editorwindow is open if somewhere else is receiving current GUI input?
@opaque zenith there's a couple ways you can make EditorWindows that are always-on-top, depending on what you need:
ShowPopup: No frame, not dragable, not dockable
ShowUtility: Desktop-style frame, dragable, not dockable
ShowModal: Normal frame, draggable, not dockable, locks input and focus until it's closed
ShowModalUtility: Utility + Modal
other than that you can probably implement your own EditorWindow to achieve it too
Is there a way to get or display the comment/summary of a classes variables, that I cant edit? I want to display the import options of ModelImporter, and it would be a little tedious to write out every variable, look up the documentation for it then copy + paste, is there a better way to approach this?
If it isn't your code then there is not. Well if you have the docs downloaded you could get the file path and maybe read it from there.
Hm, is there not a way to "display" the variables or serialize them myself from outside the class? Like will I basically have to recreate every variable myself as the only alternative?
What are you wanting to do...? I thought you said you wanted to get the doccomments from the members of a class.
pdb files contain the documentation for members
Basically I want to setup a editor window I can change import settings for model assets using ModelImporter, and they have a lot of variables, so either I want to try to get the comments that appear as a tooltip when you hover over them in the inspector (but in my own editor window), or just get the variables directly and display them instead of having to create all like 30+ variables for the "mesh" tab and "animator" tab and "material" tab, etc
There's no way to easy reproduce the editor though (or edit it)
Oh, those are not comments. They are either [Tooltip(...)] or hard coded in to the custom editor.
Would just using the editor for it not work?
Editor.CreateEditor(modelImporter).OnInspectorGUI()
You can have to cache + destroy it
(This is bad code, you would want to cache the editor)
Hmm, I could try it, and ill keep the caching and destroying in-mind, thanks
Can I somehow put a button inside something that takes GuiLayout
GUIContent
not layout
mb
You can't...
If something takes GUIContent then it takes GUIContnet not drawing things.
This is basically all GUIContent is.
public class GUIContent
{
public string text {get; set;}
public Texture image {get; set;}
public string tooltip {get; set;}
}
What were you wanting to do?
haven't caught up on if you solved this, but, there is a few routes you can go. One being, you do an iterator for serializedObject and then loop through all serialized properties and get their GUIContent. The other thing I can think of is to use reflection basically
me and my friends want to make a 2d game together, we want to see the same scenes while we work on the game so we tried to use scene fusion but whenever someone makes a sesion it doesnt show up in the sessions, how do we fix this ?
This isn't an editor extension question, and is also cross posting #💻┃unity-talk.
You're likely not going to find much support in this discord for Scene Fusion because of how niche it is. You should go through their community if they have one, or their support.
ok
does anyone know at least relying on Unities implementations, if you can make a new stage in code? Atm I'm making new classes that inherit from stage, but, am sorta confused a bit on the documentation. For example, is any scene opened part of just the MainStage, then there is a PrefabStage, but outside of that, scenes are all part of the MainStage, unless you make them part of prefabstage, and can't make new stages in code?
I'm inheriting from PreviewSceneStage, guess maybe I just need to understand how to use that better
I guess there is PrefabStage also
nvm this stage stuff seems like garbage, going to just go the route I was going
@opaque zenithwhat exactly are you trying to do?
you can make your own Stage with PreviewSceneStage
Stages are usually used as customized editing containers for things that you don't want to have in the main Scenes you have open
similar to how Unity handles now prefab editing, they are opened in isolation in their own stage that contains the preview scene for said prefab
nothing of super importance atm, but, the stage system is very convoluted (imo) when you can just do EditorSceneManager.NewPreviewScene();, or, just load a scene with masking to a camera
I was creating a sceneview instance for some of my modifications in the editorwindow, so, was trying to take advantage of some of the things in SceneView since it already existed, but, the mess of what stages seem to be mixed with the annoyances of internal and not wanting to use workarounds, seems like just a massive mess vs just making your own scene with lights
I mean, that is basically what they do anyways when you read it, but, they do a lot of confusing things, like, idk if stages just aren't where they want them right now, but, literally feels like stages are adding more of nothing to something. Like, you take a scene, put it into a stage, so that you can edit... that scene
to give a better example,
previewScene = EditorSceneManager.NewPreviewScene();
camera.scene = previewScene;
camera.name = typeof(T) + "Camera";
EditorSceneManager.MoveGameObjectToScene(camera.gameObject, previewScene);
GameObject plane = GameObject.CreatePrimitive(PrimitiveType.Plane);
EditorSceneManager.MoveGameObjectToScene(plane, previewScene);
I just did what the the stage mess does
stages's main purpose isn't only to make preview scenes
they are meant to be containers for the scenes that you load and open
they added to the API the option to create your own custom stages for editing purposes
the use is arguably very niche
I haven't personally used them for anything
but i saw someone trying to use them to render simultaneously multiple cameras and do edits on a single scene
another possible use case I can think of is adding customized controls depending on the type of custom Stage you are currently using. The same as the Prefab Stage does
So for example lets say you have a Stage that you use to isolate rigged meshes that shows you tools for editing the animations, avatars, etc
And you have another different Stage type to load in multiple different lighting setups that you can quickly swap to inspect how materials and shaders look on an object under different conditions
the Stages API offers convenience for cases like that
How do I fix this error?
Im trying to remove list elements on a serialized object with a button
but when I do it errors
same thing if I remove the try {} btw
you use prop immediately after deleting it
An easy way of handling it can be to apply the serialized property after the delete statement, then calling EditorGUIUtility.ExitGUI();
thanks!
Im dumb I didn't realized lmao
but it also seems like from online it makes a null element if you delete it like that and you have to do it twice?
If you're removing an array element containing an objectReferenceValue you should set it to null before calling Delete
calling Delete twice is a kinda buggy way of doing it that I wouldn't recommend
It just throws an ExitGUIException that Unity catches further up
That means your property isn't an object type
so using objectReferenceValue isn't valid
There's no need to set anything to null then
Hey, I'm working on an ChangeLog Editor which autoUpdates the Version so I can't forgett it. Now Unity tells me it is ReadOnly, but their Editor can change it. Some Ideas how to fix?
Please @deft quail me for an answer
is Reflection.Emit allowed, safe and recommended for editor-only code?
I'm not very experienced with reflection and I was trying to override a float value to make a GUI control bigger
An AOT platform cannot implement any of the methods in the System.Reflection.Emit namespace. The rest of System.Reflection is acceptable, as long as the compiler can infer that the code used via reflection needs to exist at runtime.
yes the documentation says that, but is that for runtime code, editor code, or both?
That means that Reflection works in any environment that it can be used in. Emit can't be used on any platform that relies on AOT, therefore, you can use Emit in any instance that isn't AOT as in, not at runtime
but there is instances where you can use it in both runtime and editor
if you are talking about something ethical, well, ethical isn't law, though it can be, and not really relevant
so... does that mean I can use Reflection.Emit in my custom editor tools? 😅
sorry, I'm not very literate in this topic
yes, and even at runtime on platforms that support JIT ( just-in-time) code. AOT is (ahead-of-time)
i see, thanks!
Hi, I'm having some trouble with editor scripting. I'm trying to detect keyboard input in the editor. I'm able to detect the key down events using an editor window and OnGUI(). The problem is the editor window must be focused. I would like to detect the key down events even if the editor window is not focused.
That is generally a bad idea. Why are you wanting to do that?
MenuItem is the trick
yeah iirc you can use any combination of key bindings (Ctrl, Alt, Shif + Key) in a MenuItem
globalEventHandler
I was going to say. There is a application wide callback somewhere for it iirc.
Type : public sealed class UnityEditor.EditorApplication
3.4.0f5 ⟩ 2022.1.0a11
Unity Doc
Field : internal static globalEventHandler
3.4.0f5 ⟩ 2022.1.0a11
GitHub Source
Well the idea was to be able to have shortcuts for an editor tool im working on.
Most of the time, Editor tool means you work in a context.
If you work on the big picture, globalEventHandler is the only way I know to interact from anywhere
Try the Shortcuts system from Unity
@onyx harness I'm not 100% sure, but I think their shortcut system uses the globalEventHandler callback for doing that
Yes
Thanks for the suggestions. I'll look into it.
I can't tell, but wouldn't be surprise
It's internal.
On the right, use the C# Reflection Generator to have the code snippet
@swift belfry this
[MenuItem("With Hotkeys/Hotkey 1 _g")]
public static void Method1(){
Debug.Log("Menu item with Hotkey G");
}
[MenuItem("With Hotkeys/Hotkey 2 %g")]
public static void Method2(){
Debug.Log("Menu item with Hotkey Ctrl + G");
}
[MenuItem("With Hotkeys/Hotkey 3 #g")]
public static void Method3(){
Debug.Log("Menu item with Hotkey Shift + G");
}
[MenuItem("With Hotkeys/Hotkey 4 &g")]
public static void Method4(){
Debug.Log("Menu item with Hotkey Alt + G");
}
[MenuItem("With Hotkeys/Hotkey 5 %#&g")]
public static void Method5(){
Debug.Log("Menu item with Hotkey Ctrl + Shift + Alt + G");
}
they automatically appear on the Shortcut Manager
@patent pebble Oh interesting. That's very convenient. Thanks
if you don't want to use MenuItems you can manually set them via code
there's an API for it, though I've never used it
MenuItems should be fine
in case you want to check it out
https://docs.unity3d.com/Manual/ShortcutsManager.html
go to the last 2 sections "Bypassing the Shortcuts Manager for custom tools" and "User-defined shortcuts"
I think that can be used for making shortcuts that only work on certain EditorWindows, but I'm not entirely sure, never used it
Hmm. I think ill use MenuItems for now, but I'll probably explore the second option as well
it seems fairly simple
doing this seems to work
[Shortcut("Some Shortcut Name", KeyCode.B)]
public static void SomeMethod()
{
Debug.Log("Global shortcut B");
}
the constructor accepts also a Type parameter, I assume you pass your EditorWindow type and it only works when that is focused
yeah works fine
public class EditorWindowForContextualShortcut : EditorWindow
{
[MenuItem("Editor Scripting/Shortcuts/Contextual Shortcut")]
public static void MakeWindow() {
GetWindow<EditorWindowForContextualShortcut>();
}
[Shortcut("Contextual Shortcuts/ Shortcut 1", typeof(EditorWindowForContextualShortcut), KeyCode.Alpha8)]
public static void SomeMethod() {
Debug.Log("Contextual shortcut 1");
}
}
this seems very cool to add functionality to existing things like the SceneView, Project Window or Hierarchy Window
the last tools I had for those all managed their own shortcuts internally and the Shortcut Manager didn't know about them
time to do some refactoring 👀
Hehehe, well thanks again
no problem, I had all of this stuff saved on my bookmarks but never gone over it
"i can reinvent the wheel on my own, I don't need no Unity APIs" 🙃
anybody know how to make little panels like this?
I just want the panel nothing else
What do you mean the 'panel'? What part is that for you?
It is a UnityEditorInternal.ReorderableList if you are interested in that.
Well you can use the GUIStyle for it.
wait what guistyle is that
and also where would I assign that? would I just create some sort of rect?
I don't remember what the style is called, RL Background maybe? You can find out using the IMGUI Debugger window.
That 100% depends on what you are doing. If you are using GUILayout scope then you could set it as the style for that. Or for a label. Or just draw it directly.
is there a better way to save inspector variables than to put them on the component? that seems like clutter. It would make so much more sense if it only refreshed the inspector class if it was completely unloaded
Editors inherits from scriptableObject, so, you can save to a scriptableObject. You can also just save to a file. You can also setdirty the script itself if you want. You can also make a seperate scriptableObject to save to
oh I mean
can also use editorprefs
I just want to save it past the point of touching anything else
on the editor
ideally it would reset when the editor was unloaded totally
can also use hideflags to hideanddontsave
hideflags?
hmmm
might as well put it on the component then
that seems like alot of work for very little
but thank you
the name sounds confusing, because it does exactly what it says it does, but, the wording makes it seem like it wont do what people think it wont do
not really, you literally just do object.HideFlags = HideFlags.HideAndDontSave
then, in your ondisables and stuff, destroy the object you did that to
im just confused on what exactly Id even be doing. What do I make a scriptable object?
the editor class?
you do it the exact same way you do a normal scriptable object
im sorry that doesn't help
with a scriptable object i make a new scriptable object class with the data I want
so, https://docs.unity3d.com/Manual/class-ScriptableObject.html
[CreateAssetMenu(fileName = "Data", menuName = "ScriptableObjects/SpawnManagerScriptableObject", order = 1)] for example, but, since you dealing with editor you can do cooler things, such as https://docs.unity3d.com/ScriptReference/MenuItem.html
where you can take advantage of their validate feature if you don't know do something like a singleton pattern or some check somewhere to insure you only have one instance of that scriptableObject, if that is what you want that is
outside of that I don't really know what else to offer you. Can't get much easier than object.HideFlags = HideFlags.HideAndDontSave
I just wanted to make a search field that doesn't clear when you refresh the editor :/
by touching anything else or pressing enter
are you talking about recompiles, or closing the editor and reopening it
no I mean like
if you are talking about recompiles, just do HideFlags.HideAndDontSave and be done with it
oh, you want to keep focus on the inputfield?
I also want to make a foldout that opens and closes but that will close every-time I update the inspector too cuz the bool value will reset
@wanton arrow share your script
you are either not assigning the value of the text field to any variable
not much more than what I posted above
yeah
I just find it annoying that it clears everything end you repaint the inspector
I guess theres no easy way around it
your TextField returns a string
put that in a variable
okay, the question you asked didn't even have to do with the problem you had
it's ok, extending the editor can get a little bit overwhelming at the beginning
tbf you never told me it doesn't reset
but I think my lack of understanding made my question confusing
and I realize now I never added the code in the first post
remember that you probably want to get the data of the TextField to your World class
not just have it in a variable in the WorldInspector
in that case yeah
if your data is not supposed to be "saved" to the World class, then it's fine
yeah that was the whole reason I asked
It felt like bad practice to put it on the component
ah right I just scrolled up and saw your question about that
it's usually a good idea to separate concerns yes
I have a bigger problem where unity keeps crashing tho
lemme move to #archived-code-general
This channel is for creating your own editor extensions. You want #🎥┃cinemachine
how come the reflected type is all roomNode
they are most definitely not
theres strings, ints, bools, etc
Debug.Log(item.ReflectedType) always prints "RoomNode"
oh im dumb I misunderstand "Reflected Type"
how do I get the type of a memberinfo?
stop typing butter stop typing you know how to do this 🥴
just for the good practice of answering ur own questions when you solve them, I need to actually cast the member to something like FieldInfo or a PropertyInfo to get the type, not all members have types like that
thanks for coming to my ted talk :)
I would like to have JSON files to manage items in my game and hopefully be able to edit them through the editor (so I can link to Prefabs for models and things like that). Any resources on how to begin with stuff like this, I have extensive C# experience, but only recently started using Unity.
I suggest scriptable objects
unless they need to be edited from an outside source scriptable objects are basically that but already done for you
Editable outside is nice, but not a requirement (I'm the only one working on the project right now)
def go with scriptable objects
you can basically make custom assets by making c# classes that hold the data you need
tons of recources online
"type is not a supported pptr value"
on property.objectReferenceValue
how do I check if that exists before I ask?
google got me there after some needlessly complicated answers
When using GUILayoutOptions is there any way to introspect the values of a collection of these passed into you without resorting to publicizing Unity? I want to find out say a GUILayout.Width has been passed in and pull out its value. I have cases where I want to say put a search field on top of a SelectionGrid and the selection grid needs to grow to the full size but I want to make the search field equal the calculated width of one of the cells.
GetLastRect?
I need to do this before it renders. Besides the search field is above the thing I am scaling it too so I would need a time machine and call GetNextRect()
this is an example of a use case I want to support
There's a GetRect as well but you probably just want to calculate your rect manually here
Rather than use GUILayout
here is another use of the same class in a different config
this is a whole framework for building mod UI like this
I don't really want to implement my own whole layout system for this. I just want to look in my GUILayoutOptions and see if there is something specifying width and get the value. If there is not a better way I'll just publicize unity and access the internal fields
Not sure, referencesource probably
what is referencesource?
Hi! i've got a little problem. I've created an editor script, that draws a class of mine, lets call it the ActionScriptable.
Within this ActionScriptable, i have an array of a custom class, that i have a property drawer for. Lets call it character array, for example.
When i try to draw my character field with a simple propertyField(), i get a nullref, but the strings are well defined, and the property is set... Is it bc the character class isn't a monobehavior?
Edit: it can't draw it, because the content is null, i think. Like the array is empty. Which is normal, because i'm supposed to set it through the editor...
Or so i thought, because i've added like = new CharacterComeGo[0]; to my array but it doesn't work
(well i forgot to make my class serializable lol)
Looking for an asset or an advice. I want to have prefabs shown as tabs, so when I click on a prefab, the editor enters to prefab view for that prefab. Also, this would solve the issue where after clicking on Play, you have to search for that prefab again in the project. It's really slow time consuming workflow that's for example solved even in Godot.
Think Visual Studio tabs where every tab is a C# script. You can open new ones, close existing ones, etc.
At the moment I switched to this workflow and I have prefabs in the Scene so it's easy to find them after every edit, but this is a temp solution, tabs would be so much better:
The PrefabsEditor applies all the changes when entering PlayMode and destroys all the children after that.
Hi! Do you guys know any similar tool for Unity like Landscape Splines for Unreal?
Wrong channel
I'm sure it is of no use know, but just to let you know the IMGUI debugger get's all of it's info from the C++ draw/layout commands. So it does not having any info about layout besides what the width of the rect is.
@waxen sandal if you are interested ^
Figured, just never checked ;P
Yeah, was figuring as much. Just thought I would let you know since I did know 😛
What you might be able to do is to add a callback to PrefabStage.prefabStageOpened and have it open a new scene window with the prefab. What you want to do is what I would consider more advanced, you will probably have to look at the source code to see how unity handles opening prefab stages, and how it decided which window to use.
If creating a GameObject in the hierarchy, how do you make it have a unique name like name (1)?
Nevermind I was doing it wrong because I was setting the name before parenting.
What version added the default position for new gameobjects being 0, 0, 0?
not 100% sure, but, I see that 2020.2 is the first one with scene view in preferences in the manual
is it possible to have the OnDestroy behavior in edit mode?
right now you get the classic
Destroy may not be called from edit mode! Use DestroyImmediate instead.
if you try, but destroying immediately has, other side effects that make things not work in my use case
so now I have code working in play mode, but not in edit mode
As in you want OnDestroy to be called or you want Destroy to work in Editor?
well, both! I want the behavior of OnDestroy in edit mode
but calling it in edit mode will throw an error with the message above
Is it ExecuteInEditMode/ExecuteAlways?
yeah
like I could do some sort of Editor delayed call to destroy it the next frame but, it feels, deeply cursed
I was under the impression that worked, or perhaps I'm thinking about when the editor unloads the scene
I guess EditorApplication.DelayCall is your best option then :/
yeah :c
it's just, not exactly the same, since the object won't be marked as destroyed/equal null for the rest of that frame
but it might be okay in my case
also it is, deeply cursed, that command buffers silently fail to draw when a mess is null
it just doesn't issue the draw call at all, and doesn't throw any errors or log anything
Hmm, that sucks, unfortunately I'm not aware of any other approaches
sooo many of my issues in Shapes is dealing with object lifetimes and camera events and command buffer shenanery ;-;
you'd think it would be easy to issue a draw command with a temporary mesh
but
(:
Yeah.. It's a pain dealing with things that work both in and outside of playmdoe
public static class SerializedObjectExtensionMethods
{
public static SerializedObject ConvertToSerializedObject<T>(this T t)
{
SerializedObjectExtension soe = ScriptableObject.CreateInstance<SerializedObjectExtension>();
soe.Set(t);
SerializedObject serializedObject = new SerializedObject(soe);
return serializedObject;
}
}
public class SerializedObjectExtension : ScriptableObject
{
[SerializeField]
System.Object systemObject;
public void Set(System.Object systemObject)
{
this.systemObject = systemObject;
}
}
This seems to work for something I'm messing with to convert anything into SerializedObject easier for me. Will this potentially cause any problems? Obviously I'm manually disposing of the scriptableobject when done with it since I'm not creating an asset
I uhh what why
idk, I may still not fully understand serialization
but I was looking at trying to control my serialized things easier so I could create something as a serializedObject on demand, like in a localScope. I was having problems trying to convert something as a serialized Object without making it a scriptableObject in this sense. Probably has to do with the fact that the "Object" doesn't exist, in a sense
Does this even work? I don't think system.object is serializable by Unity is it?
Also this is ew, pls no.
it does and it doesn't. It didn't do exactly what I was looking for, but, it works because ScriptableObject is a UnityEngine.Object
Alright, just know that I would consider this bad code. You are not using the system how it is designed to be used and will cause some things to potentially not work as intended.
I'll get back to you when I get this working, what I'm trying to at least. If you can program it, isn't it intended? 😛
Lol 1000% not. There is most definitely things that are indented and things that are not. This is even more true within Unity.
Hey, I'm trying to make a tool to edit AnimationClips, specifically trying to remove PROPERTIES, but I couldn't find anything that actually removes a property, only things to modify curves and other unrelated values, does anybody know how?
i cant find "Tools for Unity" in Visual Studio options
im trying to get intellisense for unity code in visual studio
Instructions are in #854851968446365696
i figured it out
Hi , Can any one tell me how to do something like this , I wanna make a label that I can change its value by pressing twice like the one in the animator exposed parameters
You use Event to get if the mouse is down on the rect of the label and click count. If the click count is 2 then you show a text field.
Hey friends, can anyone point me to the api docs surrounding the selection box in unitys scene view?
Any way to make a Scriptablewizard window not close when I hit apply(I don't want to disable the button)
Making your own is the only way afaik
you can inherit a class from AssetModificationProcessor to manage asset deletion, maybe theres something similar but for scene objects...?
Oh I realized, that my question would be better suited here. #archived-code-advanced message
Does anyone have an idea how I could plot a math function (linear, quadratic etc) in the inspector? Converting it to AnimationCurve would be tricky.
I don't think there's a public API or any documentation for the SceneView selection rectangle
if you just want to access the selected GameObjects you can use the Selection API
you can just get the position where you click down and the position where you release the mouse (using the callback SceneView.duringSceneGui or Editor.OnSceneGUI())
make a rect from that
if you want to implement your own selection logic you can use some stuff in the HandleUtility and SceneVisibilityManager classes
If I make modifications to an asset(not prefab), how do I save it?
probably AssetDatabase.SaveAssets
maybe probably too EditorUtility.SetDirty before saving the asset
I'm doing both. Not working.
share your code then, someone may be able to help
I've never had any problems saving assets
Wait it's a Scriptable object, not asset.
I'm not using serialized objets.
Because it's a builtin unity asset.
And I'm calling it's functions to modify it.
I don't think it'd be possible to do with serialized object
ScriptableObjects are assets
i have tools that create and save scriptable objects manually, they save just fine
if you don't share your code it's harder to help 🤷♂️
EditorUtility.SetDirty(defaultStringTable); AssetDatabase.SaveAssets();
The code is separated across files.
Default string table is a stringtable that unity's localization system creates.
@dawn root why are you setting the string table to dirty instead of the object containing it?
The stringtable is a scriptable. It's being modified with an editorwindow
ah
Any other ideas why it might not be working?
i have no experience with Unity's localization tools
and without seeing the code, it's hard to tell
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.
Line 104-105 saves the asset.
is your defaultStringTable ever modified?
do you change its data in some EditorWindow?
In this case, I'm not sure where the data lies. The localize() function inserts some entries which most certainly modifies. I can even see the changes in the editor until I quit Unity.
The stringtable contains multiple tables. Each of which are scriptables which are also modified. Might it be worth saving those too?
maybe
try dirtying the individual tables too
I remember making a tool that dealt with nested scriptable objects
and I had to dirty those nested objects to get it to save correctly
Gonna try then.
No dice.
no idea then, try looking around in the localization thingie documentation
I assume it's a package that has its own docs
Okay, I tried selecting the asset in the project settings, repeatedly hit "select dependencies" and then set them all to dirty. It worked.
It's such a stupid solution that I'm laughing rn.
exactly my feelings quite often when making editor extensions 🙃
i assume you know, but just in case, AssetDatabase has methods to select dependencies
EditorUtility has the CollectDependencies method too
Thanks for the help.
anyone has a solution?
@random scarab to make a MaskField you just provide a string array for the labels
what are you using this for?
I know that I need string[]. the problem is that I dont know how to get the layernames.
I'm currently cleaning the inspector of my script. Just basic custom inspector stuff. Making Foldouts, Toggle etc. But I have trouble making it for the LayerMask, because I dont know how I get the string[] of all Layers.
Basically how do I get to this list via script.
Isn't it just returning the index of the layer?
@random scarab it gives you the names
keep in mind it doesn't work with index numbers
they are bitmasks
So basically I have to list the names by myself using LayerMask.LayerToName(). Ok thanks for the input. I thought there is an easier solution to that.
you need to the correct bit shift operation
i think you need to bit shift left with the index of the mask
for example to get value from the layer at index 5, I think you need to do this 1<<5
a LayerMask can support up to 32 LayerMask for a singular gameobject
the documentation for LayerToName gives you an example at the bottom of the page
so do a loop through 32
yeah I get that. Thanks both of you 🙂
List<LayerMask> example = new List<LayerMask>();
for (int i = 0; i < 32; i++)
{
string name = LayerMask.LayerToName(i);
if (!example.Contains(LayerMask.GetMask(name)) example.Add(LayerMask.GetMask(name);
}
not 100% sure if this will work, just typed it out here
might have to add null checks and/or have the list be int or string or something
can probably also add a break if the is no more masks, but, the int number is so small I don't think it matters
this is incorrect, you can't use index values
you need to get the correct bitmask value
what I did is the correct route you go
you don't directly access these with an index
you access the bitmask this way
I just don't know what LayerMask itself is, and you might need to store as a string, or int or something
@opaque zenith you don't, LayerToName doesn't work the way you think it does
LayerToName takes an integer argument. This argument selects the name of Layer and returns it. The layers are listed in the inspector. As an example assume User Layer 13 has a string. This string can be accessed by calling LayerToName with the value 2^13, which is 8192.
I hope it does, or the manual is wrong
the code snippet you shared is wrong, you are just using the index
not the bitmask integer value
its working though. I got my desired outcome
List<string> layerNames = new List<string>();
for (int i = 0; i < 32; i++)
{
layernames.Add(LayerMask.LayerToName(1<<i);
//or
layernames.Add(LayerMask.LayerToName(2^i);
}
Mathf.Pow(2, i);
yeah, mine was just pseudocode
why is the initial number 2, I don't actually know
working just fine, eventhough I did not power i
i = 2 is wrong. It should be 0 of course
good to know, am unfamiliar with this specifically
Atleast that is the result and it correlates with base.OnInspectorGUI() LayerMask selection. Cheers 🙂
side note, it cold where u live!
wait, that is C
i dumb
@random scarab @opaque zenith damn, I didn't know they handled index values too
I always used bitmaks values instead
hey, your guess is as good as mine haha. I haven't ever used this
yeah I just checked, even internally they use them with index values 😓
So we all learned sth atleast 😄
With IMGUI, is there a way to implement label dragging to edit a field values with a custom label? I feel like there is, but I am not finding it.