#↕️┃editor-extensions
1 messages · Page 60 of 1
it seems counterproductive to hold a reference to the database in the item class itself that is part of that list
also, since this is only used in the editor it should only be called there as well, hence why i put it in the custom inspector for the item
Then, if you feel going through the AssetModificationProcessor is a viable solution, go for it.
People here give advices, tips, but if it works, it works
it seems counterproductive to hold a reference to the database in the item class itself that is part of that list
@steady crest That is true, it really depends on the context, how you deal with your design
yeah, I would much rather do it the way you are suggesting. but when i do it that way it seems to fuck up with the data storage.
i dont know why exactly, but Im gonna look for it
I feel it is strange that OnDestroy() is being triggered when you deselect an Object
I will post a few snippets of what I am doing, so you can follow and see what i am trying instead of just trying to blindley explain tbh
Do do
ItemDataEditor(Item custom inspector. without ongui cuz irrelevant)
void OnDestroy()
{
var window = EditorWindow.GetWindow<EditorManager>();
window.ItemDatabase.Remove(item);
}
adding the item to the database
[TitleGroup("Item manager")] public ItemDatabase ItemDatabase;
[SerializeField, HideLabel, HorizontalGroup("Item"), HideIf("itemDatabaseUndefined")]
private string _itemName = string.Empty;
[Button(name: "Create item"), HorizontalGroup("Item"), HideIf("itemDatabaseUndefined")] void CreateItem()
{
ItemData item = CreateInstance<ItemData>();
item.Name = _itemName;
if (!Directory.Exists(Application.dataPath + "/Items"))
{
AssetDatabase.CreateFolder("Assets", "Items");
}
AssetDatabase.CreateAsset(item, "Assets/Items/" + _itemName + ".asset");
_itemName = string.Empty;
ItemDatabase.Add(item);
Selection.activeObject = item;
}
that should be everything, I think @onyx harness
Shit Unity crashed
I have just noticed that this code seems to work, but only if the itemdatabase inspector is open
@steady crest That's very dangerous to store a database in an EditorWindow
It should be independant
oh its a scriptable object in itself, that is stored in that editor window
oh wait wtf am i doing
I will need that data at runtime, so I need to reference that SO in the scene
Mikilo I can’t seem to understand what HasPreviewGUI does and the documentation is horrible
I need to access that database to manage player inventory. I may have overlooked that
Well the best would be to delete the ItemData from the Database itself. Not ItemData self destructing
yes, but how? do I check the database for elements that are null and remove those?
Tbh, that's a way X)
I'd prefer not to have to do that if possible xD
Or, if you don't like, stay with your OnDestroy() accessing the database
But dont use EditorWindow
That's misleading
@trim charm HasPreviewGUI seems to tell if the Editor contains a preview
I would have say that the name is pretty self-explanatory
the editorwindow is just used to make items and add them to the database, instead of needing to navigate the menu to find the SO when you right click
Thought so but the documentation said something else so confused me a bit
the items, and database are scriptable objects that are independent from it
but they are accessed by it to work on them for ease of use
Damn you making some sort of asset @steady crest ?
I am making an inventory system, not an asset per se, but I am going pretty deep into it
Thought so but the documentation said something else so confused me a bit
@trim charmThe doc is just saying that you can override it, but at the end, it tells if yes or no it has a preview
@onyx harness I did some more testing and I can surely say that OnDestroy is not called when an asset is deleted from the assetdatabase.
if it is on the custom inspector, its called when the inspector window is closed.
if its on the SO, its called when the object is removed from the scene as part of a gameobject.
so because of that, for my delete to work I need to use the AssetModificationProcessor
So you are saying that OnDestroy() from a ScriptableObject is not triggered when you delete its asset.
accoridng to what I am seeeing that seems to be the case
And you are absolutely right
We learn something new everyday, that's why we are programming I guess 🙂
exactly, tho I cant help but feel some pride considering how much you know that I found something 🙂
Be proud, be proud, use it to push yourself beyond your screen 😄

