#↕️┃editor-extensions
1 messages · Page 16 of 1
I have just finished structuring a Custom Package, I exported it using the Assets/Export Package... utility.
I realized that when I import the package back through the Assets/Import Package/Custom Package...
it gets imported to the Assets directory... would it be possible to have the package import to the Packages directory instead?
I've seen some packages do that, not sure how though!
- Can i focus a specific folder (not any particular asset, just folder) in the project browser window via script?
a folder is also an asset, I think you should be able to do so by using the EditorGUIUtility.PingObject method.
is there a way to have UnityEvents as parameter in an UnityEvent
https://docs.unity3d.com/Manual/CustomPackages.html
Use the Package Manager Custom Packages (not the legacy unity package)
Note that the Packages folder is read-only
this may be true, custom packages however are not read-only...
I would've used package manager for that manner, but I really would love to keep things simple...
just a legacy custom package should do the affair!
for example this custom package: <https://github.com/rurre/PumkinsAvatarTools/releases/tag/1.3.9>
gets imported into the packages directory when importing it...
I'm still trying to figure out how that's being done... xd
If I were to guess it's this file here: https://github.com/rurre/PumkinsAvatarTools/blob/master/package.json
Specifically the localPath key
that's what I thought/did, however... it didn't seem to have changed a bit the import behavior...
I have a very simple extended editor for the AudioImporterInspector where I am drawing the default inspector, as well as a button(that for now does nothing). Anyway it works to draw a button along with the default audio clip(not source) asset, but I keep getting The previous instance of UnityEditor.AudioImporterInspector has not been disposed of correctly. Make sure you are balling base.OnDisable() in your AssetImporterEditor implementation
I'm calling it through reflection and the method should be valid? https://hatebin.com/dspvphwjhp
OOoooOOoOoo! this is it xd
cheers mate!
I'm using reflection to call InvalidateCacheRecursive() (ICR) on a ReorderableList, which is referencing an IList.
In one project, I use the ICR method in order to refresh the list when an item is added to the real source, outside the reorderable list's functions. It works perfectly.
But in this current project, I am using it after Clearing an array, Resizing it, and Copying new values into it.
ICR alone doesn't work.
I solved it by setting the reorderableList.list = _theSameArray;
But I can't understand why that is necessary, or why it would be any different.
public void FindAssets()
{
var found = FindAssets(_typesToFind, _parameters.SearchInAssetFolders);
Array.Clear(_data.AssetsFound, 0, _data.AssetsFound.Length);
Array.Resize(ref _data.AssetsFound, found.Length);
Array.Copy(found, _data.AssetsFound, found.Length);
this._data.InvalidateCacheRecursive();
Debug.Log("Test " + (_data.ReorderedAssets.list == (System.Collections.IList)_data.AssetsFound));//False
this._data.ReorderedAssets.list = this._data.AssetsFound;//But why?
}
Sidenote: It's probably not necessary to maintain the original array, if this is the solution I end up using.
PS: Figured it out. Array.Resize() allocated a new array. Will just use List<T> instead.
I'm trying to close Visual Studio whenever it gets opened like so:
[InitializeOnLoadMethod] // call `ShutdownVisualStudio` on editor startup (and/or other irrelevant cases...)
private static void ShutdownVisualStudio()
{
// ensure that `WaitForVSToBeOpened` is called...
EditorCoroutineUtility.StartCoroutineOwnerless(WaitForVSToBeOpened());
IEnumerator WaitForVSToBeOpened() // local method...
{
var devenv = Process.GetProcessesByName("devenv"); // try to get the task if it's running...
if (devenv.Length < 1) yield return new WaitForSecondsRealtime(30F); // if not, retry after 30 secs
else // then terminate it
{
for (var i = 0; i < devenv.Length; i++)
{
devenv[i].Kill();
devenv[i].WaitForExit();
devenv[i].Dispose();
}
}
}
}```
it's very *hacky* I know, and actually doesn't work... xd
would you have any suggestions to improve the above, or at least to get it actually to work xd
a batch or powershell script would probably be easier
which could be executed by C#
hey so I was building a simple tool that requires me to create a custom select. Its a bit hard to phrase but basically i want to reimplement this:
to use fixed bounds
so say I click somwhere in the scene view it will select objects withing a 10 unit radius
Initially i did this using raycasts but the issue with that is it only works if obnjects have a collider
ideally i would like this to work without a collider. I know its possible cause unity already lets u select objects that have no colliders. But i was wondering if that part was accessible to us for extending
you can read unity source code, but im sure that one is in native
oof guess ill have to give up on that one. Kinda sucks that there isnt any way to access the built in slection stuff but oh well
thanks for taking ur time to respond anyway
i didnt say there is no way to access it
i said the code for it is on native side most likely
oh am i misunderstanding
got it thanks for the hint ill give it a look!
Hi,
context: Animator Window.
I would like to override the Make Transition context action to handle the creation of transition with custom settings
Yo, I have a question... how can I loop through each array element and change it's name?
SerializedProperty waveListProp = property.FindPropertyRelative("_waveList");
for (int i = 0; i < waveListProp.arraySize; ++i)
{
SerializedProperty element = waveListProp.GetArrayElementAtIndex(i);
...
}
Now... how can I change the name of the array elements?
you mean element 0?
You mean Element 0? That isn't a name, that's just what Unity shows as the label for array elements
Well, yes, the label
If you had a string field in your element called Name it would show that, the label will just show Element N without that.
If you wanted to change the label it would be easiest to make a property drawer for the list elements
then you just draw the property field with whatever label you want
Oh, yeah, the second one works fine. Thanks
For some reason my brain melted and thought I can't do that for a ScriptableObject

Is there a way to generate default MonoBehaviour script header in custom inspector?
the one which says script name and double clicking it allows you to quickly get to script in IDE
that one
There is a serialized property called m_Script, which you can draw as a PropertyField
oh, interesting
Hey can someone explain to me how I can add this editor extension to my unity? I havent done this before and couldnt ifnd a solution yet
With the SerializedProperty binding system in UITk, anyone know if there is a way to have a sub element path not relative to the parent?
I have a toggle element, with two children, the toggle switches which child is visible and active. But right now the child paths are being relative to the toggle's path, which I don't want.
Maybe with the full path?
I was thinking maybe, but the issue is that it is a thing in a list, and I do want it relative to that. I think Foldouts don't have this issue... maybe I should look at that. Or maybe I am just trying to have my cake and eat it too haha
Does anyone know how to fix this Missing Command error in VSCode?
Close vscode. Regen your .proj files,. Open vscode then do, ctrl + shift+p then pick Reload Developer Window wait until it propagates, may take a while depends on how big your project is
you only need to do this once everytime you regen your projects
Can someone for the love of god tell me why this property is throwing an NRE?
https://hatebin.com/pjzodlfqbv
https://hatebin.com/yqoqncavhu
From what I understand, it's because you shouldn't treat a ScriptableObject as you treat a class/struct. By default, a SO field stores a reference to the object, but this object is not serialized. You have to create a new SerializedObject first to access its properties. The following code should speak for itself :
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUILayout.ObjectField(property, label);
SerializedObject serializedObject = new(property.objectReferenceValue);
// Ensure the ref to your ScriptableObject is not null or you won't be able to access its properties
if (serializedObject != null)
{
// Since we created a new SerializedObject, we can use FindProperty instead of FindPropertyRelative
var valueSP = serializedObject.FindProperty("_value");
float floatValue = valueSP.floatValue;
EditorGUI.BeginChangeCheck();
floatValue = EditorGUILayout.FloatField(floatValue);
// Save the change to your property if a change was detected
if (EditorGUI.EndChangeCheck())
{
valueSP.floatValue = floatValue;
serializedObject.ApplyModifiedProperties();
}
}
}
(I did the bare minimum for the presentation, but it is functional)
Thanks 🙏
I did a small mistake. Here is the corrected code :
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUILayout.ObjectField(property, label);
if (property.objectReferenceValue != null)
{
SerializedObject serializedObject = new(property.objectReferenceValue);
// Since we created a new SerializedObject, we can use FindProperty instead of FindPropertyRelative
var valueSP = serializedObject.FindProperty("_value");
float floatValue = valueSP.floatValue;
EditorGUI.BeginChangeCheck();
floatValue = EditorGUILayout.FloatField(floatValue);
if (EditorGUI.EndChangeCheck())
{
valueSP.floatValue = floatValue;
serializedObject.ApplyModifiedProperties();
}
}
}
[UIToolkit] [MultiColumnListView]
Is it possible to make each item (row) of the list stretchable in y axis when I add more items to its cells? I see MultiColumnListView has fixedItemHeight variable, which is nice for constant row heights, but I don't seem to see more flexible equivalents for that.
I appreciate the very simple approach, the comments helped me familiarize myself with the functions too 10/10 would ask for help again
In january, it was still an internal feature according to this post : https://forum.unity.com/threads/make-visual-element-resizeable-at-runtime.1387182/
One way to do it, but I assume it is a very bad way to do it, would be with multiple nested TwoPaneSplitView (https://docs.unity3d.com/ScriptReference/UIElements.TwoPaneSplitView.html).
According to this post (https://forum.unity.com/threads/how-do-i-make-elements-resizable-within-an-editorwindow.951843/), even if there's no out of the box solution at the moment, you might obtain what you want with a MouseManipulator.
Thanks for the links, gonna take a look. 🙇♂️
Something important to note with this is that you need to dispose of the SerializedObject.
That is talking something very different. The height of the elements in ListView and MultiColumnListView are controlled, and don't use layout because the elements are recycled.
Oh sry, I misunderstood you wanted to resize on the Y axis. My bad ^^'
Why? And how?
You want to change the virtualizationMethod to DynamicHeight. This is only in 2021.2 and newer https://docs.unity3d.com/ScriptReference/UIElements.BaseVerticalCollectionView-virtualizationMethod.html
Why: Because otherwise it will cause memory leaks and possibly odd behavior.
How: serializedObject.Dispose();
Generally it is best to just create one and reuse it within the class, but Unity doesn't have a good way to clean up a property drawer. So I would just dispose of it at th end of the method.
You can also use a using statement for it
using (var serializedObject = new SerializedObject(property.objectReferenceValue))
{
// Code here to get `value` property and draw the field...
}
Thank you bunches, I’m trying to familiarize myself with property drawers, but surprisingly Unity’s documentation doesn’t help much
Really? They docs seem pretty decent to me on them. Is there something specifically you are having a hard time with?
I suppose like the methods are there but there is a lot less code examples than their normal library
What should happen if I reset a component that has a Custom Editor?
Oh, I wasn't aware of this. Thanks 😮
Thanks. Works like a charm. 👍
So are labels like the entire width?
Not necessarily
Perfect
What do you think of this implementaton?
I took what you gave me and merged it on to one line and added the spacing in between the object field and the property
I feel like it is very, fluffy, there may be better ways to achieve the same goal I am not aware of
The proportions dont really make sense either, like youd think /2 would give you half width but it seems unity stretches the position
*Field methods have some minimum/dynamic sizes, it works great if you want teh default behaviour but not so much if you want custom sizing
After I have Reset a component, the Custom Editor for it is not appearing, the component is empty in the Inspector. Why is this happening
Sounds like you have errors somewhere
how to override default setting in make transition inside animator?
I want transition duration = 0
#🏃┃animation probably helps better
the default unity system of presets made for this doesn't work. I think i have to override the editor
I have no errors or warnings in my console
when debugging the code goes through OnInspectorGUI() as it should
If I DrawDefaultInspector() at the beginning of OnInspectorGUI() the custom editor will appear, glitched but it's there somehow
so I think that the problem is the editor not being drawn in the right place for some reason
before resetting my component the editor was drawn correctly
alright, so the problem is Begin/EndHorizontal(), specifically the ones inside a method I'm calling from OnInspectorGUI()
it's weird that it worked before resetting
Guys, if my application has .NET debug libraries (plugins) with debug symbols included (mdb), does Unity optimize these libraries when compiling my application, or it will use the same library files upon compilation?
Il2cpp or mono builds?
Both
I mean, sounds like il2cpp should do optimizations
Idk if a .NET library compiled with debug config differs in any way besides the .pdb generation
Mono build just copies the library over. I've just checked it out
So I will reformulate my question: "Does a .NET library compiled with debug config differs in any way besides the .pdb generation?"
Yes
Both because there's the DEBUG preprocessor define and optimize code is not enabled on debug builds
hmm
So I'll have to include both a debug and a release library version in my package. I guess I can use one or another based on the DEBUG definition
I guess theoretically if you run il2cpp on a non optimized assembly it could generate worse code (or better, goes both ways really)
It's not DEBUG in unity
UNITY_EDITOR suffices
It's UNITY_EDITOR || DEVELOPMENT_BUILD
Fixed it! I returned before EndHorizontal()
So I am doing some editor work and trying to set addressables AssetReference from the editor. Something wasn't working, so I dive in to see how the PropertyDrawer handles, that way I can just copy how it does it.
And... I will not be copying how they do it. It scares me.
They set it directly, not via SerialiedProperty, and there is like 4 levels of utility methods that it goes though before actually setting it. And they mix editor and runtime code... 😨
So I guess time to do some debugging to figure out what the issue is instead haha... 🥹
(Silly PropertyDrawer mistake. I was caching the property. Still, the addressables editor code is wack)
Question:
Is there still no way to reset a SerializedProperty? I feel like I came across something but forgot. Specifically asking for resetting new array elements.
Is it possible to have public fields inside editor scripts
I want to attach a script template asset to my editor script
so that I can create custom scripts from the context menu
using UnityEditor;
using UnityEngine;
public class AssetsContextCustom : MonoBehaviour
{
public static MonoBehaviour componentScript;
public static MonoBehaviour systemScript;
public static MonoBehaviour authoringScript;
[MenuItem("Assets/Create/DOTS Component", false, 1)]
private static void CreateNewAsset()
{
ProjectWindowUtil.CreateScriptAssetFromTemplateFile(componentScript.ToString(), "NewComponent.cs");
}
}
But where do I find the public static fields in the editor?
Unity cannot serialize static fields and so they will not show up in the editor.
The way to do this would be to either have just straight .txt or some other extension files, and read the contents of them. The other way would be to just have the tempaltes as strings inside of your class.
so "public string componentScript"
?
or could I access it through the file system somehow, or is that not allowed
Actually actually, this would be the best way if you don't need anything fancy https://medium.com/@tuznev/how-create-custom-script-template-in-unity-ab2cbb6172b5
No need for any custom editor scripting
hmm this seems very limited, it can only ever make the same exact file, it cant really fill a template based on a fileName I provide
#SCRIPTNAME# in the file will be replaced with the file name the user inputs.
Does anyone know how to change a gameobject under a prefab to be an instance of a different prefab (preserving overrides)? When I use ConvertToPrefabInstance I get an error that it's a prefab already (even though it's the child of a prefab). When I use ReplacePrefabAssetOfPrefabInstance I get "Input instance is not an outermost Prefab instance root.".
Aight so, i've stumbled upon the need for code generation in my project
i know that input system has well, a """code generator""" for input action assets
multiple quotation marks because ideally i wouldn't want to do the same because, christ, it looks like pain
is there like, a proper way to use code generation? i was thinking about using partial classes and having code generation on them
proper way would be to use roslyn code analysis api, syntax trees, tokens etc
from there you can either generate/compile it at runtime or dump on disc as an assembly, or files
there are also T4 templates
Tbh, if you want to do something simple, just write some strings to a file and let unity compile it (or use the roslyn api)
IIRC unity doesn't support incremental source generators yet so it can be a bit slow
A supportive community for Blender artists of all levels. Share your work, ask for help, and learn from others! https://discord.com/invite/blender
Hi, I have this problem trying to assign new field to a button
public class ButtonTextColorView : Button
{
[SerializeField] private TMP_Text text;
[SerializeField] private ButtonTextColorTransition textTransitions;
protected override void OnEnable()
{
base.OnEnable();
}
protected override void DoStateTransition(SelectionState state, bool instant)
{
base.DoStateTransition(state, instant);
if (textTransitions.colors.ContainsKey(state))
{
text.color = textTransitions.colors[state];
}
}
#if UNITY_EDITOR
protected override void Reset()
{
base.Reset();
text = gameObject.GetComponentInChildren<TMP_Text>();
}
#endif
[Serializable]
private class DictionaryOfSelectionStateAndColor : SerializableDictionary<SelectionState, Color>
{
}
[CreateAssetMenu(fileName = "ButtonTextColorTransition",
menuName = "ScriptableObjects/UI/ButtonTextColorTransition")]
private class ButtonTextColorTransition : SerializedScriptableObject
{
public DictionaryOfSelectionStateAndColor colors;
}
#if UNITY_EDITOR
[CustomEditor(typeof(ButtonTextColorView))]
private class ButtonTextColorViewEditor : ButtonEditor
{
private SerializedProperty _text;
private SerializedProperty _textTransitions;
protected override void OnEnable()
{
base.OnEnable();
// or any other private field
_text = serializedObject.FindProperty("text");
_textTransitions = serializedObject.FindProperty("textTransitions");
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
// for object
EditorGUILayout.ObjectField(_text);
// for array
EditorGUILayout.ObjectField(_textTransitions);
serializedObject.ApplyModifiedProperties();
}
}
#endif
this problem comes because the classes are private? but I can't use the SelectionState enum otherwise
Anyone have any resources for building propertydrawers for lists?
It doesnt seem to follow the pattern value types follow
The problem is you should be defining ButtonTextColorTransition in its own file. Is SelectionState an enum of yours or is it from Unity ?
SelectionState is from Unity defined inside the UI.Button class
There is a way to use it from a new file. or I have to create a copy and compare the values with the real one?
Since SelectionState is a protected enum, you won't be able to access it outside a class that inherit from Button like ButtonTextColorView. But you could define your own enum with similar values and use it as key for your dictionary. Then in your DoStateTransition(), you "convert" the SelectionState into your own enum (using int values of both enums) and it should do the trick.
which method am I supposed to override in order to implement a different preview for the AnimationClip class?
currently I have this in place:```cs
[CustomEditor(typeof(AnimationClip))]
class ACPreview : Editor
{
static readonly System.Type ac_t = typeof(Editor).Assembly.GetType(AC_TN);
const string AC_TN = "UnityEditor.AnimationClipEditor";
static Editor editor;
void OnEnable() => editor = CreateEditor(target, ac_t);
void OnDisable() => DestroyImmediate(editor);
override public void OnInspectorGUI() => editor.OnInspectorGUI();
override public bool HasPreviewGUI() => editor.HasPreviewGUI();
override public void OnPreviewGUI(Rect r, GUIStyle s) => editor.OnPreviewGUI(r, s);
}```
however! it seems all wrong since it doesn't show the preview nor does it allow a model drop...
oops, nvm! xd
this was it: OnInteractivePreviewGUI
anybody knows if Awaitable api would work in edit mode or not?
You mean tpl?
tpl?
oh you meant TaskParallelLib? if so, no.. it's the new https://docs.unity3d.com/2023.1/Documentation/ScriptReference/Awaitable.html
I would imagine some of it to work but haven't used it myself
yeah, kinda wondering how'd it deal with the frames while in edit mode. As in frame precission/consistency between edit mode vs runtime
I doubt that's a consideration of the system
guess I should download 2023 and try it now 🥹
🥹
Should I use the Repaint Event in OnSceneGUI() for drawing handles or is that unnecessary?
private void OnSceneGUI()
{
var script = (MyScript)target;
var position = script.transform.position;
var previousColor = Handles.color;
Handles.color = Color.green;
Handles.DrawWireCube(position, Vector3.one);
Handles.color = previousColor;
Debug.Log(@"I'm inside a method that doesn't need to be force repainted!
It's repainted whenever needed automatically!");
Repaint();
Debug.Log(@"So it's ok to remove the `Repaint()` method from above my originating line of code,
It's just redundant mate!");
}```
Not that repaint actually
This Event Type
I see, so something like this you say:
if (Event.current.type == EventType.Repaint)
Handles.DrawWireCube(position, Vector3.one);```
for handles, I think this approach makes more sense! as it calls them much less!
Does anyone have experience using Using Unity adds using IronSource? I need to setup my monetization scripts but I have no idea how and the videos I have watched are all outdated. I use visual scripting for my game. I am not very good with coding at all . Can anyone show me the ropes to initialize the adds and trigger them? Thank you
any reason why the highlight of the camera is red?
Hard to make out, but is that cinemachine free look? That's normal
https://docs.unity3d.com/Packages/com.unity.cinemachine@2.5/manual/CinemachineFreeLook.html
I guess to help differentiate it
I think you'll have better luck asking in #archived-unity-gaming-services.
Thank you
What's the most useful editor extensions you write for you components? Are there any code samples of useful editor extensions?
I mean custom editors
for code samples, try this on a google search
site:github.com intext:CustomEditor intext:UnityEditor
Is there a way to reload unity without having to open and close the project?
no, its this isnt really an extension per se
you normally would not need that tho. May I ask for what purpose?
I assume you can try reloading the project EditorApplication.OpenProject(pathToProject);
never really tried it
ok, thanks
isnt there a button somewhere tho? if not Ill just create ta script
create a new c# script in your project and put it in Editor folder then add this snippet
[MenuItem("Tools/OpenProject")]
public static void OpenProject()
{
EditorApplication.OpenProject(Directory.GetCurrentDirectory());
}
assuming you want to re-open/refresh the already opened project so GetCurrebntDirectory should do it I think
give it a try
it will show in Tools->OpenProject
I recommend look at the docs on how to deal with custom Editor scripts etc
ok, let me run it
Well
that just closed the current project and reopened it
Defintely a step in the right direction
the whole editor too?
so it works?
I'm confused here 😅
ok, so unity gets slow after hours of use
for example, if you click on a color property in editor, there is like a 1 - 2 second delay
you ever exp that?
proly? depends on the scale of your project. That can be normal
yea normally, I would reload the editor to unfreeze it, but this will mean I have to close and open the project.
How to reload editor without having to close and reload
then I've no clue for that... just wait some good fellas here to answer that. Should be quick
still your solution worked, and its much faster than manualyl doing it, so thanks for the help!
np!
You can't
Slimtv's solution is the only way
Alright, thank you 🫡
Hello everyone, is this where i can ask about exporting/importing packages?
It depends of what you mean
I have a problem that when i import the custom package my assets have the "missing scripts" error and the asset itself becomes invisible
as for the button... there kinda is! right click in the project window then Reimport All (same as Assets/Reimport All)
I dont think thats it
I would say #💻┃unity-talk is more appropriate
I think "Reimport All" won't reload the editor so that it solves the editor getting slow
that might be due to some dependencies that didn't get included when the package got exported...
that happens when said dependencies are in the Packages directory instead of the Assets
you think you say... xd
did you try it at all?
Well, I assumed you would convince me otherwise and confirm that it solves it all x)
only the one experiencing the issue could confirm it xd
As far as I can tell, re-importing all assets won't empty the editor cache and all garbage that can bloat the editor, but I might be wrong and will test it
OK, I confirm that it closes the editor.
BUT it reimport all assets which is kinda overkill lmao
xd
(hopefully, the sandbox I tested with was kinda empty)
So long story short, don't use that button xD
how do i get those dependencies then?
usually form the Package Manager, however! I wouldn't know what they were xd
you'd better off contact the author of the package I'd say.
uh the funny is its just a package of things from my other project so im the author xd
It could be different thing : error when exporting, error when importing, or your package missing a depedency
Kinda hard to tell exactly
By dependency I mean: you have a prefab with a script and just tick the prefab but not the script for example
ok so i've imported the effects asset that the package was using and the "missing scripts" error dissappeared but the asset is still invisible
(but it's supposed to be ticked automatically)
Invisible in your project window ?
Otherwise, can you share a screen pls ? 🙂
here it is, both in prefab view and in game
Did you import your meshes as well ?
If you select one of Tree_XXX object, do you have an actual mesh renderer with a proper mesh assigned to it ?
hm yea my original prefab doesn't have any mesh renderers
oh wait nvm
looked at the wrong object
the imported objects have no mesh filters, the main one does
Ok, so you're missing the actual mesh in your package
So you'll have to find it in your other project and add it to the package
So that the reference doesn't break
can't find those meshes in assets folder : (
Did you use and external package ? something like speedtree for example
Since you're using a terrain, you might need to import it in your new project
well so i got a tree from an online package, modified it in blender and then imported from blender to unity, right now its just as prefab and can't see any meshes
its a .fbx
then add your fbx to your package
You imported it in the first place, so it should be somewhere in your Assets folder
Otherwise, your trees would be invisible in the original project too
okaay, i've just imported the whole folder where the .fbx might have been an it worked, im too lazy to search and find out which fbx was for which object
thank you very much that worked👍
Np 🙂
it also take forever to finish 🤪
Yes, it depends on what needs to be reimported 🥲 It's like opening the project for the first time after cloning a depository (or deleting your library folder and reopening the project)
Hey 👋 Is there a simple way to draw a rect behind a propertyfield? I have objects like the one I am attaching a picture. The properties are generic and can be of any height. My use case is to use alternating colors to more easily distinguish lines.
you use EditorGUI.PropertyField() to build each line ?
In any case, before each line you build, you can do:
GUI.Color = yourActualColor;
It should change the background color.
Hey I'm pretty new to editor extensions. I would like to make a similar table for my Skill Data Dictionary similar to an ArrayList.
But I don't know how exactly I can create a field for my Objects (ScriptableObjects in this case)
And how to create a table like List has
What is your Skill Data Dictionary right now ? an actual dictionary ?
correct
Dictionary are not friendly with custom inspector unfortunately and there's no easy way to make them look like the default list of Unity. But it appears you already handle the serialization part since you already achieve to make it visible at all.
I'm picking the values out of the dictionary for this one, it's maybe not perfect but works for now haha
but I haven't found a way to drag/drop an object, there is a ObjectField but it's saying something about SerializedProperties
The way I would do it, which I won't assume to be the best way : A Serializable C# object MyObject that wraps your data (type, level, skill name, skill values) and have a public or [SerializedField] List<MyObject>. You will be able to use a default list inspector that way + you're sure it is properly serialized (which is not guaranteed for a dictionary). The build the dictionary using this list whenever you're SkillManager is loaded.
I know it doesn't guarantee the uniqueness of SkillType which is your key
So you can add an OnValidate() method in your script that check whether or not you're trying to define a new object with a key that is already used and set the default key to the first avaiblable type
Yeah that makes sense, so basically I make a "Wrapper" and can store it in a normal List
Yup
I never really understood why dictionaries aren't supported by default 😄
Unity's mysteries
If you were working on a professional project, I would suggest you to use OdinEditor
Which make that kinda thing way easier without having to know anything about custom editor scripts
But it's pricy so...
Not hobbyist-friendly
Oh very interesting, thank you very much 🙂
I mean you either learn how odin (and still learn a bunch of custom editor things) works or you learn how to make custom editors
Not like odin replaces it completely
Yes. At my workplace, in most case, predefined attributes are enough for gameplay developer when they want to have a nice inspector. But you're right it isn't enough if you want to do some other things.
NaughtyAttributes is pretty extensive
Yeah that's a popular one
The thing I need to learn is how they do things like [EnableIf] which can access variable ._.
Bunch of reflection
and serializedproperty abuse
You can just go up the stack and go look at other properties
That's what I imagined, but I assumed I was kinda naive to use such a bruteforce way haha
It really is just the easiest way
you can do this pretty easily with generic-attributes in c# 11... sadly Unity doesn't support that yet 
Hmm?
Personally Never really tried it with Unity, but I can imagine it would work wonders for cases similar to EnableIf in naughty attributes
I'm talking about this https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11#generic-attributes
Yeah I know what they are but wondering how they help
I guess it makes comparing a little easier but the data still has to be constant so it's a bit meh still
When I open a script in Visual Studio's code for a little it just stops responding and I have to close it and open it everytime. How can I fix this?
nvm it just stopped happening 🤷♂️
intelisense is not working on visual studio code
I am trying to write to files in unity and Im having a problem - my files wont update with my changes unless I delete them first, and I don't want to delete them because that breaks GUID and references.
if (AssetDatabase.LoadAssetAtPath<Mesh>(newAssetPath) != null)
{
Mesh existingMesh = AssetDatabase.LoadAssetAtPath<Mesh>(newAssetPath);
EditorUtility.CopySerialized(meshCopy, existingMesh);
EditorUtility.SetDirty(existingMesh);
}
else
{
AssetDatabase.CreateAsset(meshCopy, newAssetPath);
}```
this is how I am writing new meshes/to the meshes, what possible reasons would cause the write to fail to make any changes at all when outputting to something brand new works completely as expected?
I can only guess that my writes arent being applied in CopySerialized?
what should I use otherwise though?
You need to call AssetDatabase.SaveAssets() to write the changes to disk.
Oh yeah sorry after that bit I run save, I didnt paste the entire code because its large.
I found the real problem though. The generated meshes had read/write set to false. It wasnt throwing any kind of error telling me that I was trying to write to read only meshes
The meshes themselves are being made by unity in this method so I never thought to check and see if it was making them from scratch with read/write false 
okay, I need help doing a little thing
I need the currentActiveSkill property, to keep the value of the class BasicMelleAttack I puted inside.
At the current momment it works some what, i can save values inside this class that is inside the scriptableObject, but at the momment I hit play, or get out of the unity, the property resets, anyone knows a way to solve this?
hello,
we are using (default / fallback) custom editor for Unity objects
this works well for most things but we noticed that drag & drop multiple objects into arrays/lists in the inspector does not work anymore
does anybody know how to (easily) recover original behaviour?
Hi! I'm trying to display a list for an object's property that is not a Unity Object in an Editor Window. I cannot figure out how to do this because I can't get a SerializedProperty from it. The only solution I've explored was creating the list UI from scratch. While it works, styling it and getting all the functionality (drag and drop) just doesn't seem straightforward at all. Any and all help will be greatly appreciated
If the object is marked as serializable and has serializable members then it should work as normal
In about 95% of cases the class is on some Unity Object. Otherwise the data will be lost on domain reload. If it is in that 5% of cases where it isn't, what I tend to do is to make a temp ScriptableObject with that class as the only field, and create an instance of that SO so you can create a SerializedObject from it.
They mean they want to show a list from a POCO. Meaning there is no SerializedObject. Assuming I understand correctly that is.
Original explanation doesn't really make it clear. If there is no SerializedObject then yeah, you can't show it easily. If it's using an Editor or Editor Window, they are both ScriptableObjects and you use them as the "temp ScriptableObject" for serialization to display purposes
Ahh yeah, I was assuming it was 'stored' else where. But if using a temp SO, then that already defeats the point. You are right.
Btw, @visual stag what do you think of adding a quick section to your huh.how site on the classic "Why aren't my values saving when I change them in my custom editor"? I find my self typing the same thing over and over. I feel like I did have a resource I would link, but I can't remember what it was now... or I am just misremembering.
there's something pinned to this channel
I checked and didn't see anything. Am I blind?
It's the bottom-most pin
Oh, I was meaning something more direct/explicit
Maybe that is good enough though
I honestly find it a really painful thing to explain because people love to avoid serialized properties, and then when they run into issues then try to mix and match and it all falls apart
people also love to overcomplicate their setups by avoiding property drawers and just making complete editor overhauls and shit
Yeah, it is pain. I basically don't help people beyond simple things if they refuse to use SerializedProperties. Just too much work
I just point people to the pins and leave 😄
I'll add something to my site though, and I might also make a flowchart for how to consider making extensions (property drawers over editors, etc)
What I was thinking/asking was basically something along the lines of "This is why your things are not saving. You should be using serialized propertie. The reason is because it saves automatically, it supports undo, it supports prefab overrides, and is the intended Unity way."
apparently
lol
there's a lot of pages okay 😛
But yeah that is pretty good. Might be worth expanding a tiny bit. Maybe just to mention that SerializedObject is the strongly recommended way. And add the word "save" in there to help beginners out. Idk lol
(Also, that last bullet point seems disconnected)
It's a footnote
Ahh
I need to update the footnote styling a bit
What are the chances I can get you to add that to one of the pinned messages so I can link it to people easier?
Also, not on the main page it seems, not sure if there is another way to get to it that I am just missing. I actually looked on your site before even asking the question just to make sure you didn't already have it there 😄
Unity C# source code
📚 Resources
Unity Editor Foundations
API Versioner
IMGUI Debugger
Packages
Editor Coroutines
GraphTools Foundation
Package Validation Suite
Immediate Window
Quick Search
Playable Graph Visualizer
Search Extensions
Blogs
Talks
- Prefab System (Slides 45 and onwards are a good resource for anything prefabs)
Tutorials
IMGUI
🗺️ Roadmap
Thanks vertx! 😄
You can get there via Custom inspectors > Variable changes don't persist or Variables > My variable becomes unassigned when I enter Play Mode. > I am having issues with persisting changes from the editor.
I can definitely improve that, I'm always tweaking the routes and figuring out what works best for all the content, as moving one thing might mean other setups no longer make any sense, so it is a bit of a house of cards. Slowly massaging it into a better place. I haven't been properly interested in editor extensions for a while though so I haven't touched that area much.
I think I got over it all when I realised I was overcomplicating most things and 99% of stuff is just property drawers 😄
Once unity made collections reorderable by default most of my custom editors disappeared
Hahaha, makes sense
i need help with handles.cap stuff
how do I make it stay the same size no matter how zoomed out or zoomed in the camera is
Calculate the size using https://docs.unity3d.com/ScriptReference/HandleUtility.GetHandleSize.html
cool thanks
Alright, thanks. I figured that out, but now I've run into yet another issue. The custom PropertyDrawer I'm using for the objects inside the list property depend on some external properties to populate a dropdown. I've been struggling to figure out how to "pass" said properties to the drawer.
I considered trying to package each SerializedProperty inside the list inside ScriptableObject alongside each of the properties, but then I cannot render the resulting SerializedObject array out into a list. I just don't know how to do this without adding the properties I need onto the original class, which would just result in some disgusting, unintuitive code imo.
Error: Object reference not set to an instance of an object at the line serialData.Update(); in Reset(), even though I initialized serialData in OnEnable(), which should execute right before Reset()
According to Debugging it's actually the reverse
this is happening when selecting an object with this editor
Anyways the thing I actually want is a function that is called when I press the Reset component button in the Inspector's context menu, but apparently Reset() gets called whenever I select the object
Looks like this is in a Editor class, yeah? Reset() is called per ScriptableObject. So it is called when the Editor class is reset (or created), not when the target is reset.
There isn't really a way
I don't really understand the set up so not sure what to recommend. If you want to explain the sitiation a bit more I could maybe give some suggestions though.
List index
after a Reset the list gets emptied
and I have a field that chooses an element
What?
I have an intfield which corresponds to an element in a list
From the snippet I can see, it looks like you are storing editor data. Is this data per-object? Does it need to be? If not, unity has a couple of classes that are well suited for storing editor only data.
well that's a different thing
I'm storing editor data in an asset made from a ScriptableObject class
Basically, I am wondering, do you need to reset the editor state? Looks like it is just what is selected. And that doesn't need to be reset, that can be handled without it.
I would look in to ScriptableSingleton, and also SessionState for storing editor only data.
Are those Serialized?
Yup. SessionState, as the main implies, is only saved during the editor session. While ScriptableSingleton can either be only during the session or saved to either the project settings or preferences
But do they need to be saved through SerializedObject/SerializedProperty?
Nope
Oh then that would make my life easier
Also, if you only need it while the inspector is open, you can just save it on the Editor class itself
won't do
Does ScriptableSingleton record changes to the Undo history?
Not by default. You can use Undo.RegisterCompleteObjectUndo
Interesting, thanks
Anyone know how to circumvent an issue with SceneUtility.GetScenePathByBuildIndex()?
https://docs.unity3d.com/2021.3/Documentation/ScriptReference/SceneManagement.SceneUtility.GetScenePathByBuildIndex.html
Apparently, if you have an unloaded scene inside the build list, it will count it as a scene index
so that's mildly frustrating
In my given example, I get build index 14, which is correct as per the Build Settings, but when I call that method, it returns the scene at index 13 because there's an earlier unloaded scene in the list?
Any way to circumvent that unloaded scene without editing the Build Settings by moving or removing that unloaded scene?
Using Unity 2021.3.17f1.
check if the scene is enabled in build settings https://docs.unity3d.com/ScriptReference/EditorBuildSettingsScene-enabled.html
How do I inherit ScriptableSingleton in an abstract class so it works with its children? For now if I try to Child.instance I get an error "Can not create instance of abstract class 'Parent' "
ChatGPT tells me to make a wrapper class
@gloomy chasm
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(Vigor))]
public class VigorEditor : Editor
{
[Header("Player Vigor Testing Options")]
[SerializeField] private int healAmount;
[SerializeField] private int damageAmount;
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
Vigor vigor = (Vigor)target;
if(GUILayout.Button("Heal Player"))
{
vigor.Heal(healAmount);
}
if (GUILayout.Button("Damage Player"))
{
vigor.Damage(damageAmount);
}
}
}
Anyone know why the int values dont show in the inspector
i even tried changing them from private to public and its the same result
You just make the parent generic
public abstract class Parent<T> : ScriptableSingleton<T> { }
public class Child : Parent<Child> { }
Because it is an editor class, and the fields from an editor class are not show in the inspector of the target object. Only the target object fields are. But you can do healAmount = GUILayout.IntField("Heal Amount", healAmount); to show in the inspector.
Note that fields on a Editor are only saved while the object is selected. Selecting a different object destroys the editor instance.
Now I can't do Parent<ScriptableObject> x = new Child
You don't do that at all. It is a singleton. Are you familiar with the singleton pattern?
Correct, generics don't work that way. What are you trying to do?
Polymorphism
What I had is the Parent abstract class PathEditor and its implementations ExpressionEditor and BezierEditor
And then I had a List<PathEditor>
and for example you could iterate through the list and call GeneratePath() and each implementation has its own overriden method for it
Is patheditor a scriptablesingleton?
Yes
public abstract class PathEditor<T> : ScriptableSingleton<T> where T : ScriptableObject
So, I have a CustomEditor script that sets up the inspector for another class. It was working fine previously. I only noticed it stopped working when I added namespaces to the class and to the editor script. Then, it still looks visually correct, but it doesn't accept any input, even though the buttons give visual feedback when my mouse is over them, so I know it's at least detecting that. I had read something that said adding namespaces could screw up the serialization, so I'm not sure if maybe that's the issue or not, but if it is I'm not sure how to fix it. Anybody have any thoughts?
I think you're trying to coerce ScriptableSingleton into something that it is not
For example, you imply that you can have multiple instance of a BezierEditor/ExpressionEditor and that's just not possible with ScriptableSingleton
Those 2 things are probably unrelated
True, what I actually have is still a List<PathEditor> but it only has one instance of a PathEditor child. I do this so that when I choose which PathEditor I want in my custom editor I can look it up in that list
pathTypeSelection = (PathType)GUILayout.Toolbar((int)pathTypeSelection, System.Enum.GetNames(typeof(PathType)), EditorStyles.radioButton);
and then elsewhere I look into the list like this Options[(int)PathTypeSelection]
So can't you just do PathEditor p = Child.Instance then?
Why does it have to be Parent<ScriptableObject>
Is the reason why you can't
Parent is PathEditor in this case
and this is why
I'm trying to use ScriptableSingleton<T> to save editor data
Right
What you probably want to do is have a class that handles all your drawing shit and saving that then has a variable for ExpressionEditor
Rather than trying to do some cursed shit with generics
Well that's what I did before, I used ScriptableObject and SerializedObject
But today I'm checking out ScriptableSingleton
because debugging with SerializedProperties is harder
Hi guys
How can we Undo record changes to some RenderSettings properties?
Consider the code below, line 136.
How to get field type in SerializedProperty if objectReferenceValue is null?
Want to bind type value of UIToolkit ObjectField objectType with property to mimic inspector field
is there any easy way to make the index display next to array elements?
This doesn't seem to work. I have an object that implements ScriptableSingleton<> inside my Editor script. I'm using that method inside OnInspectorGUI() and it registers the name in the edit menu but when I Ctrl-Z, nothing happens, not even unfocusing the selected object. Can I do it in OnInspectorGUI() or does it need to happen elswhere?
Data Based Composition
Can I access a MyClass : ScriptableObject's vector2 variable with serializedPropertyMyClassList.GetArrayElementAtIndex(i).FindPropertyRelative("vector2").vector2Value?
nope, you would need to make a SerializedObject of the serializedPropertyMyClassList.GetArrayElementAtIndex(i).objectReferenceValue
Can any Custom Editor guru's spot what I'm doing wrong here? This was working at one point. I have no idea why it's no longer working since I didn't do any changes that should break it. Visually it looks exactly as it should in the editor. If I mouse over the buttons, or the circle context button to assign a reference, or over top of the int for "Weights", the cursor or buttons change visually so I know it's detecting the mouse there, but when I click anything, absolutely nothing happens. On the Add Behavior button's if statement, I changed from using "r" to new Rect(0,0, 100, 100), and then the button worked, but it's a mess then obviously. I have tried a bunch of other modifications and nothing else has worked.
Please host your code on a site so it's easily viewed https://hatebin.com
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
How the heck does this site work? There's just 3 buttons and 2 of them just seem to remove the code I just pasted in while the other one just seems to color code it?
ah ok that's what was confusing me. lol
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.
hmmm i don't think it's possible to create class attribute in unity in order to modify rendering of the class properties since there is only property and decorative drawer
PropertyDrawers can be applied to non mono classes and CustomEditors can be applied to monobehaviours
but property drawers is a customer property drawer of a property attribute and that expect you to attach your attribute to a class property not to the class itself, i don't want a custom editor since i just wanna do one thing. which is hiding a single public var from the base class
I can't parse that sentence
PropertyDrawers can only be used on PropertyAttribute, i will attach my attribute to the class itself not it's class member/property
class attributes like addcomponent, requirecomponent
i want a class attribute that lets you hide specific public fields that was derived from the base class and not be rendered in the inspector
i only need to hide one so a customer editor is so overkill
we can create c# class attributes but that we need a unity drawer for that to actually feed you the rect, serialized property and GUI contents of the class fields to actually modify how stuff is drawn to the inspector
So there's a rust library that's for converting VMF (Valve Map Format) files into generic 3D files, and it can be used in Blender as a plugin to import VMF files, but is there a way to use it for Unity as well?
You can target serialized types with property drawers, you don't need to target an attribute
but how can i hide a field from the base class inside the class that derives it
some classes that derived from that base class doesn't need that variable exposed since it doesn't use it
Make a drawer or editor that avoids drawing or hides the field based on the conditions you care about. DrawDefaultInspector has an overload (or undocumented variation, I forget which) that can exclude fields for example
Hi ! Is there a reason a call to AssetDatabase.SaveAssets() would make my editor suddenly very slow with no end to this performance issue ? Could it be due to the volume of data being written to the disk ?
For some reason, the memory used by profiler keeps increasing infinitely after SaveAssets of SaveAssetIfDirty is called.
Here it is before, somewhat stable :
And here it is right after either of the two function is called
And I'm sure it is the call to either of this function that is responsible of the situation since I tried commenting it and everything is fine when it doesn't happen
If someone know if it's a normal issue and it's just that I shouldn't be using SaveAssets or what could be going on here, any insight is welcomed
It could be the volume, but my guess might be a recursive call. Where are you calling SaveAssets?
Having a weird issue with extending UnityEngine.UI. My script inherits from UnityEngine.UI.Dropdown and has an alternative to the UnityEvent/DropdownEvent m_OnValueChanged_ UI.Dropdown uses . I have a custom inspector script, and I have tried to inherit from both DropdownEditor and SelectableEditor. Either way I get the same error: All of the serialized properties have their own version of this error:
UnityEditor.UI.DropdownProEditor:OnEnable ()```
This si the editor script in question: https://hastebin.com/share/cadafocuya.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
THe affected properties are: m_template, m_CaptionText, m_CaptionImage, m_ItemText, m_ItemImage, m_Value, m_Options, and m_OnValueChanged. I am not calling any base methods.
What does DropdownPro look like (I don't mean the methods, just what fields, events, properties, etc. are on it)
It uses the same property names as the UI system; I've double checked that all the property names match correctly.
What does it inherit from?
UnityEngine.UI.Dropdown
Well, there ya go
The parent class (DropDown) already defines m_Value, so if the class that inherits from it also defines m_Value, what is it supposed to do?
Unless of course I am misunderstanding what you are saying/doing
Except that in DropdownPro, I hide the inherited value with the new keyword:
[SerializeField]
new private int m_Value;
That does not matter in the slightest. Unity's serialization system walks over the 'raw' form of the class
Basically it just goes and collects every field marked with [SerializeField], and saves it.
So having two with the same name doesn't work.
This is how most every serialization system works I believe
So what do I do? It would really suck if I had to essentially recreate and/or copy the code of UnityEngine.UI just to make my extension work. It's not really an extension then anymore
Why do you need to define the properties that already exist?
Because they are private, and therefore are inaccessible in the inherited script.
Are they not exposed by properties?
they are exposed in a really weird way, tbh.
What do you mean? It looks fine to me
So this is one of them in the UnityEngine.UI:
[SerializeField]
private Image m_ItemImage;
/// <summary>
/// The Image component to hold the image of the item
/// </summary>
public Image itemImage { get { return m_ItemImage; } set { m_ItemImage = value; RefreshShownValue(); } }
so am I supposed to only reference the property in the inherited script?
Yeah, that is how inheritance works
The point of something being private is it can only be accessed in the script it is defined in. It can be exposed using either public or protected properties or methods.
I'm actually not sure how to go about this. So take m_Value and value. in UnityEngine.UI they are:
[SerializeField]
private int m_Value;
// ...
public int value { get { return m_Value; } set { Set(value); } }
Which is fine. But I do something different in the inherited class:
new public int value
{
get
{
return m_Value;
}
set
{
if (Application.isPlaying && (value == m_Value || options.Count == 0))
return;
m_Value = Mathf.Clamp(value, 0, options.Count - 1);
RefreshShownValue();
// Notify all listeners
UISystemProfilerApi.AddMarker("DropdownPro.value", this);
switch (callbackType)
{
case CallbackType.Index:
onValueChanged.Invoke(m_Value);
break;
case CallbackType.Label:
onLabelChanged.Invoke(options[m_Value].text);
break;
case CallbackType.Sprite:
onSpriteChanged.Invoke(options[m_Value].image);
break;
case CallbackType.Index_Label:
onValueLabelChanged.Invoke(m_Value, options[m_Value].text);
break;
case CallbackType.Index_Sprite:
onValueSpriteChanged.Invoke(m_Value, options[m_Value].image);
break;
case CallbackType.Label_Sprite:
onLabelSpriteChanged.Invoke(options[m_Value].text, options[m_Value].image);
break;
case CallbackType.All:
onValueLabelSpriteChanged.Invoke(m_Value, options[m_Value].text, options[m_Value].image);
break;
}
}
}```
What would be the correct way of doing this?
You would simply do base.value instead of m_Value. Though, depending on what you are planning on doing exactly. I might recommend that you instead have your DropdownPro component create a hidden Dropdown component that it manipulates instead.
Why?
Because while using the new keyword does work, it also leaves you open doing if a user does something like this
Dropdown dropdown = GetComponent<DropdownPro>();
dropdown.value = 0;
It will actually set the value using the value property defined on the Dropdown component and not the value property defined on DropdownPro
Hmmmm. You're right, that's a problem. I still want to try to avoid using a hidden dropdown component though, if I can help it.
For context: what I was doing previously was to create an entirely new class that mirrored the functionality of UI.Dropdown completely. But I don't like that solution and it feels clunky. I'd rather inherit. But it's hard to do that and also swap out properties I don't need or am replacing.
Yeah, the easiest way would be a hidden dropdown component. The only other one I would really consider is recreating the whole Unity component.
^ That's what I did before trying this. And it does work, perfectly. But it feels clunky to do that.
Gotta pick your poison I guess
Because I'm doing this for a potential released asset, I am hesitant to just mirror the component code. I have seen other assets do that. A few drawbacks though are:
- my component would not be interchangeable with Dropdowns if used with other assets
- questionable license concerns
I don't wanna be the guy who goes "well [x] popular asset does that, so it must be ok"
- It would if all of the serialized fields are named the same.
- Not sure on the legality. Strictly speaking, probably not. But I am not lawyer. What I tend to do is to use it as reference, and do my own implemention. Often a litter nicer or one that works better for whatever feature I am doing.
That's fair. #2 is really what I'd prefer
There are also multiple instance of Unity devs say "Feature X is internal or not being backported, so you can copy it". The general understanding is that if you are keeping it within Unity, that is fine to copy it.
Ah, I see. Okay. That gives me a bit more perspective.
Sorry, I didn't see your answer. After some more test, I can confirm it is not the volume and it's more of "trying to save while serializing". I can't really go into detail since I don't have access to the whole code (a big part of it is in a DLL and I don't have access to source) and I'm still trying to build my understanding of what the author (of the code I'm trying to fix) . I wanted to make sure this behaviour wasn't normal.
My first guess is the original author is calling AssetDatabase stuff in a place they shouldn't have, but I'll keep investigating since I found some more case that freaks my profiler (like "Save Project").
Found the source of the problem. An infinite loop.
I have a component with a List of ScriptableObjects. How do I save them when editing a prefab?
Also, maybe related, what does (Clone) mean in an object's Inspector name?
does anyone know a way to render a sprite from a spritesheet in an editor window other than just ripping the pixels from the source texture and making a new texture with them?
- Create a SpriteAtlas out of a SpriteSheet
- Get the SpriteAtlas object and the name of the sprite in the SpriteAtlas you want to use.
public SpriteAtlas SpriteAtlas;
// IMGUI
public override void OnInspectorGUI()
{
var texture = AssetPreview.GetAssetPreview(SpriteAtlas.GetSprite("MySpriteSheet_4"));
GUILayout.Label(texture);
}
// UIToolkit
public override VisualElement CreateInspectorGUI()
{
var root = new VisualElement();
var texture = AssetPreview.GetAssetPreview(SpriteAtlas.GetSprite("MySpriteSheet_4"));
var image = new Image {image = texture};
root.Add(image);
return root;
}```
thank you
how to draw texture2DArray in GUI ?
var texArr = ( Texture2DArray ) mat.GetTexture( pSpriteSheet );
EditorGUI.DrawTextureTransparent( index ? ? ? )
I suppose you're instantiating the object at runtime: if you don't set the name to the object instance, by default, its name is the prefab name suffixed by (Clone)
Got another weird one. I am making a custom UnityEvent drawer using Reorderable List (allowing the reordering of events in a UnityEvent). One feature I'm adding is the ability to clear the list entirely:
if (GUI.Button(trashButtonRect, trashButton, ReorderableList.defaultBehaviours.preButton))
RemoveAllEvents();
...
private void RemoveAllEvents()
{
if (m_ListenersArray == null || !m_ListenersArray.isArray)
return;
m_ListenersArray.arraySize = 0;
}
However, doing this gives me an error:
UnityEditor.ScriptAttributeUtility:GetHandler (UnityEditor.SerializedProperty)
UnityEditorInternal.ReorderableList:EnsureValidProperty (UnityEditor.SerializedProperty)
UnityEditorInternal.ReorderableList:DoListElements (UnityEngine.Rect,UnityEngine.Rect)
UnityEditorInternal.ReorderableList:DoList (UnityEngine.Rect,UnityEngine.Rect)
UnityEditorInternal.ReorderableList:DoList (UnityEngine.Rect)
UnityEditorInternal.EventProDrawer:OnGUI (UnityEngine.Rect) (at Assets/GIB Games/EventsPlus/Editor/EventProDrawer.cs:99)
UnityEditorInternal.EventProDrawer:OnGUI (UnityEngine.Rect,UnityEditor.SerializedProperty,UnityEngine.GUIContent) (at Assets/GIB Games/EventsPlus/Editor/EventProDrawer.cs:81)```
I wonder if you get a different result if you use the https://docs.unity3d.com/ScriptReference/SerializedProperty.DeleteArrayElementAtIndex.html api
May just need to apply and call https://docs.unity3d.com/ScriptReference/GUIUtility.ExitGUI.html
Navi: Same result when iterating through it with DeleteArrayElementAtIndex.
vertx: This one's new to me. Where would I implement this?
After you set the array length
ApplyPrefabInstance() doesn't seem to save my prefab which I am editing in isolation from Prefab Mode (after double-clicking the prefab in the Project tab). In a Custom Editor, I'm editing one component with a List of ScriptableObjects. In OnDisable(), I tried to SetDirty() all elements in that list and to mark the scene as dirty but same thing
Now I don't get any errors, but the list doesn't clear. (progress, i suppose)
Did you call ApplyModifiedProperties before Exit Gui?
vertx you are just amazing.
Just spent too long fighting with the engine to know all the secrets
After I exit Prefab mode clicking on the same Prefab causes errors to pop up about this element not existing. The custom editor remembers the last element selected, but in the list all elements are now null.
I am almost done with this whole system...it's an overhaul of UnityEvents and UI components. Things like: reorderable UnityEvents, multiple-argument unityevents (including dynamics) auto null-catching, saving UnityEvent structures as prefabs, and more
Thank you a whole lot
https://docs.unity3d.com/2020.1/Documentation/ScriptReference/PrefabUtility.GetCorrespondingObjectFromSource.html
GetCorrespondingObjectFromSource(component.gameObject) , where component = target as componentClass, returns null instead of the prefab asset
Trying to debug but getting the following error
No connection could be made because the target machine actively refused it 127.0.0.1:56360
anyone experienced anything similar? (it worked last week)
Is there a way to statically tie in a static method to do something before assemblies reload? I am adding in message pack to my project and would like to run a bat script to generate some message pack stuff.
Use [InitializeOnLoad] to subscribe your static method to the beforeAssemblyReload event https://docs.unity3d.com/ScriptReference/AssemblyReloadEvents-beforeAssemblyReload.html
Excellent
weird, had to restart it twice 😄 restarted yesterday didn't work, started working today and it's working
when in Prefab mode, is the target gameObject a part of the prefab asset or a prefab instance?
According to Unity QA from 2019, "In Prefab edit the objects are directly available and not instances or "live copies" unless they are from nested Prefabs."
However when trying PrefabUtility.SavePrefabAsset(component.gameObject), where component = target as componentClass, it throws an error 'ArgumentException: Can't save a Prefab Instance'
Whatever it is, how do I save the edited prefab to its asset along with ScriptableObjects?
Different question: ScriptableObjects seem to go null before I can call OnDisable() when deselecting the object. How do I prevent that?
I'm not exactly sure, but I think you're not supposed to call OnDisable on your own because I'm almost sure that it'll make two calls then, your own one and the actual one that's invoked by Unity
If you're deselecting from your own code, you could eventually put your own "BeforeDeselect" method in it and ignore the OnDisable unless you really need to do something in there that can't be done at an earlier point from your own code
Optionally, I don't know, but there may be some kind of callback when the current Selection changes which you could utilize
(looked it up, Selection.selectionChanged may be helpful)
I need some help i have this code https://gdl.space/atahuporuf.cs and iam making a script which you attach to a game Object and depending on Vector3 or Transform being chosen i want you to see 2 fields where you can input a eather Vector3 start and endpos or transform start and endpos. I have a enum and if its set to Transform i only want you to see the transform fields. An if the autoset variable is true i just want you to see the endPos field of either Vector3 or Transform
i have all of these extensions downloaded and the packages installed in unity and i still dont have intellisense for unity
Regen your project files in Unity editor , then in vscode press ctrl + shift + p then select Reload Developer Window and wait unilt it's done propagating the changes. Depends on how big your project is, it may take a while
After changing my abstract class from inheriting ScriptableObject to having the [System.Serializable] attribute, my List of that class can't be found by FindProperty; it returns null. What else do I need?
SerializeReference?
That worked, thank you
Help
what is the problem though
is it possible to add an icon here for my own custom tool
navigating the docs to find editor stuff is quite confusing
Yeah-ish. Look at EditorTool and EditorToolContext
i am looking at the api
kinda confusing lol
like i have the overrides activating, but its not clear how i listen for mouse interactions with the scene window
in the OnToolGUI method
Here is a simplier example than the main EditorTool page provides. https://docs.unity3d.com/ScriptReference/EditorTools.EditorToolAttribute.html
ah i see the info comes from EditorWindow
okay starting to understand it now thanks 🙂
Sort of? Basically you treat the OnToolGUI method like a normal OnSceneGUI method
OnSceneGUI i dont seem to have available with EditorTool class ?
Sorry I was referring to a method that is on the Editor class.
Is there any possibility of Drawing a 3D Model in an EditorWindow?
Not directly no. You need to create a PreviewScene, add a camera and light to it, then render the Mesh in there and get the output of the camera in a RenderTexture which you can then show in the editor window
You can use the PreviewRenderUtility to help with this.
Oh Alright, Thanks!
is it intentional that you dont get mouse up event for left clicks in editor
when i left click i only get mouse down but right clicks get both down and up
not sure if thats by design or some quirky bug
public override void OnToolGUI(EditorWindow window)
{
Event m_Event = Event.current;
if (m_Event.type == EventType.MouseDown)
Debug.Log("Mouse Down.");
if (m_Event.type == EventType.MouseDrag)
Debug.Log("Mouse Dragged.");
if (m_Event.type == EventType.MouseUp)
Debug.Log("Mouse Up.");
}
It is because the mouse up event is getting used. If you use the down event you should be able to get the up even iirc
well if something else is using it how would i ever get to use it in my tool 🤔
kind've strange
The Scene view itself is using it. Again, I think if you event.Use() the mouse down, you will get the mouse up as well. But I don't remember for sures
oh and unity just crashed to desktop 😄
it seems unity uses the mouse up for left click so it replaces it with Used
not sure if i can get it before what ever tool is using it up
@gloomy chasmwhats the difference between EditorTool for a component and inherting from Editor
kind've confusing
EditorTools live in the scene
Editor lives in the inspector and has the same life time as the component (i.e. when it is deselected it disappears)
so if im doing say a waypoint graph and i want to click in the scene editor to add waypoints
i should use an editor tool for my Graph type
and not inherting from Editor
Both work, EditorTools can also bind their lifetime to that of a component
(but is not required)
not sure which one i should really use then
Iunno which channel to post this in, but ive been having this issue for a while and cant find a solution that works anywhere. Im trying to build an APK and i keep getting this error.
Warning literally says that the SDK is probably readonly
Go fix that and #📱┃mobile is the place
I tried searching for that error to see how to fix it and tried everything anyone on any forum post said and didnt solve the error.
Thank you!
seems EditorTool does not work for scriptable objects
-_-
i cant seem to get OnToolGUI to activate
or the other override-able functions
either that or i'm dumb of course thats a real possibility
Idk the api doesn't seem that complicated tbh
well i select my scriptable object - click in the scene and the function doesn't trigger
this is what i tried:
[EditorTool("Graph Editor", typeof(GraphSO))]
public sealed class GraphEditor : EditorTool
{
public override void OnActivated()
{
Debug.Log("TEST");
}
public override void OnToolGUI(EditorWindow window)
{
Debug.Log("TEST 2");
}
public override void OnWillBeDeactivated()
{
Debug.Log("TEST 3");
}
}
Of course because you need to activate it. Look at the tools overlay when the object is selected. You should see a new button to click
i have it selected but no Graph Editor button appears
i presume i should see a button that says GE on it
Right, that is a SO, the editor tool is scene based so only works on components (when specifying type).
so only monobehaviours
thats a pain i wanted to edit SOs with the tool without them being actual game objects in the scene
how do you disable selecting items in the scene unrelated to your custom editor when the editor is active
hmm strange i can drag my SO to the editor object field but i cant select it from list of files with the popup window it provides 🤔
DelayedTextFields don't seem to record changes with Undo.RecordObject() but TextFields do, is there any trick?
Yes it does
How do I create an array dropdown box like this? The gray box with Element 0 & 1?
Instead of the Sub Category being a number, I want to do something like this
how would I make a property field a square? I want to have an image field that appears in the inspector as a square and not a long line, but I cannot find any info online on how to go about changing the size, etc.
ObjectField with a larger height (eg 64)
will that also display the image?
It should do the texture/sprite input you see in materials
just by making the height taller? ok
I figured it out by creating a CustomPropertyDrawer for the "Categories" struct
Struggling with getting the scaling correct though?
float inspectorWidth = EditorGUIUtility.currentViewWidth;
Rect categoryRect = new Rect(position.x, position.y, inspectorWidth * 0.30f, position.height);
Rect subCategoryRect = new Rect(position.x + inspectorWidth * 0.30f, position.y, inspectorWidth * 0.55f, position.height);```
Yano watching the vid I think I figured it out, the left side is a static pixle size, so if I make the % of both = 100% and then - the value of the left it should work
So the position that OnGui passes appears to be the pixel position relative to the inspector so "position.x" should be it
Yeh so subCat width of "inspectorWidth * 0.70f - position.x - 10" seems to work well 
You can use a ReorderableList to do it. It's internal but accessible. This helped me to setup it in the 1st place: https://blog.terresquall.com/2020/03/creating-reorderable-lists-in-the-unity-inspector/
They're not asking how to draw a list, and you wouldn't really use ReorderableList any more seeing as they are reorderable by default now
Oh, my bad, I misunderstood the 1st part of their question since they were talking about "the grey box with element 0 and 1".
List are reorderable by default, but do you have any control on options like "hide add/remove footer" ? Genuine question.
IIRC no
You don't have that control no, though you can do various hacks to modify it
OK. Thx 🙂
I have a custom editor for a ScriptableObject which needs to save some metadata about the object to work properly. However, since this info is only needed in the editor, I don't think it should be saved in the ScriptableObject itself. The .meta file that accompanies it has a userData field which seems just right for this. I'd have to save this metadata every time the asset is serialized, and load it every time it is de-serialized. So, how can I achieve this? (I know of ISerializationCallbackReceiver, but the ScriptableObject should be totally oblivious to this metadata - and thus this functionality shouldn't be relayed to it)
userData is specifically for the Importer afaik
thus you can only get it with https://docs.unity3d.com/ScriptReference/AssetImporter.GetAtPath.html
Maybe my question wasn't very clear - my problem is not with writing to userData, I don't know how I can execute the code whenever the asset is serialized/deserialized. SO, what I want is basically something like ISerializationCallbackReceiver, but which works in the editor script instead of on the ScriptableObject itself
I don't think there is?
I want to write a script, something that will make your job easier. a button that when I import a gameobject it will automatically apply to all the throne's state prefabs in that gameobject. I made this bot with the help of bing ai, but now when I go to a gameobject, its name, layer, tag, etc. It's hidden and I can't see it. I asked bing ai again, he gave suggestions but didn't fix it, maybe you can fix it? here is the code:
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(GameObject))]
public class ApplyAllEditor : Editor
{
public override void OnInspectorGUI()
{
// Base inspector GUI
base.OnInspectorGUI();
// Draw the default inspector
DrawDefaultInspector();
// Get the selected game object
GameObject gameObject = (GameObject)target;
// Check if it is a prefab instance
if (PrefabUtility.IsPartOfAnyPrefab(gameObject))
{
// Draw a button to apply all changes
if (GUILayout.Button("Apply All"))
{
// Apply all changes to the prefab asset
PrefabUtility.ApplyPrefabInstance(gameObject, InteractionMode.AutomatedAction);
}
}
}
}
(Actually, there is no bug. But the old look was better. I could choose from there as I wanted. In the current view, I have to write the name of the tag by hand.)
string pathFormula;
public void PathOptions()
{
Undo.RecordObject(this, "Edit path options");
EditorGUI.BeginChangeCheck();
pathFormula = EditorGUILayout.DelayedTextField("Path Formula", pathFormula);
if (EditorGUI.EndChangeCheck()) ApplyPathOptions();
}
When I change the DelayedTextField values in the editor I can't undo it, while with a TextField I can.
Unity version 2021.3.3f1
Steps to reproduce: 1. Download and open the latest attached project ("delayedintbug.zip") 2. Modify the custom field on the "SCRIPT...
ah
Hey guys, has anyone worked with Uni Web View here?
Why can't I see what Uni Web View looks like in the editor?
I have to make a build to see what it looks like
you have concerns?
Hello, I wanted to make some graph effects but I couldnt beacuse I didnt have high diff pipelines so I installed it and all my textures disappeared so I uprgraded all shaders in materials and everything was okay. But my textures were ugly. They were extremely pixalated and those graph effects didnt work. I decided to go back but ctrl + Z didnt work, so I removed it from package manager and cahnged project settings but afterall I cant figuje out how to repair my textures because everything looks like this
How do I create the seperation line like below create?
By setting a priority number on your menu item which is sufficiently far away from the nearest priority menu items.
Ohh it automates it if there is a big enough gap? Thanks
Is it possible to completely override the menus?
I feel there is so much bulk in a lot of the menus... Like the Assets/Create menu has literally everything in it and I bet nobody here uses half of the things in there
Not really
In 2023 all menus are searchable so the content and order matters a lot less
I don't know what you mean by them all being searchable? Where do I search?
They might be referencing this https://docs.unity3d.com/Packages/com.unity.quicksearch@1.1/manual/index.html
You can use it to search for menus and menu items
Does anyone here use Unity tools extension in VS code?
Well the search thing isn't a feature I need at all... Would be nice if I could just make my own menu and get rid of all the bulk but we make do with what we've got I suppose
The new Msft oe? yes, it's splendid... even the debugger is super smooth in 2023 🥹
no more random freezes that the legacy one introduced in 2023
Is it not possible to make a custom editor script trigger getters and setters properly?
I'm trying to get a setter to run by setting it via IntField but it doesn't seem to do anything?
I've written a renderer component and I have been using Update to check for changes in the inspector to run code to create meshes and assign sprites etc, but I was thinking of using setters instead so that it would do it right away, but it doesn't seem to trigger the Debug.Log on the right.
Left is the custom editor script, right is the script itself.
Not sure if there's a smarter way to make it do things on change in the inspector because I don't like relying on Update and "if(oldValue != value){oldValue = value}.
Nope
Hi guys. I recently upgraded my project from 2022.3LTS to 2023.1.6. After clear all obsolete warnings and errors, my project runs well and can build a functional windows port. I also use symbolic link to make a UWP version, and it also ran well before. But this time, I build UWP failed and meet the error code below:
https://gdl.space/nuyatowira.md
hello everyone I was trying to write a editor script to paint and export tiles..the tile holder holds gameobjects with spriterenderer containing some tile sprites but when I export the tile holder as prefabs all the sprites assigned to sprite renderer of tile objects are gone..when i debug the asset path of the texture they are all fine..can any one suggest me what might be the problem.
why are serialized classes recognized as "generic" type by serialized property types? why can't it say the real type?
oh nvm
I have the same issue with EditorGUILayout.Slider
I would be happy to hear how to make Undos work with those, if not I'll use ordinary fields
I'm currently working on a custom editor window, and
Whenever I close and reopen Unity, all the text is black, it becomes white again when I get the project's scripts through compilation again
I assume it's a bug, but I don't know...
Either your code or some other code is modifying a built in GUIStyle.
If i recompile my scripts without any modification, the text color becomes white again. I'm not exactly sure if it's my scripts since this is the case...
Anyone know how to fix omni-sense??? Its red and I think thats the problem, but I dont know how to fix it
why does it work in visual studio but not visual studio code??????
Check the #854851968446365696 channel for info about configuring your IDE
Can anyone help me,
I use VSC and i have the Unity,C#,C# Dev Kit extensions and ive done everything that this doc tells u to do https://code.visualstudio.com/docs/other/unity but i still dont have intellisense ive followed countless tutorials and re-installed a bunch of things but it still doesent work
Hello
I would like to understand why Unity reset my variable on playmode : I write a script to build a grid, then it set a grid component to a gameobject wich contain grid information ...
The probleme is my gridConstructor setting my other script in EDITOR, but once I go playmode, my script is reset
this is in editorm you can see my cell grid is set up ( width, height, and grid variable)
this is in play mode
Are those values serialized, and are you dirtying the object when you make the change?
Yeah
when i'm create my component i'm doing this
public void CreateGridComponent()
{
if(TryGetComponent(out CellGrid existingGrid))
{
DestroyImmediate(existingGrid);
}
CellGrid cellgrid = transform.AddComponent<CellGrid>();
cellgrid.Initialize(m_grid,Width,Height);
#if UNITY_EDITOR
UnityEditor.EditorUtility.SetDirty(cellgrid);
#endif
if (m_shouldConstructorDestroyedAfterGenerate)
DestroyImmediate(this);
}
I dont know if it is a bad way to do this
should I serialize all value I want to pass in parameter ? (maybe this is my problem)
No, m_width and height should be serialised
The values you want to persist must be serialized
Ok
I ll try to do this on the second script, it's maybe the answer, because my grid constructor is serialize, but not my created grid object
Oh yeah
that was that
Thx a lot @visual stag i'm not used to coding in editor x)
Juste to see, my object create was'nt serialized, so, that's will not work
is the Unity plugin for VS 2022 Community broken after the last update?
Probably not but this is the wrong channel
the "Probably not" was superfluous
I'm making a custom parser to make custom editor windows where unity reads a text file and draws respective elements
but the issue is that it doesn't recognize "\n" as a new line character it just reads it litterally.
I've noticed that if I draw a box with the actual function that draws it, directly in studio code, it does recognize the \n. I don't really know whats going on here...
How are you parsing the text?
If you Debug.Log the text in the file, is it what you expect it to be, without quotations?
What happens if you use \\n instead of \n ?
What if you put a Space between the \n and followup content?
(Probably nothing, but testing is cheap)
I'm not sure, but I think when reading from a file, it's reading \n as actual content, not as an escape sequence
Also, may I ask how you'd include dynamic content in that workflow? If somebody wants the window to show Variable XY?
Quick Google search lead me to this
https://stackoverflow.com/questions/5717678/read-from-file-without-special-characters
There are no escape characters in a text that you read from a file. Escape characters are used when you write a string literal, for example in program code.
Idk how accurate this is
Guys it appears i managed to mess up my entire editor with a single click. I clicked on the recognize git repo button in Vscode, now everytime i need to install the unity extension again even though i had everything i needed installed already. Can someone tell me how to disable this again without removing my git repo?
And im also getting IDE0059 on my start and update functions
Can't help you with that one, sorry, my only guess would be to uninstall and reinstall VSC and to not do it again, your VSC probably shouldn't care about your Git Repo, it should care about the stuff that's within Unity
The second one is easily found on Google
https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0059
Also, this channel is for helping with EditorTool development
I'm pretty sure this is it. This was the main suspicion I have
Thanks a bunch!
In the stack overflow answer though it simply replaces the "\n" string with spaces... hm
I did try to work around it by removing and re-adding the \n characters but that didn't work either 🤷♂️
You could you use a StringBuilder instead, I think it should have an accessible method to insert a line break
But can't promise
In general, if I'm not completely off here, strings are immutable, every time you do += it will actually create a new string instance with the contents of newText + s under the hood, that's not especially bad and we are used to doing string stuff the simplest way, no need to overcomplicate, but it's something you should at least be aware of
Yep
Immutability of strings
String objects are immutable: they can't be changed after they've been created. All of the String methods and C# operators that appear to modify a string actually return the results in a new string object.
I see I see 🤔 I'm gonna have to try that
I'm saying this because it's basically another good reason to use StringBuilder, theoretically
Another one for you, so don't take my advice for gold 😄
Important
Although the StringBuilder class generally offers better performance than the String class, you should not automatically replace String with StringBuilder whenever you want to manipulate strings. Performance depends on the size of the string, the amount of memory to be allocated for the new string, the system on which your code is executing, and the type of operation. You should be prepared to test your code to determine whether StringBuilder actually offers a significant performance improvement.
You'd want to use myStringBuilder.AppendLine(myString) instead of myString + "\n"
Gotcha!!
I've used AppendLine,, but it doesn't rly work
I've initialized a new StringBuilder then for each line I appended it to the StringBuilder, then I converted it to a string
What does happen?
Show Code 😄
one moment
You don't want to append each Line to the string builder, you want to use Append mostly, and when you find "\n" then you AppendLine instead
Using AppendLine should give you the string you provide together with a line break after
Or only a line break if you call without arguments
But, first let's see the issue, what's the output?
I'd almost advise you to create your own Tokenizer, it's quite simple
Because imagine the user types stuff like something bla bla\\nothing blabla
\\ in this case would be output as "\" in a correct scenario, but in our current one it'll just trim the "n" in front of nothing
I fixed it! The fix was to simply have the split function consider "\\n" instead of "\n"
double slash
Because in the text the slash and the n are considered separate
so I simply checked if the string contains \\n, in which case I split according to \\n instead of \n
Otherwise I split acording to \n
Nice 😄 glad it's solved
But honestly, now try writing weird stuff with escape chars, let's see what happens
try \t, let's have some fun 😄
And \\!!
Alrighty
Btw, if it's for your own use case only, don't bother to much with them, I'm getting flashback from a previous Tokenizer/Parser Project
😂
static string GetTextWithLineBreaks(string text)
{
StringBuilder newText = new StringBuilder("");
string separator = text.Contains("\\n") ? "\\n" : "\n";
string[] textParts = text.Split(separator);
foreach(string s in textParts) newText.AppendLine(s);
return newText.ToString().Substring(0, newText.ToString().Length-2);
}```
this was the fix
Interesting 😄
If the text doesn't contain \\n
Couldn't you at that point just return the text?
Maybe, if text contains \\n, you do the StringBuilder work, else u just return text
when I type "\\n" it means I'm having the script recognize the slash and the n as separate characters, which can only occur if I have the string be read from a text file. The other case is if I type the string directly in Code, so it considers "\n" as one character which is the line break
Hello so I am trying to make a script that makes a object in a scene but not on runtime (run in editor) also it needs to stay there. So basically I just need it to automate creating a objects
ok. so i have a question/goal i am trying to do and i am not sure if this is the correct channel to ask in but here goes...
i am trying to create a list of gameobjects that can be accessed through the editor, globally instead of a specific scene.
i'm planning on importing some objects that contains some strings of data, but depending on that data, it will instantiate a specific game object.
since i'm trying to let this work regardless of what scene i am in, i'm trying to find where/what am i to write this at in the editor to be able to always access this list.
would ScriptableObjects help in this case?
Yes, you can also use Resources combined with a Singlenton manager to load them automatically at runtime or save them to a SO as well
funny thing about that... i've been trying to wrap my head around singletons lol. and after reading up about it, i'm stuck at a weird feeling like "i know nothing of it" and "i think i've always been doing this??"
but, my previous attempts failed because, i was trying to assign the instance in a way i normally do through runtime. but now i assigned the instance to a Resources.Load (which im feeling a little mixed about..)
on that subject... is there an alternative to Resources.Load() ? i kinda didn't want to break the way i organized my assets, so being able to get the asset path without having to toss them into resources would be great
also thank you for answering my question ^^
Well only in the Editor currently https://docs.unity3d.com/ScriptReference/AssetDatabase.LoadAssetAtPath.html
You could just have the SO in the resources folder and load them in during edit mode and then access the SO at runtime
Singlenton would simply be a script with a static reference to the instance you want others to access and thus other classes can access it with just the class name
On top of that you can make it DonDestroyOnLoad and change the instance if required
ah ok... thank you, now i realized i was overthinking it this entire time XD
also this looks like exactly what i wanted! 😮
Edit: it works! just have to use the full path and name and extention to get what i wanted lol
hmmmm how do we forced a foldout to be always expended...
nvm there is a property attached to the serialized property for that
hey, I am pretty new to unity, I need to use linux native functions for a task, is there any code example that goes over this ?
https://docs.unity3d.com/Manual/NativePlugins.html I found this, but they use dlls (I am not fully sure how csharp and unity would work on linux as linux uses a different yet similar library loading scheme than windows. dlfcn.h over what ever windows uses)
not quite sure what you mean. you can do dllimport to .so files for Linux
[DllImport ("someLib.so")]
private static extern int someFunc ();
Unity's nativeplugin is just a managed wrapper so it should just work
ahh okok
Update: it's not Slider, but anything in the parent class isn't recorded in the parent class. I swapped the Slider for a FloatField in the parent's virtual method. I'm calling RecordObject(this, "...") in the child then calling base.method and only the variable in the parent class isn't recorded
Also sometimes the Undo works, but if I click away it stops working
Ok, no, it's just for some reason one variable doesn't want to be recorded
Hey everyone, I'm having issues with Undos not registering in a custom Editor Window. I'm relatively new to working with Serialized Objects and Serialized Properties, but from what I've seen shouldn't they work with the Undo system automatically. This is a stripped down version of what my setup looks like:
{
private SerializedObject m_scriptableObject;
private SerializedProperty m_testFloatProperty;
private void LoadScriptableObject()
{
m_testFloatProperty = m_scriptableObject.FindProperty("testFloatProperty");
}
private void OnGUI()
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_testFloatProperty);
if (EditorGUI.EndChangeCheck())
{
m_scriptableObject.ApplyModifiedProperties();
}
}
}```
Finally found the problem, it didn't have the [SerializeField] attribute
phew
how do i fix
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
@delicate anchor 👆
what's the status of including (non-unity) packages in asset store plugins?
I want to include another (free) package of mine in my upcoming plugin, either through github or using like OpenUPM or so
but I'm not entirely sure if it's supported on the asset store yet
I've researching this myself since two months ago, still no dice
the staff said they're working on it (there's a thread on Unity forum from 2020)
mmkay
if you're interested https://forum.unity.com/threads/adding-a-dependency-to-an-asset-store-product-in-a-projects-manifest-json.1108304/#post-8608380
kinda sucks tbh
this is a little different though, right? I don't need a dependency to an asset store asset
same rule applies
alright
due to licensing issue that might come from those assets
in my case it's my own (public and free) package I want to include
you might have to just put a copy of that package in your plugin, instead of linking directly to github as a dependency
otherwise, an update to the github package could break your plugin, and unity doesn't want that
if I understand you correctly
hmmm, yeah, I just don't like that workaround in case people already have it installed, or if I want to use that package in a different plugin down the line
then there'd be namespace collision unless I make a script or something to swap the namespace
does anyone know how to get the current type of the field that a PropertyAttribute is assigned to?
or just to get access to the object that the attribute is on generally
PropertyDrawer has attribute and fieldInfo properties, which your drawer inherits and can access.
oh i was looking in the wrong spot. thanks!
Then you could put that non-unity-exclusive package on the asset store, and use that as a dependency maybe? It shouldn't be a problem, since it works in unity
automatically downloading dependencies on assets store only work on Unity official packages
mmkay, I'll just have to include it directly then ;-;
I wonder if we can just check for the assemblies, and if they're not available then programatically download the git package via initializer is allowed by assets store? 🤔
Can you call a method in one editor script from another editor script? I realize in most cases if you have functionality across editor scripts you'd likely just want it to be in an external class, but I was curious and unable to find a straightforward answer online
There is no straightforward answer, it depends what scripts you're talking about. If you have a common function, make a static helper method
mostly hypothetical but I feel like I somewhat frequently need to modify or reference properties on different scripts across custom inspectors
If Script A and Editor Script A need to call a method that changes a property on Script B, and Editor Script B had a method to do that, is there an easy way to call a method on an instance of Editor B and get the intended results?
I'm of the understanding that (ScriptB)target sections wouldn't work correctly because Script B's inspector isn't open, and I suspect serializedProperties wouldn't work correctly either (given they're always found OnEnable).
So would my best course be to find the serializedProperty of property B via things like findPropertyRelative, or are there other general methods for accomplishing the same goal?
I would create a static helper method that you pass the properties/objects to that performs the common work
Are there any extensions that might fix this weird Editor UI behavior? For context, this is an array of my custom class that stores cycleName(string) and cycleLength(int) variables, this overlapping only happens on Element 0, on every other Element the array UI expands to make room
If you are using IMGUI: https://unity.huh.how/programming/editor-extensions/property-drawers/getpropertyheight
If it's just the first element then it's a bug that has already been fixed in later versions
it is
also is there a better way to do this (unity 2019.4)?
buildMap[i].assetNames = AssetDatabase.FindAssets("", new string[] { bundle.Value })
.Select(AssetDatabase.GUIDToAssetPath)
.ToArray();
this seems very slow
I have this as an alternative but I'm not sure how reliable this is compared to findassets
var assets = Directory.EnumerateFiles(bundle.Value, "*", SearchOption.AllDirectories)
.Where(path => !path.EndsWith(".meta"))
.ToArray();
Look at the Search API
Yeah, ooh. Sorry I misunderstood.
for now I just use enumeratefiles, it seems to work for my purpose well so far and is significantly faster than findassets
one of the bigger bundles takes several minutes with findassets
Hey so I have property which is an array, which has the [SerializeReference] attribute and it displays like this in the editor (see image). But when I use Odin, it works perfectly. I will use Odin anyway but that would be cool if this is fixable 😅
It is because they are null.
In base-Unity there is no drawer for it, only the values that are assigned in it.
There are various drawers that add a dropdown, including mine
can you add dynamic list of entries to menu?
similar to attribute [MenuItem("Assets/Build Bundles/Android")] but if I want to make submenu with dynamic items
theoretically its possible, if by clicking on menu item you create a GenericMenu
havent tried but i dont see why it wouldnt work
doesnt work
Hi ! Is there a way to use LoadAssetAtPath to load a subobject of a Maya file for example ? Or do I have to use LoadAllAssetsAtPath, then parse the array, to get it ?
(I guess this chan is more appropriate)
It probably works but you might have to sync to EditorApplication.Update instead of calling it in MenuItem
behaves weirdly, only works from window onGui
I figured that LoadAllAssetRepresentationAtPath would only load sub assets, which was what I wanted
What's the use of the attribute then if you can't use it out of the box and you need to do a drawer to add a dropdown to chose from the inherited classes?
I see, thanks!
But honestly they should just do the base dropdown
You can assign values in code and they will serialize and display, there is just no built in editor for doing that. But yeah, I agree there should be something
Thanks! @visual stag @gloomy chasm 👌
i thought this gives total overriden control over the height of the field? GetPropertyHeight
cause it doesn't when rendering a class field
im trying to render only the children of a serialized class to get rid of the damn foldout and it's indent
hmmm what's it's doing is erasing the parent foldout field from the face of the earth but it's not modifying the field sizes of the children
Any ideas how to fix UIToolkit's Rect, RectInt and Quaternion PropertyFields that are cut on the right side?
private void SetClassesToSpecificTypes()
{
switch (_variableProperty.propertyType)
{
case SerializedPropertyType.Rect:
case SerializedPropertyType.RectInt:
_propertyFieldsContainer.AddToClassList("property-fields-container-rect-rect-int-alignment");
break;
case SerializedPropertyType.Quaternion:
_propertyFieldsContainer.AddToClassList("property-fields-container-quaternion-alignment");
break;
}
}```
```css
.property-fields-container-quaternion-alignment {
margin-right: 1px;
}
.property-fields-container-rect-rect-int-alignment > PropertyField > * {
margin-right: -5px;
}
.property-fields-container-rect-rect-int-alignment > PropertyField > * > .unity-base-field__input > * {
padding-right: 4px;
}``` got it
- Using imgui. I have a fairly large inspector, and i need to .BeginChangeCheck on only 2 values of it. How can i do this without rewriting the entire inspector from scratch?
I managed to fix it, there were a couple of issues but the main one was that my dialog was a scriptable object. Now I am confused about how to allocate the proper space for my class in the inspector, as everything has been squeezed into the same area
I'm currently loading an uxml asset as such:
AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/FolderA/FolderB/Editor/Resources/MyWindow.uxml");
However, this is meant to be distributed to others, as such, people might want to move my asset from FolderA to some other place.
What is the best practice to load these assets but allowing potential users of my asset to move the asset folder to wherever they want?
use any relative anchor
ie find a unique scriptable/file
or reference directly in a scriptable config
it also seems to be in Resources
so you dont need to load it through asset db
path can be resources relative
If it's distributed to others why is it not a package? Then people won't have to move it because it'll just be in the packages folder
Do you mean that I should put it under Plugins > FolderA > ... ?
If so, that is my next step. Regardless I want to make sure that if people want to move the whole package to fit their own custom folder structure, they can.
Or do you mean specifically under the Unity Packages folder?
Isn't that limited in that users can no longer edit the code if they want to, for example?
They would have to embed the package if they wanted to edit it's code, but it'd still end up in the packages folder anyway and the path to it's assets would remain the same
Can you explain what you mean by "embed the package"?
This might sound oddly specific, but how might one accomplish transform position/rotation fine-tuning using a Gamepad within the editor not during play mode? e.g. joystick manipulation of transforms from gamepad input
I would use the new input system, which works in the editor https://docs.unity3d.com/Packages/com.unity.inputsystem@1.7/manual/UseInEditor.html
And generally would you say you prefer to have your packages in the Packages folder instead of inside Plugins then?
I've gotten so used to importing something from the asset store and having it in the main Assets folder that I'm happy if it sits in the Plugins folder.
I do feel like having to do all those steps to change and embed the package could become annoying, and I do know some of the users have already edited the asset to their needs.
I've seen the new input editor's raw data stream from the sticks, but not sure how to interface that to editorongui events etc, but this seems like an avenue
If something is third party and is not a package it annoys the hell out of me and I generally turn it into a package my self. I believe asset store assets can now use the package structure and are automatically embedded? But I have never looked into it.
Also, it's really one step:
Copy and paste the package from wherever it is into the Packages folder
I presume you just read Gamepad.current directly from OnGUI and it should just work
Right, I suppose that makes sense.
I'll have to find some documentation on how to prepare a package to be released on the asset store. As it stands I only know how to release it as a folder in the Assets folder.
My editor keeps giving me the error "Serialized Property is null" when I try to execute this code:
[CustomEditor(typeof(DialogInteractable))]
[CanEditMultipleObjects]
public class CustomDialogEditor : Editor
{
public override void OnInspectorGUI()
{
EditorGUILayout.PropertyField(serializedObject.FindProperty("dialogs"));
serializedObject.ApplyModifiedProperties();
}
}
``` The 'dialogs' property looks like this inside of the DialogInteractable class:
```CSharp
public class DialogInteractable : MonoBehaviour
{
[SerializeField]
public Dialog[] dialogs = new Dialog[0];```
The Dialog class itself is a ScriptableObject, because I want to correctly size the property drawer that its associated with. However, this has been causing me some issues as this is what I think is causing my null pointer error. I think this because when I removed the inheritance from ScriptableObject and made it a plain object, it didnt give me a null pointer error. Im hoping that someone could do one of two things; Help me find a way to make this work with the Dialog class Inheriting from the ScriptableObject class, or for me to be able to size the property drawer for the Dialog class without relying on Scriptable objects
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
Dialog instance = ScriptableObject.CreateInstance<Dialog>();
SerializedObject childObj = new SerializedObject(instance);
SerializedProperty ite = childObj.GetIterator();
float totalHeight = EditorGUI.GetPropertyHeight(property, label, true) + EditorGUIUtility.standardVerticalSpacing;
while (ite.NextVisible(true))
{
totalHeight += EditorGUI.GetPropertyHeight(ite, label, true) + EditorGUIUtility.standardVerticalSpacing;
}
return totalHeight;
}
``` This is the code I was using before to size the property drawer
The error is definitely being thrown from this code, and not a property drawer that is being invoked because of the property field?
Yeah, the property drawer itself works fine when its a plain object, and it does reference a line in the property drawer code however thats because the SerializedProperty is null
Im not sure which of the two is to blame to be honest, this is all very new to me
The stack trace would show you what was involved
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
drawerProperty = property;
// We can't use GUILayout in property drawers; we need to calculate each field's position.
// The position we received should contain all the fields in our class; it uses the height
// returned by GetPropertyHeight. We'll use it to calculate the position of each field.
var titleFieldPosition = position;
titleFieldPosition.height = EditorGUIUtility.singleLineHeight;
EditorGUI.BeginProperty(position, label, property.FindPropertyRelative("dialogTitle"));
``` It was the last line that triggered the exception, which then pointed back to the first line of the OnInspectorGUI method
So it's dialogTitle that is the issue? Which if this was a drawer for Dialog would make sense
It is
However when I comment out the line that looks for the "dialogTitle" property the stack trace moves to the next instance where I call the FindPropertyRelative method
As your previous code here did, you can't just access the properties of an object without creating a serialized object that represents it
I have a serialized object how to pinned to this channel if this is confusing. It's certainly hard to explain lol, but as you did it right in the other example I assume you're at least vaguely aware you can't just walk directly into the properties of the scriptable object
Yeah, the issue I thought this would create is that it would end up editing a new instance of the object instead of the one present in the array/list
Serialized Object is just a window into the serialized data, it points to the data of whatever instance you created it from
So it just tells the datadrawer what kind of data to create an input field for?
Ive changed the drawer to create an instance and to use that to find the properties but the exception still occurs
I've gotta sleep, but you should perhaps link your current !code and what the exception points to and hopefully someone else will step in to help
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Alright, thanks for your help!
Halfway there - got input into ongui now
so i have a script that i want to use on all of my colliders, but if i add it to all of them, it causes unity to freeze. so my plan is to create a method where i can 1 by one add them and wait maybe 1 or 2 frames then remove them and repeat that for every collider, totaling up to around 300 different colliders.
is there a way to:
- call the script to do something similar to a coroutine in the editor so i can have it pace itself as it iterates through every collider
- bring a progress bar so i can see how long it may take
long story short, i found a pretty decent polygon collider editor that allows me to auto update my colliders to be a bit closer to pixel perfect, but it really causes everything to crash if i dont pace it.
objectField.TrackPropertyValue(property, _ =>
{
CreateEditorFromProperty(property);
});```
```cs
private void CreateEditorFromProperty(SerializedProperty property)
{
editorContainer.Clear();
Debug.Log(property.objectReferenceValue);
if (property.objectReferenceValue != null)
{
foldout.style.display = DisplayStyle.Flex;
CreateEditor(property);
}
else
{
foldout.style.display = DisplayStyle.None;
}
}
private void CreateEditor(SerializedProperty property)
{
if (_editorCache != null)
UnityEditor.Editor.CreateCachedEditor(property.objectReferenceValue, typeof(ObjectEditor), ref _editorCache);
Debug.Log(property.serializedObject);
InspectorElement.FillDefaultInspector(editorContainer, property.serializedObject, _editorCache);
Debug.LogWarning(editorContainer.Children().Count());
}``` I'm trying to create UnityEngine.Object property drawer with inline editing. But it seems like FillDefaultInspector does not show up, altho it exists. Switching inspector object fixes it. It logs fine. I tried to use events such as AttachOnPanel or OnGeometryChanged
Does anyone know how I could check if a collapsable element has been collapsed inside the inspector view? Currently, it looks like this when my array is not collapsed:
You need to correctly position the list and/or the toggle or vice-versa
This isnt a collapsable element ive created in my drawer, its one unity creates because its trying to display an array
What Im asking is if theres a way to access this collapsable element and check if it has been collapsed or not
Are you creating this with UI Builder UXML or creating the objects using a class constructor?
Success, the tool works! 🎊
Not at all what I asked. Anyways, if you're using UIToolkit, I believe only by using reflection:
public override VisualElement CreateInspectorGUI()
{
_root = new VisualElement();
InspectorElement.FillDefaultInspector(_root, serializedObject, this);
_propertyField = _root.Q<PropertyField>("PropertyField:ObjectList");
_propertyField.RegisterCallback<GeometryChangedEvent>(UnityIsTerribleSometimes);
return _root;
}
private void UnityIsTerribleSometimes(GeometryChangedEvent evt)
{
var listView = (ListView)_propertyField[0];
var foldoutObject = typeof(BaseListView).GetField("m_Foldout", BindingFlags.NonPublic | BindingFlags.Instance)?.GetValue(listView);
var foldout = (Foldout)foldoutObject;
foldout.RegisterValueChangedCallback(evt =>
{
Debug.LogWarning(evt.newValue);
});
}```
Sorry, I just didn't understand what you wanted to know. I only just started using these aspects of unity. Anyway, I fixed it already
You want to periodically apply components to GameObjects? Have you tried async?
yeah, want to add a component, apply some settings, then remove it after a frame or 2. and iterate that through the rest of the list.
nope, never tried async.
Why would you want to do that tho? You just want to set some settings to some Colliders? Why not just get those colliders and run a function on them?
because im having the script automatically adjust the polygon colliders to fit closer around the sprites
so i don't have to manually edit 200+ sprites to have the accurate collissions i want lol
so i was hoping if there was an editor equivalent of coroutines or something
public class PeriodicallApplyComponentsToObjects : EditorWindow
{
[MenuItem("Tools/PeriodicallApplyComponentsToObjects")]
public static void ShowWindow()
{
GetWindow<PeriodicallApplyComponentsToObjects>("Periodically Apply Components To Objects");
}
private void CreateGUI()
{
var gameObjects = FindObjectsByType<Collider>(FindObjectsSortMode.InstanceID);
DoAsync(gameObjects);
}
private static async void DoAsync(Collider[] gameObjects)
{
foreach (var collider in gameObjects)
{
var rigidbody = collider.gameObject.AddComponent<Rigidbody>();
collider.isTrigger = true;
await Task.Delay(1000);
DestroyImmediate(rigidbody);
}
}
}
}``` There is probably a better way but... good luck
😮 so async kinda looks like a coroutine. that's cool
also thank you very much! ^^
Hey everyone, I'm trying to create Undo functionality for a custom Editor Window for editing a scriptable object. I've tried just using Serialized Properties (as far as I can tell these are supposed to work with the Undo system automatically), and also just manually recording the Undos myself using Undo.RecordObject(). However I can't get it to register Undos for the Editor Window. Ctrl+Z always just rolls back whatever change happened last outside of the custom editor window. Anyone know the best practice for handling Undos in Editor Windows?
Have you used Undo with the EditorWindow itself?
How do you mean?
The EditorWindow is a ScriptableObject
Like recording the Editor Window instead of the Scriptable Object?
Oh
I see
So I can do Undo.RecordObject(editorWindow) basically? I'll try that
Alright it's registering Undos, but Ctrl+Z isn't rolling back the changes. The code setup I have is essentially this:
{
private SerializedObject m_scriptableObject;
private SerializedProperty m_testFloatProperty;
private void LoadScriptableObject()
{
m_testFloatProperty = m_scriptableObject.FindProperty("testFloatProperty");
}
private void OnGUI()
{
EditorGUI.BeginChangeCheck();
Undo.RecordObject(this, "Edit testScriptableObject");
EditorGUILayout.PropertyField(m_testFloatProperty);
if (EditorGUI.EndChangeCheck())
{
m_scriptableObject.ApplyModifiedProperties();
}
}
}```
It's now actually properly consuming the Ctrl+Z as well, but the changes don't appear to be happening.
are you applying modified properties in the serializedObject?
I am, it looks like the properties are actually being rolled back but they just aren't being displayed. If I close and reopen the editor window they are rolled back to what they should be. I tried running the LoadScriptableObject() and then Repainting on the undoRedoPerformed callback but the changes still aren't being shown until I close and re-open the editor window
Are you using IMGUI or UIToolkit?
IMGUI
I don't remember how it was done in IMGUI. I've been mostly working with UIToolkit. Maybe you need to reset the values with some method call.
using the .Update() on the Serialized Object seems to work
sometimes it's randomly delayed but I'm not sure why
like I'll hit Ctrl+Z and it will visually update after like 2 seconds
fixed it, forgot to Repaint(); after updating. Thank you so much for the help!
Task.Delay(1000) isn't the same as 1 frame, you'd need customYield if you're using async/await for it to sync properly with Unity's frame timing
well it's for editMode, proly doesn't really matter
ok, just updating you. while i didn't end up using async. this helped me a lot with making my editor window. and i ended up getting a different method for my colliders which wasn't nearly as expensive. so my script is working fine without using async. but im keeping this for learning purposes. 🙇🏾♂️ thank you again ^^
Hello! :)
I'm trying to take a screenshot of a UI element through script. So far I managed to write this:
public class MyView: GraphView
{
public void TakeScreenshot()
{
var width = (int) Math.Floor(contentRect.width);
var height = (int) Math.Floor(contentRect.height);
var tex = new Texture2D(width, height, TextureFormat.RGB24, false);
tex.ReadPixels(contentRect, 0, 0);
tex.Apply();
var bytes = tex.EncodeToPNG();
var path = Application.dataPath + "/Screenshot.png";
File.WriteAllBytes(path, bytes);
Debug.Log($"Screenshot width: {width} - height: {height}");
Debug.Log($"Saving screenshot at: {path}");
}
}
This works almost exactly like I want it to, except that it seems to cut off a chunk of the top right of the image.
I've compared the width and height of the image to the variables in the script, and to the UI debugger (checking the width and height of the ui element I'm trying to screenshot) and it all matches up, however at the end it seems to always cut off a chunk of the editor window
What can cause for the undoRedoPerformed callback to be called multiple times?
Debug.Log() writes once when undoing but twice when redoing, although my problem is with undoing rn
Is there a way to progamatically toggle this?
Profiler api?
I see 'BeginSample' and 'EndSample', but no controls for turning it on and off through code
I was looking for a function to turn it on, didn't even occur to me it could be a property
thanks
Idk why, but one of my fields doesn't show up in the inspector.
That's how I draw them:
And these are the classes:
And that's the inspector, the formation is empty
Weirdly it works when defined as an array instead of a singular class instance
I have no idea why it does that.
The [HideInInspector] is causing this. Do you need it?
The [HideInInspector] is on the child fields, probably shouldn't affect the whole class?
Even without it the whole class in the inspector is still empty
The size is correct, works in an array, but doesn't work when by itself
I've also put it on a separate script without a custom property drawer and it worked there
For some reason it doesn't want to work here, when drawn with my method in my custom property drawer
The propertyRect you pass to EditorGUI.PropertyField, I don't see where you're setting its height before the call. You call GetPropertyHeight afterwards.
The height is always the same, it seemed to work without any issues with anything I passed into the method so I didn't change it, and even if changing it, it still stays empty
Wait, I might be dumb
Let me check something
Yeah, I was an idiot
My method was probably done incorrectly and required every drawn property to have it's own PropertyDrawer
both the missile type and missiletimestamps had their own PropertyDrawers so they showed up
made a PropertyDrawer for the formation too and it works now
Let's just say that's it's not a bug and rather a feature and continue working
But thanks anyways
so i have a weird thing i'm trying to figure out. so my editor window is fine more or less.
but when i run my task, it works as long as i dont switch window focus rom unity. after that, everything breaks.
any suggestions on what to do about solving this issue?
Is there something I need to look out for when editing a List through Serialized Properties?
I have a List of myChildClass which inherits a Vector2 from the abstract myParentClass. I create a list from the SerializedProperty of the List, insert a new myChildClass object at the beginning, change the Vector2 value, then save the list back to the SerializedProperty.
After doing SerializedObject.ApplyModifiedProperties however, I can see that the List received the new object with the Vector2 of the default value.
I create a list from the SerializedProperty of the List
Why do this when you can justInsertArrayElementAtIndexand set theGetArrayElementAtIndexvalue?
I need to call some methods while changing the list, otherwise I would need to ApplyModifiedProperties a lot
Random question. I installed an editor extension (fast script reload). it didnt work properly so i uninstalled it through the package manager. But now none of my scripts want to compile the normal unity way...
Have you restarted Unity?
I was recommended to post in here with a query I have:
Hi guys! New here and just getting back into Unity (I've forgotten so much 💀 ) and I have a question that I haven't been able to get answered on the forums, and ChatGPT is a bit stumped with
In the project window all C# scripts have the same icon - paper with the corner folded down - and I'd like some way for script files to automatically change their icon depending on what class they are inhereting from. So all Monobehaviour use A, all Editor use B, and all [insertcustomclassname] + children use C?
I know ScriptableObjects have this functionality (kinda) but I'd like something similar for all script types. I've tried a couple of things, but so far nothing is working
Is there perhaps an extension out there that can assist with this?
Nope, you would either have to manually assign the icons, or write a editor extension yourself that does it.
😭 I knew the manual route would be the way to go
Thanks for the response tho 😄
No problem, good luck!
#🛠️┃probuilder would be the appropriate channel for this question. This channel is for discussing creating editor extensions.
Oh my bad ill post it there. thanks
It's a bit of a late reply and I saw that you resolved your problem, but on the topic of editor coroutines:
You could make a custom enumerator by inheriting from IEnumerator (which is what a coroutine uses, too). From that point, you will have to handle stepping through the enumerator which can be as simple or complex as you'd like. Hook it up with the editor time or update callbacks, or iterate through it when a button is pressed, or when a certain condition is met!
We use it in our project and the control you get from making a custom IEnumerator is great!
@alpine bolt figured Id include you in the tag just to show another method!
ah ok cool, thanks for the information 😮
The editor equivalent to coroutines is using the Editor Coroutines package ;P
New to editor extensions and just looking to be pointed in the right direction, what would I wanna look at if I wanna mess with how Unity updates the inspector when you click on assets and scene objects
😔
Tried looking but could find stuff where you override a specific MonoBehaviour but I wanna touch it more on Unity’s end
bump
I basicially wanna get when the mouse clicks an object or asset and tries to update the inspector to reflect this, but add my own conditionals so certain things won't update the inspector on selection
Make an editor that inherits from UnityEditor.UI.ButtonEditor targeting your type, then:
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
EditorGUILayout.PropertyField(_yourPropertyHere);
}
hey anyone know how to get intellsense working in vsc
i am using unity version 2022.3.7f1
!vscode