#↕️┃editor-extensions
1 messages · Page 111 of 1
ok I'm gonna keep track of the Port class you told me to create in the script that handles loading the View of graph view
Sounds good
ok so now I can add them here no problem
Yap
wait what changing member info to field info just worked???
?
nothing, it worked
Cool
so now every single Node class has a list of variables and ports linked to each other
so now in this function I have the parent port and the child port, along with the nodes that correspond to both of them
Sure
ok one last issue and this is done
I made this function here
and I want to reference it here and I have no idea why it doesn't show up
ok nvm now I know why
well now that I'm using FieldInfo instead of MemberInfo it doesn't seem to get any of the PortAttributeInfo correctly-
What does the code look like currently?
You need to use GetFields, not GetMembers
I did change it to that
then I saw that using fields doesn't work for some reason
went back to memberinfo
and now it's still broken
just like my brain after all of this
Which parts did you change to use FieldInfo?
Then that wasn't the issue
There's no reason that GetCustomAttribute will fail for FieldInfo and not for MemberInfo
Chances are you might have accidentally missed a spot to change
You don't need the field.CustomAttributes.ToArray().Length > 0 btw
yes
omg I know what the issue is
omg I may be stupid, as you could probably already tell
ok
foreach (FieldInfo field in node.GetType().GetFields(flags))
{
var attribute = field.GetCustomAttribute<PortAttribute>();
if (attribute == null)
continue;
var info = new PortAttributeInfo(field, attribute);
var port = InstantiatePort(Orientation.Horizontal, attribute.direction, attribute.capacity, field.FieldType);
// etc.
}
What's the point of the portattributinfo class
to get info for whether or not the port should be input or output, and to determine it's capacity
is that needed anymore?
cause it doesn't seem to work anyway
It doesn't seem to have much use from the code samples shown
It's just for this Port newPort = InstantiatePort(Orientation.Horizontal, info.portAttribute.direction, info.portAttribute.capacity, field.FieldType);
Yeah you can just pass in the values from the attribute directly
attribute.direction would be the same as info.portAttribute.direction so there's little point in PortAttributeInfo existing if that's all it's used for
I keep messing up the variables and then being shocked why they don't work
ok cool
so now I have a list of all the variables and the ports that correspond to them, and I need to specify them where the selected line is
I have a list of all the nodes in the tree which I can access from this script
and then those nodes inside the node tree have a list of ports and variables that correspond to them
so now I need to make the links
I have the parent port and the child port
ok so now I just need a function that gets me the variable from the port it corresponds to
and my brain has decided it should just fry and die
so now I can get the variables in a read format, aaaand I need to be able to set them
...
ok so apparently this did work
I changed the type to object and reanalyzed the code a bit
and now when I add a link between them
I get an object from the variable of the first node, and one for the second node
only issue is-
it's an object
cause I needed it to be of reference type
and I don't only need strings so I couldn't use that, even if it was also a reference type
I just need to cast this as the type of the variable
so kept track of the type but it doesn't let me use it
uhh
one issue
I can't just cast it using a variable
so I have no reference to the original variable
and variables can be either strings, gameobject, literally anything
so I can't just go parentObject as string
cause it could be something else
so I keep track of it's Type as well
but I can't dynamically cast it like that apparently
it gives me a red line if I do so
yeah no that doesn't work, but it's also kinda useless if you don't know at all what type you'll be working on. what types could it be?
well
it's really hard to explain-
but rn I have objects that need to be casted
there really isn't any other way I can get the type except by using a variable
i'll have to read the previous posts a bit
ok I found a function
Convert.ChangeType
I hope it works
nope
it does not
apparently Expressions can help-
ok, i read your posts. why do you need the variable as the correct type?
because I need to pass data using reference types
so instead of creating a copy of the variable
it creates a reference to the original
and to do that I need to use the object type of variable
but then when I assign that variable, it's not gonna be read as a string or gameobject, just, object
so I can't debug.log it and stuff for my nodes to work
I can keep track of the type of variable I need it to be at runtime
and I just need to somehow cast it from an object to that type at runtime
yeah, i faced a similar problem before. if you have relatively few object possibilities, you could use If(object is GameObject obj) => Log(obj);
ok so apparently I can't just use an object and then cast it later
so I need to somehow store the data in binary and then load it-
right?
You need to use reflection to set the variables
Since you don't know their type at runtime
You can use the field info you saved to do this
Fieldinfo.setvalue
You can't pass value types as reference types this way
I get this in return from the object
uhh
I changed it to object
?
I didn't know how to use FieldInfo
cause I needed to pass the variable
so, I changed it to object from FieldInfo, because I needed it to be a reference type of variable
Wut
You cast fieldinfo to object?
forget I said anything
Lol
no
You need both, tbe
I changed the class that held the info for the port and the variable
I changed this to object
The reference to the class and the field info
from FieldInfo
In order to set the value via reflection
ok so now I have a reference to the field info of the variable from the start port, end the end port
so now I need to convert it from a FieldInfo to the variable it was originally
so I kept track of the ports and the variables that correspond to them in a class
originally the "variable" one was of type FieldInfo
so now, I have a reference
to both the variables of the start port and the end port
and I just need to set the variable from the end port to be equal to the variable from the start port
so I get a reference of the first variable string stringToOutput
Ok, so use the fieldinfo of the start port to get the value (boxed as object)
Then use the fieldinfo of the end port to set the value
Almost
and then you told me to do it as FieldInfo
ok cause it was giving me an error lmao
Yah that's not correct
then how-
Should look something like this
Endportfieldinfo.setvalue(endport, startportfieldinfo.getvalue( startport) );
I'm on phone so forgive the pseudo code
You need to get the field info for both the start and the end port
Code 😓
You're passing the field info as the object reference
You need to pass the port object
Not the field info
Read my pseudo code again
ohhh
childFieldInfo.SetValue(edge.output.node, parentFieldInfo.GetValue(edge.input.node));
like this?
nope
nope
why would it work
I wrote .node
I am an idiot
Field stringToOutput defined on type String_Node is not a field on the target object which is of type
UnityEditor.Experimental.GraphView.Port
That's my bad, I meant to write the node
Replace start port and end port with start node and end node
now it looks like this
childFieldInfo.SetValue(parentView.node, parentFieldInfo.GetValue(childView.node));
shouldn't it be like
the other way round-
cause it's the childFieldInfo I need to be set to the parent
Yes it should be the other way around
I don't understand the node part
Child with child, parent with parent
parentFieldInfo.SetValue(parentView.node, childFieldInfo.GetValue(childView.node));
that's better
Which is the parent and which is the child
Is it flowing parent to child
Or child to parent
from parent to child
the data needs to be passed from parent to child
the first node to the second
and all I have are the FieldInfos of the variables
both being boxed
Then you need to switch the parent and child
as FieldInfo or object I have no idea anymore
But switch both parts
ok it still won't work
wait what
wait WHAT
IT WORKED???
of course it works the moment I lose all hope
of course it does then, like always
Told you
Remember that code will always do exactly what it tells you to
and I'm almost finally done with this stupid graph
Not what you want it to 😄
yes
exactly
there's just one more thing to fix now and it's finished
thank you smmm
oh god what if I change the first one tho-
if I change the first variable it has no way of knowing to change the second
ok this will take more time but thank you lol
I'm gonna go take a break because I've worked like 6 hours on this today-
gets up from chair and crumbles into a million lego pieces
That's why you do it while you're executing the graph
You don't need to sync it at all times, that's a waste
It only matters when you're actively doing something with it
yeah but this is the only script that can sync it-
I think I can like
change it
but that part of the code is still messed up
I will be back tomorrow I guess lmao
there's a system for this already online but it didn't work for me, and plus, I made it this far so
NodeGraphProcessor on Github
but it didn't work for me
Okie
Is there a way to render a struct inside of an OnGUI call (readonly is fine)?
Yes
This is outside of a unity serialization context though
I just want to display the values inside a struct the way unity would display them
Since it's serialized you can get the serializedproperty and use editorgui.propertyfield
But it isn't being serialized anywhere
You're creating it in th editor?
It's just on the stack, e.g. inside the OnGUI method
You can manually draw the field values using guilayout.label
I don't know the structs type, it's just an object
I think I'll just call ToString for now and just override that for visualization purposes
Yeah it's just for debugging purposes
The reason I have such weird requirements is I want to display the ECS component values of an entity, and those aren't serialized in the usual unity sense
ah, I see
So I understand that you can draw a box handle for editing objects using UnityEditor.IMGUI.Controls BoxBoundsHandle, but is there any way to round the corners?
Or to draw a curved line for the corners
The curve doesn’t necessarily need to be editable with handles but I just would like some way to attach it to the boxes on the corners
I’m talking about functionality similar to the rounded corners you can apply to the 2D box collider component
Any help with this would be great
Can you show an example of what you are thinking?
If you want what I think you do, then you will most likely need to draw the whole thing yourself using the Graphics API
Well it’s only necessary to have in the editor
So I’d use gizmo’s/handles in the OnSceneGUI method to draw it
Just wondering if there’s a simple way
Actually internally the Handles API uses Graphics to do all of the drawing
As far as I know, there is no built-in way to have rounded corners on any gizmos
I’m away from my PC at the moment so I can’t give a code example but the thing the closest would be the BoxCollider2D
The BoxCollider2D is able to support rounded corners
I was just wondering how it is able to do that
I don't really work with 2D so I'm not sure. But I took a look at the source code and it seems to just be a box handle. I don't see anything about rounding corners
Could you link me to the source code?
Thanks, that was quite useful even if it didn’t solve my issue, I’ll also look into the box collider 2D code to see if I can find anything
can you still get kite
Any idea why I cant see the edges, the port successfully connected
e.outputPort.ConnectTo(t.inputPort);
but no edges being drawn
in the context of connecting ports programmatically if that will help
checking all edges in the graphview var edges = graphView.edges.ToList(); returns 0, meaning the edges weren't created at all
Managed to do this. I was a dumbass, I didn't add the newly created Edges to the graphview 🥲
in case anybody wants to connect their graphview programmatically, it's quite simple :
var edge = e.outputPort.ConnectTo(t.inputPort);
e.outputPort.Connect(edge);
graphView.Add(edge);
edge.MarkDirtyRepaint();
I just found out that GraphView api is deprecated in favor of Graph Tool Foundation, like damn, i've spent many hours with this.. like dayum
It is not deprecated at all! GTF is built on top of GraphView. GraphView is just a generic, view-only way of creating graph views while GTF is a view+data package that uses GraphView to show and editor data in a graph. It is a higher level and more specific thing.
Also GTF won't be out until at the very earliest 2022.2, more likely 2023.x though
the exposed APIs are very nice to look at too, also
You can think of GTF much like that NodeProcessor github project
if you see the example of GFT, it doesn't look like custom editor tool at all
What do you mean?
see how they did it in the example, hard to explain as english isn't my 1st language
long story-short, it doesn't look like customEditor code
I have, do you mean it looks hard to extend/do custom stuff with?
the best part about looking about the graphtools foundation package docs is the billion namespaces and 3 of them say GTFO
GTF is such an ugly mess...
no it's the opposite
it's just feel a bit clunky after toying around with it for the past two hours
Oh, yeah deffinitly
It is a pretty bad API and also doesn't have the same structure as existing APIs
well, whether we like it or not, they will replace what used in ShaderGraph, Bolt etc with GFT soon (see the link below, after this!)
'soon'
such a big word, I know XD ....
I am looking forward to seeing the roadmap from GDC to see if they say anything about it
the staff themselves said that in the link above(proly from other thread, just see if it's there if I'm not mistaken)
Not that I doubt it will be, but the above thread that claim is just from some random
I just realized that Benoitd took over GTF, he also is/was one of or the lead for UITK, so I have high hopes that it will improve
There's another thread where the staff answered one user, not in that thread yeah
I don't blame them if they wanted to deprecate graphview tho, it's been stale since 2018
on the other hand, I don't think Unity would just deprecate it either, like, they invested so much money into it.. ya know
@gloomy chasm @visual stag been searching the thread about 'graphview' being deprecated which i saw earlier today, see this, its unity employee who said it.. https://github.com/alelievr/NodeGraphProcessor/issues/73#issuecomment-671071879
And sorry for the ping 🙃
Yeah, kinda sucks tho... It has so much potential
As long as something in this form exists and does the job then I'm happy
and as long as I'm not working for Unity and having to deal with whatever internal pain caused them to reevaluate
Kind of odd they would ditch GraphView considering ShaderGraph and VFX Graph use it. But I have to assume they had some design issues with it...?
Either way, with Benoitd handling GTF I think it will end up being good. He at least knows how UITK works haha.
My only concern with GTF would be that it would cause limitations in creation graph views due to being more data oriented instead of strictly view like GraphView is.
Will just have to wait and see I guess.
Thank you, that's perfect! (sorry for delayed response) Only thing I'm still struggling with is getting the source value so I can check if the modification is redundant. I'm using PrefabUtility.LoadPrefabContents to load the prefab I'm checking property modifications on, but when I call PrefabUtility.GetCorrespondingObjectFromSource() on the modification's target object I always get null returned. I can't revert all of the modifications, just the redundant ones, so I somehow need to find the corresponding value in the parent prefab
GetCorrespondingObjectFromSource is the only function that sounds like what I want, but I guess it isn't. Perhaps I need to get the parent prefab via the variant's root and manually find the matching object by path in the hierarchy of something?? hmmm
What do you mean "redundant" modifications?
Good q. For context, I'm working on a UI styling system. You can bind styles to component values via UnityEvents. So when you apply a style you're essentially invoking a bunch on UnityEvents that can change arbitrary properties on a prefab.
I'm trying to make the styles apply in the editor, but if you have a prefab with a style component on it, and a prefab variant, and I apply the style on both, the prefab variant will set the same properties as the parent prefab, but the changes will be property overrides which is not ideal considering it's the same values as the parent prefab.
Then there's the case where you might override/add specific bindings on a variant and those changes should persist as property modifications.
So tldr: there's basically just a ton of edge-cases when making a tool that can write to arbitrary properties and my best attempt at a solution is to see all property modifications on a prefab variant after applying a style and revert the ones whose values are unchanged from the parent prefab
(sorry for the text dump. no sweat if that doesn't make any sense!)
Hmm, I think that makes sense. My first thought is "ehh, just use UITK that does all this for you" haha, but that isn't really an answer.
Would getting a SerializedObject of the parent prefab('s component) and then just checking each property to see if they are different work?
just use UITK
yea ikr 😭
would love to, but it's still missing world-space and custom shader support which is needed on my current project
getting a SerializedObject of the parent prefab('s component)
yea that's what I was thinking, but getting that parent component is what's stumping me. wasn't sure if there was a clean way in the api. any component on any object in a prefab could have modifications so i need to find a way to get the corresponding object on the parent.
PrefabUtility.GetCorrespondingObjectFromSource()seems to be for prefab instances, but I'm crawling over every prefab asset in the project.
idk if this is helpful, but this is the structure of the function
private static void ApplyPrefabStyleBindings(string prefabPath)
{
var prefabRoot = PrefabUtility.LoadPrefabContents(prefabPath);
try
{
var stylables = prefabRoot.GetComponentsInChildren<Stylable>();
if (!stylables.Any())
return;
foreach (var stylable in stylables)
{
// If this is stylable part of a variant we need to do some complex shit to avoid redundant property modifications
if (PrefabUtility.IsPartOfPrefabInstance(stylable))
{
// this is the tricky bit
}
// Otherwise we can just apply the style cuz this is an "original" stylable
// and any changes it makes should propagate to variants automatically
else
stylable.ApplyStyle();
}
PrefabUtility.SaveAsPrefabAsset(prefabRoot, prefabPath);
}
finally
{
PrefabUtility.UnloadPrefabContents(prefabRoot);
}
}
Perhaps PrefabUtility.GetCorrespondingObjectFromSource() isn't working because I'm calling it on the game-objects returned by PrefabUtility.LoadPrefabContents(prefabPath). If that function is just writing plain ol game-objects into an isolated scene with no link to the actual prefab asset that would explain why GetCorrespondingObjectFromSource only returns something for nested prefab instances since those would still be linked to their source prefab 🤔
OH SHOOT. propertyModification.target is on the parent prefab 🤡
is there a way to get individual sprites ? Im trying to create Sprite component and pass it the relevant tiles
@tough cairn I'm not sure if there's a way to load a specific sprite by name but you can use AssetDatabse to load everything from the file and then filter that list to the one you want
then unload everything else
Yeah, that is the only way to get subassets if they are of the same type.
gtk
Also, as far as I know if a main asset is loaded, all of its subassets are as well.
that doesn't make sense to me, how would one access them once they're loaded
What do you mean?
if you load the main asset you don't also retrieve a reference to the other assets in the file
so they'd be pointlessly loaded in that case
So I got curious and you are right. Only note is that if you load a sub it will also load the main, but you can then unload the main and the sub will stay loaded
that makes sense -- if you're loading a sprite it's referencing the main texture
so that would have to become loaded
I am making a custom inspector to hide/show a couple of properties based on the state of an enum. It works great, but writing the custom inspector is very verbose, because I have to call EditorGUILayout.PropertyField(abcdef); for every single serialized field in the class... which means I have to retrieve and store a SerializedProperty reference for every single field... is there some other way?
At the very least is there some way to generate these from a given monobehavior automatically, since they're always identical boilerplate
Perhaps... I can use reflection to walk through the fields on the monoB and only operate on the ones I want that way... 
As far as I know that's the only way to do it
You can iterate over all of them, or use DrawDefaultInspector
You can iterate through them with some fancy code, but almost everybody just does it this way
If it's a small custom inspector it won't be worth it, but if it has tons of variables it might be worth trying
I'm pretty sure i am on to something with the reflection option... will report back
Oh I see
No need for reflection it'll just list them
Can I use Gizmos in OnSceneGUI() somehow? If not, is there an alternative to Gizmos.DrawSphere() that I can use in a UnityEditor.Editor?
Hmm I don't see a way in serializedObject to just get all of them
How are you iterating over them? serializedObject only seems to offer them to me by name
in FindProperty()
.GetIterator() and then using .Next(..)
Handles class
I recommend googling how to do it as it is a bit hard to understand without seeing it
Oh I see, that should be enough 🙂
The only relevant one I can find is SphereHandleCap, but doesn't that include interactivity? I'm looking for drawing a simple "gizmo" for purely visual feedback
how can i use Shader.Find with a shader graph asset in editor script ? ❓
or should i just rather use AssetDatabase ?
@gloomy chasm Hmm do you know of some way to differentiate between the properties that would actually show in default inspector drawing?
The iterator is returning lots of hidden properties that I assume are just part of MonoBehavior
NextVisible(..)
Just a heads up that the field for m_Script will be picked up by NextVisible(), but the default Unity MonoBehaviour drawer will draws that field as disabled. So you have to manually look for it and draw it as disabled if you want to match their style.
Yup already skipped it
😄
This works GREAT btw thanks for the pointers
Now I can just loop in OnInspectorGUI and check for name of specific property to modify how it appears
Now to make this generic 😛
nvm i fugured it out - added the shader to project settings in Always include shaders and now i can use Shader.Find
can i get editing tools in unity
Due to my concern of GraphView being deprecated in favor of GTF, after closely inspecting the internals of GTF, I can savely assume that they won't deprecate it !?(at least, not as soon) turns out GTF heavily relies on the GraphView, like literally running on top of it
so fingerCrossed 🥲 or else I'm wasting my time integrating vroid with the graphview for the past months👀
Either way, I should've researched on this before starting the project 😵💫
so i want to replicate something like this where select objects become colored and appear in the hierarchy, tried searching around but no luck, how could I pull this off?
Hi guys. I want to write an editor script to upgrade UI.Button to my custom controller. I need to move button.onClick to my controller (gbtc) which has a UnityEvent activeEvents type field. How can I move that?
for (int i = 0; i < button.onClick.GetPersistentEventCount(); i++)
{
Debug.Log("Button onClick " + i + ": " + button.onClick.GetPersistentTarget(i) + " " + button.onClick.GetPersistentMethodName(i));
gbtc.activeEvents.AddListener(???); //UnityAction is expected here
}
This is printing fine the targets and methods. But how do I convert it to a UnityAction type which I could then add to the UnityEvent?
Even if you can convert it to a UnityAction, anything you add with AddListener will not be serialized. UnityEvent doesn't have a public scripting API to modify the persistent listener list.
Yep you are right. I got it working with AddVoidPersistentListener like this:
UnityAction action = (UnityAction)Delegate.CreateDelegate(typeof(UnityAction), button.onClick.GetPersistentTarget(i), button.onClick.GetPersistentMethodName(i));
UnityEventTools.AddVoidPersistentListener(gbtc.activeEvents, action);
Is it possible to create some sort of virtual scene?
The use case is that, I'm making my own UI framework and would like to preview each component in editor by running it, as if it was the real game.
There are preview scenes, but they don't have their own play mode separate from the regular play mode.
Do you need it to be in play mode to preview it?
No sorry if I didn't make it clear, I want to preview without going into play mode.
Currently what I have is that, each UI component is just a simple .cs script, and the editor extension mounts it onto an editor window and emulate what it probably looks like in play mode
But as you can imagine it's a bit problematic, I'd like to have a real virtual scene to mount the component in instead, so I can look at things like hierarchy, click on the mounted game objects and inspect the components, etc.
You mean like what you get when you open a prefab?
Yeah.
You can implement your own through this API
https://docs.unity3d.com/ScriptReference/SceneManagement.PreviewSceneStage.html
Nice, seems to be what I'm looking for.
Is there a quick example somewhere to get started with it, or I just have to read through the docs and piece together how it works?
I've never used this API, so I'm not sure.
Ah okay, thanks still 😄
If my base class has ExecuteAlways attribute, does subclassing it inherit that as well, or do I have to add that to all my subclasses?
Hi all, have a super simple class here tagged with [System.Serializable], and trying to display them inside an array / list in the inspector, but the ui isn't scaling to the actual number of properties
Do I need to write a specific editor script for this/could someone point me in a direction I can look?
Thanks
actually it's only element 0 that's acting strangely, element 1+ seems to work fine
A class? What if you try converting it to a struct, does it display fine then?
Shouldn't make any difference
If there isn't an Editor or Property Drawer here, this just seems like a bug
A couple useful tools in there. Surprisingly he didn't include the serializable dictionary
ok so I have an OnGUI function that checks for input, and whenever I press the spacebar it opens a menu, but it doesn't work if I do it while hovering over the graph view
also, my graph view doesn't display if I scale it on auto-
on the height
for the size you can try setttoparentsize StretchToParentSize
oh ok
ok one issue now is that it stretches to the whole editor window, and if I add a parent over it, it just doesn't work anymore-
make layers, so you don't have to parent all uielements in one container
nvm it just doesn't scale at all on the y axis
even though the flex is set to 1
I just can't set the height to auto
thats weird stretchtoparentsize should do that for you
make sure your graphview is at the bottom-most of the rootvisualelement
e.g:
graphView.StretchToParentSize();
rootVisualElement.Add(graphViewInstance);
rootVisualElement.schedule.Execute(()=>SetToolbar());
it appears normal in the ui builder if I just use the standard tools, but doesn't actually display in the editor window
you don't even need to adjust the flex with stretchtoparentsize
after you set all, try to Repaint the editorWindow then MarkDirtyRepaint to the graphview
you can see all the hraphview's properties and methods here https://docs.unity3d.com/ScriptReference/Experimental.GraphView.GraphView.html
ok
yeah, it doesn't work more than 500 px
no matter what
either 500, or it just doesn't display
UnityEditor.UIElements.DefaultEditorWindowBackend.RecreateWindow ()```
well, try to make a clean editorwindow then add just the graphview with nothing else, see if it works
it should work or else people will throw rocks at Unity 🙂
You just need to play along with it, I mean, learn how to use it
omg it works-
see 🙂
ok now tell me
if it was already added
root.Add(splitView);
WHY DO I NEED THIS-
omg now even scaling on auto works-
6 years and this program still manages to give me rollercoasters of anger
I don't want to break the hype, but GraphView will be deprecated soon 😃 in favor of GTF
I-
try to avoid it while you still at the early stage of your project
...........
why, in the hell, is it not marked as deprecated
is it available already?
can I make the switch now?
still a rumour, but one of the employee of Unity stated that they are no longer maintaining it
oh cool
makes sense considering you can still link ports that are of different types
yes, but do note, there are ZERO documentation on how to use it. Your best bet is to tinker with the (clunky and buggy)examples that come with it
aight
of course there's no documentation
whatever
it's not like I would've understood it anyway lmao-
good luck!
thank you-
I-
am scared lol
everything graph view related is just dialogue system-
you can make your own vscripting with it, just like BOLT
that's what I'm trying to make
I don't really see a reason to switch tho-
like, I can do undo/redo system myself
and I know how this one works
so
the only issue is the fact that for some reason you can connect a port of type gameobject, for say, with one of type string-
I tried both, turns out to just be a bug. Tried in a different version of unity and it's working fine
Anybody worked in mirror unity?
Wat
Could you elaborate?
Yea sure. Mirror Networking in Unity. It is a multiplayer server similar to photon.
how is that #↕️┃editor-extensions related tho... sounds like #archived-networking would be more appropriate
Cool then thanx
Does anyone here know how you would set grid settings in the editor via code? I'm not sure where to start looking for this.
Reflect/use serializedobjects into this https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/SceneView/SceneView.cs#L627
Would it be possible to remove the dock window and create your own window dock for a Custom Editor?
What dock window?
You mean show one editor window inside of another?
no not at all
I want to remove the entire window part for a borderless-like window.
so I can do a more customized full curved UI design
thanks
I take it I'll have to entirely create the draggability and resizeable functions
What Navi linked, but with that said, you can't curve the border of the window. And also, just as a note, it is better to always try to have your editor/window have the same styling/design/ux as the default editor
Yeah, you will
I had an idea that I could override the default style with a custom scaleable image for the background.
You will still see the background of the window
Best case scenario you could get the background of the window to show as black. But Editor Windows don't support transparency of specific areas.
iirc if you dig deep enough in to the source code there is a method to set the alpha of the window, but that is the whole window and I think it doesn't work on Mac
yeah I think Macintosh overall doesn't support that due to finder limitations
I can live without the external window curve
some in-editor panels I may do curved.
Please don't
(I mean it is your thing you can do what you want. But if you plan on sharing it, it makes it a lot harder for others to use)
the main reason I want to do a custom design is so I can use different colors and do a custom top-bar.
curved is more or less not necessary anyway
plus this isn't going to be shared as I'm just trying to see how far I can take Editor Window design before I do anything further with the concept
like Editor Window Animations.
better to experiment and rule out than to never have experimented at all
There is almost never any need to add special coloring to controls in the editor. Simple labels and or icons work basically all of the time and allow for a consistent editor experience
That may be the case for a lot of examples.
but again, experimenting is better than never trying at all.
Popup windows are still a handy thing and even if I find I don't want to do this idea further, I will have learnt more than I will have if I didn't.
Thanks for the conjecture too, I'll keep it in mind for UI/UX.
How come editor classes don't need to have the ExecuteInEditMode attribute?
I'm really new to editor scripting
Because Unity calls methods in Editor classes outside of playmode
oh, so it's because for example, the if (GUILayout.Button("My Button")), it's done in OnInspectorGUI(), which is called outside of playmode?
is that every frame..?
oh, so does pressing an editor button redraw the inspector?
I see! Thank you
when you say UI, you mean.. anything in the editor?
okay, thank you!
also if you want to do it every frame (which can be inefficient on a case-by-case basis)
you can just use the update void and call Repaint() repeatedly.
not recommended but it's an option....
quick question, is there a way to delete an edge? like a function in graph view?
Heya. Is it possible to draw properties just like the inspector would draw them in an editor window if you have the serialized object of the type you want to be drawn in the editor window. I can't quite get this to work like the inspector. The closest I get is by using serializedObject.GetIterator() but that looks more like all the properties are in a big array and not like the inspector would do.
GetIterator is correct, you would then use property.NextVisible(true) to iterate over them.
However if you just want to see an editor, you can use var editor = Editor.CreateEditor(targetObject) to create one and then call editor.OnInspectorGUI() in your own window
Is there any case where a UnityEngine.Object could be referenced by an serialized field of an asset and not have a GUID?
(debating storing string references to ObjectReferences via asset GUID instead of GlobalObjectID)
what does it take to get the Unity Editor to display properties of array members in the array list?
You're going to have to elaborate. If you serialize an array of something serializable, then they'll be visible.
I have a MonoBehavior that has an array of objects that has properties including and int and a Sprite
If that object is marked as serializable its members will appear as long as they are also serializable
when I add a new object to the array, it just shows me a blank text box
with @Serializable?
sorry, @SerializeField
[Serializable] on the class, and the members have the usual public/[SerializeField] requirement
okay, I think I was missing the []
hmm, autocomplete still isn't giving me Serializable
it's in the System namespace
yeah, I just found it
thanks!
sometimes it's the obvious stuff
hmm, still not showing anything
This should be all I need, right?
[Serializable]
public class GameTiles : MonoBehaviour
{
[SerializeField]
public GameTile[] gameTiles;
}
[Serializable]
public class GameTile : MonoBehaviour
{
[SerializeField]
public int weight = 0;
[SerializeField]
public Sprite sprite;
}
MonoBehaviours are inherently serializable, so the attribute is redundant.
[SerializeField] on a public variable is redundant.
Having GameTile be a MonoBehaviour means that you'll just see an Object field in the list, where you drag and drop components into the slots.
If you just want classes in that list without objects in the scene then that type shouldn't inherit from MonoBehaviour
should it just be standalone then?
public class GameTiles : MonoBehaviour
{
public GameTile[] gameTiles;
}
[Serializable]
public class GameTile
{
public int weight = 0;
public Sprite sprite;
}```
If you need GameTile to be in the scene on different objects then this is not the setup
I'm going to use GameTile in a script for match-3 blocks
the weight determines how likely a given tile is to be selected
Yay! It works now!
thanks again
that should make it so I can edit the weights on different levels
is there any way to make subclasses of the specified parent class selectable in the above array list?
thanks it works :)
hey, do we have Odin experts here? wanted 2 know how to draw parts of an OdinEditorWindow manually
something like EditorGUILayout.PropertyField(SerializedObject(this).FindProperty("MyInt")); but in Odin style
Is there some way to have an "OnEnable" or "OnCreate" for a property drawer using IMGUI? I need to configure a GenericMenu whenever my property drawer is first created. If not, bad hack solutions are also welcome
just create an empty Constructor
Wait constuctors are allowed? Interesting. This should fix it for me, thanks 🙂
@vapid prism not entirely. But u mentioned hacky solutions are allowed
Any idea how to disable mouse events on the edges in the GraphView?
Yes there was some Boolean variable or sth that would say that the event is consumed
Don't remembered what it exactly was tho
Does anyone remember how to call the this window, but with their own text? I once saw a friend find it, but now I can't find it.
if you meant pickingMode = ignore well that won't work
but I guess overriding the HandleEvent for any mouse events should do the job, but i thought there's something builtIn for this
Hmm, no actually it was something else. Let me search a little bit. Tho I never used it so I can't check my codes or whatever. But I believe it was pointed somewhere in the docs tutorials
That little unresizable window that gives some info is usually called a Dialogue. So maybe that's the same for Unity
thank you, I'll wait for it while doing my own research on this 🙂
Call this method when you've used an event. The event's type will be set to EventType.Used, causing other GUI elements to ignore it.
aight, I'll see what i can do with it, thanks a ton!👍
proly I can just intercept it on TrickleDown instead ?... hmmm
well, it works
edge.RegisterCallback<MouseDownEvent>(e => e.StopImmediatePropagation(), TrickleDown.TrickleDown);
Thanks!
I fount it. https://docs.unity3d.com/ScriptReference/EditorUtility.DisplayDialog.html
Can someone help me figure out a solution to my problem?
The custom inspector serializedObject.FindProperty() wont work with a variable that has a Getter/Setter
I've updated my Unity Project from 2020.1.0f1 to 2021.2.17f1, also the packages JetBrains Rider Editor and Visual Studio Code Editor. since then Reload Script Assembles takes 3~4 sec from previously ~1 sec.
looking for a solution i found this https://forum.unity.com/threads/reloading-script-assemblies-takes-a-long-time-and-keeps-getting-slower.1228698/ i dont know what I am looking for at Profiler window however
That is because FindProperty is a misnomer, it actually only finds serialized fields (public fields or private fields with the [SerializeField] attribute)
Thx
Does anyone know if there is a list somewhere of what the built in USS class names are?
how drunk was this guy when he wrote this
You mean class names used by built-in Unity elements?
That is what it does though...
Ah, that is better
Lol, my brain just automatically fixed it to "to iterate"
anyone know my ide literally dies on this line? theres obviously nothing wrong and when I comment out that line - no errors
Is it because it is called enum?
There are built in USS class names such as "unity-button", but I couldn't find a list of them anywhere
Ah, yeah as far as I know there isn't one right now
Is there a better way to add custom behavior to the "+" button in the Editor array list view than to implement a reordable list in a custom editor display and assign the custom behavior in ReorderableList.onAddCallback?
I specifically only want to add a GenericMenu with some pre-built options for things to add to the list on top of adding a custom item.
Is it possible to customize this part of the inspector when I select a script file asset?
That's not the inspector for your script. That's inspector for cs asset files and seems like an internal thing. Sorry :(
You can probabyl create a generic monoscript editor but I would suggest not to do that
Why is that?
https://github.com/Unity-Technologies/UnityCsReference/blob/d0fe81a19ce788fd1d94f826cf797aafc37db8ea/Editor/Mono/Inspector/MonoScriptInspector.cs
fyi this is the script for that. Possibly if you make a new customeditor with that attribute it will work
Because it'll apply to all Monoscripts and thus you might fuck up something
Thanks.
Well I'm not using it to modify the script, but I just want to be able to use reflection and do some logic
Check if the script contains a subclass of a base class, and if so add a "preview" button to that side of the panel that opens up a prefab stage and mount that script.
I don't think that could mess anything up?
@glacial sail
[UnityEditor.MenuItem("CONTEXT/MonoScript/test")]
public static void test()
this works
That's for right clicking the asset right?
three dots as well
I mostly want it on the inspector view because I can also add fields to let me setup values for the preview.
My second option would be to have my own editor window and have it detect selection change (but that requires an extra click to switch to the window, or have it permanently take up screen space)
Third option would be to bring up this window via a menu item/keybind.
Would be nice if I could just append to the current inspector, or whatever the term is.
you can do it
afaik you can grab existing editor windows and position yours, did that long ago
tho just keeping it as a tab is also an options
we have lots of those
Hmm yeah
I guess it's not worth the hassle to save that 1 click.
I'll just make it in my own editor window and dock it as a tab somewhere.
Hey, need your help guys
I want to make a tool where my colleagues reference all components to reorder under a category
exemple: I want to add a "Camera" category, where any gameobject implementing any of the red-arrow components will be under
what I have:
what I want:
problem: I reference "monoscript" in my list but I want any component, wheter it is implemented by Unity (Camera/Transform/etc.) or by the team (any of the monobehaviour scripts we write) is it possible?
for now I have ```cs
m_scripts[_index] = EditorGUI.ObjectField(_rect, m_scripts[_index], typeof(MonoScript), false) as MonoScript;
FindObjectsOfType(monoScript.GetClass())
nah that's not the problem
i dont want to reference only monoscript
but any component from unity
whether it is a monobehaviour or anything we implement
any of these
var allComponentTypes = UnityEditor.TypeCache.GetTypesDerivedFrom<Component>();?
then how to adapt this to be compatible with the typecollection
I dont know what the type collection is
GetTypesDerivedFrom<Component>() returns a typecollection
when I click here, I want to reference any component like when you click the "add component" button in a gameObject
I want to see something like this
but add it to my list
Ok cool, use var allComponentTypes = UnityEditor.TypeCache.GetTypesDerivedFrom<Component>() to get all the types.
Are you confused how to add the elements of a TypeCollection to a List?
no, i am confused about what to put here
because you cant put a TypeCollection here
And thats not what you want either right, you dont want a collection of types there. You want a single type
yes
So you have an ObjectField, which can show UnityEngine.Object. This cannot show a System.Type, which the type collection contains
afaik there is no UnityEngine.Object for the type of Camera.
Why dont you do a Popup, with the types?
that's.. actually not a bad idea
In case you are interested how Unity does it
thx
reorderable ListView doesn't support for multiple items reordering at once?
it has listV.selectionType = SelectionType.Multiple; but when dragged, only single item actually reordered
also in the context when listV.reorderable set to true
After researching about making custom shapes in uielements, i stumbled upon this https://docs.unity3d.com/ScriptReference/UIElements.MeshGenerationContext.html
so basically we can create our own custom shapes for our UIs...
dayum Unity, you're in the right direction.. for once, at least
how can I call the Initialize phase before OnCreateGUI()?
I need to create a custom window and pass a variable to it, before OnCreateGUI() is called
like a constructor
but I can't pass the data from another script then
Are you not calling ShowExample from another script?
it doesn't work
no
it's a built in function
even if I do this it doesn't work
Then ShowExample has to find the object and use the data somehow
How can I prevent the scene view camera from zooming on scrolling? I've tried this with directly setting it back to little success (at best it jitters), and I've tried eating the event but that's just too destructive to other editor stuff. Any advice?
.
Scratch that, from some more digging I think it's straight up not possible so I've just got to pick my poison. New problem.
How can I set the active object in the hierarchy? I've used Selection.activeGameObject and activeTransfrom and the like, and they do select the object I want. It doesn't show that properly in the hierarchy though. Any idea why?
@craggy latch wasn't I talking to you about this problem before?
it's definitely possible
Not without either eating the event or setting it back after it happens.
you can eat the event without it being "destructive to other editor stuff"
Oh?
here, let me rustle up some of my code
I thought it was either that the event existed and so would be used to zoom, or didn't and nothing could use it.
I mean, if you override zoom then you won't be able to zoom
that's a given
but you can conditionally control that
Ye but I mean things like OnSceneGUI also get eaten if you use the event up.
https://docs.unity3d.com/ScriptReference/Editor.OnSceneGUI.html See for yourself. Second line.
yes I know that
you can't eat all of the events
you need to only eat the event you're using
here's a method overriding left mouse click (arguably more important than scroll wheel)
private void HandleMouse ( Event evt ) {
if( evt.type == EventType.MouseDown && evt.button == 0 ) {
var worldMouse = GUIExtras.GUIToWorldPoint( evt.mousePosition );
var gridMouse = new Vector2Int( Mathf.FloorToInt( worldMouse.x ), Mathf.FloorToInt( worldMouse.y ) );
SetCursorLocation( gridMouse );
evt.Use();
}
}
private void BeforeSceneGUI ( SceneView scene ) {
activeScene = scene;
var evt = Event.current;
toolId = GUIUtility.GetControlID( FocusType.Passive );
if( evt.type != EventType.Repaint ) {
DoToolbar( activeScene );
}
if( evt.isKey ) {
HandleKeys( evt );
} else if ( evt.isMouse ) {
HandleMouse( evt );
}
}
here's the BeforeSceneGUI callback
I think I'm treating events a little too much like frames in my head then if eating on doesn't really matter beyond the specific thing that's happening.
this is directly plugged into beforeSceneGui
in the first snippet I am eating the event
but I'm only eating it if it is specifically a MouseDown event with the left mouse button (that's what button == 0 means)
if I were to just put Event.current.Use() at the end of my BeforeSceneGUI method, then yah I'd be eating layout, repaint, mouse, and keyboard events
that would give you the symptoms you're describing
Ah, I see my mistake then.
everything shares the same Event.current
it's like one of those conveyer belt sushi places
you can pick up and eat the sushi you want -- as long as you get to it first -- but if you eat every sushi you come across there's nothing left for anyone after you
TIL - I shouldn't eat all the sushi.
nope, you'll get sick
There's also some things you should understand about hotControl, but I'm not sure you need it for just overriding scroll behavior
so that can be a topic for another day
If you have a non dyanmic Font in unity is there a way to stop the editor from spamming warnings when you assign that font to a GUIStyle? If you don't set it in the style it won't render; but if you do unity logs Font size and style overrides are only supported for dynamic fonts.
Anyone happen to know a way to tell, for a prefab variant you have selected in the project, if a given property on a given component is overridden from the base?
So I've found where the warning for my non dynamic font sizes is coming from in the source code
{
if (settings.font != null && settings.font.dynamic)
return settings;
if (settings.fontSize != 0 || settings.fontStyle != FontStyle.Normal)
{
if (settings.font != null)
Debug.LogWarningFormat(settings.font, "Font size and style overrides are only supported for dynamic fonts. Font '{0}' is not dynamic.", settings.font.name);
settings.fontSize = 0;
settings.fontStyle = FontStyle.Normal;
}```
I tried force assigning the fontSize and fontStyle in the GUIStyle to match the statement and even put an if block in the GUI update to not render the GUI element if the values aren't assigned correctly like this
```if (_buttonStyle.fontSize == 0 && _buttonStyle.fontStyle == FontStyle.Normal)
{
if (GUI.Button(position, new GUIContent(label), _buttonStyle));
{
ShowPicker();
}
}```
and I'm STILL seeing the warning when the Button renders.
I am trying to write an editor that has a property field to select assets from the project(no scene) When i set the type and try to select an asset there is nothing listed. I was hoping to be able to select a prefab by component. Is it at all possible. Currently i can assign the values but have to manually drag it in. This is using the UI Builder
No, Unity does not allow picking a prefab asset based on component
Is it possible to split inhering classes into different serlized objects. Lets say we have 2 classes. Class2 that inherits from Class1. When class 2 gets a serlized object it will have data from both Class2 and Class1. Would it be possible to make 2 new serlized object one of which only contains the properties for Class1 and one which only contasin the properties for Class2?
Nope
What is the goal/reason for wanting to do that? Maybe I can suggest an alternative solution?
Hi everyone.
I have a problem with a Custom Inspector for my current project. I Would need a SerializeReference and Subclass Selector for a Generic type.
[SerializeReference, SubclassSelector]
public IAbilityDataScore<IAbilityScoreContainer>[] m_AiScores = Array.Empty<IAbilityDataScore<IAbilityScoreContainer>>();
This is how it looks inside the Code. Does anyone of you has a quick idea if its even possible to get a prober Selector here ?
The answer depends on what SubclassSelector is and how it is implemented?
But if you mean generally is it possible to do, then yes.
oh yeah i shouldve mentioned it that its a tool ... its like 3am here and im tired. Sorry.
So it should be possible to select a Class that inherits from an interface by interface even tho the class implements a generic type? (hope this sentence makes sense...)
It is possible to do yeah. Whether and how much custom coding for the selector you need is a different matter
yeah :/ i face this really problematic problem right now that i Need the editor function to select classes out of a list. But inside the code, i would need a more specific reference to it to generate some code in the background and i have no clue how to get the generic type from the interface
type.GetGenericArguments()
can i access this if i only have the interface that is not generic?
i think im trying to get data thats impossible to reach.
okay nvm ... GetType().UnderlyingSystemType.BaseType.GetGenericArguments() gives me the answer but DAMN This looks messy.
want to draw a list of classes and have those classes have a custom property drawer but this happens..
[CustomPropertyDrawer(typeof(Option))]
public class OptionDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginProperty(position, label, property);
EditorGUILayout.PropertyField(property);
EditorGUI.EndProperty();
}
}
Option being the type of the class in the list
why aren't they drawing in the correct place
anyone know anything about xNode?
For options, I want to have a port for when the option condition returns true and when it returns false
I have a list of 'option's and option is just a simple class
public class Option
{
public string text;
//If true, condition(s) will act as a roll. You'll be able to choose this option but will go to a different result based on if it's true or false
public bool isRoll;
//Conditions needed to be able to choose this option
public OptionCondition[] conditions;
//Only used/set by AdventureEngineParser. If false, button is disabled and cannot be chosen.
public bool canChoose;
[Output]
public Node onTrue;
[Output]
public Node onFalse;
}
however not sure how to turn these specific fields into ports
since the Option is contained in a list
I have to draw the list and then draw Option and draw those two fields as ports
so I made an editor script that goes through properties of a class and splits them into menus based on property attributes to easier edit a large section of properties on a script. The thing is though that this breaks when using inheritance since the editor script will get the serlized properties it need to draw the property in the editor window and the fields it needs to detect attributes in different orders. The serlized properties start at the base class where as the fields start at the child class.
Is there any way to call a method from a serialized property? for example I'd like to call the GetArgs() method on the serialized field foo:
[Serializable]
public class Foo {
[SerializeField] float f;
public float GetArgs() {
return f;
}
}
[Serializable]
public struct Bar {
[SerializeField] Foo foo;
}
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(Bar))]
public class BarDrawer : PropertyDrawer {
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
EditorGUI.BeginProperty();
if (GUI.Button(position, "Run Bar")) {
var foo = property.FindPropertyRelative("foo").objectReferenceValue as Foo;
var args = foo.GetArgs();
// do something with args
}
EditorGUI.EndProperty();
}
}
#endif
but I get the error: "Der Typ "UnityEngine.Object" kann nicht mit einer Verweiskonvertierung, einer Boxing-Konvertierung, einer Unboxing-Konvertierung, einer Umbruchkonvertierung oder einer NULL-Typkonvertierung in "Foo" konvertiert werden. [Assembly-CSharp]"
basically you can't convert from UnityEngine.Object to Foo
also how do change the language of the error messges? I changed all language packs in vs installer to english?
You can't
You can find it though through reflection and the property.serializedObject.targetObject field
Language is probably based on your currentculture
Anyone?
is it possible to inject a drop down element inside all shader graph nodes ?
I feel like I'm missing something, I have a ExecuteAlways MB and Update does work, but it doesn't seem like IPointerClickHandler works?
For context, I'm trying to make my own UI button and make it also work in editor where I can click it in scene view and it will do something.
Ok so I might have just messed up. I've been informed that Unity's Graph View is no longer being developed, and is being replaced instead with another system, that has no documentation. Is there any way I can keep that package in future Unity versions?
no
Ok great!
So what the fuck do I use then
I just, wasted a month.
Gotta fucking love Unity sometimes!
i think this: https://docs.unity3d.com/Packages/com.unity.graphtools.foundation@0.11/manual/index.html not 100% sure, but pretty confident
Wait but
Someone from Unity posted a github page for it-
Incase it isn't safe to use anymore
but if it won't be continued....do you really want to build upon deprecated tech?
I mean
I did
I don't need more than what it does
Idk, there's no documentation on anything else
And I know how to use this one
don't ever think that you definitely never will extend your tool
i've posted you the docs
And I know another package that has all the features I could ever possibly need that uses the old system
I think it uses that one
Yeah I doubt I'll understand them
I'll try to look into it more
the off doc docs (as i like to call these) are imo always much better understandable than the standard unity docs
I genuinely don't know if Graph View is actually deprecated
I can't find anything about it online cause there's like so little resources
@cosmic inlet There is no official word on GraphView, and it is being 'widely' used (numerus unity packages and asset store assets use it) so it is still safe to use. I don't see it going any where for at least a couple of years.
That is assuming that it even is 'deprecated' internally
it is / was never safe to use btw. it's even marked as 'experimental' api
Yeah I saw someone mention that they thought it was a bad idea to use it because of the "Experimental" part
Well, 'safe' to use. A number of packages use it, along with a number of assets. So even if Unity does deprecate it, they will know this and not remove it.
So then they snet a link to the github page in case something were to happen
Ok well, at least I don't have to stress now
that makes the statement even worse
Yeah, thought so
ReorderableList is in the internal namespace but has been in for years and is widely used
So just because something is in a 'experimental' or 'internal' namespace doesn't actually mean that much
Ok thank you!!
isn't shader graph is build on Graph View API ?
still. people, update your api's damnit. technical debt and long deprecated features are a cancer of development
bump
Sure is
Sure is
🙂 that's a question lol
then its safe to build tools with it then @slim zinc
I was saying it is possible 😛
Just get the node and traverse it's ancestors (or children)
simple UITK stuff
sounds like difference in opinions rather then fact
maybe seek other plugins / assets from the store that have long term support ?
Well, they have documentation on it, so regardless of anything else, it is 'intended' for public use which means they will not remove it hastily
yes. of course definitely opinions.
that doesn't mean it should be recommended to people
node.hierarchy[0].Add(new Label("My label"));
will that work without modyfing shader graph source code ?
There is no public reason to not recommend it to people and imo it is better than recommending a really old community driven IMGUI solution
i like IMGUI
Oh you mean like but still in to shadergraph code?
i want to add drop down on top each shader graph node
graph tools foundation is not imgui
That is fine, I like IMGUI too, but I like UITK better. And it is simply a fact that UITK is the future of all editor tooling UI in Unity.
I was referring to xnode and the like
¯_(ツ)_/¯
and i was always referring to graph tools foundation
don't use 3rd party assets for things you can do natively in unity......
Ah, well I was just talking about in a general sense of what to recommend people. I do not recommend GTF because it is not being publicly developed meaning no bug fixes and there is very high chance that it will have its API overhauled before its 1.0
yes
that's unity XD
hmmm that does make it harder...
but possible with reflection somehow ?
is there any callback in the Editor for when the name of a gameObject was changed?
Not that I'm personally aware of, I just use a janky Update() check for when the current name and last seen name of a derived class are not equal, and then raise my own event if necessary. Possibly useful, here's a stackoverflow post about a library called Harmony. https://stackoverflow.com/questions/4538017/monkey-patching-in-c-sharp
Just remembered there's OnValidate function, which I can utilize just for this use case
I think there is, see this https://docs.unity3d.com/ScriptReference/EditorApplication.CallbackFunction.html
also see this
Actions that trigger this event include creating, renaming, reparenting, or destroying objects in the current hierarchy, as well as loading, unloading, renaming, or reordering loaded Scenes.
well thats a big thanks, didnt know about renaming
me too, kinda handy
I have this script to create diferent files in the Asset folder. But the TextFields doesn't work, they don't update and i dont undestand why. Thanks for the help.
using UnityEditor;
using UnityEngine;
using System.IO;
public class CreateFile : EditorWindow
{
public string editorWindowText = "Choose a file name: ";
public string editorWindowTermination = "Choose a file extension: ";
string newFileName = "New File";
string newFileTermination = ".txt";
static void Create(string name, string term)
{
Debug.Log(name + term);
string copyPath = "Assets/" + name + term;
if (File.Exists(copyPath) == false) // do not overwrite
using (StreamWriter outfile = new StreamWriter(copyPath))
outfile.WriteLine(" "); //File written
AssetDatabase.Refresh();
}
void OnGUI()
{
string inputName = EditorGUILayout.TextField(editorWindowText, newFileName);
string inputTermination = EditorGUILayout.TextField(editorWindowTermination, newFileTermination);
if (GUILayout.Button("Create new file"))
{
Create(inputName, inputTermination);
Debug.Log(inputName + inputTermination);
}
if (GUILayout.Button("Cancel"))
Close();
this.Repaint();
}
[MenuItem("Assets/Create/Text File")]
static void CreateProjectCreationWindow()
{
CreateFile window = new CreateFile();
window.ShowUtility();
}
}
you have to use the same string as param and return
what do you mean?
TextField accepts a string
that string will be available in the ui to edit
after you edit it, it will return a new string
to continue editing the same string, you have to supply it next frame
the same string
But I have inputName as the return value, right?
the new string is returned every frame
you have "hello world" you type D it returns "hello worldD"
and since you are giving it the string that doesnt change, it will display the same thing in the field every frame
Its complicated. iirc the GraphView will 'destroy'/'unload' nodes once they go out of the view a certain amount. So it isn't as simple as just finding the node and adding an element to it. However if it was, then all you would need to do is to get the shadergraph window via reflection and Resources.FindAllObjectsOfType, and then traverse the rootVisualElement until you find the node you want and then add it to that element
is it possible to subscribe / unsubscribe to visual element events via reflection like on-children changed , on-window-focus , etc .. ?
unfortunately there is no nice "children changed" event for visual elements
But if you can do something 'normally' you can do it via reflection
scanning the whole tree 2 times per second shouldn't be too expensive im assuming
No need to do that, simple get the exact elements you need
Open up the UITK debugger and inspector the SG window to figure out the hierarchy and the 'path' to the element you want
However if it was, then all you would need to do is to get the shadergraph window type via reflection and Resources.FindAllObjectsOfType(..)
that method is really a life saver
wait so FindAllObjectsOfType will only work for the elements inside the window , or rather it can also find the window itself ?
FindAllObjectsOfType will find all loaded UnityEngine.Objects of the specified type
i see , so it should do the trick then
Yup, it is actually the only way to find editor windows if you are not referencing them
GetWindow(..) actually uses that internally to get the window
Actually, that isn't exactly true, you can also get the MainView and traverse its descendants to find windows. But that is a bunch of reflection and most likely slower haha
Good call haha
That's brilliant! Thanks for sharing ❤️
silly question, but how would I be able to group several script fields into a dropdown like this one, with a custom inspector?
I used something like this :
public MClass : MonoBehaviour
{
[System.Serializable]
public class Variables
{
[Range(0,1)] scale = 0.5f ;
public bool flag = false;
}
public Variables vars ;
void Start() { .. }
}
it will automatically do the grouping of the parameters
yeah I know bout that, but I was wondering if it could be done via a custom inspector, since I'm not really up to change every single reference to have the class infront
sounds like you need a custom attribute
Yeah you can use a custom editor to do it per script
There is also this project on github that allows you to use attributes to group them https://github.com/gasgiant/Markup-Attributes
trying to add child at index 0 with no luck ...
var title = container.Children().First(); container.RemoveAt( 0 );
var contents = container.Children().First(); container.RemoveAt( 0 );
var btn = new UnityEngine.UIElements.Button();
btn.AddToClassList("profile-node-dropdown");
btn.text = "injected";
contents.Add( btn );
container.Add( title );
container.Add( contents );
That is because VisualElements have a contentContainer element where Add(..) will add children to. An example of this is the Foldout has a child element which everything is added to so that it can just change the display of the child instead of the display for every child
You need to use element.hierarchy.Add(..) instead
Also, you can use both the indexer or ElementAt(..) to get a child at an index
what's an indexer ?
element.hierarchy[0] ?
Yup
Just in a general sense, not UITK specific. Like how lists and arrays work, you can actually implement an indexer in your own classes and they can take any value, not just int.
// Mock spline class...
public class Spline
{
// get a position along the spline given a time value.
public Vector3 this[float t]
{
get { return _curve.Evaluate(t);
set { _curve.AddPoint(t, value);
}
}
oh i though that the indexer parameter was limited to int
looks like i might use that later , thanks 🙂
Yeah! They are pretty cool! It is what Dictionary uses too
didn't quite work ended using position absolute
Ew
actually looks ok im my case
Well if it works for you!
is there UI Elements way to add icons ?
i got it working with a IMGUI so far :
var button = new Button();
button.Add( new IMGUIContainer( () =>
GUILayout.Label( EditorGUIUtility.IconContent("d_Toolbar Plus") ) ) );
I use the Image element (it is a VisualElement)
If you just want a 'icon button' (a clickable icon) I normally just use an Image and add the Clickable manipulator to it
cheers
button.Add( new Image { image = EditorGUIUtility.IconContent("d_Toolbar Plus").image, tooltip = "Create new profile" } );
Editor folder can be nested anywhere and doesn't have to be directly under Assets, right?
correct
If you use assembly definition files it doesn't even have to be called Editor
@glacial sail ping in case you missed it
Thanks.
But it should be in order to follow conventions and make it clear to everyone else that it is (and to yourself in the future).
My scripts in Editor folder doesn't get autocomplete, any idea how to fix it?
Using VS Code.
Moving them outside of Editor makes them work, but that's not ideal obviously.
Nevermind, restarting O# and it works again, classic O#.
what is O#
OmniSharp, what powers C# in VS Code.
need to detect when editor has just launched, is there a native way?
InitializeOnLoad with SessionState checking whether it's already executed this session
nice, thanks
is it possible to detach children of visualelements from the parent so it can be parented to another?
Hello channel I am currently working on a project where i need to have two very different build targets. One is building Unity as a library for android and the other one is building a standalone App for android. The difference is a few settings in the project settings and one setting in the preferences. And i am currently stuck on finding a way to set certain project settings. Namely the custom manifest and gradle template checkboxes. Does anyone know if and how this is possible from an editor script?
is there a EditorUtility.DisplayDialog that allows the user to enter a string ?
no
Hi all, does anyone know which one of these inspectors is used for scriptable objects? https://github.com/Unity-Technologies/UnityCsReference/tree/master/Editor/Mono/Inspector
SOs don't have one, it is just the base Editor class
Same with components
I see, thank you
Do you know if its possible to use the base editor class to do something akin to this for SOs?: https://forum.unity.com/threads/extending-instead-of-replacing-built-in-inspectors.407612/
And if so, how I might go about doing so. Any advice/learnings would be greatly appreciated!
(I should add that I've managed to get it working for GameObjects, mostly by replacing the parts that say transform)
If you want it to work with custom editors, than there isn't an easy way to do it.
I think the way that would work in every scenario is to inject UITK elements in to the inspector. But that would involve a good bit of reflection and fancy code
Noted, thank you. Only just approaching reflection, so sounds a bit out of my depth for now. Throwing this out there in case you (or anyone else) has any alternative suggestions to achieve my ultimate goal: which is to have some extra buttons in the inspector for all objects
You could put them in the header easily using Editor.OnAfterHeaderGUI (or something, I don't remember the event name exactly)
I'll have a look, cheers!
Seems to work a charm! Thanks a lot 🙂
How do I make EditorGUILayout.ObjectField for Texture2D display inline instead of this?
I've found that using GUILayout.MaxHeight(16f) works but that's a hardcoded height, is it defined anywhere?
Actually the correct value should be 18 instead, but yeah that's kind of the problem.
try EditorGUI.singleLineHeight
Anyone using MyBox? I'm running into a strange issue, I'm using [DisplayInspector] but its showing twice:
Edit: Moved over to NaughtyAttributes. Problem solved.
Exactly what I'm looking for, thanks.
Is there a good resource for learning about writing modules to extend Unity's Sprite Editor? I saw Sprite Editor Window functionality can be extended by providing custom module. but that is... less than entirely helpful. I'm not really sure where to begin, since I don't have much experience with Unity's UI stuff.
Yeah. The 'somehow' is what I'm hoping to figure out. 😄
What are you trying to achieve?
Because the api looks pretty straight forward assuming you only have to implement it and Unity finds and creates it for you
public class SpriteExtension : SpriteEditorModuleBase
{
public override bool CanBeActivated()
{
return true;
}
public override void DoMainGUI()
{
}
public override void DoToolbarGUI(Rect drawArea)
{
}
public override void OnModuleActivate()
{
}
public override void OnModuleDeactivate()
{
}
public override void DoPostGUI()
{
}
public override bool ApplyRevert(bool apply)
{
return true;
}
public override string moduleName { get; } = "Test";
}```
and it shows up in the Sprite Eidtor in the dropdown
Does anyone know what this error means when making a custom editor?
Assertion failed on expression: '!(o->TestHideFlag(Object::kDontSaveInEditor) && (options & kAllowDontSaveObjectsToBePersistent) == 0)'
UnityEditor.HostView:OnLostFocus ()
essentially I go to create a SO that the editor references, and as soon as I click off the SO turns white in the project and loses it's UI obviously, and the console shoots this error at me..
Unity 202.3 3.31f in case it matters
seems to be stemming from:
hideFlags = HideFlags.HideAndDontSave;
🤔
Can you show your code
Is there cleaner way to do this or do we just have to litter like this everywhere we need edit mode specific logics?
#if UNITY_EDITOR
if (Application.isPlaying)
{
Object.Destroy(_gameObject);
}
else
{
Object.DestroyImmediate(_gameObject);
}
#else
Object.Destroy(_gameObject);
#endif
Hi guys, posted this #archived-shaders message
But also asking myself if its not more Editor based.
Are we supposed to create a custom Editor UI for Shadergraphs ?
hey
i Have two buttons styled like this using UIElements
how could I style them like these (without using Stylesheets if possible)?
not sure how visible this is but I'm trying to put labels inside this grid of buttons, but a label seems to offset my button by a lot; how would I offset a GUILayout button?
or maybe a better question would be "how do I make the label take up less space"
edit; added GUI.Label
There is this that you can subscribe to in the editor https://docs.unity3d.com/ScriptReference/EditorApplication-playModeStateChanged.html
also see all the stuffs here https://docs.unity3d.com/ScriptReference/EditorApplication.html
which some you can incorporate it with InitializeOnLoad
I have some code that’s meant to be run both at runtime and edit mode, and they don’t really work in a callback manner.