So
I knew there were something wrong
If you call AssetDatabase.DeleteAsset(). It won't trigger the OnDisable/OnDestroy.
But if you call Object.DestroyImmediate, it will.
I might say, it is a bug.
The best would be to destroy through Object then AssetDatabase.
I am deleting the asset in the project window tho, I am not calling a delete function (manually)
Yep, I see, use the processor callback, that's about right
Maybe I will report this bug later
for now at least I would say, if its a bug that might be something worth reporting
go ahead, I'm all for improving the engine 😄
there isnt a bounty program for bugs is there 😊 @onyx harness
reward: unity pro for a month
#bestreward
quickly pump out some games without the unity splash logo xD
This choice is very poor and annoying
People are running from the splash logo
While on the other side, people are running toward the Unreal splash logo, a sign of might
lol
I mean, i cant count the amount of times I have seen people asking how to change the bytes on the launcher so they can have dark mode...
even though I find the editor dark mode being a premium feature quite stupid
I guess it generates enough shiny cash
to be an argument
It's not our business, I understand them
But they are worth billions, I don't understand them
i dont mind it tbh. but back to the splash screen,
there are so many games that are pretty shitty made with unity that show the logo that unity gets a bit of a bad name
with all the new stuff they are bringing with newer version, I dont doubt it
I still dont know half of what unity has probably
Probably, we all are permanently late to the game
Pretty much life of a programmer.
I need some help with the EditorGuiLayout Foldout header and using a Scrollview inside of it. I have multiple foldout headers representing an organization structure. When I expand the foldout header the scrollview within that header is shown behind the other foldout headers. How can I move the foldout headers down to below the scrollview?
Any help is appreciated. 😕
You need to reserve the space in the guilayout system
GUILayout.GetRect should be it iirc
Is there a way to get the game view inside the editor as a texture?
I'm trying to make an editor that has a preview window of the game view and was thinking about using a render texture but that is not working well with UI.
This is what I had in mind
Yes that is what I tried but it's doesn't render my UI and if I set target texture of my camera I get the message no camera rendering.
It looks like this
My game view has my UI but not the actual game.
While the scene viewer in my editor does have the game but no UI
hmmm
Idk what's in GameView.m_RenderTexture but it's probably worth checking it
Looks like the game view content
your game looks fun to play
That's just an example scene for the tool I'm making😅
@waxen sandal thanks I will look into that
@waxen sandal Thanks. I will see what I can do.
Do you know any packages like ModTool for free?
@navi
I tried to use the get control rect did not work.
The scroll view is in a begin vertical and that is in a foldout. other foldouts still render over the scroll view
Other foldout headers
I'm trying to set up an inspector script to let you toggle the active state of prefabs that are children of that object by selecting icons of them. Is there a good tutorial on setting up prefab preview icon buttons in the inspector?
SUPER specific question / can't find the issue:
Has anyone encountered an issue when making a PropertyDrawer for a class (object, not UnityEngine.Object), where when you try to use property.isExpanded = true, its child properties cause the inspector to jump up n' down in Height specifically when the child properties are being manipulated (ie: EditorGUI.Slider, etc)
I'm tired of working with buttons in Unity, does anyone know of a decent theme/colorswatch script that can help automate setting these colors for me?
Anyone know of a texture unpacker? (I.e. something that unpacks a sprite atlas, saves the indivual textures, extracts the sprites but keeps the GUID references?)
A UI asset we're using has a sprite atlas that uses maybe 10% of it's 4k x 4k texture file and I need to repack it.
All I have is the PSD imported in Unity with individual sprites setup through the sprite editor.
I'd like to move the sprites & textures out of the PSD, keep the links, and let Unity's sprite packing do it's thing instead.
I don't think you can do that
The GUID probably refers to the atlas rather than an individual sprite
The FileId probably refers to the individual sprite
At least that's how it works with DLLs and monobehaviours in it
Technically you can rewrite the files to fix the references but that's probably not worth it unless you have a lot of references
Won't Camera.current.ScreenToWorldPoint(vector3); work in editor scripts?
When are you trying to get Camera.current? It will only not be null if there is a camera currently rendering.
In a method which takes a SceneView as argument..
And when is this method invoked?
Whenever I place the cursor in scene
It's spawning the object.. But at other position... Every objects spawn at that point only.
Have you made any effort to ensure this method is invoked at some point while a camera is being rendered?
I assume you've used this line of code with success in non-editor scripts?
Yes
Oh.. No.. It's in the editor script itself
Hmm..
Yeah.
Are you sure you don't mean Camera.main instead of Camera.current?
I have used Camera.main in normal scripts
But you want to use Camera.current instead?
In normal scripts?
Your original question was:
Won't Camera.current.ScreenToWorldPoint(vector3); work in editor scripts?
Yes
Did you mean Camera.main?
No
And you understand that Camera.current will be null unless a camera is currently rendering
Yes
And a camera usually only renders at the end of the frame, so you can't assume Camera.current will be anything but null except at the end of the frame?
That's why I was asking about the method that this line is in
Because that method has to be invoked while a camera is rendering
Otherwise Camera.current will be null and you'll get a null reference exception
In the same method I have used Camera.current.ScreenPointToRay... It works..
Then there is no problem
What do you mean it won't?
It doesn't spawn objects at the point where I click
Oh, I had not noticed the console..
That script had an error in the line above this one so it wasn't working ...
Now, everything is perfect.
i need help with my script for some reason if i'm compile scripts is Getting only type to base class. (In Editor)
code:
public List<GUINodeBase> Nodes; list for storage elements
base class
public class GUINodeBase
{
//some code
}```
other Class
```cs
public class StartNode : GUINodeBase
{
//some code
}
public class NormalNode : GUINodeBase
{
//some code
}```
check
```cs
if (Nodes[index].isSelected){
if (Nodes[index].GetType() == typeof(StartNode)){
Debug.Log("Start Node");
}
if (Nodes[index].GetType() == typeof(GUINodeBase))
{
Debug.Log("BaseClass");
}
Why don't you try Nodes[index] is StartNode instead?
nope is not working
I have a question about asset import processing. I used the OnPostprocessModel to set some default values on my imported meshes, like lightmap UV generation. However now when I do that, if I want to change these settings for a specific model to something that's not default, it resets back to default once I press 'Apply'. I tried with OnPreprocessModel as well but it's the same thing. Is there a different function I should be using?
Hey all. I'm struggling to understand on how Unity handles asset loading in the inspector. I'm searching all available objects for some metadata, so I'm loading them all, checking for my requirements and adding the ones I need in a list. When I do that, the whole operation takes around 5 seconds. After that, it takes 200-300 msecs. The same test but without filtering, simply loading all the assets, somehow takes 15 seconds each time.
Does anyone have an idea on what may be happening?
EDIT: Found the reason. Apparently, searching by t:Object yields different results to t:UnityEngine.Object. Searching by t:UnityEngine.Object fetches only the objects whose path ends in .asset. Any ideas on why this is happening?
Can anyone point me to a good introduction into editor scripting? learn.unity has like 3 different courses on it
I know you're not allowed to re-distribute the unity dlls, but if you scrape the typedefs for externs, are you allowed to distribute that "empty api"?
why not just go straight to the source https://github.com/Unity-Technologies/UnityCsReference ?
@visual stag I'm generating extern definitions for another language to transpile into C# dlls that can then be loaded as unity plugins
I would imagine they'd let that fly, but someone might be actually versed in what goes, I'm not, sorry 🙂
I would imagine so too, just wanted like ... verification before I got too deep 🙂
I'm having a hard time determining how I would best overlap (and offset) UIElements Images (imaging a couple playing cards stacked on top of each other, but offset so that you can see that there are two).
I know that I can accomplish this with absolute positioning, but as soon as I do this, all the stacks of images (I have multiple) get bunched together.
What I think I'm looking for is a way to have absolute-positioned elements within relative-positioned containers.
Actually now that I'm explicitly setting the width and height of each "container" (which contains a stack of cards), it seems to be working better.
Event.current.mousePosition is a vector2..
If I want to get the mouseposition of z like if you have z and x axis in your game.. I want to get the z position of mouse...
How to get?
Also I have created an array ( say bl) of bool
In editor all of them can be set to true.
I only want to set 1 of them to be true...
If bl[0] is true bl[1] is false , and when I click bl[1] ,b[0] should be set to false.
@weak bone #💻┃code-beginner would be better, this doesnt sound like editor scripting.
nevertheless, your mouse does not have a z position unless you mean you wanna raycast to an object in the scene
Okay. As I was using them in editor scripts I asked it here.
How could i make an editor “brush” that places objects around where i click?
Similar to the terrain brushes but not
Do we have some UIElements experts here?
The following code "serializedObject.FindProperty("isExpanded");" always returns 'false' when using a Foldout Element instead of an PropertyField.
public class MyMono : MonoBehaviour {
[SerializedField] private boolean isExpanded;
}
[CustomEditor(typeof(MyMono)]
public class MyMonoEditor : Editor {
private VisualElement rootVisualElement;
private void OnEnable()
{
rootVisualElement = new VisualElement();
var visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("MyMono.uxml");
visualTree.Clone(rootVisualElement);
isExpanded = serializedObject.FindProperty("isExpanded");
Debug.Log(isExpanded.boolValue); // always returns false if using Foldout --> Bug?
}
public override VisualElement CreateInspectorGUI()
{
return rootVisualElement;
}
}
<UXML xmlns:ui="UnityEngine.UIElements" xmlns:ue="UnityEditor.UIElements">
<ui:VisualElement name="MyMonoExample">
<ui:Foldout binding-path="isExpanded" name="foldout"/>
<!--<ue:PropertyField binding-path="isExpanded" name="foldout"/> Does work-->
</ui:VisualElement>
</UXML>
hello all
item.sprite = (Sprite)EditorGUI.ObjectField(new Rect(rect.x, rect.y + 40, rect.width, EditorGUIUtility.singleLineHeight), "Item Icon", item.sprite, typeof(Sprite));
says that this method is obsolete and i should use alowSceneObject method but i can not find much on the internet how to use it
There's an overload that's not obsolete
It doesn't say to use the allowSceneObjects method, it says to use the overload that has that parameter
@whole steppe
I think you have to get a SerializedProperty for your sprite and set the objectReferenceValue
spriteProperty.objectReferenceValue =
EditorGUI.ObjectField(spriteRect, spritePickerProperty.objectReferenceValue, typeof(Sprite), false);
Thanks it worked, the overload method was it.
Would you do allowSceneObjectcs:true or false
hi!
How to set up unity to open only one vs studio instance per project?
Each time I click on an error from Unity Console, it opens a new instance of Visual Studio
https://forum.unity.com/threads/alternative-inputactionasset-c-wrapper.870556
Hey all, sharing this tidbit of useful code! An alternative C# Wrapper for InputActionAsset
Is it possible to use a Texture Atlas for images used in custom editor GUIs? (I'm using UIElements if that makes a difference)
The docs seem very tailored to sprites used in-game.
I have a problem with a color picker I made for my game which basically changes the color of my rocket. It works just fine in editor. But when I build it shows the color changing, I confirm it, but when I get into the game the colors are the same as they were when I built it/ when I set them in the editor. Is there a fix for this?
I think without some code its hard to decide.
Is there a damn way to receive all states with their names and assigned clip from a animator at runtime ?
I already reversed engineered their animator source code and could not find a way to acess their "GetStates" methods...
So i hope someone here has a genius idea
Hiho! Quick question. I have an editor script that just adds a label a 3 buttons to another scripts, the thing is that when it is active it duplicates the inspector properties/attributes. Any fix for this?
Is it normal for EditorPrefs to get wiped out every time the editor reloads?
That's what's happening with me and it seems... counter-intuitive.
Not normal
😦
I switched to using save files in the user's local app data and I'm still getting the issue so, it's some other cause. Thanks for the sanity check, @onyx harness.
@glacial onyx you're calling base.OnInspectorGUI and DrawDefaultInspector
@glacial onyx you're calling base.OnInspectorGUI and DrawDefaultInspector
@visual stag yeah, figured it was the base method doing that, so I took it out ^^' But thank you anyway! ☺
is there a builtin way of handling double clicks with UIElements?
or should you make a custom manipulator?
Clickcount works for me
which bindingflags do I need to only get the methods of a class that I added myself when using reflection?
Is there any way to change animation curve tangents positions in code?
I can do it manually on the editor changing a kreyframe's tangets to weighted
but I can't seem to do it in code
that seems to be the only things I can do with the tangents
but I can't figure out a way to just set the tangent position to act as a control point
I'd like to replicate that behavior programmatically, but I don't know if it's even possible in Unity
(the tangents are the small grey boxes that you can drag and move around)
IIRC you can if create a serialized object from it
Or just look at the editor that is drawing the curve
I'll try that
I know how to provide values for the tangents and how to manipulate them
but I can't seem to be able to replicate the weighted tangents behavior
which bindingflags do I need to only get the methods of a class that I added myself when using reflection?
@steady crest rephrase please and be more explicit
For an item database I am creating, I have a buch of public functions defined (was using unityevents). I am trying to get the function dropdown to only show the functions I want it to show. Because they are inside tscript the event is located on. I want to find the functions that I have defined myself, while lfiltering out all the other default monobehaviour functions
Since I don't know your context, use Static | Instance | NonPublic | Public to get them all
public class Entity : SerializedMonoBehaviour
{
[SerializeField, OnValueChanged("OnEnable")] private string Dimension = "red";
public List<UnityEvent> onHit = null;
[HideInInspector] public List<string> options;
public void Destroy()
{
Destroy(gameObject);
}
public void ChangeColor(string color)
{
}
}
I want to make a unityevent dropdown, that only shows those 2
@onyx harness
essentially, I am trying to make a list of unity events. where each unity event takes only one function. without it looking all clunky
Use Instance | Public
And in the returned list, make sure the MethodInfo has Entity as DeclaringType
this seems to be doing what I want it to do
tar = target as Entity;
methods = tar.GetMethods(typeof(void), BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
tar.options = methods.GetNames();
public static List<MethodInfo> GetMethods(this MonoBehaviour mb, Type returnType, BindingFlags flags)
{
return mb.GetType().GetMethods(flags)
.Where(m => m.ReturnType == returnType)
.Select(m => new {m, Params = m.GetParameters()})
.Select(x => x.m)
.ToList();
}
now I just need to figure out how I can change the way the unityevent behaves and display only those functions @onyx harness
Write a PropertyDrawer for UnityEvent
i ve never actually worked with propertydrawers, only custom inspectors im afraid
You missed something
Yep, i avoid using custom Editor at all cost
oh I see
And prefer PropertyDrawer
hmm. How do you write a propertydrawer for UnityEvent? or should I just make an entirely different drawer?
Look up a tutorial and write an attribute to apply on your UnityEvent
fair enough
if i overwrite it, I assume it would make all unityevents behave like the one I creatae
I just want to create a dropdown that only shows the functions I have reflected from that list of methods
Yes, and for that you need to resimulate the entire drawer
And customize the dropdown
I'm not sure it's gonna be worth it
There might be an other technique
Faster to implement but really tricky
PD for Object, if you detect the Object is from a UnityEvent, you do your drop down
Hmm. If I make a custom drawer for a function, parameter pair in a horizontal group. And make a list of those instead
But this trick is majestically tricky
List<string, parameter> kind of thing and that string is the reflected name of the function and the parameter field is the parameter of the function. Would that work?
@onyx harness
With the string being a drop down field
Doesn't sound too horrible to make either
Why a List ?
Cuz every hit from the player on the entity executes element 0. Which is removed after it executes and when it's empty the entity is destroyed
I have an editor that does something similar
Except for func<> rather than events
I also have a custom event thing in some other project but that's ooold
I could do it with actual delegates tbh. Just need to make sure that data is serialized
They're not actual delegates since you can't serialize them afaik
Hmm. I'm gonna have my work cut out xd
Hi guys, do you know if there is a way for Unity to identify a file change in a text file and call a method?
@unborn bluff AssetPostprocessor
So for text files, I assume I need to use OnPostprocessAllAssets, but from the input parameters it does not seem to be a "modified" list: https://docs.unity3d.com/ScriptReference/AssetPostprocessor.OnPostprocessAllAssets.html
Is a modified Text Asset or any asset for that matter just re-imported?
What I mean is, when modifying a text file, will that text file just be re-imported again and thus it should appear in the "string[] importedAssets"
probably imported
Alright, I'll take a peek at it. Thanks
Must I wrap code in PropertyDrawer.OnGUI with EditorGUI.BeginProperty and EditorGUI.EndProperty?
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginProperty(position, label, property);
EditorGUI.BeginChangeCheck();
// [...] Draw property
if (EditorGUI.EndChangeCheck())
property.serializedObject.ApplyModifiedProperties();
EditorGUI.EndProperty();
}
I'm wondering
how did you get to this point?
Thinking to use these in PropertyDrawer?
who taught you that?
mmmm, I don't remember. I think that I found them with intellisense accidentally and then thought I should use them always.
To be exact, all my property drawers have that XD
The Unity documentation doesn't say much about them
The Unity documentation doesn't say much about them
@burnt dove That's why I am wondering why people tend to use them without knowing their purpose
Well, it says "BeginProperty", so I got the impression that if my code didn't call it, the unity editor may not work correctly (documentation says "BeginProperty and EndProperty automatically handle default labels, bold font for Prefab overrides, revert to Prefab right click menu, and setting showMixedValue to true if the values of the property are different when multi-object editing.")
Sometimes I found that Unity doesn't save stuff when I modify it, so I always use EndChangeCheck + ApplyModifiedProperties to be sure
And did you see the difference when using them?
With BeginProperty nothing. With EndChangeCheck and ApplyModifiedProperties only when I used them in custom editors, not custom property drawers
Because the default editors are handling it
And in your custom Editor, you forgot to handle it
Apply() is suppose be at the Editor level
That explains a lot
Is there a way to make my editor method appear as a menu item and get executed on clicking that menu item ?
Add a menu item with %CONTEXTMENU% iirc
@waxen sandal Thanks, I actually was missing the keyword static 😅
Ah yeah
how do I constrain a propertydrawer to only apply when an attribute is provided? Cant seemt o find the right syntax
@steady crest [CustomPropertyDrawer(typeof(attribute))]?
yeah but its [CustomPropertyDrawer(typeof(UnityEvent))] and I want it not to apply everywhere @waxen sandal
Instead of UnityEvent put your attribute type
but it is a propertydrawer for the UnityEvent tho
I just dont want it to overwrite the default @waxen sandal
PropertyAttribute to be specific
if I gotta do that, whats the difference with a custom inspector?
You mean a custom editor?
ah, so its kinda like how css is defined for one element, whereas a custom inspector does it on the whole object?
yes, wrong name oops
well, im drawing a list of my element I want, so a propertydrawer is probably easier
PropertyDrawer for a type will do it for every property that is that type, PropertyDrawer for a PropertyAttribute will only do it with the individual marked properties, and a Custom Inspector is for the whole component/SO
not 100% sure I get it, but I'll need to try it out to see how it all functions 🙂
I need to figure out a way to get the parameter of the drawn function (there will always be 1 for a valid function) and display the editor field that is defined for that object.
so if the parameter is an int, it should draw an int field, if its a string, a string field etc... How would I go about getting this?
public class EntityEditor : OdinEditor
{
private string[] functionNames;
private int index = 0;
public void OnEnable()
{
var t = target as Entity;
var methods = t.GetMethods();
functionNames = methods.GetNames().ToArray();
}
public override void OnInspectorGUI()
{
GUILayout.BeginHorizontal();
index = EditorGUILayout.Popup(index, functionNames);
EditorGUILayout.TextField("");
GUILayout.EndHorizontal();
}
}
Naturally the GetMethods returns the relevant functions on the object and names converts methodInfo to a string
ah
@waxen sandal how can I tell this ObjectField to instead draw the default inspector for that element?
public override void OnInspectorGUI()
{
GUILayout.BeginHorizontal();
index = EditorGUILayout.Popup(index, functionNames);
var param = methods[index].GetParameters();
if (param.Length != 0)
{
o = EditorGUILayout.ObjectField(o, param[0].ParameterType);
}
GUILayout.EndHorizontal();
}
cuz now it expects a string object
If you have a serializedproperty you can
but having a serializedproperty woud require me to have a typed variable for that drawer wouldnt it?
Yes
hmm I would ve hoped to do it dynamic. oh well. guess it ll need to be a switch statement
well, I only have 3 possible types, if I make a variable of type Object and switch it with string, float and GameObject. draw the respective inspectors manually?
hmm I cant convert Object to string it seems
@waxen sandal something like this
public override void OnInspectorGUI()
{
GUILayout.BeginHorizontal();
index = EditorGUILayout.Popup(index, functionNames);
var param = methods[index].GetParameters();
if (param.Length != 0)
{
switch (param[0])
{
case typeof(string):
o = EditorGUILayout.TextField(o);
break;
case typeof(GameObject):
o = EditorGUILayout.ObjectField(o, param[0].ParameterType);
break;
}
}
GUILayout.EndHorizontal();
}
well, pseudo code, that doesnt compile
You might want to use isassignablefrom if you're going to be supporting complexer types
you mean I should make custom definitions for it?
No
IsAssignableFrom is a method that checks whether a type is assignable to a field of the other type
So you have support for derived types
oof, im gonna have to look that up
callling that method between UnityEngine.Object and GameObject or string both return false
Debug.Log(param[0].ParameterType.IsAssignableFrom(typeof(Object)));
Try the other way around
same thing @waxen sandal (was getting food, back now)
oh, it was using UnityEngine.Object, I needed to use System.Object
but how exactly does that help me assign that? I need to use a UnityObject for an ObjectField to work
Is this a good way to destroy an object when all its ParticleSystem has die?
bool destroy = true;
for (int i = 0; i < particleSystems.Length; i++)
{
if (particleSystems[i].IsAlive())
destroy = false;
}
if (destroy)
Destroy(gameObject);
@steady crest It's useful when you have a player and e.g. a networkedplayer that derives from player
Then your field type can be player but you can also put networkedplayer in it
But since you're not really doing that, there's probably no need
basically what I want to do quite bluntly is to assign the return data from the fields to an object that can store either of the default unity types
switch (param[0].ParameterType)
{
case string:
o = EditorGUILayout.TextField(o as string);
break;
case typeof(GameObject):
o = EditorGUILayout.ObjectField(o, param[0].ParameterType as GameObject);
break;
}
a switch case like this isnt allowed either, so im currently turning it into an if
Which types are you trying to support?
string, float, GameObject
yea
https://hastebin.com/ijozopevat.cs @waxen sandal
I wanna try smt like this but casting the floatfield value to float also isnt valid
@steady crest What is o? A System.Object?
yes
You can cast it like this: (float) o
that is different from casting with as?
Yes
static vs dynamic?
which cant be done cuz float is not nullable got it
Correct
dope, it works. now I need to convert that editor to a propertydrawer for an attribute
But you can do this:
else if (param[0].ParameterType is float floatParam)
{
o = EditorGUILayout.FloatField(floatParam, param[0].ParameterType);
}
thats probably safer
all I need to do now is make that into an attribute drawer instead of a custom editor
or at least, figure out how that works
What if the method has more than 1 param?
method wont be valid and wont be found by GetMethods
hmm that might be bad design since i am constraining the input options
GetMethods definitely finds methods with more than 1 param
well yeah, by default. im doing some filtering
Ah ok
fair point tho
trying to figure out how I can turn this thing into a propertydrawer is gonna be painful for me tho
Should be easy though
My ProGrids window has disappeared, it should be on the top left as a dropdown bit it's gone. I've tries opening and closing the scenes, I've tried resetting it via preferences and I've clicked open and close in the ProGrids menu under Tools.
Has anyone got any idea what magic spell I need to cast to get the ProGrids dropdown to display again?
You'll have better luck in #💻┃unity-talk or official forum
Apparently that's where progrids questions should go according to the package
@waxen sandal do you think this idea is worth the effort I am putting into it? 🙂
or does it sound like a useless addition to the working system that is UnityEvent
I'm not even sure what you're trying to accomplish tbh
simply put, a cleaner looking version of unityevent that only uses the functions on taht exact script
I noticed there's an update, I've tried updating and removing completely and re-importing.
My ProGrids window has disappeared, it should be on the top left as a dropdown bit it's gone. I've tries opening and closing the scenes, I've tried resetting it via preferences and I've clicked open and close in the ProGrids menu under Tools.
Has anyone got any idea what magic spell I need to cast to get the ProGrids dropdown to display again?
Again, I'd like to refer you to #💻┃unity-talk or the official forum
See above for a link
There's definitely space for a more specialized editor
But I don't think you're accomplishing it in this way
left side is the mb class, and it shows the functions from that on a dropdown, adding a field next to it if applicable for the parameter of the function
haha
In this specific example you have a data set that is known before hand
So you should tailor your input towards that
E.g. A drop down with only the valid options
Ah, sorry @waxen sandal, didn't see your reply.
yeah, still also need to get those methods to be callable at runtime. which I dont expect to go smoothly either
You can look at my github to solve that
ye, that was the plan
if you remember, the exact thing this is for is the item database with a function selector, to make it more compact
even though it doesnt rly work that well, I did learn a ton about reflection and propertydrawers. at least I know about those now!
There's still so much to learn though 😉
it never ends man 🙂 at least I have actual questions that require some thought!
But i like that about it tbh
At least you're doing better than the average person in #💻┃code-beginner 🙈
still havent forgotten the compliment you gave me a while back bro ❤️
hmm how can I have this function like a tooltip without needing a label? i want have a tooltip when I hover the element
item.KeyItem = EditorGUILayout.Toggle(new GUIContent("", "Is this a key item?"), item.KeyItem);
Having an icky time with serialization. SerializedObject specifically have to saved to an asset, in order to be serialized?
Currently prototyping a tool, and saving an SO to a Monobehaviour, but it doesn't serialize apparently.
Saving a serializedobject to a monobehaviour?
Well, a List<> of SO instances on a Mono script in this case
SO being scriptableobject or serializedobject?
Lol, what am I saying, yes. a ScriptableObject 😂
Are your gameobjects in the scene?
I think it's time to take a break, renamed the class name at some point, but didn't change the file name. Works now 🙃
Thanks though 😉
is it possible to set up a variable to be only available in its custom inspector?
so you cant directly reference it via a call to the monobehaviour?
@steady crest You can make it private with [SerializeField]
It won't be directly accessible to the custom editor, but you can access it through the SerializedProperty
will that work on private variables?
I remember I think I had some trouble with that
You can find any serialized property that is serializable by Unity
private fields with [SerializeField] are just as serializable as public fields without the attribute
aight, ima try that
How can I add a section like Additional Settings to my own scripts?
@neat mulch You can always check how the Sprite Renderer editor does it
In this case it relies on this Other2DSettingsGUI() method:
https://github.com/Unity-Technologies/UnityCsReference/blob/3417c31e48410974acf40a2a461b31f9a49051ba/Editor/Mono/Inspector/RendererEditorBase.cs#L398
@neat mulch or you can write a PropertyDrawer to simulate 'grouping'
Or use Odin, or use NG Tools Free
There have an attribute for that
Should ask in #💻┃unity-talk or on the forums
Is there a way to add a listener to the button click in way that it is persistence (and hence show up in On Click event list the inspector too) ?
Awesome, it worked like a charm. I was looking in the wrong direction 😛 . Thanks @waxen sandal
It's a little hidden 😉
True 😄
Does anyone know if there's an editor-code method that functions the same as Edit/Duplicate? Object.Instantiate breaks prefab connections, and PrefabUtility.InstantiatePrefab only works on prefab assets
My goal is to be able to duplicate a non-prefab gameobject, but keep the prefab connections of its children
You might wanna look at Odin Inspector, it's on sale now @weak bone
Oh, I searched it in unity documentation..
I wanna use OnPreviewGUI
Odin has the option of a preview which is quite nice
odin is like Swiss Army knife
Just did a quick editor script which inverts the G channel of a normal map. Had to use a hack where I save a new version of the texture, so Unity's encodings ruins it a little, Anyone done something like this before?
Is there a way to add a prefab to the scene while maintaining the prefab link ?
Insantiate makes a new instance of it and it is better for runtimes not the Editing time
oooof I was wandering around the PrefabUtility page, but somehow missed this method. Thanks @visual stag
Is there some way to use PrefabUtility to apply only the Static flag overrides from a GameObject to a Prefab? I don't want all overrides, just the flags.
ApplyPropertyOverride ? I think the static flag is a SerializedProperty, so it should work 🤔
Haven't used it, so I am not sure.
@primal minnow Thanks, will take a look!
If anyone comes across my question in future, this was my method:
static void ApplyPropertyOverride(GameObject obj) {
string assetPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(obj);
var so = new SerializedObject(obj);
PrefabUtility.ApplyPropertyOverride(so.FindProperty("m_StaticEditorFlags"), assetPath, InteractionMode.AutomatedAction);
}
I'm triyng to setup a navmesh baking setup for 2018.3 as an intermediate step for building a more computed navigation graph, and I have a mesh based test terrain that i've been using.
My setup has worked fine for a while, but last night I tried to add a cave into the mesh, and once I did I tried to bake the navmesh, but it now will only bake the navmesh against the cave floor, and not the exterior surface. Anyone have any clues on why this might be?
I'm only using the 2018.3 built in navmesh utilities, I'm not using the NavMesh Components repo
I will if I have to, but I'd very much prefer not to
I've tried various things to fix the issue, but I'm honestly just hacking my way forward in this regard, I'm not sure what debug utilities are available to me. I have tried splitting the mesh into multiple meshes, that change anything, the part that isn't baking remains not baking when I expect it to bake.
I messed with the agent parameters a bunch, nothing seemed to make any impact on what was not being baked.
Hello guys, I have a problem that before the start in the inspector, the image scale is 1 1 1 but after the start, the scale changes depending on the scale of the Canvas that is scaled to fit the screen. What should I do and how can I avoid the problem of resizing?
In the code, I specify that the image should be linked to the panel, which in fact does not change the size (because only canvas resizing), but the image still changes its size...
If you have any answer, ping me or pm. ty
i little bit cheated by setting his vector3 scale to 1f 1f 1f after instantiate, but i guess it's not solution, so if you have answers always welcome.
Someone experience in creating PropertyDrawers with UIToolkit. My question is, is it common to register callbacks in the CreatePropertyGUI() method or should i create some kind of caching to avoid multiple registrations?
Do any of you use Odin?
They have their own discord server, really active community there discord .gg / WTYJEra Have to slice the link or my message get removed
a cool, will check
thank you
I thought about buying Odin but I think I'm gonna stick to UIToolkit
the UI builder tool is pretty easy to use
The thing odin provides is.. alot .... ALOT of attribute. Thats really handy.
Odin is for the weak.
PropertyDrawer is for the brave.
yeah but UI builder is just click and drag
idk, I'm always very hesitant to incorporate 3rd party stuff into my project
UI Builder is awesome
it would be a lot better with Data Templating
Well, it IS a lot better with data templating, speaking from experience
what do you mean with that?
idk, I'm always very hesitant to incorporate 3rd party stuff into my project
@lucid hedge don't if you can.
Wont have licensing issue, or legal stuff to handle. Less headache because more control of your code.
And I'll probably learn more 🙂
I don't have any deadlines or schedules to follow, so why not take the time
what do I mean
so very simply put
You add a ListView to your UIElement UXML that you're loading for an EditorWindow or an Inspector
you "Bind" that ListView to an Array of "MyType"
Using a mapping MyType is resolved to a UXML file that was built to render that type
how I am doing it specifically is using the TypeName to look up a file in a Resources/Templates folder
and then ListView will automatically just populate itself with the templates from that folder based upon the types its supposed to render, with support for multiple data types/rendering in it
its a very useful and powerful way to build UI
if you want to see what that looks like in action, you can check out my VisualTemplates repo
which is honestly poorly named
Hi! How should I go about modifying .meta files of textures I generate through code? I havent found any good guide on how to work with them through code
Can you expand on that? @onyx harness
Iterating using SerializedObject's SerializedProperty gives you access to a lot of data
but this is very manual
Look for importers or such
Would it be possible to make a good [Indent] property attribute that indents fields in the inspector?
I have a bad implementation here
using System;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
[CustomPropertyDrawer(typeof(IndentAttribute))]
public class IndentDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.indentLevel++;
position = EditorGUI.IndentedRect(position);
EditorGUI.PropertyField(position, property, label);
}
}
#endif
[AttributeUsage(AttributeTargets.Field)]
public class IndentAttribute : PropertyAttribute { }
there's a few issues (example image at the bottom of message)
- it looks bad, it should just indent the label right? (maybe I'm wrong on this one)
- some fields like Vector3 are two lines tall if they're squished too much which breaks the layout a bit
- If possible I'd like to have the attribute be passed an int for how much to indent and have the change in indent level persist until the next Indent attribute. It would look like this
[Indent(1)]
public float someBool;
public float someFloat
[Indent(-1)]
...
- I'd like the attribute to be compatible with other attributes like [Range] and [TextArea]. Right now my attribute indents and draws the property. I wish there was a way to defer the drawing of the property and just change the indent level
Here's my test script and what it looks like in the inspector.
You can see I have to add an [Indent] to each indented property individually, the [Range] is overriden by the [Indent] and the indented Vector3 overflows onto the next property
public class TestComponent : MonoBehaviour
{
public int unindentedInt;
[Indent]
[Range(0, 3)]
public int indentedInt;
[Indent]
public Vector3 indentedVector3;
public string unindentedString;
}
I'm not sure if this is a ton of work, if so, it's all good. I'd just like to get an idea of how hard/possible an indent attribute would be to make. I'm guessing it's possible since the [Space] attribute accomplishes a lot of what I'm trying to do, but I have struggled to find a property drawer for the space attribute which makes me thing the space in the layout is accomplished some other way
Use decorator drawer?
@onyx harness aaagh thank you
I'm trying to use the export scene to obj script from the market and it's giving me the nullreference error on this line, i do not even want the materials to be exported, i tried simply commenting the line out but that just makes the script not work.
for (int j=0; j < msh.subMeshCount; j++)
{
if(mr != null && j < mr.sharedMaterials.Length)
{
string matName = mr.sharedMaterials[j].name; <-------------------
sb.AppendLine("usemtl " + matName);
}
else
{
sb.AppendLine("usemtl " + meshName + "_sm" + j);
}
int[] tris = msh.GetTriangles(j);
for(int t = 0; t < tris.Length; t+= 3)```
On this line?
just check the things for null and append the line used in the else instead
@onyx harness the line with the arrow
mr.sharedMaterials[j] is null then
maybe i should ask this, is there script written for unity 2018 that will export meshs to obj or fbx files that works?
Obj is a pretty easy protocol, FBX is few orders of magnitude harder
Are favorites saved with a project?
more specifically can they be shared via a repo of the project easily?
@onyx harness obj is fine, and i don't want materials or textures, all i want is to turn all the meshs in a scene to a single obj file. i almost got this to work, it started, went about 11 percent in, then, teh same null refernce error... https://github.com/monitor1394/ExportSceneToObj
FBX is not a file format, it's a container format for multiple file formats. They literally just stuff a 3dsmax, maya, and motionbuilder format in there completely separate from each other.
https://i.imgur.com/sorIAwy.png why do i have none of the unity highlighting?
in Unity make sure Edit > Preferences > External Tools > External Script Editor has Visual Studio set correctly
all fixed, thank you kindly!
huh, So Jason, I've been working wiht a Unity file ripper, Utiny, it fails to export FBX files
What you're saying is that, possibly, it just doesn't handle all the necessary format for whats in the FBX files
Can someone tell me why Procedural Worlds is not showing up in my Window task? Iam createt a new project to test something buuut i will not work/show
I use Gaia Pro
Is it possible to forcibly strip an asset from a build as part of the build pipeline? I have some prefabs that are only relevant on specific platforms, and I want to label them appropriately and exclude them from irrelevant builds
Example: Console builds don't need a "quit the game" button
I just discovered that apparently custom editor windows are effectively modal on Windows but not on OSX? Is there a way to make them modal on OSX? I mean, naturally I'd gravitate toward such obvious-sounding solutions as EditorWindow.ShowModalUtility, but despite what any reasonable human being would expect, that doesn't make the window modal.
What does it mean 'custom editor windows are effectively modal'?
@onyx harness In Windows, if I open my custom editor window, i.e. an editor window that I ...defined and created, and then click outside of that window (on a file in the Project area, for example), the window remains "on top".
Perhaps "always on top" is more appropriate than "modal", since it doesn't actually block input behind it.
Yeah, always on top is better
I agree, and I wish there were a way to make it work that way on Mac
Yes I agree
A certain number of the windows stay on top, but not all, and not custom editors...
does anyone know how to set shader keywords of material assets from editor code?
I've tried both
Undo.RecordObject( mat, "update material keywords" );
foreach( string keyword in keywords )
mat.EnableKeyword( keyword );```
and
```cs
SerializedObject so = new SerializedObject( mat );
SerializedProperty propKeywords = so.FindProperty( "m_ShaderKeywords" );
so.Update();
propKeywords.stringValue = string.Join( " ", keywords );
so.ApplyModifiedPropertiesWithoutUndo();```
but they both silently fail, leaving the asset without the keywords :c
oh actually my bad this might work
sec
ignore me until I get back 
okay yeah first one works the problem was elsewhere!
Haha, glad you got it working
Made a super useful property drawer to fix a bug in 2019.3.0
A bug with displaying enums @gilded sonnet?
@pastel spruce Yeah. They showed up as int values in a serialized refrence of a nested class
Annoying
good fix
Thanks!
Can I hide the Script field in a ScriptableWizard?
I also wonder if you can hide script!
although I want to hide (Script)
and use a custom icon
Custom icons are possible just a hassle iirc
is this possible without hardcoding an icon into the gizmos folder?
I want people to be able to put the plugin anywhere, not force them to have a specific folder setup
and it looks like Gizmos is a special folder that has to be in root from what I can tell
and well, it only fixes the icon, not the title itself
Not sure if this works and is persistent
I can remember some reflection/serializedobject way to set it
oo actually that is serialized in the script import settings
looks like it's possible then!
Nice
You can't hide the 'Script' field.
And you can't modify the Component name
You can access the icon via m_Icon if I remember using a SerializedObject
But for real, I think it's possible to hide '(Script)', but it's a hell of a trick
hi how to rotate gui element ?
by element rect
i'm using something like this :
public void DrawConetion(Rect rect, Rect OtherRect)
{
Vector2 This = rect.position + (rect.size / 2);
Vector2 Other = OtherRect.position + (OtherRect.size / 2);
Rect MidlePoint = new Rect((This + Other) * 0.5f - new Vector2(Size / 2, Size / 2), new Vector2(Size, Size));
Vector2 dir = (This - Other);
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
var matrixBackup = GUI.matrix;
GUIUtility.RotateAroundPivot(angle + 180, MidlePoint.position - (MidlePoint.size / 2));
DrawState(isSelected);
SSS = GUIUtility.GUIToScreenPoint(this.rect.position);
GUI.matrix = matrixBackup;
this.rect.position = RotateAroundPivot(angle + 180, MidlePoint.position, Size);
Handles.DrawAAPolyLine(5, this.rect.position, SSS);
GUI.changed = true;
}
is working but is offsetted
is there a nice way to destroy the components that were required by another component, in its OnDestroy?
destroying required components in OnDestroy throws an error saying that they're, well, required, and you can't delete them
I saw something about using the editor/inspector OnDestroy for your type, and destroying in there, but that seems kinda, weird, to have that tied to the inspector object?
A funny thing you can do which is... not great, but perhaps okay? Is if you use something like [ContextMenu("Remove Component")] you can override the base implementation, which also replaces it in the context menu. Just doing it like that will reorder it poorly in the menu though, and obviously only handles the context menu removal
I don't have a good answer, though that might be of note 😛
@blissful burrow thank you of mentioning that method to hide the (Script)! Really neat
oh, I see it was you @visual stag haha
never knew this was possible, very clean
Wait, hiding the (Script)? Are you talking about what I just mentioned, or something else?
I think so
or maybe not
by using AddComponentMenu("Effects/Stylized Water")
the name of the component gets renamed and removes the '(Script)'
oh maybe that's not what you were talking about
Ah, that wasn't what I was talking about, but that is neat 😛
Looking at the code if you also add an [ObsoleteAttribute] it shows as X (Deprecated)
also NicifyVariableName used to be called MangleVariableName 😆
@lucid hedge oh, this? https://twitter.com/FreyaHolmer/status/1253813908114112512
wrote about how to do both in the thread!
in this case I wanted to remove the required components. specifically, I want a mesh filter and a mesh renderer to be required, but I also want them deleted if I destroy my own component
(essentially all of this is to make my script "act" like a custom renderer component)
yeah, I saw the tweet about it
the icons look really 'native', I love it when tools blend in with the editor
very clean
Is my solution of absolutely no use, are you looking for something that will also handle some other destroy condition?
hm, it should be any destroy call
so if you call destroy in runtime it should also delete them
maybe I should just not use RequireComponent and handle that myself
in that case it would let me destroy them in on destroy
also your solution is wonderful and hacky <3
I really do wish there was nice ways of doing this sort of thing, but if I have encountered it before I haven't remembered it
gotcha
yeah I just want to extend from Renderer, like, that's all I want to do ;_;
but now I need to do all these shenanigans to work around it
I mean, not even Unity handles it well, if you have a Image component for example, you still have to manually fnangle the Canvas Renderer afaik
it's just in your case you have 3 components so it's very digusting 😛
hehe, yeah~
have you thought about using DOTS and entities to do the rendering part?
I've never touched DOTS and entities, mostly because so much of it still seems to be shifting and changing, and because I've never had a use for it
I am pretty certain you can link them up cleanly and only have one monobehaviour in the inspector, and it'd be super fast.
But I am not at all knowledgable about it either, I just wouldn't rule it out as the parts of the API you'd be looking at would be the most mature parts
(well, I have touched the job system which I guess is technically part of DOTS)
gotcha
yeah possibly! I think if this library grows and becomes something people really want DOTS support in I can definitely look at adding support for that
but I think for 1.0 I'll skip it
because it would delay the release by a lot most likely
what's the plan again, only available for a certain tier of patreons?
initially yes!
If I remember and I see that it's an easy thing I'll get you a link, because I see Unity starting to use it for some of their systems and I also want to start doing the same where appropriate ;P
Okay cool! I hope the launch goes well
thanks @visual stag !
yeah I hope it goes well too, I'm a little worried people might not pick it up since it's not being released through the asset store and all
but hopefully there's interest regardless
I think it's super compelling, especially with your maths visualisations. I've seen a few tweet threads with polls, but I'm not completely across whether it's usable for stuff like edit-mode gizmos?
I'd like a pretty backend for making nicer debug lines 😄
you can use it in OnDrawGizmos!
the immediate mode side of the library allows you to do that
Draw.Line( a, b, ... )
Draw.Disc( pos, radius, ... )```
etc!
and thanks!
it's wild how long it takes to make the component side of the library
so much UI work
(although I guess I'm making it take longer because I care a lot about good UI)
That's my favourite part 😄
I like it too! just takes a lot of time
yeah, it's really difficult to get everything looking cohesive whilst also not straying too far from Unity's prexisting styles
Nice. Are you supporting older versions too?
It gets really tedious when you swap between new UI and old.. then non-pro and pro
UI Toolkit really does make that faster, but it takes even longer to set up
good question, some of my UI got a little janked up when I switched to the version with the new UI
I think I'm going to mostly care about the new UI
and the old UI will be secondary
#if UNITY_VERSION
rect.x += 1;
#endif
ahah
yeah
these buttons are now messed up because of that
because I guess padding in buttons or texture sizing in buttons is different now? 🤷♀️
I used to use Toolbar buttons a lot and now they 100% do not work in vertical blocks
so much just doesn't work any more and I need to make my own styles or change colours or whatever else
yeah I think I might just leave the old versions looking old and only care about the new versions
I've had too many nightmares dealing with versions from the time with shader forge
also there's an alignment difference on the left side there and that stuff just kills me 😛
haha yeah that used to not be there! I'm pretty sure I actually did per-pixel adjustments specifically for that
found an old pic for the line component
the buttons in the old one seemed to expand size based on image
maybe new ones don't?
what are you making?
Is there a reason you've chosen a colour per vertex over a gradient over the line?
I feel like it might be more annoying to use as a colour per vertex, I would have to make a thing to automate it with a gradient 😛
Maybe there is a Gradient color mode. It's set to Per Vertex in that screenshot.
Ahhh true
spoilt for choice if that's the case 😄
@severe python https://twitter.com/FreyaHolmer/status/1251547144378605568
ahh, nice
ah sorry for late response! was getting food
yeah that! thanks for linking @visual stag ~
so, I have a partial gradient color mode implemented
@visual stag @severe python gradients are currently disabled though because it has implications that I haven't spent time resolving and implementing
- if you only have two vertices, the gradient on the line will only have two colors, regardless of how many data points and color stops your gradient has. Sampling would only happen at the start and end, since the verts of the polyline are the only things holding data, so this probably needs to be clarified somehow, but, that's doable
- if I want to not make it be a gradient sampled on a per-vertex basis, that means I need to store the gradient as a texture somewhere for lookup in the polyline, which means that texture has to be stored somewhere, as well as the material has to be copied and made unique just because it's now using a custom texture
- (assuming I don't do 2) there are two ways of mapping a gradient to a polyline, one is based on points (middle point is 50% through the gradient), the other is based on percentage of distance, which means that'll be some CPU overhead in generating the polyline, plus, well, explaining the two modes and making it clear how they work
I know how I'd answer most of these questions, it just felt a little low prio and not super important compared to many of the other things I went on to work on!
I could imagine each gradient point involves spitting your line to get a new vertex to blend with, but yeah, nothing sounds ideal
yeah, which, also has implications on its own
I think I'd go the texture route before doing that
I need to sleep, it all sounds very good though, can't wait to see all the finished editors 🙂
thanks! and have a good night!
okay weird quirk question!
it looks like hide flags don't get serialized in material assets
does anyone know what gives?
specifically, I want to set hide flags to hide in inspector
okay actually they do if I CreateAsset with those flags, but not modifying an existing one
works in my case, so, never mind me!
this question didn't exist
stop navi
I'm assuming you're setting the object as dirty?
Undo.RecordObject so yes?
hey guys...for some reason I got my package manager and textmesh pro buttons deleted in the unity window UI...
any idea how to get them back?
It happened after I installed the Unity Uninstaller package from the asset store
using Unity 2019.1.8f
( @waxen sandal oh weird set dirty actually worked but not undo. does that mean it, didn't detect a change or something? anyway thanks!)
Perhaps some properties are excluded to make sure you don't accidentally register those and let the use undo them?
manifest.json has "com.unity.package-manager-ui": "2.1.2" included and restarted unity multiple times and tried reset packages to default
Does Unity has a way to set value of SerializedProperty has System.Object (not UnityEngine.Object). I mean, something like mySerializedProperty.objectValue.
pretty sure there isn't a way, those are only for unity objects. I don't think Unity can serialize any object reference unless you specifically set it up so that it will
and even if it could it would serialize a copy and lose all references, since references don't really exist in serialized data outside of unity objects referring to assets and such
I think that's what SerializedProperty.managedReferenceValue is for
That might be intended for the new [SerializeReference] attribute
the heck I've never seen that before
Don't remember that property
Looks like there's no way to read the value of a serialized class/struct property with SerializedObject/SerializedProperty. Everyone has been working around it with Reflection.
Oh, well, there is always reflection
@blissful burrow interesting for temporery editor stuff
yeah!
oh this is a thing that exists?! Yoink!
Given a SerializedProperty, how can I know if it will take 1 or more lines in the Unity inspector when it's drawn?
In other words, I want to know how much space will it take if I do EditorGUI.PropertyField(position, property, label, true)
You'd have to create an instance of the PropertyDrawer and calls its GetHeight method
It looks like all of that is internal, so you'd probably have to use Reflection to call PropertyHandler ScriptAttributeUtility.GetHandler(SerializedProperty property)
And then call PropertyHandler.GetHeight
Ok, thanks @short tiger
I found that method by just checking what EditorGUI.PropertyField does
Ohh
@severe python oh, it doesn't exist builtin in Unity! but I made it exist
(unless it also exists as a builtin thing and I missed it)
Hello! Question about attribute drawers:
Is there a way to apply an attribute to a collection (e.g. string array) and not each individual element of the array ?
What I would like to do is create an attribute that replaces the inspector element of a collection with a popup item selection.
This is in contrast to creating a whole custom editor for each script I want this applied to.
For example: in the image attached, the left (A) is how it appears as default. I would like it to appear as it does on the right (B)
The way I would like it applied would be like this:
[Popup] string[] StringArray
Not without a custom editor
I think
@cerulean musk
Thought, you could apply the attribute on each element of the collection (as you are doing) and only draw the first one.
I mean, each element should be stored in an static field of your property drawer, which is in change of only allowing the first element of each collection to be drawn
Interesting...
I've got the power now
@blissful burrow I quite don't understand why you would need such attribute.
Can you explain me what scenario led you to need to destroy a mesh in a static?
generating a mesh asset that's used in editor, but has to be cleaned up so that it doesn't leak every time you do an assembly reload
Then my real question is how do you create it without the ability to 'automatically' destroy it?
I mean, in the Editor world, we are most of the time granted a OnDestroy/Disable() coming with Awake/OnEnable().
it's created in a static constructor, so there's no owner really!
Custom Editor, EditorWindow, EditorWizard and others, they all have a way out. Even at the assembly level
Hum... Ok
yeah I know, if I was using any of those I'd use OnDestroy etc!
Just for your information, there is a way to create an Object and make it persist through a Domain Reload, but it implies loading from a '.asset'.
UnityEditorInternal.InternalEditorUtility:LoadSerializedFileAndForget(String)
right, yeah, there's no asset in this case
the ManagedreferenveValue is read only
its set via SerializedReferenceAttribute
also @blissful burrow I'm not sure what you're talking about in your ping to me
oh I was, I have a situation for that right now
Making a temporary render mesh for visualizing a navigation graph
Hi all, anyone here with experience using code generation for Unity who wish to give their two cents on the subject? Are there any good libraries or do you prefer to develop it yourself?
You mean stuff like T4? @unborn bluff
I don't even know what T4 is.
Text Template Transformation Toolkit. It allows you to do metaprogramming in any language, useful for C# which doesn't have metaprograming in-built.
Cool, was not aware that existed. I have never done code generation before. My friend adviced me that you could make some simple code generation by creating a template text file and just use string.Replace(). It sounds simple.
But I warn you. Unity is not compatible with them.
I mean, T4 templates require modification of the .csproj, which is regenerated by Unity. So each time Unity loads your project it breaks your templates. People asked to Unity fix that, but they said no.
If you want to use T4 in Unity, you must create a solution and project outside your Unity project and then import in Unity either the .dlls or the generated .cs files.
At least that is what I do
Alright, that sounds like a bit of a hazzle - Thank you for the headsup.
There are paid assets which fixs that. Hovewer I haven't tested it. (https://assetstore.unity.com/packages/tools/utilities/t4-code-generation-63294)
Cool, was not aware that existed. I have never done code generation before. My friend adviced me that you could make some simple code generation by creating a template text file and just use string.Replace(). It sounds simple.
@unborn bluff much simpler, if it works, it works
EditorGUILayout.LabelField(Keybindings", EditorStyles.boldLabel);
thank you
Update on my popup drawer situation:
Just remembered that popups are ints and NOT string collections in and of themselves.
Might explain some things, might mean my issue is solvable with some awkward workarounds.
Worst eureka moment I've had this week 😞
Anyone know if UIElements supports rich text in any capacity, or if I have to use an IMGUI container for that?
full rich text is not necessary, just the ability to change the colors of different parts of the text in a field, for example
not currently
f
that's what I'm thinking
each word being a label is a little wierd, but I'm sure you can make something like that work
provided text field cursor position and stuff is all accessible
I'm installing Visual Studio Community 2019. besides "Game development with Unity" is there anything else that needs to be checked? any individual components?
This channel is for creating extensions to the editor, so any of the other general channels is an appropriate place to ask.
But all you should need to do is in Unity make sure Edit > Preferences > External Tools > External Script Editor has Visual Studio set correctly
thanks
anyone have experience creating custom editors for state machine behaviours?
it seems there's a bug where right click > Removing the state machine behaviour deletes the SMB, but it doesn't destroy the custom editor
so you got a custom editor hanging around in memory that you can't destroy unless you restart unity
I'm getting an error every time I start drawing a list of buttons in the scene. Like I hit shift A to open the list of buttons and it gives an error of
Aborting
but after that it draws the buttons just fine until I try to close and reopen them which then gives me the error again
Example code ```
[InitializeOnLoad]
public class ExampleEditor : Editor
{
static ExampleEditor()
{
SceneView.duringSceneGui += UpdateGUI;
}
~ExampleEditor()
{
SceneView.duringSceneGui -= UpdateGUI;
}
static public void UpdateGUI(SceneView sceneView)
{
if(shouldDraw)
DrawExample();
}
static void DrawExample()
{
Handles.BeginGUI();
GUILayout.BeginArea(new Rect(0, 0, 100, Screen.height));
for (int i = 0; i < 10; i++)
{
if (i == 5)
GUI.backgroundColor = Color.red;
else
GUI.backgroundColor = Color.white;
GUILayout.Button(i.ToString());
}
GUILayout.EndArea();
Handles.EndGUI();
}
}
every time I set shouldDraw to true I get the error message
to destroy a custom editor you can use DestroyImmediate iirc
@quasi monolith
keep a reference to it somewhere and invoke destroyimmediate when you delete the state itself
@left panther sort-of off topic but - what's the use case for a custom editor without the [CustomEditor(typeof(...))] attribute?
as opposed to like, EditorWindow
You can still create and embed them using https://docs.unity3d.com/ScriptReference/Editor.CreateEditor.html right?
hm!
might actually be useful, maybe, for the stuff I'm doing
so say I've got, components for
Cat : Animal
Dog : Animal
Bunny : Animal
can I make a custom editor for Animal when you have a mixed selection?
([CustomEditor(typeof(Animal))] doesn't work)
Does it not?
it didn't back when I tested it
you need to pass another argument
pretty sure I tried that one too
Hrmmmm it's working for me
add [CanEditMultipleObjects]?
I've got that
Sometimes you need to reselect things for that message to go away after compiling
it can be a little weird
I did that
I have so many editors that are referring to a base type and are displaying the editor on a sub type
I'm unsure what could be wrong
how do you mean?
CatEditor : AnimalEditor
DogEditor : AnimalEditor
etc.
was thinking if that invalidated some type checking somehow
so how exactly would that work
Surely the subtypes are defining what their editors show
yeah, but there's functionality shared by all of them that I have in the base editor
I have a ScriptableObjectInspector
that works to draw headers on top of all my scriptable objects:
[CustomEditor(typeof(ScriptableObject), true), CanEditMultipleObjects]
and I have other editors that inherit from it and call its base. functions
eg:
[CustomEditor(typeof(LootTableBase), true)]
public class LootTableInspector : ScriptableObjectInspector```
Then I have a specialised editor of a derived type with the functionality of the base type, and anything that doesn't have a specialised editor still gets the base editor
sounds like the same as my use case, except my base editor isn't showing up
if you are overriding the functions in your inherited editor you will need to call the functions on the base class still if you aren't
yeah, all of that stuff is working fine
your base editor isn't abstract or something is it?
it's specifically when I have a mixed selection where there's, well, no editor showing up at all
Ahhh
and no it's not abstract!
Sorry, I hadn't twigged that that was the issue. I have not tested that usecase, though it would make sense that it would work with the shared editor, I can imagine Unity not working like that ):
so it's possible it might work if I don't inherit from the base editor?
I could probably work around that
I'll test some things
o, thanks!
One way you could get around this is to have one editor, and for it to switch into calling the functions top down instead of bottom up.
If you detect multiple targets of different types you only show the base editor
you could align it yourself with GUILayout.Space I presume?
but maybe you want it to be less, hacky, and more precise
Wow, Unity's ability to multi-edit is even worse than I knew. You can't even multi-edit two different types that use the same editor. That's really abysmal ):
I suppose it makes sense in some senses with SerializedObject, but it's still sad
so now you need a fourth component to be the multi-editing component 😛
what could be a possible reason for my SO not to be able to get serialized?
What's the circumstances? You're making changes via an editor?
yes I am, making a hatebin as we speak
https://hatebin.com/hmkzakwroy is the editor for https://hatebin.com/rejkekiqlh
so, numerous things
you can't mix and match editing the target and serializedObject
By editing the target you need to call serializedObject.Update before calling serializedObject.Apply... because Apply will just write whatever is currently stored in the SerializedObject, which does not update from changes you make to the target automatically
You might be lucky with your ordering in such that DrawDefaultInspector may be doing this for you though
damn, didnt think that was a thing...
so you might be in luck there
Otherwise, if you're making changes to a target you need to use Undo.RecordObject to inform Unity that changes have been made
if you're not using the Undo functions you need to call EditorUtility.SetDirty
Those two functions are different in that Undo is called before changes, and SetDirty after
yeah, that makes sense seeing as your property change is made immediately before applying
everything else is a change to target, which will be overwritten by that
Generally mixing and matching SPs and direct access to target can get you into these sort of troubles, but with careful management of the Update, Apply, Undo, and Dirty, you can manage it. It's just a bit of a minefield
any recommendations on a proper fix? Can I somehow acess the event property from the target?
I could do it with those funcitons, but if i can access it from the target it would probably be better
I think you could fix it by wrapping your property access in a change check scope and only calling ApplyModifiedProperties if you detect a change
(getting rid of line 71)
i moved it into a changecheck on the event property, time to test
It's hard to know entirely what's needed though as I'm a little wary of the DrawDefaultInspector call after your target modifications
you may need to call serializedObject.Update(); before that, but lets see this first
Doesn't apply only apply modified properties?
the changecheck does not seem to fix it. maybe I should remove that drawdefault?
its only used to draw an enum dropdown, I could draw that from the custominspector tbh
dunno why I didnt in the first place
oh I know, because I have no way of drawing the list as a dropdown the way I have it set up
@waxen sandal I have had all sorts of strange and ridiculous scenarios where serializedObject and target modification have utterly failed to do what I expected them to do. The worst ones involving things that are not synchronous, like the Undo functions. It's just a nightmare.
The worst part is that it's changed over the years and some of the things which were previously bugged are now not, so who knows. I live in fear of anything that isn't cleanly modifying one or the other 😛
@visual stag The only thing that stays consistent is that it's broken 😉
I draw the default inspector for the last 2 elements in the object, those being the _event and PartOfSet
Tbh, I would just do everthing with serializedproperties
I generally do that too
It lets you be somewhat sane at least
multi-edit and undo built in
just extremely verbose on the variables side, but easy PropertyField on the other ;P
how would I go about converting it tho?
can you get a screenshot?
of the inspector window?
ye
nice wdaewfagaegfafa
xD
You made a typo it's wdaw not wdaew
I just needed to edit and see if it tracked the changes
Damn forever in shame
well, SerializedObject/Property is very similar, you just gather the properties in OnEnable with
serializedObject.FindProperty("PropertyName")
Then you can just draw them with EditorGUILayout.PropertyField
Whatever isn't possible do do with PropertyDrawers ([Delayed] is a good attribute already)
you either make your own property drawer, or you just do exactly what you're doing already, except you use the serializedProperty.fieldTypeValue relevant to your type. Like serializedProperty.objectReferenceValue would be for your Sprite property.
remove the SetDirty and it should all work the same
that seems very un-typesafe
The only thing that is annoying is that all the properties are referenced via strings
could probably go overkill with it and reflect variable names
nameof should work
if they're public you can nameof ^
does taht work on both variables and properties?
ima try that. with one variable first lol
properties won't work at all with SerializedObject, as it's only talking about the actual serialized representation of the data
but more generally, nameof works with everything 😛
I mean, there's no way that serialized in your old version either 😛
yeah, that wouldn't serialize in general. If you're just using properties, then there's your whole issue 😛
you can tell whether Unity is serializing anything at all by looking at the Debug-mode inspector, as it'll be the raw data as saved
Thjat works as well but old data is also still serialized
true
var t = serializedObject.FindProperty("Name");
EditorGUILayout.PropertyField(t, GUIContent.none);
if (check.changed)
{
AssetDatabase.RenameAsset(AssetDatabase.GetAssetPath(item), item.Name);
}
how do i prevent that from firing every time I change the name?
I would like it to only fire when field is entered / deselected
add a [Delayed] attribute to the field and it'll work as it did previously
it seem to be delayed, but the assetdatabase always displays the previous version I placed in there. even with the assetdb refresh
you should use t.stringValue instead of item.Name
oh, I was using the actual value fromthe target, which hasnt been updated for the serializedObject?
yep
I think im starting to get it with these fields, should probably do the FindProperty calls in OnEnable tho
btw, Rider (at least, mine) isn't good at inspecting the contents of SerializedProperty and I avoid it, because it's likely to crash for me 😛
thats pretty cool actually. I dont have any contacts like that im afraid xD
Matt is my favourite dev 😄
he's very well spoken and he's put in so many of the features that make rider great for us
Yeah he's great, but you should not forget the other developers
what'd you help with?
Also a bunch of things in another repo regarding solution generation to support csc.rsp files
would be nice if rider wasn't expensive
It's not though