#↕️┃editor-extensions
1 messages · Page 68 of 1
Why are these two fields not listed under my mesh renderer inspector?
(Screenshot above was sent by a friend) How would I go about getting these to show?
(2018.4.20f1 is the version)
Is there an easy-ish way to make a text field with a list of filtered results (auto complete)? If unity has some API for it or if there's a community gist that'd be great too.
I'm currently using Ryan Hipple's searchable popup. It looks great, but you have to tell it to Show and it pops up with its own text field. (as shown in video) I'd love to just have a single text field that shows filtered results as you type.
I tried making my own popup, but have been struggling with getting it to show properly based on typing in the text field of a property drawer. Getting lots of crashes and errors 😦
If there isn't a premade solution I'd love pointers on the correct way to approach it.
From the time I've spent on the problem it seems I need to use PopupWindowContent so the GUI doesn't get clipped by the bounds of the component editor area.
The text field is drawn with a property drawer and I got stuck figuring out when to call PopupWindow.Show(...)
Before drawing the text field I have this snippet
// create and set a unique id for the text field
int controlID = EditorGUIUtility.GetControlID("PropertyID".GetHashCode(), FocusType.Keyboard, rect);
string controlName = "PropertyID" + controlID;
GUI.SetNextControlName(controlName);
// draw the text field
so that i can check if it has focus.
if it has focus, and it wasn't already showing, I show it
if (GUI.GetNameOfFocusedControl() == controlName)
{
if (!wasShowingPopup)
{
PopupWindow.Show(rect, popupContent);
...
Unfortunately this was giving me errors and always resulted in a crash eventually
@orchid pelican please don't post random off-topic images
i'm trying to resize gui box to fit a label's current text
@mighty oasis style.GetSize()?
so that i can check if it has focus.
if it has focus, and it wasn't already showing, I show itif (GUI.GetNameOfFocusedControl() == controlName) { if (!wasShowingPopup) { PopupWindow.Show(rect, popupContent); ...Unfortunately this was giving me errors and always resulted in a crash eventually
@wispy delta check if the textfield is being edited, not just focus
hello , how can i use python in unity for editor scripting
the docs dont help
solution
@onyx harness good call, that works much better! I'm also using a SearchField instead of a TextField which should make getting up/down callbacks easier.
One issue I'm running into is the popup taking focus away from the search field when it is shown.
I tried doing
PopupWindow.Show(rect, searchResults);
EditorGUIUtility.keyboardControl = searchField.searchFieldControlID;
and
PopupWindow.Show(rect, searchResults);
searchField.SetFocus();
but neither seems to work. As soon as I type a character the popup gets focus. Any ideas?
The focus is given to a Control
But moreover, the focus is given to the window first, then down to the control
Keep the focus on the Inspector
@wispy delta
The problem with pop-up window is, they might catch the focus anyway, otherwise they automatically close
You might have to handle your own window
goootcha. I'm probably doing a bunch of redundant stuff here, but the inspector still loses focus. anything look off, or should i make my own popup system @onyx harness?
if (check.changed)
{
if (!searchResults.IsOpen)
{
// Get search field window (inspector)
var window = EditorWindow.focusedWindow;
// Show popup
PopupWindow.Show(rect, searchResults);
// Refocus on search field window
window.Focus();
// Do everything that could possibly give control back to the search field :P
searchField.SetFocus();
EditorGUIUtility.hotControl = searchField.searchFieldControlID;
EditorGUIUtility.keyboardControl = searchField.searchFieldControlID;
}
}
To be honest, the system is pretty hard to grasp, or nobody have ever found a way to explain to me.
I never used hotControl or keyboardControl, I tend to prefer SetFocus ToControl
But this one needs to be handled correctly between Repaint and Layout
haha fair. it's all a bit convoluted. so there's a chance it'll work if i only change focus during the correct event type?
Yes, event type phase is very important to master when you deal with these things
looks like the internal PopupWindow.Init function has a giveFocus option which is hard coded to true. Perhaps making my own Show function with that exposed and a bit of reflection would make this easier
Yes, that's what I said, pop-up grabs the focus
Just create a window and show it as borderless
idk what EditorLayoutDrawer is but GUILayout and EditorGUILayout doesn't work within property drawers. it expects you to use GUI and EditorGUI within the supplied rect. if you use layout gui functions they'll be drawn below the drawers
https://forum.unity.com/threads/custom-property-drawer-in-list-layout-messed-up.563035/
@rocky flicker
ah EditorLayoutDrawer from one of our libraries sorry :d
yes GUI is worked just fine thank you @wispy delta
well i am listening if u willing to tell @onyx harness
GUILayout.BeginArea
I don't advise to use it, because sometime it implies other things, but it is convenient sometime
For speed production purpose
last time i tried creating an area within a drawer it was invisible. saw a couple forum posts mentioning you can't nest areas which surprised me, but you know more than me haha
It seems logical that you can't nest area
But it is different than what we are talking above
With BeginArea, you just plant a layout rectangle, and draw inside it
gotcha. i assumed an area had already began by the time the property drawer was drawn, so calling BeginArea there would be nesting an area
Begin/EndArea is the same as using (new GUILayout.AreaScope()) right?
yea it is. not sure why i was getting invisible gui. must've been some other issue
As you stated, PropertyDrawer is not wrapped between Begin/EndArea :)
liiitle bit of progress. i tried making my own window but was running into lots of issues: getting errors about antiAliasing not being valid, window not opening in the right place, not being borderless etc
i decided to not make my own window for now and made this abomination of a method to let me show a popup without it getting focus.
public static void ShowPopup (Rect activatorRect, PopupWindowContent windowContent, bool focus)
{
Object[] objectsOfTypeAll = Resources.FindObjectsOfTypeAll(typeof (PopupWindow));
if (objectsOfTypeAll != null && (uint) objectsOfTypeAll.Length > 0U)
{
PopupWindow popupWindow = objectsOfTypeAll[0] as PopupWindow;
PopupWindowContent currentContent = (PopupWindowContent)popupWindow.GetType().GetField("m_WindowContent", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(popupWindow);
if (popupWindow != null && currentContent != null && currentContent.GetType() == windowContent.GetType())
{
popupWindow.Close();
return;
}
}
if (!(bool)typeof(PopupWindow).GetMethod("ShouldShowWindow", BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, new object[] {activatorRect}))
return;
PopupWindow instance = ScriptableObject.CreateInstance<PopupWindow>();
if (instance != null)
instance.GetType().GetMethod("Init", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(instance, new object[] {activatorRect, windowContent, null, 1, focus });
if (Event.current != null)
GUIUtility.ExitGUI();
}
Good-ish news: the popup doesn't close immediately. It has to first gain focus for it to close when it loses focus.
There's still some kinks to work out tho. It doesn't close unless you click on and then off of the popup and a null ref is thrown from EditorWindow.Close () on recompile
I need some help with the dark arts of attributes and reflection:
I have a custom attribute named Watch. I need to get all the fields and properties with this attribute.
This tutorial https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/accessing-attributes-by-using-reflection shows how to retrieve attributes for classes but in this case I don't know the System.Type of the fields/properties.
I've tried googling for the answer but i can't find it.
public class TestClass
{
[Watch()]
int test1;
[Watch()]
int test2 { get; set; }
}
do you need the type of the field that has the attribute, or the type of the classes that have fields with the attribute?
this attribute is only for fields and properties
I need to get a reference to the Watch attribute for every field/property so I can access the name and value of the field/property and some optional parameters of the Watch attribute
var fields = anyType.GetFields();
foreach (var f in fields)
{
var attrs = f.GetCustomAttributes(typeof(Watch));
if (attrs.Length > 0)
{}
}
Does anyone know how I can get mouse3 and mouse4 in a unity editor window? I saw this online: $"Current Mouse Button: {(KeyCode)Enum.Parse(typeof(KeyCode), "Mouse" + Event.current.button, true)}" but don't seem to work, anyone has an idea?
I dont think Unity transmit those extra buttons
But if you are on Windows, you can know it
var fields = anyType.GetFields();
Umm I don't think looping through all the fields is a very performant option. Reflection stuff is pretty expensive but isn't there a better way?
It all depends on what you do
I think I can confidently say, 100% of the time, Reflection is not an issue
I guess I can cache this
🙂
but like,
if you know at compile-time all the fields with this attribute can't the compiler generate a list or something that has only the fields with this attribute?
is it technically possible?
yes
If you are in the Editor only
I have to say it: It won't be worth it
Even if we talk about 10k Types having some Watch
hey! wanted to ask how to make a dropdown in the unity inspector to show or hide float values through a C# script
is it an array of floats, or an enum? what's the context?
im coding a weapon class and wanted to have public values like ammo, reload etc. for each weapon i want in the game. However it clutters up the inspector so i wanted to know if there was a way to hide and show them through C# code
not before no
public string playerOneWeapon;
public string playerTwoWeapon;
public string playerThreeWeapon;
public string playerFourWeapon;
//WEAPON STATISTICS
public float ammo;
public float reloadTime;
public float timeBetweenShots;
private float shotTime;
public Sprite Sprite;
public Transform ShotPoint;
public GameObject Projectile;
//PISTOL STATISTICS
public float pistolAmmo;
public float pistolReloadTime;
public float pistolTimeBetweenShots;
public Sprite pistol;
public Transform pistolShotPoint;
public GameObject pistolProjectile;```
I wanted each of these sections to be able to be hid and shown in the inspector
rather than all shown at once
so unity doesn't have an "easy" way to add foldouts natively without creating a custom editor. but if you're familiar with attributes you know that unity provides some to allow for quick inspector customization
you can create sliders with Range
[Range(0f, 1f)] // makes the float show up as a slider with a min of 0 and max of 1
public float someFloat;
add spaces with...Space
public Vector3 someVector;
[Space] // creates a space between these properties in the inspector
public int someInt;
and a few more
^ with that being said (sorry if you were already aware) some people have made their own attributes to handle foldout
here's the first one i found. no idea if it works
https://github.com/PixeyeHQ/InspectorFoldoutGroup
if you don't want to use an attribute i can show you how to make a custom editor that does it tho (it's a bit more work)
this repo has a lot of attributes you could use to customize the editor without write custom editors
https://github.com/dbrizov/NaughtyAttributes
@wispy delta Thanks! the https://github.com/PixeyeHQ/InspectorFoldoutGroup link looks like exactly what i need. I'll fiddle around with it until i get it working
@wispy delta I have downloaded the C# files
do i just drag them into the inspector to make them work or is there a special way to make it work.
it's all done through code
using Pixeye.Unity; // put this at the top
[Foldout("Current Weapon")]
public string playerOneWeapon, playerTwoWeapon, playerThreeWeapon, playerFourWeapon;
[Foldout("Weapon Stats")]
public float ammo, reloadTime, timeBetweenShots;
private float shotTime;
[Foldout("Weapon Stats")]
public Sprite Sprite;
[Foldout("Weapon Stats")]
public Transform ShotPoint;
[Foldout("Weapon Stats")]
public GameObject Projectile;
[Foldout("Pistol Stats")]
public float pistolAmmo, pistolReloadTime, pistolTimeBetweenShots;
[Foldout("Pistol Stats")]
public Sprite pistol;
[Foldout("Pistol Stats")]
public Transform pistolShotPoint;
[Foldout("Pistol Stats")]
public GameObject pistolProjectile;
@toxic timber
@wispy delta Thanks so much, its up and working : )
awesome 💯
Hey, Anyone know how I can create an EnumField (UIElements)?
How can I set the enum values for the field?
(in C# script)
Pass GUILayout.Width(width) to it
no this other
??
I'm not even sure what you're asking
I don't think there's a built in thing
You need to give each side a "fixed" width which you change by how much the divider moves
i need smth like this but have no money 🙂 https://assetstore.unity.com/packages/tools/gui/editor-gui-table-108795
ok so did someone use UI Builder package?
@full vault You are looking for a splitter? Or something like that
too hard understand it
To make a splitter you need 2 things:
- a variable "size"
- know how to handle drag & drop
Did someone implement a simple table? If so, how? You need to be able to add / remove items. Reorder (optional) and change properties. And also change the width of the columns. In principle, all this can be done through the multicolumn tree view, but I do not understand at all how it works
Is it possible to get a reference to these two assemblies at runtime?
Define reference
Assembly-CSharp contaisn all code that's outside of AsmDefs and outside the Editor directory
Editor can't be used in runtime because it's intended for Editor only code
by runtime I mean runtime in the editor sorry
I need a reference to the Assembly class for each one of them
You can but you shouldn't
AppDomain.CurrentDomain.GetAssemblies gives you all of them
You can also use this https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assembly.getassembly?view=netcore-3.1
I am currently using GetAssemblies
I would like to get a reference to only these two
You got a list of all of them, you can just take the ones you want
Or you can use that other method
You know the name, just filter the rest out
filtering them by name is actually a great idea
Or you can do a smart filter
Since your attribute Watch is from your own Assembly "A".
You can filter out any Assembly not having a reference to your Assembly "A".
If you are in Assembly-CSharp-Editor, this filter might not be that efficient
much better
yeah
the second method doesn't really offer any advantages
I don't plan on creating other assemblies so it's fine
It does at some point
Imagine a world, where your Attribute Watch is being used by someone else
By dependencies handle all those cases
Yeah that won't happen
I'm not releasing my crappy tools
filtering?
psh
Do you have a type that you know is contained in those assemblies?
var assemblyCSharp = typeof(TypeInAssemblyCSharp).Assembly;
Does anyone use the Peek Tool from the asset store? I'm new to programming and I wanted to know if its recommended?
I own it
I like it but I don't use it much since I don't do that much Unity work at home
But you're also asking in the wrong channel
Oh im sorry , what would be a better channel to ask?
#💻┃unity-talk probably
Oh i tried over there and didnt get a response. so i thought i was already in the wrong area lolz
Thanks @waxen sandal
how do you use cinemachine to go straight from point A to point B instead of curving?
#💻┃unity-talk Is probably your best bet
Hi, does anyone have an idea how to implement a curve editor in an inspector/custom editor. I've looked on the forums and google but so far I found no solution.
Handles.DrawBezier?
@vernal garden unfortunately it's all internal and was never exposed - you can use reflection but... I've at some point in the future I think there may be a revamped exposed UITK version for us if you can wait 🤞
Well lets hope so 😅 but thanks anyway!
I just ended up making my own version but as you can imagine it's fairly involved - good luck
that seems to be for in the scene view, what I'm looking for is a curve editor for in the inspector itself :/
Handles.drawbezier works
Handles works in a GUI context, therefore in Inspector
there's no floating system for GUI Editor stuff?
what is a floating system?
like floating divs, or a grid layout group, without having to position everything manually/static
They have EditorGUILayout
Ok maybe what I mean to ask is after you create a horizontal or vertical layout, you can create buttons/textures/toggles etc. Will Rect(0,0) put them all at the top left corner, or is there a way to make them appear sequentially?
Yup
Ok how do I do that 🙂
GUIContent.none, GUIStyle.none?
Is there a way to reliably run editor code in the background yet?
Searching for this ability always seems to lead to disappointment.
EditorCoroutines are a thing now as well
how i can do tabs in Window?
What kind of tabs
like in browser
Like fully draggable and stuff?
Or just show different content on which you have selected
diffrent content via selected
Use GUILayout.Toolbar
That returns which one is selected
And then just draw based on what it returns
Can I somehow wrap the elements in a container and then get the height of this container?
Only available in Editor
There's also some methods like https://docs.unity3d.com/ScriptReference/GUILayoutUtility.GetLastRect.html
something doesn't work
var scope = new EditorGUILayout.VerticalScope("t");
var rect = EditorGUILayout.BeginVertical();
GUILayout.Button("a");
GUILayout.Button("a");
GUILayout.Button("a");
EditorGUILayout.EndVertical();
tab = GUILayout.Toolbar(tab, new string[] { "Object", "Bake", "Layers" });
switch (tab)
{
case 0:
m_SimpleTreeView.OnGUI(new Rect(0, rect.height, position.width, position.height));
break;
default:
break;
}
you use a scope in a using block
what you're doing is opening one and never closing it
@visual stag ty
hmm what's a good way to get the world position within a PropertyDrawer? It's for showing a popup. I'm using UITK if it makes a difference.
WorldPosition of what?
of wherever the drawer is drawn... if I grab e.g. root.worldBounds it's relative to the window it's in
Ok, I'm confused. Can't help you there
Say you have a propertydrawer that adds a VisualElement, let's call it 'root'. If you get root's worldBounds (or transform etc) it will be relative to the editor window it has been drawn in. For showing a popup I need to add the position of the editor window making it what I was calling the world/global position. So either I need a way to get the editor window from the property drawer (don't think this is possible?) or I need some utility that gets the global position.
It's really confusing that they're calling it worldBounds here
Nah
It's not
I googled it
Lemme check my code, I have something similar somewhere
thnx - it's easy to do when you have a custom editor window obviously but I'm trying to build a property drawer that can be used anywhere
Ah fuck, it's not the same
It's a custom window as well :/
If you've got the root element then you can try to find all EditorWindows and compare the RootVisualElement of them perhaps?
Otherwise I wouldn't know
ok thnx - I'm just taking a look at GUIUtility.ScreenToGUIPoint
yea, doesn't look like it.. maybe I can mix it somehow 😩
ok it's a bit hacky but I think I can use EditorWindow.focusedWindow as it's for a popup so I think the relevant window should always get focus
how can i add a triangle to a button, like a popup box in the editor? similar to this:
I'm trying to style a EditorGUI.Foldout in the above style
I'm trying to make a custom EditorGUILayout.Popup like the picture shown
How can i left justify text on a GUILayout.Button please?
I need a way to get the editor window
@split bridge
private static bool initializeCurrentEditorWindowMetadata;
private static PropertyInfo current;
private static Type HostViewType;
private static FieldInfo m_ActualView;
public static EditorWindow GetCurrentEditorWindow()
{
if (initializeCurrentEditorWindowMetadata == false)
{
initializeCurrentEditorWindowMetadata = true;
LazyInitializeCurrentEditorWindowMetadata();
}
if (current == null)
return null;
object guiView = current.GetValue(null, null);
if (guiView != null && HostViewType.IsAssignableFrom(guiView.GetType()) == true)
return m_ActualView.GetValue(guiView) as EditorWindow;
return null;
}
private static void LazyInitializeCurrentEditorWindowMetadata()
{
Type GUIViewType = AssemblyVerifier.TryGetType(typeof(Editor).Assembly, "UnityEditor.GUIView");
if (GUIViewType != null)
{
current = AssemblyVerifier.TryGetProperty(GUIViewType, "current", BindingFlags.Public | BindingFlags.Static);
HostViewType = AssemblyVerifier.TryGetType(typeof(Editor).Assembly, "UnityEditor.HostView");
if (HostViewType != null)
m_ActualView = AssemblyVerifier.TryGetField(HostViewType, "m_ActualView", BindingFlags.NonPublic | BindingFlags.Instance);
if (m_ActualView == null)
current = null;
}
}
There is ways to get the absolute position of a coordinate
GUIUtility.ScreenToGUIPoint can help
But there are few spots in the internal API (among them, GUI clips) where you can try to get a position
@split bridge GetCurrentEditorWindow is not universal!
Since recent version and introduction of UITK, EditorWindow might not be right, and you will get a GUIView instead of a EditorWindow
Use this one in this specific case:
public class GUIViewWrapper
{
private static Type GUIView = AssemblyVerifier.TryGetType(typeof(Editor).Assembly, "UnityEditor.GUIView");
private static MethodInfo RepaintMethod = AssemblyVerifier.TryGetMethod(GUIView, "Repaint", BindingFlags.Instance | BindingFlags.Public);
public object target;
public GUIViewWrapper(object target)
{
this.target = target;
}
public void Repaint()
{
if (this.target != null && GUIViewWrapper.RepaintMethod != null)
GUIViewWrapper.RepaintMethod.Invoke(this.target, null);
}
}
public static GUIViewWrapper GetCurrentGUIView()
{
if (initializeCurrentEditorWindowMetadata == false)
{
initializeCurrentEditorWindowMetadata = true;
LazyInitializeCurrentEditorWindowMetadata();
}
if (current == null)
return null;
return new GUIViewWrapper(current.GetValue(null, null));
}
(The toolbar is a GUIView for example)
I'll stick with focusedWindow for now as it appears to work fine in my tests with e.g. multiple inspector windows but I'll keep the above in mind should I encounter any issues, thanks.
focusedWindow is unfortunately not good
when does it fail?
as it says, it gives you the focused window
If your PD is drawing independently, it wont work
as I mentioned, it's for a custom popup menu - so clicking on the menu gives the inspector/window focus
Now, if you rely on a click event, yeah it should work
yea - there may be edge cases I haven't thought of / encountered yet
but I'd rather used focusedWindow over a bunch of reflection if it does the job
With a click behind, yeah go for it
so what we have
when i check it not null but when i getComponent there exception
Because Unity handles Object's operator == differently
"is" won't call the overridden operator
Where i can you read about it?
To those of you who have made UPM packages, does this actually work? https://forum.unity.com/threads/samples-in-packages-manual-setup.623080/
I can't get it to work at all
it's supposed to create "Samples" in the UMP window
I'm just wondering if this is a feature that was dropped, because these posts are from like February 2019
Afaik not dropped but we don't use it
I'm not really sure the best place to ask UPM related questions
Perhaps you can look at existing packages? You should be able to inspect the source of them just fine
Here works @mighty arch
I actually don't know of an existing UPM package that uses Samples
Input system has some iirc
Where i can you read about it?
@full vault https://blogs.unity3d.com/2014/05/16/custom-operator-should-we-keep-it/
Shader graph has one as well
Hm, still can't get it to work, but maybe it's because it's an "In Development" package and not a published one?
I looked at the ProBuilder one and from what I can tell I'm doing everything they are doing
Perhaps but I doubt it
I guess you already have access to the examples if it's in development
Perhaps you can try doing a "local" package that's referred by file?
Hey guys im a beginner with unity and im making a flappy bird mobile android game. can anyone plz help me make a high score script asap? thanks alot
@waxen sandal My Samples did work once I pushed the repo up to a Git and imported it into a project, so I guess it was because of it being an "In Development" package
👍
Is anybody using Tween?
@waxen sandal Actually the real reason seems to be because my "In Development" package folder was not named the same as the "name" field in the package.json file
I had it named something lazy instead of "com.company.packageName"
Is there a way to use UIElements for a custom inspector?
or are they only for editor windows
Yes, the custom inspector docs gives examples
I want to make something like this with UIElements but I'm a tad confused on how. I've tried using a toolbar and a toolbar toggle but they don't seem to be what I want.
you'll find many controls do not exist and you have to make your own
luckily that is way easier
can even do it through the UI Builder
yeah that's what I'm using, UI Builder.
where can I read up on creating my own controls?
nowhere yet really, I would just crudely do it with two buttons with different styles
would there be an easy way to have it so when one is on the other is off and it will switch between those two states based on which one is on?
the lazy way is to set it up in code in your editor
the complex way is to make your own field (with a UxmlFactory and UxmlTraits)
seems like the best way is just to go back to using GUILayouts tbh
https://docs.unity3d.com/ScriptReference/GUILayout.Toolbar.html since this is essentially what I want
is it a good idea to have a 'hybrid' editor of GUILayouts and UIElements or are you meant to just use 1 or the other
you can use IMGUIContainers to nest IMGUI stuff
I tend to not bother unless it's a complex field
There are probably others that know more about UIToolkit that can help - I have an dual-toggle with label thing I've made for a runtime
https://hatebin.com/oyqbgilbwe
But it'll have USS specific to me
it might help
I'll check that out. Thanks
How do I add a GUILayout to an IMGUIContainer? Is it .Add/.Insert?
you subscribe to onGUIHandler
kk thanks @visual stag
Good morning everyone, can I somehow build a chain of calls right in the editor? I need a list with functions in essence.
Yes
like a List<UnityEvent>() ?
I'm trying to align some text on a toggle box using GUIStyle, however when i apply boxStyle.alignment = TextAnchor.MiddleLeft; the box for toggling disappears.
GUILayout.Toggle(presetToggle.All, "All", boxStyle, GUILayout.MaxWidth(100));
is there a way i can align the toggle box somehow perhaps?
nvm, found answer.
Is it a good idea to use a script you're making a custom inspector for hold data for stuff like which toolbar item is selected so it doesn't get reset if you deselect and reselect the object? Or should I just use editorprefs for this?
does anyone know how to add custom buttons in the toolbar? I could've sworn it was a relatively new feature that unity was talking about, I don't know if it's only available in unity 2019+ or not. googling didn't get me anywhere
If that part is UIToolkit then it should be fairly easy
Only things I've heard is people adding things in a hacky way
Is there a way I can hide this part of the inspector only when I'm viewing the Enemy class in the context of a ScriptableObject? I want to be able to see it when I'm viewing the Enemy class elsewhere but for this specific case it should be hidden as it is a runtime-only class and I use the other Equipment field (at the bottom) when setting up the enemy in ScriptableObject form.
Pretty much if this worked it would be perfect:
DrawPropertiesExcluding(serializedObject, "enemy.equipment");
but it only works for the properties that are direct children of the editor, so I have to do
DrawPropertiesExcluding(serializedObject, "enemy");
and then somehow re-draw the whole enemy class bar the equipment field in it
That's not a default Unity method
It shouldn't be too hard to draw things manually though
Just use an Expander with the IsExpanded property of the Enemy serializedproperty and then just find the childs you want to draw and use propertyfiel
Doesn't PropertyField have very limited uses e.g. it doesn't work on arrays or anything that can be expanded?
No?
You can also extend whatever is implemeting DrawPropertiesExcluding to support child elements
I'm using the newest stable 2020
yeah
Weird
Reason I'm not sure about PropertyField is because this simple rename attribute, for example, doesn't work on arrays (it makes them unexpandable)
EditorGUI.PropertyField(position, property, new GUIContent((attribute as RenameAttribute).DisplayName));
Is there a function to just draw a property the default way and I can loop through the properties and skip the equipment one?
hm, maybe it's arrays that are weird rather than PropertyField
That literally finds the correct property drawer and draws it
If you really want you can check whether it's an array
And do your own array drawer thing
And then use propertyfield for every entry
yeah that's what the examples I saw did, seems like reinventing the wheel but at least it's possible
also is there a way to loop over all child properties of a property? I'm seeing CountInProperty() to get the amount of children but idk how to access them without knowing their names
GetEnumerator?
nevermind, seems like a foreach loop works as with transform as it's enumerable
GetIterator works as well
it seems that iterating over the children of a property breaks FindPropertyRelative
this log:
Debug.Log(enemy.FindPropertyRelative("equipment"));
returns non-null before the foreach, returns null during the foreach, and returns null after the foreach
I'm not sure how supported foreaching over a serializedproperty is
If you do GetIterator you get a new one
And it changes the current instance
that should be good, ty
GetIterator doesn't seem to exist so I'll have to use an enumerator
actually that's the same thing lol
Nice, I got it working, ty 🙂
with the hackiest and most bullshit script for such a simple thing but hey it works, for now
Anyone know any good free and public domain icon packs? Need some for my unity editor tool. Have been able to successfully find some but they're not similar looking (in terms of style) and it looks weird.
I've looked at tango icons but I couldn't see any that I needed (specifically: eraser, paint brush)
@digital spoke there is always https://material.io/resources/icons/?style=baseline
yeah there's a few there that I can't find
does anyone know how to add custom buttons in the toolbar? I could've sworn it was a relatively new feature that unity was talking about, I don't know if it's only available in unity 2019+ or not. googling didn't get me anywhere
@distant atlas NG Hub Free
How can i customize filters through the inspector?
Filter?
Look, I have SO and I need it to have a list of filters. When generating, the generator will check the filters.
For example. Maximum of such rooms 5 minimum 1
smth like
class FilterBase
{
abstract void Check();
}
and in SO i need List<FilterBase>
You should be able to use SerializeReference for polymorphic serialization
Then write your own editor to add/remove elements
Is SerializeReference ready to work with in 2020.1? I tried it, and it only kind of worked half ass. Even the example given on the docs wasn't working properly
Ah ok. I moved to Odin anyway for polymorphic serialization 😄
So I am assigning unity event listeners through the editor
UnityEventTools.RegisterVoidPersistentListener(tracker.CollisionStarted, 2, notifier.DoExtract);
But it isn't using the dynamic version of it.
How do I fix this?
Make sure that the last parameter points to the right DoExtract call
Then what's that other DoExtract?
Oooh it might be due to inheritance then or something.
Its VRTK stuff
No idea where it is coming from xD
Are there overloads?
yes
Is there a way to skip the overload then?
There is only 1 overload
If not, I can work around it
But if there's an overload it doesn't match the signature of the event right?
Its a void event. I think the overloaded is listed as a static one in the picture above and the base one is listed as dynamic
Maybe if I cast object to it's base class and then call DoExtract
Idk what dynamic event data is
Does that let you set parameters manually in the inspector?
Dynamic automatically passes any data to the function specified
Static uses data specified in the inspector
I'm assuming UnityEventTools.AddPersistentListener gives you the same result?
Ye
And that DoExtract method has the correct parameters right?
It doesn't have any parameters
And your event doesn't either?
It has EventData
I can set it to use the dynamic one in the inspector
It is just not possible through code
Due to the way the VRTK code is setup
Virtual Reality ToolKit
Can you show me DoExtract?
Where do I enable it?
Help > About Unity
Then type internal
You'll get some extra goodies
Then set your event to whatever way you want it to be
And enable debug internal mode in your inspector
Now you can expand your persistent calls and view what data actually needs to be set
Take a screenshot or something of that information
And then use SerializedProperties to set the same data for your method call
Ok
the difference between the two is
this
The dymanic one is set to Event Defined
The other one to void
Okay, now you can use serializedproperties to go to that property and set it to Void after you use UnityEventTools.RegisterVoidPersistentListener
UnityEventTools.AddPersistentListener gives you the same result? Apparently it doesn't give same result. Should have double checked.
I have been playing around with this for quite some time, must have confused it
Thank you though!
That's probably what you need to find and set
It's pretty messy but it'll work 😛
Yes
Pretty messy indeed
Works perfect with serializedproperty
Is there a way to update something in a script when another component attached to the same object changes in the editor? OnValidate doesn't seem to work for this purpose
OnValidate on the other component should trigger just fine
Then you can find the other script
well it doesn't do anything when I change the grid component attached to the same object
No no, you need OnValidate on the object that is changing
Not the one you want to change
well then that's impossible since I can't modify unity's source code lol
Ah
You can also use ExecuteInEditMode and manually check if it has changed
Or use a custom editor that does something similar
Or just update it in awake
Just generated a hash for the component I wanted to check at the start of the editor script, and then checked if it had changed, if so, then generate a new hash and redraw
which works fine
Hi all. Im trying to work with both Asmdef and #if platform compilation, and to be honest im not sure how this can be done
A class in my Core.asmdef used to use #if UNITY_EDITOR to access some AbcEditor class.
But now i also made Editor.asmdef and how can my Core classes still "use" AbcEditor stuff? Or this is just impossible to workaround and i need to restructure some stuff?
I'm actually not sure if you're allowed to have a reference in your AsmDef to an editor only AsmDef
I would assume so and it'll just get stripped
Anyone know how of a validation utility method or where to find docs on valid characters for asset names? i.e. they can't contain ? and I assume many other special chars
Yep, it doesnt allow me to do that. That's why i need to restructure things i guess
In that case yeah
The core class was doing some editor stuff bcoz it's trying to do some override inheritance append to VisualElement stuff, which works (until i try to build 🙂 )
Any advice on what should I look for to Draw gizmos on the Game View like what Cinemachine does?
I'm pretty sure they're not gizmos
Just IMGUI
Not sure if there's an official supported way but nowadays you can find all editor windows and then get the rootVisualElement
And just add things using UIToolkit
Resources.FindObjectsOfTypeAll<EditorWindow> probably
Should PropertyDrawers be put in Editor.asmdef?
Bcoz if i do, my Core.asm class that uses the property will complain on build
I have to do this everywhere?
#if UNITY_EDITOR
[MyProperty]
#endif
bool someVar;
You need to put them in either a directory called Editor or in a AsmDef that's marked as editor only
Yes but, the someVar is inside a Core.asmdef
If i put the PropertyDrawer script in Editor, then [MyProperty] wont even be accessible at all from Core
Thats the other way around
And you can use serializedproperty just fine
Editor knows about core, core doesn't know about editor
Core will need reference to Editor (bcoz the PropertyDrawer is defined in Editor)
No?
And [MyProperty] is used somewhere in Core
Core will need reference to Editor (bcoz the PropertyDrawer is defined in Editor)
@real ivy Im saying this if i follow what u said, then this has to be done
So you have an attribute right?
You define that attribute in Core
Then in Editor you have a reference to Core
And your PropertyDrawer with the CustomPropertyDrawer(typeof(MyPropertyAttribute)) as attribute
"Define that attribute in Core" means [MyProperty] bool someVar;, right?
Whatever the definition of MyProperty is
Probably public class MyPropertyAttribute : PropertyAttribute {}
Yes and this is used somewhere in a class in Core
And the definition
[CustomPropertyDrawer(typeof(EnumMaskAttribute))]
public class EnumMaskPropertyDrawer : PropertyDrawer```
If i put this in Editor.asm, then the [EnumMask] can't be used in Core bcoz it doesnt exist
[CustomPropertyDrawer(typeof(EnumMaskAttribute))] so this goes somewhere in Core? Where exactly?
No
Shouldnt those 2 lines be directly together?
Oooh found it
[CustomPropertyDrawer(typeof(EnumMaskAttribute))]
public class EnumMaskPropertyDrawer : PropertyDrawer```
Goes in Editor
Yea this was in the same script. That and i never wrote Attribute stuff from scratch myself..
Cheers thanks
Is there any way to disable a foldout? I have a struct in my class but I don't want it's serialized settings to be hidden/indented when open
GUI.enabled?
no I mean not have it foldout, just always be open with no indent or foldout button
Is there a way to stop my dictionary full of my tiledata stuff getting erased when unity recompiles?
Can't stop, as long as the dictionary is not serializable
Do OnBeforeSerialize/OnAfterDeserialize get called before or after functions like OnEnable()/Awake
Yes
well for reason my dictionary keeps getting cleared even when using the example unity shows on their wiki
public void OnBeforeSerialize()
{
positions.Clear();
data.Clear();
foreach (var kvp in tiles)
{
positions.Add(kvp.Key);
data.Add(kvp.Value);
}
}
public void OnAfterDeserialize()
{
tiles = new Dictionary<Vector3Int, TileData>();
for (int i = 0; i != System.Math.Min(positions.Count, data.Count); i++)
tiles.Add(positions[i], data[i]);
}
https://docs.unity3d.com/ScriptReference/ISerializationCallbackReceiver.html
it's pretty much exactly the same as the example here albeit my variable names are different
TileData is serializable (it's just a class that holds a gameobject value and two int values and has the attribute [System.Serializable] )
and I assume Vector3Int is serializable
Hello. I'd like to make a hue curve editor. Something like a CurveField with an image background (showing the hue image). What would be a good approach for this? It seems like I may have to use an immediate mode element, but I'm not keen on reimplementing the CurveField just to get an image background. Any ideas?
So, like a gradient field, but instead of using a colour picker you only have one axis and it's represented as a curve?
Yes. This image with a curve on top, to reprsent how much of hue will be used.
(except, not using the numbers)
Something like the hue-vs-hue properties in post-processing stack v2.
Maybe I could just go and repurpose them...
I would probably look at how the post processing colour curves have done it
Yes, will do that. Thanks.
Hopefully it's not one of those things that is cheating the assemblies by name to get access to internals ;D
Yep!
https://github.com/azixMcAze/Unity-SerializableDictionary on my question about dictionary serialization, I ended up using this
"Hopefully it's not one of those things that is cheating the assemblies by name to get access to internals ;D"
that gives me PTSD from the time I tried to figure out how the 2D tilemap tool renders the gizmo for grids
does anyone know if ExposedReference<T> is drawn correctly with UIToolkit (UIElements?) PropertyField?
I'm using ExposedReference<T> for a custom ScriptableObject+MonoBehaviour chain (not using Timeline or Playables) and I can't seem to get it working. I'm wondering if that might be the issue
documentation on it seems really sparse 😦
Well @visual stag I got something going using CurveEditor from PPv2! Needs some work, but happy to get this going.
I'm going to use it for light dropoff. It's meant for underwater so want to filter out the red side of the spectrum first.
Not sure if it's the right approach, but it seemed the easiest way to get there!
The CurveEditor was really easy to use, with no dependencies. The pain was the custom pass drawer. It has a bug that causes it to reinstatiate the drawer every refresh and dispose the SerialiedProperty. Made it hard to keep state.
Good to know about the curve editor, I think I've looked for one in the past and it hasn't been fun
struggling to add Undo support for AssetDatabase.RenameAsset - anyone have any pointers? (tried RecordObject & RegisterCompleteObjectUndo)
Don't think it can be handled
^
yikes... ok.. thank you
Yep...
If you do shit, you're on your own 💩
never really noticed before that if you rename an asset (e.g. in the project window) you can't undo it
At least it seems to work for subassets
renaming sub asset is different
Because you just rewrite the ".name"
When renaming an asset, you rewrite the file
The former is on an Object
The latter is on the disk
Does anyone know how can I, given a Textute2D with multiple sprites defined in it, can get an array/list/collect of all the Sprites inside it, with only a reference to a Texture2D object?
@visual stag That is how to load Assets given a path, not a Texture2D
except replace the path with https://docs.unity3d.com/ScriptReference/AssetDatabase.GetAssetPath.html if you don't know it
Ah! That is now the missing piece. GetAssetPath 😛
But LoadAllAssetsAtPath will give me an Object[]. How do I turn it into an Sprite[] ?
Hey @visual stag, do you mind if I DM you later to get some feedback on something I've been working on?
sure
will need to cast them individually, or use a Linq Select
as one of them will be a Texture2D
mmm... well, not too elegant, but at least it works
Thanks
I was hoping for a LoadAllAssetsAtPath<Sprite> but sadly that doesnt work
Anyway, thanks
Actually https://docs.unity3d.com/ScriptReference/AssetDatabase.LoadAllAssetRepresentationsAtPath.html will just return the subassets
same problem though
but at least you skip the texture2D
Not sure what an AssetRepresentation is
anyone knows about Unity.VectorGraphics package ? trying to modify tessellation at runtime but it doesn't seem to make any effects
How would I go about making something similar to Unity's tile palette?
apparently unity used GL methods to draw it (presumably they use the exact same code that they use to draw the 3D grid, which uses GL methods) but I'm not sure how to actually draw GL stuff in a custom inspector
Pretty sure you can just use GL in OnGUI
Is there a way to stop gizmos being 'faded'(?) when they're inside a mesh?
you can see that they become transparent when they're inside another mesh.
anyone know any good guides for PreviewRenderUtility?
completely undocumented (of course it is) and it seems to let you render a scene and seems to be how Unity did the grid palette window for their tilemap tool
but their tilemap tool source code keeps jumping from file to file when using it so I have no idea how they implemented it and I get the worlds worst error
doesn't even give me a trace back to the line in my code that causes it and I don't understand why it can't be created
turns out unity was just having an internal error
cool
Hey guys! Is there a way to make custom attributes interact well with other attributes?
For example, I have a custom attribute called “Lockable”
But if I do:
[Lockable, TextArea]
Public string myField;
Only the Lockable attribute works the TextArea attribute doesn’t make the text field larger. If I do it vis-versa so
[TextArea, Lockable]
Only the TextArea attribute works and the Lockable attribute seems to be ignored
so this is super dumb but how do I set the "scene" panel as the one to be focused on play ?
google is mistaking the scene panel with the actual scenes and i can get no useful info
nvm i found a workaround
Not sure if this is the right channel to ask this, if it's the wrong one, let me know and I'll delete. But for anyone who's tried the GitHub for Unity package (it's in the asset store), how was your luck with it? I was using it with 2018.4.25f1 (need to use the older Unity for Create With Code).
I was really looking forward to using it, but it made my Unity so unstable that I've had to export the project I'm working on, take out the github plugin, and re-import the project. It seems like it causes Unity to freeze almost every time I tab back into it while coding :/
Though, it could be because I had previously hooked that project up with Collab before I found the github plugin. I dunno though.
why can't we use Sprite.OverrideGeometry inside coroutines ?
Any body has a help channel?
Any useful auto complete/intellisense for vs code?
So TIL that [SerializeField] protected doesn't get saved. Only public do
Or i learnt wrong.. (This is in an abstract base class btw)
Why would you make a protected field anyways, accessing should go through properties imo
public fields serialize by default (if they are of a serializable type)
[SerializeField] is for non-public fields you want serialized.
It will work on abstract base types
I'm having some issues lately with 2020, specifically after working on a project for a while, the project totally breaks, like some kind of dependency somewhere becomes corrupted and my scene and game views are grayed out, after restarting the editor it informs me that some dependencies need to update, and upon loading my render pipeline assets are no long assigned in my project settings, and there are a metric ton of compilation errors when there weren't any previously. Not sure if this really belongs here but chat is moving so quickly in general code
If you have a lot of custom editors that could explain it but I highly doubt it
You're probably best of trying the forums or the bug reporter
public fields serialize by default (if they are of a serializable type)
[SerializeField] is for non-public fields you want serialized.
It will work on abstract base types
@craggy kite
But but but, it's not for me...
A bit more context: i'm doing sub assets SO. This sub asset has reference to the parent SO asset. Everything is fine until i close editor, open again. Reference gone
Only when i change from [SerializeField] protected to public that it saves properly
Can I describe a custom inspector for each of my own type and then call this inspector to draw in another place? to write an inspector for one type once and then combine them
If you make a propertydrawer for that type then it should just show up when you use EditorGUI.PropertyDrawer
Custom Editors can also be created using Editor.CreateEditor
Hi guys !
Does anyone have some nice ressources to get me started in editor scripting?
Need some help toggling visibility of inspector fields when choosing an enum option
First time working with Editor scripts so im not sure how i should approach this
Need some help toggling visibility of inspector fields when choosing an enum option
@naive thorn https://gist.github.com/Mikilo/8cb969a50a1eac87c9500d4f9f181324
how would I go about using this?
[ShowIf(''targetFieldName'', Op.Equals, true)]
Replace 'true' with whatever value you need
Guys anybody tried to register a ScriptableObject as in the Undo ? With me it's not working.
I have something like this gist:
https://gist.github.com/marcoswicket/b1e19c1070ceac309caae48a7adb3525
But for some reason on Ctrl+Z the Scriptable doesn't undo it's operations.
@onyx harness hope you dont mind I ask but once I get the script in what do I do from there? I cant access the property drawer atm
from the script I want to use it in
ShowIfAttribute.cs must be in a non-Editor folder.
ShowIfDrawer.cs in an Editor folder
And in your code, add the import line NGTools
aight
Or change the name space to whatever you want
Guys anybody tried to register a ScriptableObject as in the
Undo? With me it's not working.
I have something like this gist:
https://gist.github.com/marcoswicket/b1e19c1070ceac309caae48a7adb3525But for some reason on
Ctrl+Zthe Scriptable doesn't undo it's operation.
@whole steppe because dictionary is non-serializable
@whole steppe because dictionary is non-serializable
@onyx harness I thought about that being the reason. Do you know how any workaround for this?
works perfectly
@naive thorn use the MultiOp if you want to compare with more than one value
@onyx harness I thought about that being the reason. Do you know how any workaround for this?
@whole steppe Google serializable dictionary Unity
@whole steppe Google serializable dictionary Unity
@onyx harness Will do, thank you.
Does anybody know how I can update a Material that has been changed via custom inspector? I am updating a blend value in EditorApplication.update but it only sporadically changes
Are you using serializedproperties or registering it with undo?
no I am using the direct approach:
this.TargetMaterial.SetFloat(Blend1, t);
Define: sporadically changes
it does not blend smoothly but jumps in different time intervals. I am also changing the textures that are blended though. so it could be that it does not update the blend values at all and only updates when I switch textures
I am blending between a number of frames based on the current time. This is currently blending between frame 1 and 2 at 0.82 blend value.
If I press play the slider and the values in the inspector smoothly interpolate but the blend animation of the material seems to jump from frame to frame
🤔 Well thats interesting. If I set the _Blend variable up as a property in the Shader it works:
_Blend ("Blend", Range(0,1)) = 0
But I would like to avoid this as this will always set the material dirty and produce version control conflicts.
So I guess my problem is how to update a shader variable that is not a property
I removed the shader property and it still works
@thin fossil No memes, please
ok, sry
Is it possible to make a custom shading mode for the editor that hides all of the objects in the scene view so you can render just handles instead
Sort of like wireframe mode but rendering with handles and Gizmos
Should I just disable the mesh renderers?
IIRC there's some way to override the render pass
That's what I was thinking about
Not sure if that works for you though
The only reason I want to is because the edges of meshes are nearly invisible in ortho/wireframe mode against the grid
not sure if timeline belongs here but:
Any way I can add names to these signal tracks? so I can see what they are for at a glance?
MonoBehaviour returns their GameObject's name
To toy with real MB's name you need to work around a little bit with SerializedObject
Does anyone know how to solve this weird issue with PrefabUtility.InstantiatePrefab? It seems it cannot instantiate a prefab via using a prefab to get itself
if that makes any sense at all
like, if I had a cube prefab and wanted to use instantiateprefab for that same prefab using
GameObject newCube = PrefabUtility.InstantiatePrefab(cubePrefab) as GameObject;
newCube would return null
wait what ide do yall use
For C#? VS
Rider
Visual Studio myself, its the best IDE available imo, and its free
Does no one know how to solve my problem?
https://hatebin.com/oewusjokfi here's more code.
That's already better
Now, are you even sure newTile is a prefab?
What happens if you print it to the console using Debug.Log(newTile, newTile) and click on it?
Does it ping the Hierarchy or the Project?
Yes.
value is set correctly in the prefab itself
however when it's instantiated, it's replaced for no reason (I never write to the reference. I only read from it)
Define "instantiated" please
however when it's instantiated, it's replaced for no reason (I never write to the reference. I only read from it)
@digital spoke I would say because the ref is itself, so when you place it on the scene, the ref remains itself
so what's an easy way to fix that?
the only thing I can think of is storing all of the autotiling rules in a scriptable object?
I would say, get the prefab from the GameObject
Then instantiate it again from the prefab, not the Gameobject
There is API for that
GameObject tile = PrefabUtility.InstantiatePrefab(PrefabUtility.GetPrefabInstanceHandle(newTile)) as GameObject; // Returns null if newTile is a scene instance of the prefab we're trying to instantiate from it.
``` Like this?
Just prints this. Doesn't highlight anything when selected.
You are not using the right API then
seems that GetCorrespondingObjectFromOriginalSource might've worked? Highlights the correct object.
Should do the job
well apart from the fact it seems to erase all references to gameobjects when it's instantiated
GameObject basePrefab = PrefabUtility.GetCorrespondingObjectFromOriginalSource(newTile);
Debug.Log(basePrefab, basePrefab); //Confirms it's the actual prefab, rather than the scene instance of it.
GameObject tile = PrefabUtility.InstantiatePrefab(basePrefab) as GameObject;
seems to erase all references from the entire script
this is what it should look like
seems like this is just a thing that happens
I just feel that your design is fundamentally wrong
i know
but i need to use prefabs otherwise the whole purpose of this tool becomes pointless. I could just switch prefabs with meshes and just change the mesh of objects but prefabs let me modify tiles and see them change on the map
and no matter how I try to make the autotiling system work with prefabs, at some point I have to instantiate it, causing the problem.
hey folks, can anyone help me out please?
I'm trying to figure out how to show certain editor GUI buttons to be greyed out like this
ah crap, thanks
my setup is dead simple. but where would the .enabled go in this context?
https://pastebin.pl/view/68787c8c
Pastebin.pl is a website where you can store code/text online for a set period of time and share to anybody on earth
ahhh I see OK. so it's kind of like opening and closing tags in HTML or something like that?
perfect! thank you @waxen sandal 🙂
problem with references becoming null seems to be due to the fact the script on the prefab is technically referencing itself?
if I set Tile to be a different prefab it doesn't become null
which just means I've just gone in a massive circle pretty much
(also keep in mind I never write or change Tile in any way from a script. It's only read from)
which just means I've just gone in a massive circle pretty much
@digital spoke Which is maybe why your design is flawed
well if you can give me a better design im all ears
does anyone know lots about having nested serializedObject.Update() and ApplyModifiedProperties() ? I've got a case where it kinda just seems to, not work
I have some properties where I need to handle changed values in a specific way on a per-object basis (rather than using the serializedObject to modify/set all selected objects properties to the same value)
long story short - I have a field for a position, and another field for space. when switching space from world to local, or vice versa, I want to compensate for this so that the coordinates remain in the same place
so basically - on edit space -> update coordinates for each selected thing (if it changed space)
normally I could just set the property value, but in this case it could be different for all the different objects
I thought iterating through all the serialized objects of the individual types, assigning the new coordinates if needed, and then applying it, would work
but it looks like the values never actually change - they are changed on the line right after I assign, but, when all is said and done the values are unchanged
@blissful burrow are you trying to modify the serializedObject and the related Unity.Object in the same update as it were?
I'm only touching serialized properties! so probably only the serialized side of things
I iterate through all selected objects, get their serialized object, and serialized properties, and modify them if needed
ah.. so just because you mentioned .Update() and in case you didn't realise (I didn't at first), it updates the serialized object representation from the Object so you just might not need that in your case? Sorry if this is obvious stuff you know already.
but I suspect it might be an issue of me modifying the "master" serialized object, that like, targets multiple objects with a single serialized object outside of the scope of those
@digital spoke Yesterday you pointed to a link where the guy said a fine solution, go through a SO
@split bridge ah this is all in a custom editor
sure
basically this is my structure:
OnInspectorGUI{
so.Update();
so.propertyField A
so.propertyField B
// etc
if field A changed {
foreach( targeted serialized object tso ){
tso.Update();
tso.property = new value
tso.ApplyModified();
}
}
so.ApplyModified();
}
I suspect the issue might be that the last so.ApplyModified overrides all the individually edited ones maybe?
basically I don't think you need to call .Update unless your underlying object that your so represents has changed via means other than you changing so values.. does that make sense?
yeah might be true! not sure if that's the issue though
var bob;
bob.property = 10;
SerializedObject bobSO = new SerializedObject(bob);
bobSO.property = new value
bobSO.Update() // bobSO.property now updated value to be 10 again
yea, totally might not be your issue.. but if those are nested, I wonder
Wouldn't calling Update between serialization overwrite your changes ? What happens if you just apply the property once at the end of all the operation ? Without Update or the applyproperty in the loop. If the changes are dependent on each other you might have to just manipulate the object directly (not fun)
removing the last so.ApplyModified makes that part work, testing removing the nested ones now
:/ I think you want to keep the ApplyModified and remove the .Update?
can we modify the content of this window?
@split bridge yeah of course, just wanted to see if the specific parts that had the nesting would work if I removed it
which it does
so it seems like the last applyModified is overwriting whatever the nested stuff did
removing the inner update/apply makes it not work either, the data doesn't update
Could you put the actual customInspector in a pastebin ?
Just the inspector stuff, the rest shouldn't matter that much (it's mostly space transformations right ?)
and lots of other fields but
(Also we're not judging :p, the unity inspector stuff is hot garbage no matter what)
speak for yourself @graceful gorge 😄 jks
this is the inner function for the space field: https://pastebin.com/sAp0efGi
Wait do some field serialize and other don't ?
it's more like, my act of wanting to change some of the selected objects fields depending on if they were switched from world to local or local to world, doesn't seem to save in the end
the other things serialize fine, where I use the usual property fields and whatnot
@blissful burrow
You should call so.Update always, the issue is calling so.ApplyModified() without checking if there was changes at all:
OnInspectorGUI{
so.Update();
using (var soScope = new EditorGUI.ChangeCheckScope()) // this
{
so.propertyField A
so.propertyField B
// etc
if field A changed {
foreach( targeted serialized object tso ){
tso.Update();
using (var tsoScope = new EditorGUI.ChangeCheckScope()) // this
{
tso.property = new value
if (tsoScope.changed) // this
tso.ApplyModified();
}
}
}
if (soScope.changed) // this
so.ApplyModified();
}
}
on a high level, this is what I want to do:
if space changed
foreach selected object
update coordinates
you don't have to check for changes when applying it
if you don't, you will just apply the last detected values for all instances, but you want to each instance to keep the value unless there was a modification that affect all at once
so, if you don't want multi-edit support, you don't need to check, but for multi-edit you always want to check
to some extent it's both - you change the space property on all selected objects, which I do want to update on all of them, but the coordinate override is only needed on the ones that actually had it changed
(I've never had issues with multiselection using ApplyModifiedProperties without checking for changes before)
to some extent it's both - you change the space property on all selected objects, which I do want to update on all of them, but the coordinate override is only needed on the ones that actually had it changed
@blissful burrow this is exactly what will happen if you use the ChangeCheckScope
so, are you saying it should work if I just use change checking for the outer scope?
if I got your issue right, yes
that broke everything instead, oh no
no values update now, even the ones that used to work that are unrelated to the nested shenanigans
ah, just couldnt find what it was called I suppose
actually wait might be my fault
yeah the not working at all was my fault
but having the change check in the outer scope (and the inner scope that I had before) made no difference, it's broken in the same way
bleh, why did this turn out so complex
strong "I just want to..." energy
That's a lot of editor scripting in my experience
Especially package manager and uitoolkit
I dipped my toes in the package manager once and then now I'm avoiding it like the plague
If you don't care about Undo, just play with Object directly
I do care a lot about undo
The api to install and stuff is atrocious
and I know I can directly modify objects
They pretend it's async but it's not
Queueing 2 actions at the same time has no deterministic outcome
There is no event when it's completed
So you have to poll it in update
To a property that calls the native later to check whether its done
Native layer
alright I guess I might have to go the Undo.RecordObject route
with my autotiling system, it seems storing the autotile rule data on a scriptable object instead of storing directly on the script fixes the problem of references becoming null
it seems that it's because the script on the prefab is referencing that prefab (self-reference) which might be causing unity to not understand what to do
@blissful burrow No precise idea what is causing this, and no workaround that would keep undo. Can the "fill" objects be set as dirty somehow ?
mmmaybe
@blissful burrow
You should call so.Update always, the issue is calling so.ApplyModified() without checking if there was changes at all:
OnInspectorGUI{
so.Update();
using (var soScope = new EditorGUI.ChangeCheckScope()) // this
{
so.propertyField A
if field A changed {
foreach( targeted serialized object tso ){
using (var tsoScope = new EditorGUI.ChangeCheckScope()) // this
{
tso.property = new value
if (tsoScope.changed) // this
tso.ApplyModified();
}
}
}
if (soScope.changed) so.Apply // this
@regal jasper I would put the 2nd Apply() before the fieldA changed stuff.
yeah, I think it might work if I do that
but that gets complicated for, reasons~
(my code has some layers)
@onyx harness true, didn't noticed that
the reason things get complicated is that the second so.Apply is a function in the base type that does more than just that, it has to update things (mesh data, material properties etc) depending on what you changed, so this means I'd have to be able to introduce exceptions to how it works
I really wish the serialized object that the editor targets would also detect changes of the individual serialized objects you had selected
anyway record object time~
Good luck :/
thanks anyway all!
I really wish the serialized object that the editor targets would also detect changes of the individual serialized objects you had selected
We all wished a lot of things about Unity's way of signalling events...
oh gosh
it works now but I feel like it shouldn't
this is really cursed
I basically wrapped every individual serialized property field in their own Update()/Apply() pair
I really feel going through Objects and handle Undo "manually" was much quicker and less headache in your case
except then the new headache is the fact that it has to handle objects of different types
so then I'd need to use reflection and/or restructure all my stuff
but it works now so yay!

Don't you have to do that anyway with SO if you change any structure?
what do you mean by change structure?
objects of different types
as long as the serialized properties use the same path it's fine
which they would
Basically, the same with Reflection, just the way of doing diverges
well, the way of doing it is done by Unity instead of me with reflection
But yeah, it works, that's the main point 🙂
I think the reason it works now is that the parent serialized object has its properties applied before the nested structure shenanigans happen
so the outer object won't touch those inner ones
Basically what I stated here?
I would put the 2nd Apply() before the fieldA changed stuff.
yeah sort of, except the second apply is still there, haha
(just moving it gets complicated for reasons mentioned above)
what a fill~ things work
yeah
Is there a specific reason to use a CustomEditor over PropertyDrawer for your "Fill square"?
I generally never use property drawers (in custom editors)! so, preference I suppose
Fair enough
best options for serializing a static hash set of hashes and ScriptableObjects? I'm thinking another SO but just wondered if a) I was missing something obvious and b) if there were any new serialization related things for statics
ScriptableSingleton?
ha, I learned of their existence like a week ago and already forgot.. thank you, let me check, that might be perfect
on a related note.. how to deal with relative paths to uss, uxml (AssetDatabase.LoadAssetAtPath) and e.g. this theoretical ScriptableSingleton - I can only seem to make them project relative not relative to the folder the script is in which is useless? especially for an asset store package that you'd want to place anywhere? I assume I'm being dumb.
I wouldn't know
Need help creating a tool system for my 3D tilemap. Currently, there's only one tool, the paint brush tool. I want to create an API that lets me create new tools with custom functions (eg: rectangle tool).
What's the best way of going about creating a system like this?
public abstract class Tool
{
public Texture2D icon;
public abstract void Paint(GameObject tile, Material[] materials,Bounds paintArea);
}
I was thinking of something like this. An abstract tool class that I can inherit when creating a new tool.
And is there AnimationCurve in UIE?
I realised that ScriptableSingletons are editor-only I believe but I need a runtime reference. Anyone have any other suggestions? (https://discordapp.com/channels/489222168727519232/533353544846147585/740640170243653752) Addressables feels like overkill? (but I know very little about them)
Hi, I want to replace the behaviour of ctrl+d on a gameobject. I wrote my own custom method for that(When I duplicate a gameobject I like having something1, something2,. instead of something(1), and something(2),). I have 3 issues with that :
- If I ctrl+d a prefab it does not stay a prefab and I don't really know
how to create a prefab(Instantiate() does not work for this) - If I hit ctrl+d on a gameobject multiple times(ex : something) I will
only get something1. I would need a counter to increment but it is a static function,
and c# does not support static vars in a static function.
cs [MenuItem("GameObject/Duplicate %d", false, priority = -100)] private static void DuplicateGameObject() { Debug.Log("Ctrl D pressed on a GameObject"); foreach (GameObject gameObject in Selection.gameObjects) { string name = gameObject.name; int number = 0,i = name.Length - 1; while (i >= 0) { bool isNumeric = int.TryParse(name.Substring(i), out var numberTest); if (!isNumeric) break; number = numberTest; i--; } number++; string duplicatedName = name.Substring(0,i + 1) + number; Transform parent = gameObject.transform.parent; GameObject duplicatedGameObject = Instantiate(gameObject, parent, true); duplicatedGameObject.name = duplicatedName; } }
@flint vapor just so you're aware, as of 2020.1 Unity finally added preferences for numbering schemes here:
they still don't have your preference in there though (only (1), .1 or _1)
I don't know if it might be easier to detect a duplicated object and remove the brackets from the name? https://answers.unity.com/questions/483434/how-to-call-a-method-when-a-gameobject-has-been-du.html
I don't know if it might be easier to detect a duplicated object and remove the brackets from the name? https://answers.unity.com/questions/483434/how-to-call-a-method-when-a-gameobject-has-been-du.html
@split bridge Yes that may be a good thing to do
But this means that I need to have a DuplicateCatcher on every single gameobject
Questions about class extenstions should be posed here or over at #💻┃code-beginner ?
Idk :), I was thinking of extending Transform component to listen to the duplicated gameobject
@flint vapor it was just a first google result - you could use something like EditorApplication.hierarchyWindowImteOnGUI according to my second google (https://answers.unity.com/questions/1274030/unity-duplicate-event.html) if it's that important to you to not have an underscore 🙂
@flint vapor it was just a first google result - you could use something like
EditorApplication.hierarchyWindowImteOnGUIaccording to my second google (https://answers.unity.com/questions/1274030/unity-duplicate-event.html) if it's that important to you to not have an underscore 🙂
@split bridge Ok, already have that event in code, ok I can use that, thank you very much! It is kinda important, I like having things nice and clean and when I duplicate a bot1(1) and is bot1(1)(1) I just can't stand it looking so ugly 🙂
haha ok np.. good luck 👍
Wait is this channel about how Unity can improve it's editor or am i just dumb?
Man, missed opportunity on that numbering scheme thing
They should have given you a string format setup
{0} {1}
How can I get a value from SettingsProvider from another script? I have a color value in my custom settings and I want to set it to certain color values in other scripts.
it doesn't require an explanation, you could use a tokenizing text box and let the user push around the insertion tokens
if you only did a string it does require some explanation, but a tooltip explanation should be enough for anyone using something as complex as unity, even as a non programmer
https://github.com/BradFitz66/Archi-demo demo release of my tilemap tool
what does 3d mean
is it rules based?
or can you place any tile on any other tile in 3d space
How to edit a custom serializable class that is not GameObject and it's not going be added to the scene? I just want to edit values using inspector and instantiate it as a private field in my code.
How to get name of serializedObject?
anybody having issues with UIBuilder not saving changes to USS classes?
How to get name of serializedObject?
@whole steppe.name
Hello 🙂 , I'm looking for some resources on how to make scene gizmos/handles moveable. Let's say I have a sphere which is drawn like Gizmos.DrawSphere() or a rectangle drawn with Handles.DrawSolidRectangleWithOutline I now want to be able to drag that sphere or rectangle around with the normal transform gizmos for example, and get the new position of the gizmo as output. Could anyone possibly point me in the right direction or to some resources? Maybe it's just me but I can't find much regrading this...
Thank you!
pretty sure you want Handles, not Gizmos @lilac silo
DrawSphere isnt manipulatable afaik
That's fine. I mostly need it for moving a rectangle around, which is drawn with handles
interestingly enough there is nothing about moving them on the documentation 🤔
That's exactly what I'm looking for I think @steady crest !
Wrong person?
I'll try it out thank you 🙂
@onyx harness serializedObject doesn't have such member
it is the member of Editor class
Wrong person?
@waxen sandal Oops.... yes 😄
haha
@onyx harness serializedObject doesn't have such member
@whole steppeserializedObject.targetObject.namethis one?
What transform?
of teh object
targetObject is the "target Object"
I need position to draw a label at the object
If your target is a GameObject, cast it
Of course
How to check it?
targetObject can be of any Object
serializedObject.targetObject.GetType()?
if (serializedObject.targetObject is GameObject) ?
ou
I mean, you usually make the SO so you know what type it is
Or you have a customeditor/propertydrawer for a specific type
I just found some useful piece of code that works
I dunno about editor extensions and stuff
I'm new to Unity and C#
Be brave and good luck
it's harder that it looks
Not really, you just don't know the keywords to search for, and not used to it
But you are at the good place to ask
no, it doesn't work
Should really just show more code
Because obejct has derived class from Monobehavior
do you have some "only for this chat is right" pastebin or something?
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.
tell us, where is the line that is not doing its expected job?
26
You're making a custom editor for [CustomEditor(typeof(MonoBehaviour), true)]
Which means that your targetObject will also be of type MonoBehaviour
It is also not really a good idea to make an editor for MonoBehaviour since you'll have to replicate the behaviour from Unity
ok, how to add handles for Vector3 members?
before I use obejcts (they have these arrows for moving around the editor), but it's kinda heavy for just vector3
so I found this
and it works
hm, I changed from Go to MB and it works
Do buttons and stuff still have their custom UI?
how do you guys making games without using such simple stuff?
what buttons?
My UI isn't custom
I mean the canvas UI Button
There's a bunch of components that have custom editors that might be overriden by your editor now
That's not what I mean
how do i fix this?