#↕️┃editor-extensions
1 messages · Page 48 of 1
Hey! Is there a Editor specific channel as well, that is not for extensions?
@frozen bough Hard to know what your question is about exactly, but general questions about editor functionality if not specific to any channel just go to #💻┃unity-talk
Yeah it was editor specific like if there was a possibility to bucket fill a large area with boxes. For example creating a 100x100 of 1x1 ground objects
copy paste and duplicates is ofc a possibility, just wanted to check if there was a quicker way for future reference
There isn't any builtin duplication functions sadly
ah, good old copy paste it is then 🙂 thanks
I'm working on a custom editor window, and I have a reference to a class. Right now I have some of its values as a textfield, intfield, etc. Is there an easy way to wrap up the whole class and use the typical kind of inspector property drawer?
new SerializedObject(your_class_instance)
you could also instantiate new Editor for it, and use it as a sub-group for it
EditorGUI.PropertyField
if (editor != null)
{
var serializedObject = editor.serializedObject;
serializedObject.Update();
var prop = serializedObject.GetIterator();
prop.NextVisible(true);
while (prop.NextVisible(true))
{
position.height = EditorGUI.GetPropertyHeight(prop);
EditorGUI.PropertyField(position, prop);
position.y += EditorGUI.GetPropertyHeight(prop);
}
if (GUI.changed) serializedObject.ApplyModifiedProperties();
}```
the only thing, is that your_object_instance needs to be a UnityEngine.Object (so ScriptableObject or MB)
its not
Use a propertyfield then
@waxen sandal property field only when the source is a SerializedObject. it is not in that case.
@full flax r u using .NET 4.5 ?
He must be caching the object somewhere so he can just make a SO from the parent
And then use findproperty
Or the target's parent is a Unity Object
I've assumed like a seiralize to json/xml/ new() instance, but yeh
right now I'm saving/loading from a json 🤔
great. it is absolutely doable then.
Yeah, but i'' give u a trick.
hmm thanks I'll try to figure it out 🙂
class MyWrapperClass : ScriptableObject {
public TYPE instance;
}
void OnGui() {
var wrapper = ScriptableObject.CreateInstance<MyWrapperClass>();
wrapper.hideFlags = HideFlags.HideAndDontSave;
wrapper.instance = LoadFomJson<TYPE>(json);
// HERE goes my editor instantiating code
if(GUI.changed)
{
// save json
}
}
}```
But that ofc is limited to what Unity can actually serialize. I don't use that approach in my drawers inside custom windows. I just have a lot of utility methods that utilize EditorGUI.StringField etc. etc. I think it's a matter of needs and prefference
🙂
@chrome geyser The issue is not in OnGUI. It is in GetPropertyHeight()
I overrided that method just to log its return value, and it's not even called frequently enough to match the rate of flicker I'm seeing
it's pretty consistently 16
the flicker stopped happening after literally no change though, so if it comes back I'll mess with this again
You need to return the correct height there
It might be trying to figure out the height themselves
if i can recreate the issue I'll mess with that method
Does anyone know of any tuts or references about adding to the Edit>Preferences menu?
specifically #4
using UnityEngine;
using UnityEditor;
public class MenuItems
{
[MenuItem("Tools/Clear PlayerPrefs")]
private static void NewMenuOption()
{
PlayerPrefs.DeleteAll();
}
}
Thanks, I am not looking for general editor scripting info but rather SettingProvider info.
Found the docs
ah, sorry
Trying to use TextureImporter and I'm getting an error message saying that the texture could not be created upon calling SaveandReimport(). Anyone come across this before?
TextureImporterSettings settings = new TextureImporterSettings();
textureImporter.maxTextureSize = 256;
settings.readable = true;
textureImporter.SetTextureSettings(settings);
EditorUtility.SetDirty(textureImporter);
textureImporter.SaveAndReimport();```
Edit: for some reason setting the readable flag in the settings would not work, but setting textureImporter.isReadable = true is fine
How would I listen for the event that happens when a UIElements Foldout control expands or collapses?
In my case, I want to change the border color depending on whether a Foldout is opened or closed.
In a framework like WinForms or WPF, it would be something like: myFoldout.Expanded += (MyEventHandler);
I'm looking for the equivalent in UIElements.
Answering my own question, if I query for the internal Toggle control of the Foldout, and then do:
internalToggle.RegisterCallback<ChangeEvent<bool>>(...) I can effectively react to the expanded/collapsed state of the Foldout.
I want to replace the toggle button with something that indicates uniform scaling, or shared values, does unity happen to have the common "Linked" button?
Example:
does anyone know of a way to do stuff before the Editor recompiles your scripts? i'm aware of DidReloadScripts but i need to dispose some stuff before it happens rather than after.
thnx!
is it possible to create our own [Header("title")] ?
Sure?
how ?
@waxen sandal nice !
Would this be the place to ask about a custom asset importer?
it's not mine, it's the UniVRM project on github and the new Asset Pipeline v2 is breaking it
Does anyone know how to create a field that generates an OnClick handler like this?
(Screenshot from UI.Button inspector)
Ah, got it. You can create a field of type Button.ButtonClickedEvent
you have to declare your own UnityEvent type
Oh. I can't just recycle that one?
if you want to pass data through you need make a whole class because Unity doesn't serialize generic classes
Well, you can...
One of those not great coding practices
Thanks bud
it's usually just as easy as doing something like:
[Serializable] public class MyUnityEventWithFloat : UnityEvent<float> {}```
I just realized I don't need it at all because I can just put multiple handlers on my button instead of chaining EventType.Invoke
But that's good to know, I'm sure I'll run into a use case in no time.
has unity's layout location changed from ~/Library/Preferences/Unity/Editor-VERSION.x/Layouts/ ?
is it possible to open editor window from a non editor script ?
i was thinking to create some sort of editor static listener that will check for events from outside a non editor class
found [ InitializeOnLoad ] gonna try that one
got it:
[InitializeOnLoad]
class DrawGraphHook
{
static DrawGraphHook () { EditorApplication.update += Update; }
static void Update ()
{
// non editor class
DrawGraph.onInput += delegate
{
if( GraphWindow.instance == null ) GraphWindow.OpenWindow();
};
}
}
Hey guys, I am building an Editor Window which most of elements are scriptableObjects. I am callin Init method to initialize OnDeleteClicked calllback to register my action. It works as intended. After restart of Unity Editor, my callbacks doesn't work.
Does anyone know a work around or solution to that?
All created scriptableObjects are added to an object as assets btw.
they hold all their data, but callbacks.
not sure about scriptable object callbacks, maybe look into EditorPrefs ?
is your OnDeleteClicked variable is a UnityEvent ?
no, cs Action<Node> OnDeleteClicked;
is your Node serializable ?
isn't scriptableObject serializable by default?
AFAIK should be, assuming Node extends ScriptableObject
nope that doesn't do the thing either
Actions can't be serialized
You have to use UnityEvents
It doesn't matter if you put a serializable attribhute on it
It isn't magic
@waxen sandal do you remember the way to add menu item to window ( Close Tab, Add Tab ) ?
nvm found it : https://docs.unity3d.com/ScriptReference/IHasCustomMenu.html
heya, I am trying to add a button to a custom inspector [CustomEditor(typeof(LogicGraph))] like this.
It's a scriptable object which I want to add a button.
How can I obtain that scriptable object in that CustomEditor script?
I need to pass it as a parameter.
oh (target)
found it
The UIElements Debugger is very helpful, and lists the source of a particular style setting, for example specifying "unity stylesheet" or "inline". But it often just reads "11". What does this mean?
I'm assuming something like default value
But you might be able to find out by decompiling
That seems extreme, but at the same time, could be very useful. 🙂
IT could very well be the default value of the text field that's supposed to say where it came from but they don't know so they didn't override it
Probably just a bug. You shouldn't need to decompile. You should be able to find the relevant code somewhere in https://github.com/Unity-Technologies/UnityCsReference
Cool, okay, I am actually seeing now that it's likely coming from one of my own StyleSheets, and it's just not listed properly.
I want to set the minimum height of a UIElements TextField to the size actually taken up by its contents. How would I even approach this?
Auto-sizing doesn't appear to work, so the only thing I can see to resort to is measuring the actual size taken up and manually setting the height (or minHeight) to that value.
So... my current hacktastic solution (I'm finding too many of these) is to set the flexShrink property of the surrounding elements of this TextField to something really huge.
After pushing my stuff to github and pulling it on my laptop I can't use the "Attach to Unity" and it's also not showing me the auto completions how do I fix this?
Is this the right channel for this?
No it's more #💻┃code-beginner , but make sure your IDE is assigned in Edit/Preferences/External Tools/External Script Editor
To anyone who remembers my question from a week ago or so, I ended up using xNode. https://assetstore.unity.com/packages/tools/visual-scripting/xnode-104276
using this is way better than try to code an editor myself. it's extendable and free so I don't have to deal with a subpar solution, but is coded way better than anything I could make myself at my current skill level
I do have one quick question to anyone who might be able to shed some knowledge on serializedproperties though, but it's not integral to getting the editor to work, so only if you're bored or something I guess
I have a hopefully very simple question. Every time I open a script, it opens in a new VS window. how do i get this to stop?
This may or may not help https://answers.unity.com/questions/1078859/unity-keeps-opening-new-instances-of-microsoft-vis.html
Already answered in #💻┃code-beginner . Was posted twice
I think you're better off in #💻┃unity-talk or #💻┃code-beginner
ok thx
Is there a reason that a private list of a MonoBehavior would not show up when trying to get it with FindProperty?
Is it marked with the SerializeField attribute?
No... and now that you say that I realize why it isn't working and that I can just use reflection... sorry and thank 😛
No worries, brain farts happen
I am trying to figure out how to do a popup field, but without it showing the text of what has been selected. GenericMenu works, but there is no way to update if an item is selected without rebuilding the whole thing. EditorGUILayout.Popup, would work, but it also displays the text of what ever is currently selected. Any ideas?
Not sure why you want that but you can make a custom editor windows then show it as a popup
The reason I want it is because I am want the popup like what the search field for the sceneview/hierarchy has.
Anyone know of a way to make a textmesh pro button text decide the size of the button object?
I tried adding a content size fitter to the text object inside the Text object, but that only increased the size of the text itself and not the background located in the Button object.
You could try passing -1 as the selectedIndex; with any luck that'll have no selection. Then you just change the values in the array whenever a new popup selection is made
Thanks for the suggestion @cedar reef. I ended up getting it by overlaying a button over the search section that would just use a GenericMenu and rebuild it each time an item is selected.
I have a script that executed in edit mode and changed a property value based on another, but the changed property doesn't persist in play mode. What am I missing?
@odd vessel it depends on what you are changing. It may not be serialized.
I am been doing some work today adding debug/usability things to 'my' GameEvent system. Each time an event is raised (triggered), it logs to the events inspector. I can search it by method name that raised the event or by the class name, or both of course.
And clicking on an item takes me to the line in the script that it was raised at. Like how the console does with Debug.Log.
It is pretty simple, but it feels really nice to use, and looks pretty nice I think. And I am proud of it so I wanted to share it. 😛
@gloomy chasm What do you mean? it's just an integer field
I mean, what object is the field on. Like a Mono, Editor, EditorWindow, etc.
Does anyone know how to display multiple monobehaviours as one in the inspector? 🤔
[ISSUE SOLVED IGNORE] I am trying to get key events from an editor window. But I want scene key events, because I need them to work, even if the editor window is not in focus.
[MenuItem("Window/My Window")]
static void Init()
{
MyWindow window = (MyWindow) EditorWindow.GetWindow(typeof(MyWindow));
window.Show();
SceneView.onSceneGUIDelegate += OnSceneGUI;
}
private void OnDisable()
{
SceneView.onSceneGUIDelegate -= OnSceneGUI;
}
private static void OnSceneGUI(SceneView sceneView)
{
Debug.Log("On scene gui");
if (Event.current.keyCode == KeyCode.Tab)
{
Debug.Log("tab pressed!");
// Causes repaint & accepts event has been handled
Event.current.Use();
}
}
My understanding is this should work, but it doesnt seem to.
They key press is probably being swallowed by something else
Interesting. Any way to find out? I thought that if two things are listening to key press, both would fire?'
Or if there maybe is a way to take priority?
You can try some other key
Ok, ill try J. It seems random and I dont think it does anything
No change.
Add this just to make sure I am not going crazy, and it works (but only in focus of course)
private void OnGUI()
{
if (Event.current.keyCode == KeyCode.J)
{
Debug.Log("J key on gui down");
}
}
Googling some more :/
Yeah, I am just an idiot.
It is working. Nevermind 😛
Had too many windows open, and none of them were the scene view ( had game view open only).
That made me laugh way too hard, because that has happened to me too 
@candid briar you can do CreateEditor<MyClass>().OnInspectorGUI(); to show a class as you would see it in the inspector.
As far as making it so you can't see a difference between Components in the inspector. The best I can think of is to have a component that sets a hid flag on any/specific scripts so they don't show in the inspector, then draw their Inspector in it's own.
Ah there is a flag for hiding components in the inspector?
Yep hideFlags = HideFlags.HideInInspector;
That might do the trick!
Make sure to handle deleting, otherwise you will have a bunch of hidden scripts on a gameobject
Yup
Basically I have a huge player controller, but the player already has a huge list of components. So I split the player controller into even more components to make the code better and cleaner but it's easier for my designer if it's neatly contained into one component in the inspector.
So that should work fine
You would need to handle the serialization. But it could be worth it to look in to doing something like the PostProcessingstack. Where you add 'component's the the component. And so you have the classes that you add just be normal classes, so you don't need to worry about having a bunch of MonoBehaviors if that makes sense.
You would need to handle the serialization.
I use Odin so that's fortunately pretty easy
like the PostProcessingstack
I honestly would want something like that but it would be nice if I could "overwrite" the inspector editorwindow depending on theSelection:\
You could look at the source for the Inspector, you may be able to use some reflection to do something tricky.
True, I was also browsing through some of the internals to have a look at the "edit colliders" functionality of a boxcollider and it seems a decent amount of API is hidden behind it. It's just a shame it isn't documented well. (for obvious reasons too)
Yeah, I was digging through some of the code for the SceneView recently, there is so much cool and helpful stuff that is internal.
Any one got an ideas how to get handles that are set at a fixed size? I think there is a simple way to do it, but I can't for the life of me remember what it is for find how to do it.
Ye you can use sceneView.cameraDistanceand then multiply the position of what you're drawing. Unless you mean something else? @gloomy chasm
Some handle functions have a boolean that you can use for that
@candid briar so what it is specifically, I want to display some text in a handle. But I can't center the text on the pivot with Handles.Label(...). So I need to use Handles.Begin/EndGUI, using GUI.Label(...) to for the label, and HandleUtility.WorldPointToSizedRect(...) to get the rect for the label. I just want to label to be a fixed size no matter how close or far away the camera is.
Multiplying the position with the cameraDistance doesn't seem to do what I want.. unless I am doing it wrong.. which could be the case of course.
Iirc there is a method in handles to get a constant size
That is what I thought, but I looked through them all and didn't see anything
You can get the scene view camera, and use its WorldToScreenPoint to get a value you can multiply with the camera's pixel dimensions, and draw the handle at that point to do it
@cedar reef I hate to ask, but what do I multiply by what? I mean the WorldToScreenPoint returns a Vector3, but the camera is only width and height.
scaledPixelWidth/scaledPixelHeight, I believe
Actually, screen space is in pixels, I thought it was normalized
So no multiplying necessary, sorry
Just basically draw them relative to the camera
I was thinking of WorldToViewportPoint
Trying to think, I've done it basically before, but it's been a while
You basically need to figure out the worldspace coordinates of the camera's viewport corners, and use WorldToViewportPoint to get a position represented in normalized 0 to 1 values, and then use that to figure out where in the rect formed by the worldspace corners of the camera's viewport the handles should be
Oh
Oh my gosh... I just realized I think I said the opposite of what I want.... @cedar reef I'm sorry.
I want the text to act like gizmos do, so it gets small when the camera is further a way....
They stay the 'same size' in relation to the object they are on, and not to the world/screen.
Ohhhhhh
That is why I was so confused.... I'm sorry. I mean I still have no idea how to get it to do what I want, or if it is possible really.
I don't know that it is, there's no way to scale handles
Possibly some kind of reflection hack, or just make models of your own handles and render those instead
Guys, is it just me or does the new ui element wirkflow seem like a bit too exaggerated ?
hmm, as if functions which in a imgui workflow would be straightforward are broken into smaller functions and expanded
UIElements is a mess imo
Also not the whole editors is supported
And that's "by design"
Is the only way to do custom serialization by wrapping the class you want to serialize in class that inherits from ISerializationCallback?
If you are talking out-of-the-box serialization, probably
:/
I mean, you can intercept the steamingcontext before and after
And do something with that, but it's probably really inefficient
Eh, you could probably "hack" it though
You could use a private byte[] field and read/write data to/from that with your own serialization
Of course, that is going to x2 the size of serialized objects
Yeah but fuck that 😛
hi, i'm trying to display a inspector in a custom window for a object but it wont create an editor instance for me. considering it only requires an object to create a editor, should something like the following not work? what am i missing? ```cs
[Serializeable]
class A : Object {
//some stuff
}
//somewhere else:
Editor.CreateEditor(new A()).OnInspectorGUI(); //null reference
A : Object 🤔
to be clear; it's UnityEngine.Object
I don't think it's recommended to use Object directly
@whole steppe i usually derive one of those but i'm not sure i can in this paticular case...
What Navi says
yeah but i need to be able to edit an object that's not a ScriptaleObject but rather a class that can be stored inside ScriptaleObject ...
this is what i need to do:```cs
[Serializable]
class A {
//stuff
}
class B : ScriptableObject {
A[] stuff;
}
//somewhere else
foreach (A a in someB.stuff) {
Editor.CreateEditor(a).OnInspectorGUI();
}
A needs to be serializable in any case
And you can make a specific editor section just for A depending on attribute
editor section?
The editor part of A inside the entire editor of B
Let me pull up my thing. I made one a week or two ago
[CustomPropertyDrawer(typeof(SingleEnumAttribute))]
public class SingleEnumDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
int m_index = property.enumValueIndex;
string[] names = property.enumNames;
int index = EditorGUI.Popup(position, property.displayName, m_index, names);
if (index < 0) { index = 0; }
if (Enum.TryParse(names[index], out GridType result))
{ property.intValue = (int)result; }
else
{ throw new InvalidOperationException("Unable to parse value to " + typeof(GridType)); }
}
}
[SingleEnum]
public GridType GridType;
I'm sure you can do exactly the same for your Type A
@whole steppe sooo, let's see if i get you... i make a properyDrawer for A and draw the editor for B?
Yes. The editor section for A will look the way you specified it
You can add your own controls too etc
I think you can even do this without specifically adding an attribute. But I did that way too long ago
hmm, i'm not sure i can make an insector for B directly... i have things deriving A in the list. i'm not sure it will show the derived classes properies if i just make it show an array of A
No, you need to create a custom editor for A
And where ever you use A, that custom editor piece will show up a long with all the other fields
@whole steppe i think i'm starting to get what you mean. i suppose i'll go try it and come back if i run in to problems with it. thanks for now though 🙂
❔
How can I add a checkmark under my script that then extends to more options.
For example
Cooldown (checkmark)
when you check it, a new input field shows up to enter the time.
Now I want more options to show.
@cedar reef @jaunty furnace @whole steppe @gloomy chasm @waxen sandal
Is it possible to use serializedObject.FindProperty to find a property in the same class as itself?
You can provide the property path
But you can also just go down the chain with serializedProperty.FindPropertyRelative
@whole gull tagging people who aren't in conversation with you to attempt to get their attention isn't appropriate, and is likely going to make people ignore your question instead
kk
@whole gull I'm new to editor but here's what i did. I used [HideInInspector] on the property lookAtOffset. The code below is the custom editor.
using UnityEditor;
[CustomEditor(typeof(ObjectFollower))]
public class ObjectPropertyDrawer : Editor
{
public override void OnInspectorGUI()
{
serializedObject.Update();
DrawDefaultInspector();
if (serializedObject.FindProperty("lookAt").boolValue)
EditorGUILayout.PropertyField(serializedObject.FindProperty("lookAtOffset"));
serializedObject.ApplyModifiedProperties();
}
}
I don't understand, where do you attach this script?
Do you have 2 separate scripts 1 for Custom editor and 1 monoscript object
Or what you've pasted is above the code of your monoscript
[CustomEditor(typeof(ObjectFollower)] targets the ObjectFollower class.
I see, do you have to attach the custom editor script to your object then?
Ignore all the parts to do with UIElement in that script reference link, the IMGUI section is relevant
no you dont have to.
It's automatically detected
Interesting, I'll be right back 🏃♂️💨
What does EditorGUI.BeginProperty() actually do?
@tired relic how did you declare your "lookAtOffset" variable in your ObjectFollower?
I used public with [HideInInspector]
Why did you tag 5 people
@whole gull Please don't just tag everybody who you think might be able to help you
@tired relic @whole gull
You can use properties and private fields as well to keep encapsulation
Unity doesn't serialize properties by default, and you can add serializefield to fields to show them in the inspector, even if they are private
Can you expose properties to inspector?
Maybe somehow? But you shouldn't need that
Because if i could, i can just use properties instead of having properties with private field
But... you always have fields
You could make a custom property drawer and use reflection to get the property and display it, but the changes won't stick, because Unity doesn't serialize properties
A property is nothing more than a get and/or set method
I mean, you can use autoproperties so that you don't have to explcitely write a field, but it's still there regardless
Also Visual Studio has snippets to generate properties from fields with like 2 clicks
If the writing is the problem, just make a code snippet for a property with a serialized backing field
What's a code snippet?
Can you enable/disable property using the Editor class?
so much to learn 😄
Not with the [SerializeField] attribute
Where can i access it?
You just type the snippet name (mine is named sprop) and hit tab
There's a ton of built-in ones
VS has a lot of features to make developing faster. You just have to know they exist
too little exposure
I am creating a custom EditorWindow build using UIElements. I need to display an image which is fetched from an external URL. I'm not sure how I would approach this, will allowing for asynchronous loading, etc.
There's an Image class I've used before, to which I can set a Texture2D as its "image" property, but I'm not sure how to load that texture from an external URL, from within an editor script.
I see that there is a very early preview package called "Editor Coroutines", but is that required to get images loading asynchronously from an Editor script?
Couldn't you fetch them with something like UnityWebRequests?
I would think so, but all the examples I see of using that involve Coroutines.
And since this is an Editor script (using UIElements, if that's relevant), that makes it less clear how to accomplish it.
Haven't tried anything similar myself, but I think you could fetch stuff async with them
at least I've seen that done in builds
Okay, I will dig into that deeper, thank you.
Guys i found a 3d sowrd model
when i download it
it came in a winrar folder any way i can add it to my unity project?
using UnityEngine;
public class VisualNovelHelper : EditorWindow
{
string mystring = "Change Me";
[MenuItem("Window/Test")]
public static void ShowWindow()
{
EditorWindow.GetWindow<CustomInspectorTest1>("Visual Novel Aid");
}
void OnGUI()
{
GUILayout.Label("This Is A Label", EditorStyles.boldLabel);
mystring = EditorGUILayout.TextField("Name", mystring);
if (GUILayout.Button("Add a new textbox"))
{
}
}
}
``` so I'm trying to make a system that creates a new window that utilizes my string when a button is pressed (and if possible, its automatically set to unactive) can anyone help? I just got off the brackeys tutorial
to simplify it, am I able to access another gameobject's script, then that scripts function in an editor script
@low crown Not to my knowledge, but what you can do is write your editor script outside of an Editor folder so it goes into the normal project, and just surround the entire thing with #if UNITY_EDITOR/#endif
can I ask why that would matter with my problem
I must have misunderstood
and that was a while ago, could you potentioally help me with this if (GUILayout.Button("Make Fog")) { gameObject = new GameObject(); gameObject.name = "Ansunder"; gameObject.tag = "Gamer"; gameObject.AddComponent(typeof(Renderer)) as Renderer; }
the renderer component isn't getting added
For one, you can't do new GameObject(), you have to use Instantiate
well new gameobject works in this instance somehow
for adding a tag and name
should I still do Instantiate instead
Typically you should, but if you aren't getting a warning in the console about it, then it's allowed for whatever reason
For another, I believe you need to specify a specific type of Renderer, ie MeshRenderer, SpriteRenderer, etc
And use the generic version of AddComponent too, to make your life easier and avoid a cast: AddComponent<MeshRenderer>()
okay I'll try that, having a wierd problem where I cant type in it
yeah that worked, thanks
if (GUILayout.Button("Make Fog"))
{
gameObject = new GameObject();
gameObject.name = "Ansunder";
gameObject.tag = "Gamer";
_ = gameObject.AddComponent(typeof(SpriteRenderer)) as SpriteRenderer;
}```
so how do I access my SpriteRenderer's components and grab and add a sprite
SpriteRenderer renderer = gameobject.GetComponent<SpriteRenderer>();
and then spriteRenderer.sprite = some sprite
thanks
although @hoary surge spriteRenderer.sprite = some sprite doing this doesn't work, how can I format it so its an actual sprite
I'm not that stupid to not change some sprite
in y our class you need to create a Sprite someSprite; and then link the one you want there or dynamically load it. I'd go for option 1 as you still seem to be learning
so public Sprite someSprite; in the class definition then
spriteRenderer.sprite = someSprite;
thanks!
ugh
its still not adding a sprite
did I do something wrong?
if (GUILayout.Button("Make Fog"))
{
gameObject = new GameObject();
gameObject.name = "Fog";
gameObject.tag = "Gamer";
_ = gameObject.AddComponent(typeof(SpriteRenderer)) as SpriteRenderer;
SpriteRenderer renderer = gameObject.GetComponent<SpriteRenderer>();
renderer.sprite = someSprite;
}
you have to drag and drop a sprite in the editor
i did
other than that it should work unless the layering is off or something
is this editor only? does your script have a [ExecuteInEditorMode] attribute on it?
this is editor only and in an editor folder
Well something is likely failing along the way, you could set some breakpoints and try to determine what's up.
would I be better off trying to summon a prefab maybe?
@hoary surge (also please tell me if you don't want to be pinged)
maybe, it just seems like somethings not working for some reason and unless you set a breakpoint you might not know what it is
editor code can be a little weird at times
google is being annoying with the prefab thing
I can't find any way to make a new gameobject that still has the data from a prefab
why am I going through all this hardship just to avoid dragging and dropping 3 layers of fog with diffrnet opacity levels
lol
Aight I'm just gonna give up on this particular command for now
thanks for the help anyways
Hey guys, the enum popup field has a property attribute marked with. How do i update it immediately when the array was modfiied?
Here's the code
https://paste.myst.rs/2fq
(answering a question from general)
you can't make a custom editor for a class that does not inherit from Monobehaviour or ScriptableObject
You need to make a custom Property Drawer
alright thank you
so, now i have this little script
but i cant just put the serializething above the public class
so where do i put it?
You don't need to, you can just add that to a GameObject and it'll work
Oh sorry, I see what you're asking
But yeah, you don't need to do anything in that script
if you have a custom property drawer that's properly set up you don't need to do anything special apart from having the class itself be serializable
that is one way of doing it yeah
if you want to modify it directly you should be using the Undo.RecordObject function in conjunction with your changes
alright, thanks for the help 
ahhhhh, im sorry for bothering again (i only started with custom editors today)
so, now i made this:
i was hoping that i would be able to show different editor stuff based on the type that is selected in the editor
but it just leaves it blank
again, sorry for asking this much haha
It might be the multi-object editing thing that's the issue
just reselect one object and see if that works
sadly that does not work
I don't think your editor is working at all
I think it's not registering it as a custom editor for that type
AS the default inspector is still drawn
Do you have compilation errors?
no errors
Sweet
so... now for the next question..... if you are still willing to help
If you're going to change data you might want to use serializedobjects and serializedproperties
I've got to go in a few minutes but Vert probably doesn't mind
You should probably just make a property drawer for your element
how does that work? im like a total noob with custom editors
The docs are pretty good at explaining it https://docs.unity3d.com/ScriptReference/PropertyDrawer.html
Just skip the parts about UIElements
oh i think i understand it
As it's probably a bad idea to make stuff with them for now
yeah that seems better
But yeah, it provides a SerializedProperty, which is your object as Unity sees it
then you can drill down and get its serializable members with serializedProperty.FindPropertyRelative("memberName")
And use EditorGUI.PropertyField to draw them as Unity would usually be drawing them
okay, but will i be able to still use variables from it after?
wait maybe its usefull if i explain what im trying to do
like, im just trying to make it so that each type has its own variable list so to say
so that the editor wont show unneeded variables for that type
Yeah, it'd look something like this:
public override void OnGUI (Rect position, SerializedProperty property, GUIContent label){
EditorGUI.PropertyField(position, label, property);
var partType = property.FindPropertyRelative("sequencePartType");
switch((SequenceTypeBlah)partType.enumValueIndex){
...
}
}
public float GetPropertyHeight(SerializedProperty property, GUIContent label) {
return EditorGUI.GetPropertyHeight(property, label) + the height of your button;
}```
alright thanks, let me try to mess around with that a bit
just fnangle the method parameters into the right order if I got any rect, guicontent, property orders wrong
EditorGUIUtility also has static properties describing the heights of elements, so for the height of your button that would probably be:
EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing
IMGUI is a lot of learning where all this stuff lives 😛
ah, that would be property, the parameter that was passed in
this is what happens when you write code in Discord
ah sorry, that was meant to be partType
You need to cast to the type used by your original switch statement
All you're doing here is:
Drawing the original property,
Finding your enum value,
Doing your normal switch statement with the buttons in it
and then additionally to that there's the property height recalculation (seeing as we now need to account for the button you're adding)
Except instead of directly dealing with the data, you're accessing it using SerializedProperty's members (ie. .enumValueIndex, which is the value of your enum as is serialized by Unity)
Hey guys, is it a must to have fields to be public for custom editor to assign the value?
or [SerializeField] private
if you're using SerializedProperties that will work fine
made a cool single line analysis tool DrawGraph.Add( "title", value );
Hey guys. I need a help with custom editor for my ScriptableObject.
I have SO with 2 arrays, 1 is for prefabs, second is for their respective amount in wave (enemy wave) in percentages. Both arrays are the same size, and I want the second array to be presented as slider values for each field, with the overall sum of values not bigger than 100 (they are integers).
I figured out the whole logic for capping and adjusting sliders, but I can't access the array members from the SerializedProperty. I wan't to iterate the array and create a slider for each field, before that I wan't to iterate the array and calculate the cap (using simple math) -- this is all happens in OnInspectorGUI.
I read that mixing SerializedProperty and directly changing the object values is a bad practice. So how can I access my GO array values through SerializedProperty? Is there any way to do that properly?
@feral karma i plan to, very spaghetti atm
@wet vale you can use property.arraySize, and property.GetArrayElementAtIndex(...)
@gloomy chasm Thanks! That works!
np 🙂
[Solved] This is a weird one. I am using right click to open a context menu. It seems it works, even when another windows 10 window is open over it.
if (viewRect.Contains(e.mousePosition))
{
if (e.button == 1)
{
if (e.type == EventType.MouseDown)
{
ProcessContextMenu(e, 0);
}
if (e.type == EventType.MouseDrag)
{
//Debug.Log("Left Mouse Drag in " + viewTitle);
}
if (e.type == EventType.MouseUp)
{
// Debug.Log("Left Mouse up in " + viewTitle);
}
}
Is there a correct way to do a check to see if unity is the active window?
(Custom editor window scripting).
Nevermind. Sigh. Fixed.
If you just check
if (e.button == 1)
It can open through windows 10 windows.
but if you check
if (e.button == 1 && e.type == EventType.MouseDown)
It will catch that issue.
Thanks for listening 🙂
I'm very confused about flex layout with UIElements (yes I've read all the resources multiple times).
If I have a parent VisualElement with display:flex, flex-direction:column, and 2 child VisualElements, each of which have a flex-grow property set to 1, I would expect the bounds of these elements to stretch to fill the available space equally. But this doesn't happen. Why not?
Instead, they take up basically no space, exactly opposite what I'd expect flex-grow to do.
how can i detect if i clicked in the red areas? ...or more directly, how can i know if i'm interacting with the UI parts or if i'm simply clicking in the grid space?
this is a stripped down version of the rendering code ```cs
//drawing nodes and stuff first up here//
//(i'm cutting it out for simplicity)
//drawing ui overtop the nodes//
EditorGUILayout.BeginHorizontal();
DrawInspector(); //left bar
EditorGUILayout.BeginVertical();
DrawMenuBar(); //top bar
GUILayout.FlexibleSpace();
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
@jaunty furnace EditorGUILayout.BeginHorizontal(); returns a rect. You can do rect.Contains(Event.current.mousePosition); to see if the mouse is in a rect
Also you can do
using (EditorGUILayout.HorizontalScope hScope = new EditorGUILayout.HorizontalScope())
{
// My editor code that I would put between 'BeginHorizontal' and 'EndHorizontal'
}
to make it easier to read your code.
thanks! you're absolutely right, it does return a rect! damn it, i thought that was the first thing i checked 😫
GUILayout does not, but the editor version does... for reasons...
oh... maybe i looked at an GUILayout the first time around then and just made a subconscious assumption about the editor version
Yeah, that is quite possible.
at any rate, i greatly appresiate the help. thanks!
Sure thing!
scopes have the rect as variable as well iirc
@gloomy chasm @waxen sandal sorry to bother again but it seems like the rects from the layouts alternate between being the actual value and a non-assigned (x:0.00, y:0.00, width:0.00, height:0.00) rect. why? how?
Wrong pass probably
yeah, how do i ignore the pass?
It's probably only available during the layout pass so you should check that
Think it is in repaint as well. could be wrong though
Then I don't know
how do i know what pass i'm on?
Event.current. something
Yeah Event.current.type == EventType.Layout
idk if it is called EventType close to that though
Man, I can't for the life of me figure out how to draw a default property drawer from inside a custom one. Any ideas?
(To be clear, I mean of a the default drawer for a variable that is local to the custom property drawer script.)
@gloomy chasm Just doing PropertyField should do a default property drawer. Be sure to set the boolean parameter (draw children) to true if you want the whole thing
@cedar reef Yeah, I sadly do not have a serializedProperty to use though :(
The field is an array of objects, which unity doesn't serialize.
Then you can't really do what you want, other than basically recreating the default property drawer using reflection instead
That is what it seems. I did look at reflection, but couldn't find anything that I could use. The thing that draws the default property uses serializedProperties
is there a way to load .prefab files as the serialized strings? I want to do a text search on them
Just load the file using the generic file reading c# methods
neat. thanks
going to use it to quickly search for properties stored in prefabs
works as expected.
https://gist.github.com/roguesleipnir/17e67896ffe2c94e781b2790121a7f79
Hey guys, so i'm trying to fix the offset location in the inspector. I'm not sure how to approach it.
[CustomEditor(typeof(ObjectFollower))]
public class ObjectFollowerEditor : Editor {
public override void OnInspectorGUI() {
DrawPropertiesExcluding(serializedObject, new string[] { "lookAtOffset" });
if (serializedObject.FindProperty("lookAt").boolValue)
EditorGUILayout.PropertyField(serializedObject.FindProperty("lookAtOffset"));
serializedObject.ApplyModifiedProperties();
serializedObject.Update();
}
}
How do I make sure the lookatoffset is above isTeleport?
just additionally add a propertyfield for isTeleport and exclude it too
order it yourself
I see, thanks alot!
is there a way to forbid context menu of GraphView (UIElements) ?
oh i tried overriding BuildContextualMenu with empty implementation, it seems works fine, dont know if it's best practice
consider the following ```cs
[Serializeable]
public class Thing {
//stuff
}
public class Wrapper : ScriptableObject {
Thing data;
}
[CustomEditor(typeof(Wrapper))]
public class WrapperInspector : Editor {
public override void OnInspectorGUI() {
EditorGUILayout.PropertyField(serializedObject.FindProperty("data")); //show only it's data
}
}
//some other place:
Wrapper wrapper = //some instance
Editor.CreateEditor(wrapper).OnInspectorGUI();
I think that should work
You can give your own type as second param though
Does the editor work otherwise?
@waxen sandal what ”own type”?
You can do Editor.CreateEditor(wrapper, typeof(WrapperInspector))
Yeah but this should work too, right?
Yes
@waxen sandal no
Is there some compilation order shenanigans going on?
I doubt it. Other inspectors in the same assembly work just fine
Is it in the same assembly as your createeditor code?
Yes. Btw I just tried drawing a basic label and it works so the problem lies with the drawing of the data
In your customeditor or in the createeditor code?
The EditorGUILayout.PropertyField(serializedObject.FindProperty("data")); part is the problem
Sure. I’ll go try... gimme a few minutes...
Though, even if that’s the case, why would it draw the default one instead? I’m still overriding the base...
It could be throwing an exception causing unity to fall back to default
True... as Said i’ll be able to check in 5min or so... stay tight...
@waxen sandal check complete. serializedObject.FindProperty("data") is not null and ```
try {
EditorGUILayout.PropertyField(serializedObject.FindProperty("data"));
} catch (Exception e) {
Debug.Log(e);
}
Weird, no clue then sorry
okay. thanks anyways
@jaunty furnace Try PropertyField with the third boolean parameter set to true
@cedar reef i'll go try...
Is there a way to programmatically dock an EditorWindow to another EditorWindow?
I have a main window which needs to have a child window which can be hidden/shown at will. But if I call Close() on the child window and then re-open it, it doesn't reopen with the same orientation as before.
@tulip plank i'm not sure that's possible. you can set the position rect of a window but i think the docking part of it is hidden from us
I think it's theoretically possible but no clue how to anymore
@cedar reef no, wait... i've fixed the "only draw data" problem between then and now but it still shows up as a foldout type thing i need to expand. any idea how i could display data without the header/foldout thing?
Decompile and search time
I have an editor script that makes it easy for me to create new levels in my game. All the script does is set the color of a bunch of objects. It works fine. However, when reloading the scene, or restarting unity, the UI elements go back to their original color. The camera's background color stays persistent though. I don't know what I'm doing wrong. Any help would be appreciated.
@tulip plank It's possible, but you have to use reflection. You'll want to look into the DockArea class
@rocky silo i belive you need to mark the scene as dirty using EditorUtility.SetDirty(scene);
put it where you can detect the change, that is, where the color is set.
just put it on the line directly after if possible
as for what it does it tells unity it needs to save the cache/memory version of it back to disk before closeing the file(in this case the scene)
How would I get the current scene when its in editor mode?
@cedar reef Interesting, thank you for that point of reference!
I've done it before, it's a pain in the butt, and a lot of reflection
@rocky silo sorry, i belive you want UnityEngine.SceneManagement.SceneManager.GetActiveScene()
It says that it cant convert a scene to an object @jaunty furnace
@rocky silo hmm...
it seems a scene has its own method for it for some weird reason... try EditorSceneManager.MarkSceneDirty(SceneManager.GetActiveScene()); third time's the charm XD
Nope, doesnt seem to work
I looked at the docs, but I can't really understand if i'm doing something wrong
@rocky silo if it's saveing correctly, i don't know what the problem could be... sorry.
@rocky silo You should use SerializedObjects and SerializedProperties
help me out here, how can i show stuff from A and B in the inspector without writeing a seperate inspector for each new thing i derive?```cs
[CustomEditor(typeof(DataWrapper))]
public class DataWrapperInspector : Editor {
public override void OnInspectorGUI() {
SerializedProperty data = serializedObject.FindProperty("data");
IEnumerable<SerializedProperty> children = data.GetChildren(); //custom thing that gets child properties
foreach (SerializedProperty child in children) {
EditorGUILayout.PropertyField(child);
}
}
}
[Serializable]
public class DataWrapper : ScriptableObject {
public Data data;
}
[Serializable]
public abstract class Data {
public string name;
}
[Serializable]
public class A : Data {
//more stuff
}
[Serializable]
public class B : Data {
//more stuff
}
Serialization doesn't do polymorphism unless they're scriptableobjects iirc
@waxen sandal i know, that's the problem. i'm trying to find a way around the limitations of the serializer
the saveing part of the thing i've already figured out. the problem is limited to displaying it in the inspector
is this the right place to ask about UIElements?
I'm pretty confused with how it handles local pathes
e.g. to the stylesheets.
Seems that when creating something with UIBuilder, all pathes are absolute in the project. Moving around the files just breaks all of them. Making the pathes relative works when using the uxml files, but breaks UIBuilder.
Anyone seen this as well / has more insight?
All I know UIElements is mess
Anyone else? 😄
quick question. In this code:
public static void SphereHandleCap(int controlID, Vector3 position, Quaternion rotation, float size, EventType eventType);
what is controlID ?
I'm using handles just to visually debug some stuff in my scenes
I assume setting that int to 0 is what I want. But I wanted to make sure 😅
It's an unique ID so you can check whether it was cvlicking
IF you don't use it then 0 should be fine
@waxen sandal alright, thanks a lot! 😊
is there a way to rename nested/child assets ?
nvm got it
var path = AssetDatabase.GetAssetPath(t);
var assets = AssetDatabase.LoadAllAssetsAtPath(path);
foreach (var asset in assets)
{
if (asset == t)
{
asset.name = m_filName;
}
}
AssetDatabase.SaveAssets();``` where t is the sub/child asset id like to rename
can you use ui builder v0.8.3 to runtime UIs in 2019.3.0b7? I'm able to use the editor, but can't add a Panel Renderer component to anything in the scene.
ok, so answering my own question, no, you can't until 2019.3 comes out of beta.
Hey, guys. How i can get prefab from prefab instance?
I tried to use .GetInstanceID and then AssetDatabase.GetAssetPath(instanceID), but GetAssetPath return empty string, so i cant find original prefab...
found
made some graphs visualization tool:
https://github.com/nukadelic/UnityGraphs
@whole steppe I think PrefabUtility.FindPrefabRoot is what you are looking for. (Technically it is obsolete, but when you use it should tell you what to use instead)
Hey guys, can I make [SerializeField] private TowerProjectilePool[] projectiles;(TowerManager.cs) into a intpopup field for SO's projectile field?
I could do that with static array of string and int and marks that with propertyattribute but am i suppose to use static array for that?
I'm looking for this result. I did it but the way i implemented is weird.
I recommend either making a drawer attribute or just write editor code specifically for the type which then manages the array internally
I'm working on making a UIElements Inspector, specifically I'm trying to build a Search Suggest Box
I'm having trouble with Drawing order, the popup displays below some elements outside of the inspector, and I'm curious if anyone knows of a better way
I know for the Visual Tree, the only way to control drawing order is to change the order of elements in the tree, but I don't see how I can do that in this context
Eh, I solved it, the solution was to walk up the visual tree to the root of the container and add the element to the end of the list, but it seems a bit odd modifying a visual tree outside my code for this
unfortunately the text is all blank on these labels and I haven't the slightest idea why
no idea why the label keeps default color...
and what is the meaning of the 111 and 121?
I think its related the line in the USS file, but thats really a guess
w00t, search suggest box here we go!
oh i know, from doc its specificity number, but still dont know how to get my uss work...
With the UIElements ScrollViewer how do you make it work... at all?
if I add a max height ot the ScrollViewer via CSS, its elements simply become compressed rather than the content becoming scrollable
and otherwise it just extends off screen if its too much content
I tried setting the scrollViewer.verticalPageSize but it doesn't seem to have any effect
of course page size doesn't work, looking at the reference thats for how much is scrolled hwne using the scroll wheel, but I'm at a loss here
:/ well this is crap, I have no idea whats wrong here, and I can find no information
maybe you can give the elements fixed height?
or there is a Unity.UIElements.DropdownMenu, maybe could have a try
strange...
Apparently its because I'm adding it to the root most container...
which I admittedly believed was going to end up being a problem, but now I can't make this work right
I would like to thank Unity Documentation for being a liar
PopupWindow A UIElements window, displayed on top of other content.
so much ontopness
really painful lol
I can only presume I'm doing something wrong, but this stuff should be more obvious
it will be, with more people struggling with it
Okay, I figured it out
The styles that ScrollView, etc. rely upon are added in the rootVisualContainer, and I was adding my popup to the container above that
I fixed it by adding it to the rootVisualContainer
sadly, its not perfect the scroll bar buttons dont' disappear when the popup is hidden
there appears to be a kind of issue with visible being set from code which doesn't update child elements
this seems like apretty huge oversight, how can visibility not impact the visibility of child elements...
yay, its basically all working
❤ UIElements
I asked about this is a few days ago, and a few people tried to help me but I wasn't able to get my script working.
I have an editor script that changes the color of multiple objects within my scene (camera background and ui elements). When I change the color and number of the LevelSettings script, it successfuly updates the scene. However, when reopening the scene, the colors revert to their original state (Only the UI elements, not the camera background color). I know this has something to do with serializing my gameobjects (I think?) but I haven't been able to do it sucessfully yet.
Any help would be much appreciated. I can provide a video if my explanation was garbage 👀
Code: https://hasteb.in/utiwecaq.cs
@gloomy chasm You are right, thanks.
TLDR: changes made to UI via editor script are not permanent and go back to their original state when the scene is reopened
@rocky silo It should work as far as I can tell. Could be with how unity serializes the data, maybe it is not serializing the changes made with the editor script?
The camera's background color is persistent, its just the UI elements
Unity may serialize the camera differently. Thinking about it more I am pretty sure this is what is happening. If memory serves you need to set the objects you edit as dirty
I have tried doing that. I am pretty sure that is the answer, I just can't figure out how to do it correctly (This is what I was told to do last time)
Where do I set use the method and what do I set to dirty? The scene or all the UI elements?
also, there are two different setdirty methods
so the data is saved, but the ui elements are not updated?
I don't understand what isn't happening exactly
are you talking about when you hit save, and the colors change, and then you select GameManager and they change back?
when i reopen the scene, the colors are the default colors of the ui elements until i click on the gamewindow (which contains the level settings script)
this causes an issue when building because the ui elements aren't the colors they are supposed to be
So, one thing I'll mention is that you're bypassing the serializedProperty system which makes this all much smoother
As you can see, the camera background color is not affected by this and, once changed, remains changed
If you want to stay this way, I think MechWarrior is making the right suggestion
You'll have to call it on each changed object
how would i do it with serializedproperty? I havent used it before
I just want a solution that just lets me set the color of the level once, and then not have to worry about it
I would hit the Unity manual and read about it honestly, it will be better than me trying to explain it
I think this would work. But yeah, reading the manual would be good! :)
backgroundObj.FindProperty("color").colorValue = Color.White
But it would still work through editor scripting right?
you do that stuff with serialized Object and serialized property inside your OnInspectorGui code
SerializedProperty only works in the editor.
I'm running into a problem now too, I'm trying to make a custom property drawer but it doesn't work
How so?
How would I get the child of an serializedObject?
Would i have to do FindProperty("transform") and do it that way?
What do you mean?
The way I have my GameWindow prefab set up is the GameWindow object has a LevelSettings component on it that is actually refrenced by the editor script. Then I have a bunch of child objects for each different thing that has to edited (ex. Camera, side bars, progress circle, etc)
So I need to change the properties of the children
I am not sure what you mean by "child object". Do you just mean a variable that references a Object?
no, i mean that the camera and UI elements are children of the GameWindow Object
@gloomy chasm
Ah, I guess the best would be to get those how you were getting them. Then make a SerializedObject, then get the serialized property from them?
make a serialized object from the children? Won't I need one for every child then?
Oh I see, let me try it
How would I set the color of a serialized object?
@rocky silo you need to use FindProperty()
SerializedObject cam = new SerializedObject(GameObject.FindWithTag("MainCamera"));
cam.FindProperty("backgroundColor").colorValue = Color.white;
The docs aren't that clear ._.
You will need to find the private color variable. Normally unity uses m_ as the prefix for private variables.
does findproperty find that property in all components of that object?
so m_backgroundColor may be it. No, only in the refrence to that one
you can also do Camera.main to find the camera tagged as main
I know
cam.FindProperty("m_backgroundColor") is null @gloomy chasm
How can I check to see what the private vars are called?
look at the source
I thought unity wasn't open source?
The C# source is pinned to this channel
All of it's c# code is on Github for reference only.
ok, ill check it out
Nope, the Camera doesn't have a private var for background color
all it has is extern public Color backgroundColor { get; set; }
cam.FindProperty("backgroundColor") Still is null though
This hurts my head
backgroundColor = m_SerializedObject.FindProperty("m_BackGroundColor");
where does backgroundColor come from? @visual stag
you can create it if you like, it's beside the point
Oh wait, thats not the color, thats the SerializedObject, mb
OMG, i finally got it
that was way harder than it had to be lol
where is the var m_BackGroundColor in the src btw? I didn't see it when I cmd + f
Yes, it's in CameraEditor
oh ok
how do you bind to an array with UIElements
The property name I should be using should be m_TintColor for a UI Image, right?
https://github.com/Unity-Technologies/UnityCsReference/blob/master/Modules/UIElements/Image.cs
It does want to work, and I don't know if I'm just in the wrong file
._.
You can find the UI source separately, also it'd be in your project
as it's a package now
What version of Unity are you using?
2018.something
It's not a package in that version
just look at the source (also pinned to this channel)
https://bitbucket.org/Unity-Technologies/ui/src/2019.1/UnityEditor.UI/UI/ImageEditor.cs
What am I doing wrong this time? There is no color serializedobject.
Well, how do I get the GraphicEditor from the Image now. Im getting super lost
Why do you need to?
nm
ImageEditor inherits from GraphicEditor
Wee, thanks for the help yall
Ok, what am I doing wrong here. Both Indicators are images but the FindProperties return null
ok, I've looked through my code and tried a couple things but I still haven't been able to figure it out
oh
Thank you!
One last thing, Is Text Mesh Pro also open source so that I can get the SerializedProperty for some text I have?
nm, its in the packages folder
@visual stag Thank you so much for the help! I hope I wasn't too much off a bother 😆
So I'm trying to do something where I can more easily create text boxes for my game, but it only summons an empty gameobject, mostly because i have no idea how to give it
- A sprite renderer
- An actual sprite inside said sprite renderer
if anyone could help that would be greatly appreciated
how do I show a property given the bool is true?
SerializedProperty colorToTransparent = this.serializedObject.FindProperty(textureSettings + "colorToTransparent");
if(colorToTransparent == true)
{
// show another property
}```
where in my class [SerializeField] public bool colorToTransparent = false;
colorToTransparant.boolValue
thanks
in my class I have transparentColor as
[SerializeField] public Color transparentColor = new Color();
and I am trying to toggle the view if bool is true
var colorToTransparent = EditorGUILayout.PropertyField(serializedObject.FindProperty(textureSettings + "colorToTransparent"));
if (colorToTransparent)
{
EditorGUILayout.ColorField("New Color",
serializedObject.FindProperty(textureSettings + "transparentColor"));
}
but im getting error for editorguilayout.colorfield. How do I use this property?
`Cannot convert SerializedProperty to GUILayoutOption
You don't want to use ColorField
You probably Want PropertyField
Otherwise you can do propert.colorValue and do a change check for when you need to save your SO
Ok I changed that bit to EditorGUILayout.PropertyField(serializedObject.FindProperty(textureSettings + "transparentColor"));. would I add BeginChangeCheck() or something? Currently the drawer wont display the color picker if it is true @waxen sandal
sorry im new to the ongui editor
colorToTransparent is still a serializedProperty
You got to get the boolValue and put it in your if statement instead
weird. var colorToTransparent states its a bool
in my class I have [SerializeField] public bool colorToTransparent = false; that should be fine without needing to call boolValue
Unity does weird things with implicit conversion to bools
Oh actually
You're having a diffenret issue
PropertyField returns true if the property has children and is expanded and includeChildren was set to false; otherwise false.
You want to cache the serializedProperty
var property = serializedObject.FindProperty(textureSettings + "colorToTransparent");
EditorGUILayout.PropertyField(property);
if(property.boolValue)
{
//draw
}```
Like that
okay thanks. do I have to cache it like so for properties all the time? Otherwise it would be subject to the implicit bool conversion issue you mentioned?
ill start that too. thanks again for the help! I was going nuts..
Hey guys, does editor window saves itself?
Define save
@waxen sandal Like if i edit the editorwindow, the property fields on it will be gone
Am i using editor window wrongly?
You need to call save on your SerializedObject yourself
Will editor window's stuff be gone once i restart unity?
If you don't save it yeah
Are you using serializedproperties and serializedobjects?
If so use this
Otherwise I'd suggest to use them
this doesn't work though.
closing editor windows deletes the property that is in the editor window script.
Thanks though. I think i will stop working on this till i have better knowledge
@waxen sandal Ahh no wonder
where can i find the uxml(s) used by the editor? seems its not in reference source
like
So I'm trying to do something where I can more easily create text boxes for my game, but it only summons an empty gameobject, mostly because i have no idea how to give it
- A sprite renderer
- An actual sprite inside said sprite renderer
if anyone could help that would be greatly appreciated
{
GameObject go = new GameObject("MyCreatedGO");
go.transform.position = new Vector3(0, 0, 0);
}```
@low crown ```cs
if (GUILayout.Button("Add a new environment textbox")) {
GameObject go = new GameObject("MyCreatedGO");
SpriteRenderer renderer = go.AddComponent<SpriteRenderer>();
renderer.sprite = someSpriteHere;
go.transform.position = new Vector3(0, 0, 0);
}
thanks
no problem
how do you mean change?
like how do I give it an actually functioning sprite
I tried public sprite someSpriteHere and assigned it a sprite but it still doesn't seem to be working
sorry. i'm confused... where's the problem? can you assign it? does it give an error? and so on... try describeing more specifically where the problem lies.
The problem is the sprite doesnt actually appear in the sprite renderer
yet you assinged it to someSpriteHere?
si
can you supply the full script so i may test it?
one sec and i'll look through it...
@low crown fixed it! i couldn't help but to fix it up a bit in both code quality and look. hope you don't mind 🙂 https://pastebin.com/VYAHKeQb
Thanks
Does anyone know how to do the following```cs
[Serializable]
class X {
public int a;
}
[Serializable]
class Y : X {
public int b;
}
class Z : ScriptableObject {
public X c;
}
class Main {
void DoStuff(Z z) {
z.c = new Y();
Editor.CreateEditor(z).OnInspectorGUI(); // only displays a, not b.
}
}
how can i by ANY means make it display both a and b without haveing X inherit ScriptableObject
any suggestions are deeply welcome. this has been haunting me for a while now...
You can't
There is a [SerializeReference] attribute that has been added in 2019.3 that would solve your problem, but before then it will not work
i'll look in to that. thanks!
@visual stag what would be the correct way of useing it? where in my example would i place it?
over public X c; I think. I've never used it though
okay, i suppose i'll go see what i can do
it works really well overall
but beware of deeply nested hierarchies, there are some bugs
@visual stag @severe python i can't seem to use it due to protection... it's marked internal when i decompile it
what version of Unity are you using
Just to check cause you said decompile, are you working from a built game?
@severe python there didn't seem to be a finalized release for 2019.3 so i downloaded the 2019.0b7 beta. that's the version i'm trying with right now. is there a better one?
and when i said i decompiled i was decompileing the unity files with Resharper to find the issue...
do you mean 2019.3b7?
SerializeReference is newly available in 2019.3 alphas/betas
its not available in any prior version
2019.3.0b7
If so, then I'm not sure why uo can't use it, I'm using it in my Entity composer inspector
using System;
using Unity.Entities;
using UnityEngine;
[Serializable]
public struct EntityModel
{
public string Name;
[SerializeReference]
public IComponentData[] DataComponents;
[SerializeReference]
public ISharedComponentData[] SharedDataComponents;
[SerializeReference]
public ISystemStateComponentData[] SystemStateComponentData;
[SerializeReference]
public ISystemStateSharedComponentData[] SystemStateSharedComponentData;
}
Say like this then. What exact version are you useing and i’ll try that one
2019.3.0b6
I'd expect 2019.3.0b7 would work though, if you're using that, then thats potentially a regression bug
or they see SerializeReference as broken and are removing it, which would make me cry buckets
I don’t have my computer here right now but i’ll look in to it when i get home. I’ll update you then if you please?
Are there examples to make a draggable divider between two VisualElement?
I have some code for it...
but its currently broken, so its probably not a good example lol
and there were work arounds I had to use because UIElements was more buggy when I developed it
@jaunty furnace Just for yuor own proof/sanity that my serializeReference usage is working as intended
lol
Kotono, basically waht I did was create a Manipulator, and that manipulator inserts a VisualElements between elements and moves that divider to the space between the nearest 2 visual elements in the parent element I want
I had a tree structure, so i also did stuff with insert into/above the current
I wont lie though, it gets fairly complicated depending on how good of an implementation you want
When you start doing hiearchical dragging, its a little more complex, if you want to instantly pull an element out and have it positioned relative to the cursor, that gets more complicated
my situation was a little more complex naturally because my object structure was automatically updating the visual structure when its structure changed, so if you don't have something like that it should be a bit easier
yeah... I thought if there isn't a built-in solution, it may be difficult to achieve the goal
thanks a lot
its really not too hard, it just seems hard
but it definitely gets a bit difficult the more powerful versio of the concept you want
if you have a flat list that you want to re-organize, it shouldn't be too bad
i'll have a try👍
@jaunty furnace the pastebin is no longer active would you be able to dm me the code (from the sprite tenderer problem)
@low crown you didn't copy it when i gave it to you?
oh well... since i thought it was a one time thing i just rewrote it in the project i had open and deleted the file afterwards...
on threat tho. i'm a nice pal. i'll redo it for ya heh 🙂
BTW, there's no need to actually decompile anything https://github.com/Unity-Technologies/UnityCsReference
@cedar reef yeah i know, but it's just easier for me to push go to defenition right there in the editor. it decompiles the thing i'm after about 50% of the time so it's faster to just check that first
@low crown here you go, good as new https://pastebin.com/1QQgxc9a
please feel free to say what you think of the touchups. i thought i made a decent job of it!
Thanks
bah, this code doesn't work, and none of the symbols show up in the debugger so i can' see whats going wrong...
I have a question about Unity's SimplestPlugIn, is this the right channel for this discussion?
Opinions, thoughts?
Is it possible to make an “Are you sure” box pop up when a button is pressed
Cuz I have a destroy all selected game objects button
@low crown definetly! ```cs
if (EditorUtility.DisplayDialog("Are you sure?", "Are you sure?\nThis will permenetly delete the objects", "I'm sure", "Cancel")) {
//do the deleteing here
}
@severe python i've managed to get the right version and the attribute seems to at the very least not have protection now... however, the 2019.3.0b7 broke the postprossesing in the project... you know anything about it?
That isn't something I know anything about sorry
the most I've used post processing is seeing it in my packages and saying "yeah, I'll use that probably sometday"
you should look in to that... some basic bloom, a vignette and some color gradeing is almost enough to make a meh looking game in to a masterpiece
Thanks
no problem
@severe python i've got the attribute working as intended but it seems there's some issues with it... it draws souly the default inspector and no custom ones. things like enums and such just show up integer fields. is this a bug? it's quite a game breaker for what i'm doing...
got anything on that issue?
you wouldn't use it on blittable types
structs, classes, and interfaces
I'm using them on a set of interfaces for ECS
which are all implemented on structs
why not? unity supports them normaly
you'll still serialize those other types, just don't use SerializeReference
using System;
using Unity.Entities;
using UnityEngine;
[Serializable]
public struct EntityModel
{
//Note that I don't add SerializeReference to Name
public string Name;
[SerializeReference]
public IComponentData[] ComponentData;
[SerializeReference]
public ISharedComponentData[] SharedComponentData;
[SerializeReference]
public ISystemStateComponentData[] SystemStateComponentData;
[SerializeReference]
public ISystemStateSharedComponentData[] SystemStateSharedComponentData;
}
you mean there would be a problem with strings aswell?
strings might actually be different, but the question is why you think you need to add it
if I were to add ints or enums there I wouldn't decorate those fields with SerializeReference, there is no reason to and apparently it causes some unexpected behaviour
That being said, I'm writing completely custom UI with UIElements
I'm using PropertyFields in very explicit places on blittable types
you mean i should use EditorGUILayout.PropertyField() on blittables? how would i do that when the SerializeReference attribute seems to stop me from useing things like property drawers? even when i try make a Editor for the SerializeReference marked class it seemes to stop saveing changes back to the file. when i exit the field it just reverts to the previous value...
oh no, I'm using UIElements, I abandoned IMGUI faster than a bad habit
I can't really lend advice on imgui
beyond, leave it behind
gonna repeat what @severe python said.
Drop IMGUI like the sack of bricks it is.
yeah, i suppose i*ll have to go look in to that later then. i just feel as if i atleast need to finish this project in imgui as it's both large and beyond this last thing, done. i'd be a pain to redo all the visuals...
yeah, if you're that far in, I'd finish as-is and start with UIElements on the next project/feature
yeah. problem is... i don't know do to solve this last thing... you don't happen to know anything about it?
@jaunty furnace Thanks for the help! everything works like a charm (i've not been near my computer until now)
I hate serialized properties
I tried UIElements, but it felt hard to do even simple things like making a list of items. And normally only really need to do custom editors for pretty advanced things, and it doesn't UIElements was meant/good at doing complex, specialized, or advanced things. Could just be my experience.
It seems that the binding of complex hierarchies just doesn't exist yet, and that's the biggest barrier to development
Okay, so it isn't just me. Like 90% I am either making a really simple editor, or really advanced. And in both cases IMGUI just seems like the better choice. I will keep an eye on it, and see if it gets easier to work with for advanced things.
The In game system seems like it will be pretty good though. Will have to wait to see though on that as well.
Yeah, I think the worry there is that it's very early tech, especially on the creation side of things for runtime
So if you want to do something specific, which more than often comes up in gamedev there may not be a development pathway that exists, or is as well trodden as previous GUI implementations
like, the initial implementation of TMP's backend in there might actually just not work for localisation, or text revealing, etc (examples, no idea if they can be done or not)
Until they've got the binding stuff working I'm not touching it, but immediately after I'm going to make the switch and start sending proper feature requests
It's totally unworkable without the binding stuff for editor
Yeah, as much as I like where this stuff is going. I plan on waiting a while for it to mature before I switch over to it.
Binding stuff?
binding a SerializedProperties to elements properly when they're from multiple ScriptableObjects
Oh gosh.
my only issue with UIElements is that binding sucks because SerializedProperties suck
the whole thing needs a good DataTemplating system
I find the UIElements themselves to be very easy to put together, and when I ignore SerializedProperties I have a lot of success, but then you have to fill in all those gaps
A great example is that I built a SearchSuggest input box, and that was incredibly easy to do with UIElements, I've done it in the past with IMGUI and it was incredibly difficult to get right and have it be pefromant
Yeah totally. I made a documentation window with it when it was first released that had inline rich text and buttons, code highlighting, etc. Practically impossible in IMGUI, and yet I managed it quite easily with UIElement
Then I tried to make a UI for something that actually had serialized underlying data, and nothing would bind properly, everything wouldn't react to changes, and every update of Unity something entirely different would break
You can make the binding to SerializedProperties work just fine
They just haven't put in any effort into that at all
I couldn't make it work fine without adding polling when I was trying something complex last
Oh yeah as user you can't make it work at all
Properly at least
But for the Unity guys it shouldn't be too hard
All you need is an event when a value has changed on the SO
Also one of the guys on the dev team of UIElements told me that if you want to bind the visibility for example; that you should make an invisible BoolField then register the change event on that and then change the element you want to change the visibility of
Yeah, we've discussed this nightmare! It'll get better eventually. I'm only jaded because they're pushing it hard in the docs for editor with the shortcomings
I hope so
But I don't think their priorities align with my views of what it needs to improve
Serialized properties need to go
So, if any of you are interested in UIElements, but are not completely satisifed, consider trying WPF with MVVM, and the utilizing a similar code organization pattern
I had a lot of success in mre previous setup with bypassing SerializedProperties and using INotifyPropertyChanged on my data classes to get a good responsive easy to compose ui
Yeah I'm used to WPF with MVVM
I talked with someone from the UIElements team and they said that some members of their team really want to go towards a system like that
honestly, I see UIElements being potentially the best UI framework around
if they impelement a system like that, for me atleast, it would be
wpf's styling is pretty weak, it took me UIElements to really realize why CSS is a better styling system (I hate web dev)
The main weakness with UIElements atm that I see is simply connecting to data, and SerializedProperties are pretty terrible causing BindingPath to be shit
here is hopinh they go down that road official like
I want to see DataTemplates
and a ContentPresenter element
which is kinda the same statement I suppose
Tbh, I just want WPF with better styling
yeah, ditto
not important for unity, but if you haven't seen it, Xaml-CSS is a thing that exists
Doesn't look very supported though
And we're using material design for wpf
So we can't easily switch
the main reason I haven't explored it is because I don't do WPF outside of work, and I don't particularly want to migrate all my styles...
Yep same here
yeah, you know, the more I think about it, the more I realize just how limited UIElements is because it doesn't have an equivalent to Binding
not even looking at the fact that you can't easily bind to your data model, you can't bind between elements, so you can't make a toggle button control the visibility of another control easily
CSS does make this all kinda wierd though I suppose
Yeah I've had that discussion with multiple people
It's the thing that's holding it back
I think its possible to build this ontop of VisualElements however
you would need to abandon all their higher level controls and rebuild them
I can tell you, I've built a DataTemplate and ContentPresenter combo, that worked pretty well
And force everything to wrap things in properties
you don't need to, Unity can access INotifyPropertyChanged
Oh right they moved a bunch of that stuff
regardless its a very simple event
Anyways, I wanted to bind to serializedobjects since then you get undo handling and serialization for free
and the UI Hooking is pretty trivial in itself, its the automatic data conversion that is the big deal component
I think you could handle that all in a Binding class
the main issue is making sure your data always makes it back to the UnityEngine.Object
Sure you could handle that yourself but I'd rather not 😛
And you're stuck with polling if you use SerializedObject
Which I don't want to either
Polling for what, to save changes?
ah no, screw that
if you're going to go down that road, do it right, setup INotifyPropertyChange, build a set of controls that are capable of supporting a Binding markup for element attribues, build a binding class that can hook into the VisualElement.userData which checks to see if the userData object implements INotifyPropertyChanged and if it does it registers a handler on the event
I basically did that in my parametric modeler
Yeah but I don't want INotifyPropertyChange in my game code
So the way WPF handles it is basically the same, you need that event in order to have efficient generic updates of the UI
right now its lossy because you don't get to use it in your game code, but they are making a runtime version of UIElements
So once that is in, you'd be able to benefit from it in the editor and in game
True, I might take another stab at it sometime
What's the best way to load an uxml to an editor window? I don't feel like using the Load("path") is the best option
Don't know if there is any other tho
I don't think there is another way
I mean you can resolve the path from the guid or something
But it's not going to be that much better
if your distaste is about the path, then maybe you can use Addressables?