#↕️┃editor-extensions

1 messages · Page 12 of 1

gloomy chasm
#

By however tall you make the helpbox rect

errant shale
# gloomy chasm By however tall you make the helpbox rect
  • Well, i thought there's an utility for getting the default size, like the one in default editors

  • Beside that, i can't make it work. I tried doing what you said essentially, but i must've missed something not so obvious for me. I currently just try to draw the helpbox at the original position rect (it's not modified, i verified this a dozen of times), and still no luck. Are there any extra steps before drawing the helpbox that i missed?

errant shale
#
  • Yep, doesn't show up at all. Here's a piece of my script in case it helps. Before that, i tried creating a new rect and tweaking the position rect, nothing worked. The debug log works as expected, so these lines are executed properly
gloomy chasm
errant shale
#
position.height = 1000;
EditorGUI.HelpBox(position, ...);
  • Still nothing. Original height is 18
gloomy chasm
#

Should be working....

errant shale
#

¯_(ツ)_/¯

#
  • Okay, so custom inspector it is. How do i tell the inspector from the property drawer when to draw the box?
tawdry kraken
#

I have a ReorderableList with a drawElementCallback https://gdl.space/zaqelubofi.js
where I override the right-click context menu. (GenericMenu)
It works, but for some reason the Rects seem shifted down.
If I click the top-most element, the default context menu shows up.
If I click below the visual border of the bottom-most element, I get my custom context menu (even though it is in blank space).
Any hints at what might be wrong?

#

Clarification: Line 18 in the link is partially commented out.
Each element will be checking for the click, and the commented part needs to be fixed so the correct element receives the click.

if (Event.current.type == EventType.ContextClick)// && rect.Contains(Event.current.mousePosition))

In this current state, the first element 0 always receives the click first, using/consuming the event.

crude forge
#

hm. I have a ListView, I'm using SetSelection in the code for something. How do I fetch and highlight the item I want in the listview? It's selected, but not highlighted

whole steppe
#

hi!

#

umm, I'm trying to make a password text field!

with the ability to show the password when a button is clicked!
this is what I've done so far -> __https://paste.mod.gg/kuwkcxrkwgmn/0__

it works just fine... however! when the button is clicked!
it doesn't actually show up as being clicked, it only interacts on hover-over...

which isn't that big of a deal per se... but I'd really preferer the way the GUILayout.Button method works when being clicked!
it becomes link-like blue that emphasizes the fact it's being clicked!

I tried using the mentioned method directly, but that ruined the Event.current.type making it become EventType.Used instead of EventType.MouseDown...

I'd love any type of help!

crude forge
#

hm. https://forum.unity.com/threads/eventtype-mouseup-does-not-work.1407013/
running into this problem. is there a better way to go about this? basically attempting the same thing, making a quick tool system that should spawn a selected entity into the scene. 'quick', except it doesn't work because of the mouseup issue outlined here

crude forge
gloomy chasm
#

Also you should be using the EditorTools class to implement scene behaviors

crude forge
#

Hot controls?

#

Okay, that was absolutely key here. I'll look into using the EditorTool class - I found a couple examples, this was just a sticking point

whole steppe
# whole steppe umm, I'm trying to make a password text field! with the ability to show the *pa...

after some research, the GUIStyle.active.background was what I'm looking for!
however! it seems to only function on controls that support the active phase... (such as GUILayout.Button)

the button mimicking I'm doing right now in my script, does not reach that phase since it's only a label display thus
making the GUIStyle.active property useless when adding a button style to the GUILayout.Label method...

example:

var btn = new GUIStyle(GUI.skin.button);
btn.active.background = activeTexture;
btn.normal.background = normalTexture;

GUILayout.Label("Preview", btn);```in here, only the `btn.normal` property is being taken into account by the `Editor` while `btn.active` is being ignored...
any clue on how to work around this?
whole steppe
crude relic
crude relic
whole steppe
glad cliff
#

hey! Im looking for some creative solution for a stupid problem.
I have something like this in my code:

for(int i=0; i < someProperty.arraySize; i++)
{
  private void SomeLocalMethod(){
    someProperty.GetArrayElementAt(i);
  }
}

Dont ask me why, I have my reasons. Ofc after compiling someProperty.GetArrayElementAt(i) will throw index out of bound couse i is equal to arraySize at this moment and im looking for some solutions for it. I cant make that method global and cach i and then pass it, couse it is being assigned as a delegate for something, so I cant change the predetermined parameters list and somehow it needs to have access to local variables inside of for loop, so it need to stay as a local method.

errant shale
#
  • I have a gui layout button with a text so large it doesn't fit within. I read about the gui styles and i've already tried setting wordwrap and stretchheight to true, but it still doesn't work. How do i make the text to be wrapped? Here's the code and the result in case it's helpful
EditorGUILayout.BeginHorizontal();
            
if (GUILayout.Button("Open build settings")) {...}

var style = EditorStyles.miniButton;
style.wordWrap = true;
style.stretchHeight = true;
if (GUILayout.Button("Select a scene to add to build settings", style)) {...}
            
EditorGUILayout.EndHorizontal();
errant shale
glad cliff
#

im debugging it and it appears like it is empty and it may couse it, but I dont know why tho

#

i literally have this in my OnEnable

#
private void OnEnable()
    {
        alternatives = (target as FSMCTransition).conditions;
        if (alternatives == null || alternatives.Count == 0)
        {
            alternatives = new List<FSMCConditionWrapper>();
            alternatives.Add(new FSMCConditionWrapper());
        }
    }
glad cliff
#

I see where the problem may be

#

[SerializeReference]public List<FSMCCondition> conditions = new();

#

FSMCCondition is an abstract class so I used this new SerializeReference which i know nothing about pretty much, only that it helps with polymoprhism

#

and when I try to access properties in it with GetArrayElementAt(0) it throws out of bound despite there is one element there

#

i guess maybe it works differently

glad cliff
#

ok so ive been sitting here for a while and my previous problem is gone. My current problem looks like this

#
public class FSMCTransition : ScriptableObject
    {
        [SerializeField] private List<FSMCConditionWrapper> conditions;
    }

    [Serializable]
    public class FSMCConditionWrapper
    {
        [SerializeReference]public List<FSMCCondition> conditions = new();
    }
#

this is something i want to make an ispector for

#

where FSMCCondition is an abstract class, thus SerializedReference

#

for each element in a first level of a list I want to render a reorderable list (the one in a wrapper class) using ListView from UI Toolkit

#

I created a button that invoked a method to add an element to the list

#

and at the end of this method I do

serializedObject.ApplyModifiedProperties();
listView.Rebuild();
#

when list is rebuilding itself it cannot find the item added to the list while invoking BindItem

#

simply GetArrayElementAt returns out of bounds

#

but when i go into debug mode i see that this element was added properly and it is there

#

then going back to normal view it bind itself correctly

#

i dont know why the heck GetArrayElementAt cant find this object right after its being added, but finds it with no problem when reopenning the inspector

glad cliff
#

wtf...

#
Debug.Log((target as FSMCTransition).conditions[outerIndex].conditions[index]);
Debug.Log(serializedObject.FindProperty("conditions").GetArrayElementAtIndex(outerIndex).FindPropertyRelative("conditions").GetArrayElementAtIndex(index));
#

pls help ;-;
clearly object is there, but finding it as a property gives null

glad cliff
#

serializedObject.Update() fixed it... Im pissed of mainly becouse I already tried it and didnt help so didnt tryagain despite doing some other changes in a code that could affect it XD

#

anyway, now it works ahhhh

gloomy chasm
#

Anyone know of a way to instantiate a prefab without any of the Awake/Start/Enable methods of any components being called?
Alternatively, instantiate a prefab as inactive.

waxen sandal
#

prefab.enabled= false then instantiate

gloomy chasm
#

Odd

waxen sandal
#

You sure that doesn't execute anything?

#

I'd expect it to do awake tbh

gloomy chasm
#

oh, duh, yeah it does call Awake and Enable (forgot ya needed to add [ExecuteAlways]

gloomy chasm
# waxen sandal prefab.enabled= false then instantiate

Yeah, so you are right. Sadly you need to cache it and reset the state otherwise it will actually update the prefab

bool cachedActive = go.activeSelf;
go.SetActive(false);
Instantiate(go);
go.SetActive(cachedActive);
waxen sandal
#

Yeah it's annoying in editor but yo udon't need to in build

gloomy chasm
#

Really? I would think it would still in build as well

crude forge
#

ooor my hotfix appears to work perfectly? wow

vast tiger
#

Is there a way to be able start a coroutine both from Editor and Application like below?

Monobehavior:

void Start() { Rebuild(); }
public void Rebuild()
  if (Application.isEditor && !Application.isPlaying)
   {
       EditorCoroutineUtility.StartCoroutine(DelayBuildChunks(), this);
   } else {
       StartCoroutine(DelayBuildChunks());
   }
}

Editor:

public override void OnInspectorGUI() {
MyComponent controller = (MyComponent)target;

if (GUILayout.Button("Recreate All"))
{
  controller.Rebuild();
}
#

I mean so basically something like: if editor = EditorCoroutineUtility.StartCoroutine, else StartCoroutine

#

I mean, the above works. But is there a better way?

#

Like returning only the IEnumerator and running EditorCoroutineUtility.StartCoroutine only in Editor classes?

#

Also, I probably need to wrap above with #if UNITY_EDITOR so that above exports

gloomy chasm
hoary grove
#

I have this script in my project, that, the entire point of it is to place a Prefab inside another Prefab/Tilemap, when a specific Tile is placed using the Tilemap.

The problem I'm runing into is that when undoing it, I was hoping to "Destroy" the created Prefab. However, I'm now getting the following error:

InvalidOperationException: Destroying a GameObject inside a Prefab instance is not allowed.

Is there a work around for this at all? I can obviously just delete a gameobject pressing the delete key... so I dont understand why I can't do it programatically?

void OnDestroy() {
        //If it has a Linked Object, which it should, destroy it.
        if (linkedObj) DestroyImmediate(linkedObj);
        //If there isn't any wall launchers left in the scene, remove the holder.
        if (holderParent && holderParent.childCount == 0) DestroyImmediate(holderParent.gameObject);
    }

This is the call that is trying to do the destroying. I can provide more context if needed.

hoary grove
#

Looks like my only option is to upgrade Unity....

#

And upgrading Unity broke something else instead...

crude relic
crude relic
hoary grove
crude relic
#

You should be registering a created object undo, which should take care of the Ctrl z case

#

Why do you need to do anything manual when deleting? Shouldn't it get cleared up by the tool?

#

Or is that what's causing the error?

hoary grove
#

Right so, let me explain it a bit better.

When I place a Tilemap object I gather its information:

objectID = "Pref_+ " + linkedNamed + "_" + gridLayout.name + "_" + cellPosition.x + cellPosition.y + cellPosition.z;

From there I check to see if I can place it in a parent object:

if (holderObj == null) {
                Debug.Log("Not Found:");
                holderObj = Instantiate(new GameObject("Temp"), Vector3.zero, Quaternion.identity, gridLayout.transform.root);
                holderObj.name = holderName;
            }

Then I instate a prefab and place it in the parent.

        linkedObj = Instantiate(prefabObj, hideThis.transform.position, hideThis.transform.rotation, holderParent);
#

Lastly, when I delete this game object. (The Tilemap either by Undoing or by erasing) I delete it.

void OnDestroy() {
        //Don't do it in the prefab edit mode.
        if (EditorSceneManager.IsPreviewSceneObject(gameObject)) {
            return;
        }

        //If it has a Linked Object, which it should, destroy it.
        if (linkedObj) DestroyImmediate(linkedObj);
        //If there isn't any wall launchers left in the scene, remove the holder.
        if (holderParent.childCount == 0) DestroyImmediate(holderParent.gameObject);
    }
crude relic
#

I see

tawdry anvil
#

I want to create one of these toggles - what are they called?

#

I'm trying to create an extension that shows the total bounds of an object, whether via its mesh or via its colliders, etc. I thought to create a button like the ones I screenshotted above, but that would only be useful in toggling the visualization on and off. Maybe I could also Debug.Log the bounds, but might there be a better way?

#

Maybe I could just add an entry to the Menu Bar (or whatever the File, Edit, Assets, ... menu is called) with my extension controls and also create a custom editor window

#

ah wait I could use something like this tool but with all 3 fields disabled

tawdry kraken
#

@earnest talon Doesn't seem like this is documented, so in case you haven't seen them yet:
Check out EditorStyles.FromUSS() and EditorStyles.ApplyUSS()

earnest talon
#

Ill have to read the C# source for them

whole steppe
hoary grove
#

Is there a alternative for Gameobject.Find but in the prefab edit window?

hoary grove
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestFind : MonoBehaviour {
    [ContextMenu("Test")]
    public void Test() {
        GameObject find = GameObject.Find("Level");
        if (find == null) Debug.Log("Not Found");
    }
}

1: Place that on any prefab.
2: Double Click the Prefab to open it up in the Prefab Edit Mode.
3: Make sure the Prefab has a game object named "Level"
4: Right Click TestFind -> Test
5: Observe "Not Found" in Console Log.

gloomy chasm
hoary grove
gloomy chasm
#

I mean, generally it is better to never used GameObject.Find at all.

hoary grove
#

I'm not using it during runtime, so, using it for an editor script is perfectly acceptable.

gloomy chasm
#

Nah, still best not to use it because it is dependent on the string name of the GO which can be changed at any time by anyone. (plus it is slow)

#

There is almost always a better way to do the same thing depending on the use case

hoary grove
#

Same thing then, finding a reference to a script doesn't work.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestFind : MonoBehaviour {
    [ContextMenu("Test")]
    public void Test() {
        TestFind find = FindObjectOfType<TestFind>();
        if (find == null) Debug.Log("Not Found");
    }
}

At the end of the day, scripts can't be found when editing a Prefab.

gloomy chasm
#

Yeah, that is expected. The object is in a PreviewScene, not a 'actuall' scene.

#

You just gotta find it manually. But if you are trying to get it in the same prefab, I feel like there would be a number of better and more performant ways to do it.

hoary grove
#

It being performant... isn't a problem... Again, its not like I'm making 100,000 operations at once and its going to take forever. I'm attempting to find a game object, once, that's it.

And if there are better ways of doing it then please feel free to share.

gloomy chasm
zinc wasp
#

I have a system of classes, interfaces etc., how can I make a separate UI to inspect these? Serializeable would be a pain in the ass, and would also involve infinite nesting.

gloomy chasm
zinc wasp
#

an extra window in the editor, where all the classes of the system are displayed in relation to each other

gloomy chasm
gloomy chasm
alpine bolt
#

I'm serializing MonoBehaviours and ScriptableObjects and testing a nested reference situation where a MonoBehaviour is referencing a MonoBehaviour, within a MonoBehaviour, within a MonoBehaviour, etc... Is there some kind of property drawer limitation in scene scripts? There's no issue with the scriptable object side. The property drawer base is the same for both and the concrete SerializedMonoBehaviour and SerializedScriptableObject look exactly the same, just applied to different UnityEngine.Object types```cs
#if UNITY_EDITOR
using UnityEditor;

namespace TG.SerializedUnityObjects.Editor
{
[CustomPropertyDrawer(typeof(SerializedMonoBehaviour), true)]
public class SerializedMonoBehaviourPropertyDrawer : SerializedUnityObjectPropertyDrawer { }
}
#endif

#if UNITY_EDITOR
using UnityEditor;

namespace TG.SerializedUnityObjects.Editor
{
    [CustomPropertyDrawer(typeof(SerializedScriptableObject), true)]
    public class SerializedScriptableObjectPropertyDrawer : SerializedUnityObjectPropertyDrawer { }
}
#endif```
#

Left stops applying PropertyDrawer. Right continues normally.

gloomy chasm
#

Unity does have a serialization depth limit of 7.

wintry badger
#

Does anyone know how to find an open Editor (custom inspector window for a script) if you have a reference to the target object of that inspector? I know there are ways to find open EditorWindow's, but there doesn't seem to be a way to do the same for open Editor's.

gloomy chasm
gloomy chasm
# wintry badger Yes, exactly

Generally the lifetime of an Editor is controlled by the window that creates it. So if you need one, you just make one yourself. What are you trying to do?

wintry badger
#

Yeah, in this case I know the Editor is still open and needed access to the specific instance. Kind of hard to explain my use case, sorry! However, I just found in my code that I was using Resources.FindObjectsOfTypeAll to locate EditorWindow's and thought maybe I could do the same thing with Editor, and it does indeed work!

#

Of course I find the answer just after posting the question! Doh! But at least this may help someone else in the future if they are looking to do the same thing.

wraith crane
#

The docs says that in 2022.2 and above I should only implement UIToolkit in my custom property drawer. But if I only override PropertyDrawer.CreatePropertyGUI (which is the UIToolkit method) it says no GUI implemented (but if I override the OnGUI method it works)..

visual stag
#

Or, are you drawing that editor using IMGUI in the first place, or using a plugin which could be overriding the default inspector?

wraith crane
#

I'll check later and let you know (I am not using any plugin that overrides inspector)

alpine bolt
alpine bolt
#

it seems that it has to do with circle referencing. The second from last object field has the first Demo Script and after the Demo Script (1), it stops. I guess that isn't really a problem then.

wraith crane
visual stag
#

It could be if you used something like Odin, or NaughtyAttributes

wraith crane
#

Ok nope, I am dumb.. I had a custom editor (that didn't override the OnInspectorGUI method) for my ScriptableObject but it still conflicted with what I am triyng to do

#

Now I just need to understand this. If I want a toggle in the inspector, I can use:

            var container = new VisualElement();

            var overrideToggle = new Toggle("Override");
            container.Add(overrideToggle);
            
            return container;

To make it show up. But how can I know if it has been checked or not?

#

Because overrideToggle.value is always false (but I can actually check the toggle in the inspector and it remembers the state it was in)

alpine bolt
zinc wasp
#

How can I position nodes in a GraphView? I have a class that inherits from UnityEditor.Experimental.GraphView.Node, and I need to position it when performing AddElement(Node).

zinc wasp
zinc wasp
#

How do I get the height of a node? I've tried GetPosition(), but width and height return NaN

safe sorrel
#

speaking of graph views, is there a good place to start reading about this stuff?

#

I'm worried I'll be going down the wrong rabbit hole

gloomy chasm
gloomy chasm
safe sorrel
#

time to cry

alpine bolt
errant shale
#
  • Hey, it's me again. I've sneaked into ui toolkit by now, and struggle to understand how to make changes to my custom element properties reflect on the actual values in other elements. For more context you may go on reading, but that's basically it

  • I've followed this article (https://docs.unity3d.com/Manual/UIB-structuring-ui-custom-elements.html) in the manual step by step, and the problem lies in the c# properties. As long as they're a regular { get; set; } props, the custom control is fully functional, i.e. i can add it into the hierarchy. However, as soon as i add code to these properties, namely query an element and return/set its value, it stops being recognized as the control. So i can't drop it into the hierarchy, nor include it manually through editing the uxml file

errant shale
#
  • After a small investigation, i think i found the reason. Just to clarify: can i query elements after i composed the visual tree in the ui builder and not in code? Is it a visual tree at all, or just a hierarchy of independent elements?
gloomy chasm
gloomy chasm
errant shale
errant shale
#
  • I can't rn, am far away from the laptop. The queries happen in the constructor, and query specifically labels with their name
#
  • Tbh, it's almost identical to the one in the article above. The only difference is 2 label fields and an empty constructor, in which they're queried
gloomy chasm
errant shale
#
  • Do i have to explicitly add them before quering?
#
  • And also, can you elaborate on the "querying before it is build" line please?
gloomy chasm
errant shale
gloomy chasm
gloomy chasm
#

(You can just reply once you are at the computer and ready to if you prefer 🙂 )

errant shale
gloomy chasm
errant shale
#
  • Okay. It's midnight here and i won't be able to get back to the pc any sooner than morning, so until then ig. Thank you for your effort
gloomy chasm
peak bloom
errant shale
#
  • Is there any reason on why it behaves like this?
#
  • Are visual elements classes interpreted by a custom parser and not compiled?
errant shale
gloomy chasm
slim ermine
#

Would it be possible to run async methods and tasks in editor scripts? I know they're not recommended for runtime scripts

#

I'd like to make an extension that integrates Azure API into unity, but TBF I have never done something like this and don't really know where to start

#

So I could use any and all guidance out there

peak bloom
slim ermine
#

I only need to use the Text-to-speech feature, I'm not tackling the entire API, but it's still, no clue where to start

peak bloom
#

also, asyncs/awaits are fine for both edit and runtime

#

except in 2020, slight bigger overhead there

#

based on your question I assume you're new, so I suggest to not using async/await but instead use editorCoroutine

#

due to you'd need to make sure to cancel all your awaits before/after domain reloads

slim ermine
#

I've been working in unity for a year or so, but this is the first time I'm dipping into the more "backend" stuff - been mostly working with our internal framework and doing gameplay logic

peak bloom
slim ermine
#

This entire task could by automated to just one click in the editor

errant shale
gloomy chasm
gloomy chasm
errant shale
#
  • It does. Fine, i get that the children elements have to be explicitly added. They are contained in the same uxml document as my custom element, so loading it via assets database is not an option. Should i create a different document with just children elements, or load only styles and assign them to manually created objects instead?
gloomy chasm
errant shale
#
  • Cool, noted. And one more question: is it preferred to load either styles or documents with assets database api, or by assigning a default value to an exposed field of the script?
gloomy chasm
#

I feel like default value is harder to debug imo, but that is really just my opinion

errant shale
#
  • Okay. That's it then, thank you very much 👍
bright nova
#

Hi,
Is there any way to draw a rectangle in the editor UI but use a custom shader to do that?

bright nova
gloomy chasm
bright nova
#

oh right, didn't see that. Thanks.

bright nova
errant shale
#
  • How can i assign styles to the "TemplateContainer" element of my custom element? It has the default style and it wrecks my whole ui nvm, it turned out to be the root element
#
  • K, another one. How do i make my label increase its height as it wraps the text? Back at the studies i remember we had to code a holy mess in js that calculated the new height based on a dozen of magic numbers. Should i do the same here, and how else if not?
gloomy chasm
errant shale
#
  • Not for me, apparently. At least, not correctly
#
  • It definitely knows about the overflow, because after i change it to be invisible, out-of-frame lines are hidden. Even then, the label's size is twice as small as its text height
slim ermine
alpine bolt
alpine bolt
errant shale
gloomy chasm
#

Though it does strike me that there was a combination of styles that would allow the text element to change its height and based on the contained text

hollow bluff
#

Is there a way to make a string represent an integer in a custom inspector? I'm working on an RPG with an element system, (which is written in code as integers) and I'd like for my editor window to show the name of the element in a dropdown, which then sets the correct number for the code.

visual stag
hollow bluff
#

Is there a way to do it without making two separate scripts, or at least to be able to reuse the implementation for other things that I'd like to be able to use the same type of interface for? The internet is making it seem like I'll need at least one additional script for each time I want to use something like this, and that feels like a lot when all I'm trying to do is have a dropdown send a string's position in a list instead of the string itself.

visual stag
#

But you can presumably figure out how to do it with one attribute and drawer. It just might require you to specify the source of your strings every time you use the attribute

#

(https://gdl.space/yaqiwejoca.cpp is my drawer if you need more context, it has some other stuff in it that'll make it not copy-pasteable, but hopefully it helps)

hollow bluff
#

I just feel like I'm completely missing something here, and I'm not sure what. It might just be that I've done some fiddling with TextMeshPro in the past, and since what I'm going for is how dropdowns work in that system by default, doing it this way feels overly complicated. I might be wrong, though.

visual stag
#

Are you talking even more simple and you just want an enum?

hollow bluff
# visual stag Remind me what in TMP does this?

The standard dropdown object. In my old script at least, it seems like it was sending the selected position to the script, with the lable being customized in the dropdown object as a field. It has been a while since I made that, though, so I might be misreading my old code.

visual stag
#

The UIToolkit DropdownField takes a list of strings and an index, and you get a callback when that changes

#
DropdownField field = new DropdownField(property.displayName, names, index);
field.RegisterValueChangedCallback(evt =>
{
  // evt.newValue is your new index
});
#

my implementation needs to remap the index into the actual id used by the system, as it's not so simple as array indices

#

No idea what you're doing though

hollow bluff
# visual stag No idea what you're doing though

In the simplest terms, my goal is the equivalent of me saying "This is a fire type Pokemon. Fire type is type 0 in the game's code, so it's also the first choice in the type dropdown. When I choose fire type in the dropdown, set the integer value for its type to 0."

visual stag
#

Why are you not just using an enum then?

hollow bluff
visual stag
#
public enum PokemonType
{
  None = 0,
  Fire = 1,
  Water = 2,
  Grass = 3
}

[SerializeField] private PokemonType _type;
#

an enum is just a named integer, so you can assign the names whatever int value you want

#

(If you think you might insert more types later, add large gaps in your numbers so you don't change the values when that happens)

hollow bluff
slim ermine
#

StreamReader inp_stm = new StreamReader("Assets/Resources/Skript.txt");
can someone please help me understand why I cant locate the file like this?

errant shale
#
  • The file's called Skipt. The streamreader looks for a Sk**r**ipt file
slim ermine
#

Im not sure I understand

#

FileNotFoundException: Could not find file ...\Assets\Resources\Skript.txt"

#

the error message doesnt look wrong

#

OH

#

IM BLIND

errant shale
alpine bolt
gloomy chasm
#

You can pass 0 iirc

#

Along with the correct enum

tawdry anvil
shy solstice
#

I was wondering if anyone can help with this, it really feels like I'm just missing something really obvious. I'm trying to modify a script I found that is supposed to take a sliced script and create an animation.

It mostly seems to be working but whenever I attach it to the Animator on my Player->Visuals Game Object it always shows "The Game Object or Component is Missing". The Visuals Object has a child called body which has a Sprite Renderer on it. And when I manually attach a New Property to the Animation Clip, and target the body and the Sprite Renderer it shows up as attaching to the Sprite.

Here's the relevant code. It would be amazing if someone could help me here. I've been struggling for a couple days.

            var clip = new AnimationClip();
            // Create binding curve.
            EditorCurveBinding curveBinding = new EditorCurveBinding();
            curveBinding.path = "body";
            curveBinding.propertyName = "";
            curveBinding.type = typeof(SpriteRenderer);

            var objectReferences = new List<ObjectReferenceKeyframe>();
            for (int cnt = 0; cnt < animDictionary[i].frames; cnt++)
            {
                // Allows adding a hold frame to make sure the last sprite frame doesn't get cut off too soon.
                if (index >= sprites.Length)
                {
                    index = sprites.Length - 1;
                }

                var sprite = sprites[index];
                var newKeyframe = new ObjectReferenceKeyframe();
                newKeyframe.value = sprite;
                newKeyframe.time = cnt * (1f / animDictionary[i].frames);

                objectReferences.Add(newKeyframe);
                index++;
            }
            AnimationUtility.SetObjectReferenceCurve(clip, curveBinding, objectReferences.ToArray());

            // Save.
            AssetDatabase.CreateAsset(clip, Path.Combine(animationPath, animDictionary[i].name + '_' + spriteName + ".anim"));
shy solstice
#

Oh Gosh. Of course I solved this the moment I posted something. If someone else comes looking for something similar, the propertyName needed to be "m_Sprite"

unborn wagon
#

I have this editor code to generate a CardCatalog.prefab in my assets directory. However it also created a CardCatalog gameobject in the scene. This is problematic because when I execute that logic, multiple CardCatalog instances appear which is not what I want.

Is there a way to create a GameObject in code without adding it to the scene? Because I just need it to call PrefabUtility.SaveAsPrefabAsset() and not as an instance in the scene.

        public static void Generate()
        {
            var cards = AssetDatabase.FindAssets("t:Card", new[] {"Assets/_Game/Cards/Imported"});
            var gameObject = new GameObject("CardCatalog");
            var cardCatalog = gameObject.AddComponent<CardCatalog>();
            cardCatalog.cardSource = new Card[cards.Length];
            Debug.Log($"Generate Catalog for {cards.Length} cards");
            for (var i = 0; i < cards.Length; i++)
            {
                var card = AssetDatabase.LoadAssetAtPath<Card>(AssetDatabase.GUIDToAssetPath(cards[i]));
                cardCatalog.cardSource[i] = card;
            }

            PrefabUtility.SaveAsPrefabAsset(cardCatalog.gameObject, "Assets/_Game/Prefabs/Cards/CardCatalog.prefab");
            EditorUtility.FocusProjectWindow();
            Selection.activeObject = cardCatalog;
        }
errant shale
#
  • How do i make a listview responsive for items source changes? I tried calling both .Rebuild and .RefreshItems, nothing worked
gloomy chasm
gloomy chasm
errant shale
# gloomy chasm That is all you should need to do. Code?
  • Nevermind, it magically started working after i implemented multiselection. But now upon any rebuild i get an element out of bounds error, and an extra empty element is created in the view. The new source length is correct, however, and does not contain null references. Can i prevent it somehow?
gloomy chasm
#

Do you have the option to show the list count? In some versions that adds a element to the list which could throw the count off maybe

errant shale
#
  • Do you mean items source when you say list? If yes, it's not a list but an array
#
  • It turns out i had to reassign the items source. Idk why, but whatever ¯_(ツ)_/¯
warped sequoia
#

Hey i've bought some assets but when i try to import them in my project i have this

#

i cant refresh my personal packages too

#

problem solved

#

i didnt have the last version of unity hiub

peak bloom
#

@gloomy chasm are you familiar with vector api?
Say I've two individual shapes, A and B, so I have 2 Painter2D now, but then I'm planning to mask A with B via FillType, how'd you approach this?

gloomy chasm
peak bloom
#

to make holes but based on two objects

#

well... masking

gloomy chasm
#

Ooh, you mean like perform a Boolean operation?

peak bloom
#

hmmm... proly can be thought of that, but yeah in 2d space

gloomy chasm
#

As far as I am aware, UITK doesn't support any form of element masking based on overlaying (There is the style properties, but that is hierarchy stuff. And I don't think it takes in to account the visuals, just the bounds)

#

I don't think there is a non-destructive way to do it atm since UITK doesn't allow for drawing with shaders yet.

peak bloom
#

shame kekwait

#

kinda like the api tbh

peak bloom
peak bloom
#

apparently it's planned already

gloomy chasm
errant shale
#
  • How do i inherit styles? I want to have general settings in one class and specific settings in inherited ones, but i can't get it up and running. I tried both .class1 > .class2 and .class1 .class2, both simply reset styles to default and my element stops responding to any changes at all
gloomy chasm
glad pivot
#

Is there any easy way to apply asset labels when i create a new asset instead of having to manage it through menu items?

gloomy chasm
peak bloom
#

anyway to constraint editor window resizing?

#

say I want it to locked to 1200 x 900 pixels only

peak bloom
#

doesn't work I tried that before asking here

#

both min/max size didn't do anything

#

I can still stretch them in/out

real spindle
#

Is the window floating or docked?

peak bloom
#

floating

real spindle
peak bloom
#

wait.. haha that worked

#

lmao

#

thanks! 👍

#

I mean, that doesn't sound right anyway, it should refresh the panel after assemblyreloading

real spindle
#

Intuitively yeah, but I think inspectors and editors meed to be reloaded

#

Its sometimes good, you dont always want the inspector/editorwindow to reset when you reload scripts

polar bough
#

How do I detect if there is mouse input in a specific Editor Window? For instance the Timeline editor window

#

I'm trying to make a custom script that derives from TimelineEditorWindow and detecting mouse events using Event in OnGUI(), but it doesn't seem to work

#

However it does seem to work for any custom editor window I make

polar bough
#

I looked up EVERYWHERE on google, there is not a single forum that covers this. The unity API for TimelineEditorWindow doesn't seem to contain something that can allow me to do what I want either...

mild moss
#

Hi,
I'm having issue with VS Code and unity. I went throught the official documentation but still having some issues with local packages.
Intellisense and errors are shown correctly in the project files, but not in the package files.
I've already toggled the generate project for local package, but it doesn't seems to help.
Anyone has it's VS Code working in the local package files ?

#

Generate .csproj files*

gloomy chasm
polar bough
polar bough
#

I'm trying to detect mouse input events within the timeline editor window. ie if the mouse button is down or up anywhere on the editor window, I can detect that and call a method from that

gloomy chasm
polar bough
#

I see. Maybe I should be more specific about what I'm trying to achieve

#

So essentially I'm trying to implement a "snapping" feature on the Timeline for music syncing purposes. If I set the time of the director to something random, it takes in that value and returns its image value from a very specific step function that corresponds with the BPM of said song/music, which is then applied to the director as the new time value

#

By setting the time of the director, I mean dragging the time marker around

gloomy chasm
#

Ooooh.... right so that is going to take a lot of funky work. Probably not worth it imo. But it would be possible I think.

polar bough
#

The reason why I thought of a mouse event is precisely for the moment when the time is set to a specific value

gloomy chasm
#

It might be a good place to use Harmony (lets you inject code in to existing methods). Generally it is best to avoid it whenever possible ( Legally gray, but Unity doesn't seem to care as assets on the store use it), but it might be required for this. Not sure.

polar bough
#

🤔 hmm I see

#

I think I'm going to look deeper into UIToolkit, the idea seems pretty straight forward although I don't know the implementation details yet

gloomy chasm
#

You might be able to do it with UITK. As I said, you would need to add an element with a MouseDownEvent. And size it to be over the timeline. And probably use some reflection to get the timeline that is being dragged around.

polar bough
#

Right.... I'll see what I can do on that regard for now, thanks a lot for the answers!

gloomy chasm
#

Sure thing, good luck!

alpine bolt
#
    public abstract class DummyEntry : ScriptableObject
    {
        public static DummyEntry CreateInstance(Type keyType, Type valueType)
        {
            var genericTypeDefinition = typeof(DummyEntryKV<,>);
            Type[] typeArguments = { keyType, valueType };
            var constructedType = genericTypeDefinition.MakeGenericType(typeArguments);
            return ScriptableObject.CreateInstance(constructedType) as DummyEntry;
            // return GenericScriptableObject.CreateInstance(constructedType) as DummyEntry;
        }
    }
    public class DummyEntry<TKey, TValue> : DummyEntry {}
```When instantiating my Generic ScriptableObject `DummyEntry<TKey, TValue` I get a NULL ref when using ScriptableObject.CreateInstance call. However, when using the Generic Unity Object package method (`// commented code`), it works. I wonder what happens behind the scenes.
visual stag
#

Are those lines identical? I can't see what you're talking about

#

Also I wouldn't expect this to work at all

alpine bolt
#

edited

#

when using the commented line instead of the other return line, it does work

visual stag
#

There is no difference between the two still, they should compile identically iirc

alpine bolt
#

ScriptableObject != GenericScriptableObject

visual stag
#

The method is the same

alpine bolt
visual stag
#

They do all this extra work to handle it for you that fundamentally won't work by default

alpine bolt
#

My question is why does default method fail and why does package method work

visual stag
#

Because of the extra work it does, read the code and look at their implementation

alpine bolt
#

The extra work is basically this methodcs private static Type CreateClass(string className, Type type) { TypeBuilder typeBuilder = _moduleBuilder.DefineType(className, TypeAttributes.NotPublic, type); return typeBuilder.CreateType(); }I don't what this means in practice: why compile-time type creation fails. I thought CreateInspectorGUI() ran on compile-time. I know TypeBuilder allows runtime type creation, but that's all.

left sparrow
#

Does anyone know how I could add a button for all gameobjects in the inspector, I just want to add a button below the Add Component but I don't know how
Like this 🙏

thin jetty
#

If you explain better, maybe I can help you

left sparrow
#

I would like to add a button in the "Inspector" window, I would like the location of this button to be below "Add Component" and this button will be on all objects, each new object will have this button by default in its inspector

clear kite
#

I'm having hard times trying to render procedural mesh from my CustomEditor using Graphics.RenderPrimitives. It's otherwise working nice but I doesn't seem to be getting it to render once each time the scene view is drawn, it's sometimes rendered multiple times and sometimes not at all. I have tried doing it on both OnSceneGUI and SceneView.duringSceneGUI. If drawn when EvenType is Repaint, it's flickering (not drawn every time) and when I draw on every OnSceneGUI call, it will be rendered multiple times a "frame"

left sparrow
clear kite
gloomy chasm
clear kite
neon yacht
#

Eh, not sure where to put this, but is anyone aware if you can reference a variable inside of the inspector? I tried curly braces, hoping it'd work based on other programs using that, but no luck. Not sure if it's just not available on Unity? But I'd like a work around to allow people without coding experience to edit descriptions and not have to open up a c# script

gloomy chasm
neon yacht
clear kite
tepid roost
#

anyone know the name of this UI component and where its docs are if any

median nebula
# tepid roost anyone know the name of this UI component and where its docs are if any

Long dropdown lists in the Unity Editor are painful. Let's improve them, by converting them to Searchable Windows instead! 🔎

👚 🛒Get 15% off all orders over $35 on the merch store until March 1st 2022 - http://www.gamedevguide.store

Want to support the channel?

▶️...

▶ Play video
tepid roost
#

thanks

tepid roost
#

thanks @median nebula already got my logic for my node editor converted from using a context menu with nesting to this went easier then i thought it would

median nebula
shell beacon
#

Hi guys! is there a way to open\create a native independent Windows window for docking editor windows?

gloomy chasm
shell beacon
#

Oh it is planned for Unity 2023?

shell beacon
#

Super! thanks ❤️

karmic ginkgo
gloomy chasm
shell beacon
karmic ginkgo
#

ah right yeah i bothered the author to implement it since he already has some base functionality

#

misremembered

gloomy chasm
#

I don't think there is much overlap

karmic ginkgo
#

tho what you can do is render the panel into any screen

gloomy chasm
#

I was actually going to try and fake it by creating a C# application that has a window, and just open one for each floating window. Was going to link them and stuff. Create a screenshot of the unity window to show in the C# window when minimized and stuff.

shell beacon
#

I kinda hoped someone has already done that.. working with Unity and its floating windows on a multi monitor setup is a pain

gloomy chasm
#

Yeah, same. That is why I was going to haha

shell beacon
#

I tried 2023.1 beta to see what's going on there.. the floating windows now do have a title bar thank god.
But they are still annoyingly "steals focus" and "brought to front" 😒
And when you minimize the main window, it also minimizes the floating windows....

gloomy chasm
shell beacon
#

I hope it'll be more like how it's been implemented in Blender

forest anchor
#

How can I refresh scene view in Unity? I've tried the SceneView.RepaintAll(); thing but it doesn't do anything
I am calling a method for generating a mesh in a child object, and it shows up only when I select the game object with the script for generating the mesh and all the mesh components. I'm trying to make it show up instantly, after I call the method to call methods for generating meshes in children.
(Sorry if I wrote in the wrong place, but since this is editor related, I think that this channel is appropriate)

gloomy chasm
forest anchor
#

I'll send it in a second, just gotta gather it all into one piece, but quick question, can it be because there's no [ExecuteInEditMode] attribute on the parent script?

#

Here: https://gdl.space/ecoxawusat.cs
The way it works, is Intersection.GenerateIntersection() -> LinePlacement.GenerateAlongPath() -> VerticesCollider.GenerateMesh()

#

ah wait... It doesn't work like that. The GenerateMesh method wasn't being called 🤦

#

Although there is some issue still. It looks like the LinePlacement scripts gets wrong point, but after I select the gameobject and then reuse LinePlacement.GenerateAlongPath()

#

This is what I get after I call Intersection.GenerateIntersection()

#

But after I click on the gameobject that has the LinePlacement script and reuse that method mentioned earlier, it fixes itself

gloomy chasm
#

In the code you showed. None of it is ever called. So there is some you didn't share I assume?

forest anchor
gloomy chasm
#

So where is it being called from

forest anchor
#

these are called from editor scripts, but those are basically like

public override void OnInspectorGUI()
    {
        Intersection _script = (Intersection)target;
        DrawDefaultInspector();
        if (GUILayout.Button("Generate intersection"))
        {
            _script.GenerateIntersection();
            SceneView.lastActiveSceneView.Repaint();
            SceneView.RepaintAll();
        }
    }
#

I think the handles drawing can be omitted, as it's not relevant for this issue

gloomy chasm
#

Do you call any of the script.Generate___() methods in OnSceneView or OnEnable?

#

I am assuming you do

forest anchor
#

I call those only through these gui buttons. But as I wrote above, it turned out that the last function in that chain wasn't actually being called. Now the mesh shows up 😄

gloomy chasm
#

Make sure all of your code is running, and in the right order. Use debug mode in your IDE. This is just a normal #archived-code-general thing. Not editor specific 🙂

forest anchor
#

Alright, thanks, i'll go there instead.

alpine bolt
#

Anyone knows the "formula" to have perfectly aligned with default fields?
Label Width Min is 120px. As for the rest, I tried copying every default class, tried manually inserting some % value, but it seems to me it's a little more complex than 1 % width value

gloomy chasm
crude forge
#

Working on trying to add images to the elements in a reorderable list. gui.drawtexture doesn't draw inside the draggable elements. propertyfield and objectfield don't seem to have an interactable element nor a sprite unless guicontent.none is set, but don't show a sprite (just a generic sprite and the sprite name) when it is set

crude forge
#

EditorGUILayout.ObjectField doesn't appear 'inside' the reorderable rows either

gloomy chasm
crude forge
gloomy chasm
#

And GUI.DrawTexture(..) doesn't work for you?

crude forge
#

It draws it outside the RoL - about the only thing I really do want to work...

gloomy chasm
#

And screenshot of inspector

delicate shoal
#

is there a way to know if a material is an actual material and not embedded into an fbx?

crude forge
#

sure. I need a code pasty site I suppose

#
        Texture2D texture = AssetPreview.GetAssetPreview(element.FindPropertyRelative("sprite").objectReferenceValue);
        GUILayout.Label(texture, GUILayout.Height(80), GUILayout.Width(80));
        GUI.DrawTexture(GUILayoutUtility.GetLastRect(), texture);
gloomy chasm
delicate shoal
#

Ah IsMainAsset sounds exactly like what I need. Thank you 🙂

gloomy chasm
crude forge
#

I'm sort of hacking this together, but that's how I learn I suppose. hit a point... AH. of course...

#

and of course, I can just inject the right rect

#

cut the label bit out entirely

#

That was it. Thanks.

alpine bolt
gloomy chasm
alpine bolt
gloomy chasm
alpine bolt
alpine bolt
alpine bolt
gloomy chasm
crude forge
#

The issues I have been struggling with seem to be related to the construction of a ray via:

var view = SceneView.currentDrawingSceneView;
Vector2 mousePosition = Mouse.current.position.ReadValue();
ray = view.camera.ScreenPointToRay(mousePosition);

This does not point correctly in the Editor view...

gloomy chasm
crude forge
snow pebble
#

is there any way to make an editor that creates a prefab and not a gameobject in the scene

gloomy chasm
snow pebble
#

hm okay

alpine bolt
# gloomy chasm Worth a try. Might be able to just child all if your UXML elements to it instead...
        private void HandleDummyFloatField()
        {
            _dummyFloatField = RootVisualElement.Q<FloatField>();
            _dummyFloatField.RegisterCallback<GeometryChangedEvent>(OnGeometryChangedEvent);
        }

        private void OnGeometryChangedEvent(GeometryChangedEvent evt)
        {
            var width = _dummyFloatField.labelElement.resolvedStyle.width;
            _fieldLabel.style.width = width;
        }```this was the way I could achieve it. I didn't know there was a Field.labelElement variable. I don't like it, but it works-ish
gloomy chasm
alpine bolt
#

Why do you say that? You have me worried now. 😂

gloomy chasm
alpine bolt
gloomy chasm
alpine bolt
# gloomy chasm Did ya try BindableElement like I suggested?
        private void HandleLabel()
        {
            _floatFieldLabel = RootVisualElement.Q<FloatField>();
            _floatFieldLabel.RemoveAt(1);
            _floatFieldLabel.Add(_buttonFieldContainer);
        }``` This worked too and its way simpler. I had in my mind (because of `Q<TVisualElement>`) that direct children had restricted/prohibited access. I have not tried BindableElement specifically, but at least your tip lead me into this result :P. I might try that later. Thanks.
whole steppe
#

I have a group of toggles that I'd like to offset to the right a bit all at once,
they looks like this:cs // updated... private void OnGUI() { EditorGUILayout.LabelField("Exclue:"); EditorGUI.indentLevel++; // shifted horizontally... Solo = EditorGUILayout.Toggle(nameof(Solo), Solo); Mute = EditorGUILayout.Toggle(nameof(Mute), Mute); EditorGUI.indentLevel--; // back to *normal* EditorGUILayout.LabelField("Test"); }I feel like this is another Begin/End Vertical trickery
what else am I missing?

whole steppe
#

turned out as simple as EditorGUI.indentLevel ++/-- xddd

hollow bluff
#

How would I go about making a dictionary serializable? I have a custom tagging system in the game I'm working on that a dictionary would be perfect for, if only it was serializable.

gloomy chasm
#

Define a struct within that class with a Key and Value field and mark it as serializable. In the class, have a serializeField list of this struct. Then in OnBeforeSerialize, you add all of the pairs from the dictionary to the list and then on OnAfterDeserialize you add them back to the dictionary.

hollow bluff
#

New question: How would I go about changing the lable text of an element of an array in the inspector (without having to have a separate name variable in each element)?

past crane
#

Has anyone been able to display a generic derived class' inspector? The generic base class inspector displays correctly, but it's derived class only displays the base class inspector . . .

gloomy chasm
wintry trout
#

When using BoxBoundsHandle I can't move the handles. Instead starting to select area on screen. Any ideas how to fix?

_sphereHandle.radius = sphereRadius;
_sphereHandle.center = sphereCenter + transform.position;
_sphereHandle.DrawHandle();```
full cedar
#

Hi, I still haven't figured this one out:
How would I limit the amount of lines my TextArea accepts in the custom inspector?
I tried using [TextArea(1, 3)] when declaring a var but that obviously doesn't work:

item.Description = EditorGUILayout.TextArea(item.Description);

The only reply I've gotten is from RandomDiscordInvader(); and I don't think that's a solution because I don't want to resize the text are but limit the amount of lines to prevent script users from entering more lines than the description can display:
ry using the GUILayoutOption for MaxHeight when creating the TextArea . . .

past crane
# gloomy chasm What do you mean?

I have an editor for a base generic class ValueObject<T> that displays some fields. I also have an editor for a derived generic class NumericObject<T> : ValueObject<T> that displays extra fields but its editor is not drawn, only the base editor . . .

full cedar
# full cedar Hi, I still haven't figured this one out: How would I limit the amount of lines ...

ok, I've made this w the help of gpt, is there really not a better approach to this?

        #region Description Text Area
        item.Name = EditorGUILayout.TextField("Item Name: ", item.Name);

        EditorGUILayout.LabelField("Description");
        var descStyle = new GUIStyle(GUI.skin.textArea)
        {
            wordWrap = true,
            fixedHeight = EditorGUIUtility.singleLineHeight * 3
        };
        _description = EditorGUILayout.TextArea(_description, descStyle);
        var lines = _description.Split('\n');
        if (lines.Length > 3)
        {
            _description = string.Join("\n", lines.Take(3));
            GUI.changed = true;
        }
        #endregion
gloomy chasm
gloomy chasm
past crane
gloomy chasm
gloomy chasm
past crane
gloomy chasm
past crane
#

yeah, like SO_Float : SO_NumericObject<float> . . .

gloomy chasm
#

The issue might be having two editors set as falback

#

It might be defaulting to the most base editor

#

Which is the ValueObject

past crane
#

that's what i'm thinking . . .

gloomy chasm
#

Easy to find out 😉

past crane
#

i was trying to do it without creating an editor for each concrete type since CustomEditor has the 2nd param to effect child classes . . .

gloomy chasm
#

Try removing the true from the ValueObjectEditor CustomEditor

past crane
#

and the generic <> worked when doing [CustomEditor(typeof(SO_NumericObject<>), true)] . . .

#

nah, it still shows the base . . .

gloomy chasm
#

[CustomEditor(typeof(SO_NumericObject<>))] shows the base still?

past crane
#

whoa, that's weird. it reverts to the default inspector. it does not show the base for SO_ValueObject<T> or its immediate parent SO_NumericObject<T>. i'm inspecting a SO_Float SO asset . . .

full cedar
# gloomy chasm That sure does look like chatGPT code

I ended up w this which is still quite long but seems to be doing exactly what I wanted(edited the gpt code to my liking):

        #region Description Text Area
        EditorGUILayout.LabelField("Description");
        var descStyle = new GUIStyle(GUI.skin.textArea)
        {
            fixedHeight = EditorGUIUtility.singleLineHeight * 3
        };
        _description = EditorGUILayout.TextArea(_description, descStyle);
        var lines = _description.Split('\n');
        if (lines.Length > 0) for (int i = 0; i < lines.Length; i++) if (lines[i].Length > 25) lines[i] = lines[i][..25];
        GUI.changed = true;
        _description = string.Join("\n", lines.Take(Mathf.Min(3, lines.Length)));
        GUI.changed = true;
        #endregion
gloomy chasm
# full cedar I ended up w this which is still quite long but seems to be doing exactly what I...

No need for the style stuff, that is poor for performance and you can just do EditorGUILayout.TextArea(_description, GUILayout.Height(EdiGUIUtil.singleLineHeight * 3));
Also, don't do GUI.changed, that is already done by EditorGUILayout when it draws a field and a value changes.
You can also split out the line selection in to its own method to make it cleaner string ClampStringLines(string text, int maxLines) {.. }

full cedar
past crane
#

@gloomy chasm wtf mate, i quit and reloaded unity, and now it displays properly. the extra stuff is random gui to see if anything would show . . . 🤦‍♀️

cinder oracle
#

where do these materials come from? I mean in this case its obviously due to the Image component, but in code?
how does unity know what materials to append as an inline editor? how can i add or remove items from this section in my own editors?

#

i couldn't find anything specific on the editor classes for Image, Graphic, or CanvasRenderer

gloomy chasm
# cinder oracle where do these materials come from? I mean in this case its obviously due to the...

That... is actually a good question. To tell the truth I'm not sure. I took a look at the PropertyEditor, but didn't see anything there. From inspecting the inspector with the UIToolkit Debugger, and looking at the PropertyEditor code, it seems to just be drawing the Editor for the material along with all of the other editors. Nothing special there. I am not sure how it is provided though. A couple of ideas. You could try inheriting from Renderer and or have a field called m_Material to try starting off with.

#

Lookin in to it more, looks like it is done internally in c++ by the ActiveEditorTracker

cinder oracle
#

I don't want to inherit from Renderer as that's not something my script should do, but I tried having a (serialized or not) field named m_Material, but no luck

#

also, thanks for your response and for looking into it, really appreciate it

eager oracle
ivory frigate
#

hello I'm not sure why Unity couldn't find the plugin that I'm loading

DllNotFoundException: Myplugin assembly:<unknown assembly> type:<unknown type> member:(null)

#

is this due to x64 architecture, but was x86 architecture. You must recompile your plugin for x64 architecture

full cedar
karmic ginkgo
#

is it possible to pass a list to the project window for display?

#

hijack the search query

sour oracle
#

So they probably have to get the right version or compile it themselves

full cedar
cinder oracle
alpine bolt
#

Any way to avoid the circle artifacts in this? cs painter2D.Arc(center, m_Radius, 0, Angle.Degrees(360));The only work around I know is using 359.999f instead of 360f, but it's not what I want

peak bloom
#

that is weird, I've no issues with Arc in vector api

#

what Unity version you're using?

alpine bolt
#

2022.2.17f

peak bloom
#

someone also reported similar issue in 2021

peak bloom
alpine bolt
#

This "fixes" it and doesn't break the stroke```cs
painter.BeginPath();
painter.Arc(center, m_Radius, 0, Angle.Degrees(359));
painter.ClosePath();

painter.BeginPath();
painter.Arc(center, m_Radius, 1, Angle.Degrees(360));
painter.ClosePath();

painter.Fill();```

alpine bolt
whole steppe
stark compass
#

Is there a plugin to create a character customization in unity?

gloomy chasm
#

Either #archived-networking or #💻┃unity-talk maybe would be the right place to ask about this. This channel is for discussion around creating editor extensions. Best of luck! (You can just delete this message and paste it in to one of those instead as cross posting is not allowed)

eager oracle
#

hello, im trying to build an EditorWindow that helps me place objects in a grid. I want to show a sphere around a certain collision point, but Handle's I draw don't show up.
I subscribed to SceneView.duringSceneGui += MySceneGUI;
In that method I do:
Handles.color = Color.red; Handles.RadiusHandle(Quaternion.identity, hitInfo.point, 2); Handles.DrawWireCube(hitInfo.point, new Vector3(5, 5, 5));
but no handles show up in the** scene view**.
any ideas why?

gloomy chasm
eager oracle
gloomy chasm
eager oracle
gloomy chasm
#

Basically, are you 100% sure that the Handles code is being reached?

#

It either is not being reached or the position is wrong.

#

My guess would be on the former

eager oracle
eager oracle
gloomy chasm
#

Oh, I know the issue LOL

eager oracle
gloomy chasm
#

It is because you are only drawing on mouse move

#

That means it will only draw the handle for the single frame that the mouse moved. Mouse stops moving, handles stop getting drawn

eager oracle
gloomy chasm
#

Handles only draw during layout and repaint haha

eager oracle
#

I don't ever repaint. should I?

#

The whole gizmos / handles / editor / editorwindow stuff is so twisted and convoluted

gloomy chasm
#

No I mean it only draws during repaint events. It caches the image. Don't worry about it

eager oracle
#

So I should somehow draw the handle in OnGUI()?

gloomy chasm
#

Basically, just remove the if (e != null & e.type == EventType.MouseMove) and it should work

eager oracle
#

this would have easily taken MANY MANY hours to figure our for me

#

i seriously appreciate the time you took to understand my problem. i am so relieved you have no idea...

gloomy chasm
#

Glad I could help! 😄

whole steppe
#

hey!

#

I've always used the UnityEditor.Event inside an EditorWindow to detect keyboard input from the Editor
however, this meant that I'd need an instance of said window, also I noticed that the Event class is supposed to be used inside a GUI method...

is there a way to still be able to detect keyboard input from the editor at anytime?

gloomy chasm
whole steppe
#

omg!!! hi!! <3
yes yes!! >////<
you feel me right!!

#

I was thinking of using the EditorApplication.update and handle keyboard input from there,
but I didn't test if I'd still be able to use the Event.current property...

gloomy chasm
whole steppe
#

our love will last 99 lives my eternal warrior! 💝

gloomy chasm
#

lol

whole steppe
#

about that...

is this how it should be done? else, what am I doing wrong?```cs
private static EditorApplication.CallbackFunction globalEventHandler;``````cs
[InitializeOnLoadMethod]
private static void AddGlobalEventHandler()
{
var delegateField = typeof(EditorApplication).GetField("globalEventHandler", BindingFlags.NonPublic | BindingFlags.Static);

var @delegate = (EditorApplication.CallbackFunction)delegateField.GetValue(null);
    
globalEventHandler = (EditorApplication.CallbackFunction)System.Delegate.Combine(@delegate, globalEventHandler);

globalEventHandler += GlobalEventHandler;

}``````cs
private static void GlobalEventHandler()
{
Debug.Log("a new globalEventHandler call");
}```

hollow bluff
#

Is there a good pre-existing extension for serializing dictionaries? I tried serializing them myself, but I just didn't get how to do it. I have poked around some, and while I really liked this one: https://github.com/Prastiwar/UnitySerializedDictionary, it doesn't work with ScriptableObjects, which is where all of the dictionaries I need to serialize would go. I also tried out this one: https://github.com/azixMcAze/Unity-SerializableDictionary, and while it does at least work, its presentation is nowhere near as good the first one. I also tried to figure out a way to rewrite the first one's property drawer to work with the second one, but I couldn't figure out how to do that either. Thanks in advance for any help!

gloomy chasm
hollow bluff
gloomy chasm
alpine bolt
#

So buggy when I mess with arcs

whole steppe
lean tangle
#

Hi everyone, I'm trying to write a drag & drop box in an editor. I borrowed some code from someone else and the drag/drop works perfectly. The problem I'm having is that I want to update a list inside a class in the original script. Would anyone have any experience with this?

Basically, I have a property called axle, this property is a class that houses a list of wheels. I am trying to drag and drop wheels into a drop area to update the list of wheels. When I drop, I see it changes, but then if the editor tick updates, it goes away.

The reference to the target script is here: CleanerAxleSettings axleSettings = target as CleanerAxleSettings;

                Debug.Log("Wheel doesn't exist, add it " + axleSettings.axle.wheels.Count);
                CleanerAxleSettings.Wheel wheel = new CleanerAxleSettings.Wheel();
                wheel.mesh = mesh;
                axleSettings.axle.wheels.Add(wheel);
                Debug.Log(axleSettings.axle.wheels.Count);

I'm not sure what's happening and why it's deleting itself from that list. I have serializedObject.ApplyModifiedProperties(); after all of this as well, it just doesn't stay updated

gloomy chasm
#

Because you are doing ApplyModifiedProperties, you are actually discarding the changes you are making to axel.wheels.

#

The very much recommended way is to use SerializedObject and SerializedProperty

lean tangle
#

@gloomy chasm Thank you for that explanation. I'm new to the editor window, so I'll look up what you're talking about to get a better understanding. I think one of my problems as well was not being able to dig down into the axle variable to find the wheel list. But then as you're saying I am discarding the changes, so I will need to look into that as well. Thank you!

eager oracle
#

hello, i am trying to cast a ray from the middle of my scene view, to a certain point. For that I am using SceneView.currentDrawingSceneView.camera.ScreenPointToRay(mousePos) , but that is not originating from the middle of my scene view, but from a seemingly arbitrary point. The ray is cast from an EditorWindow script. any idea why?

by the middle of my scene view ** i mean the fact that wherever my camera is pointed at the current time in the scene view, that displays what I see there (is the camera interal? idk)

eager oracle
eager oracle
# gloomy chasm Sorry, I meant `HandlesUtility` <https://docs.unity3d.com/ScriptReference/Handle...

for some reason, whichever method I use from here:

Ray ray = SceneView.currentDrawingSceneView.camera.ScreenPointToRay(mousePos); Ray ray = SceneView.lastActiveSceneView.camera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 1.0f)); Ray ray = HandleUtility.GUIPointToWorldRay(new Vector2(Screen.width / 2f, Screen.height / 2f));

the ray always originates from 0, 0, 0, instead of the middle of my current viewing angle.
I can always rotate the camera by holding alt and see the origin of the ray, which shouldn't really be possible if it was truly originating "from my eye".

(I am drawing the ray with Handles.DrawLine(ray.origin, ray.direction * 100);

wonder what i'm missing.

gloomy chasm
eager oracle
# gloomy chasm Can you show a screenshot or gif of what you mean?

hope this explains it: I want the ray to come from the middle of my scene view window (regardless of viewing angle or zoom), to that green prefab (surrounded by circles).
instead, with all 3 methods it originates either from the origin, or a point close to it in this case.

gloomy chasm
eager oracle
gloomy chasm
gloomy chasm
#

No problem!

#

(To be clear, I mean to use sceneView.position.width in places you are using Screen.width 👍 )

eager oracle
gloomy chasm
#

Top left

eager oracle
# gloomy chasm Top left

it seems like I have the same problem, but playing around with the movement a bit, it looks like it might have something to do with the way I am drawing the ray?

Handles.DrawLine(ray.origin, ray.direction * 100);
does this look correct? because it does to me

eager oracle
gloomy chasm
eager oracle
shell beacon
#

Hi, anyone here familiar with EditorWindow.ShowAsDropDown(Rect buttonRect, Vector2 windowSize) ?
I'm trying to do this but it's just opens the window as regular window.. idk what I'm missing...
The window I'm trying to ShowAsDropDown is of type EditorWindow and currently empty and I'm trying to open it from an Editor script.

#

Like so:

if (GUILayout.Button("Test"))
{
    SearchWindow window = EditorWindow.GetWindow<SearchWindow>();
    window.ShowAsDropDown(GUILayoutUtility.GetLastRect(), new Vector2(500, 375));
}
#

And SearchWindow is:

using UnityEditor;
public class SearchWindow : EditorWindow { }
``` 😐
#

EditorWindow.CreateInstance kinda does work.. but isn't great

gloomy chasm
shell beacon
#

Thanks, I needed to add a few stuff to make it work

whole steppe
#

hey! hey!

#

is there some easy way to know what certain things do in the UnityEditor?

such as, revealing the underlaying actions from any of Unity's editors...

#

like, when I click on Other..., then pick a texture!

the Editor starts doing things! some of which I'd like to know!

karmic ginkgo
#

do you consider reading unity sources easy?

#

youre out of luck anyway

public static extern void SetIconForObject([NotNull] Object obj, Texture2D icon);
whole steppe
whole steppe
#

bruh! you made me type a wall of text just to shut me up with the link,
I like that xddd.

pretty useful stuff (if not exactly what I was looking for!)

karmic ginkgo
#

what were you looking for?

whole steppe
#

well, this is like a whole EditorWindow,
I'll just clone it and see what it has to offer xddd

whole steppe
#

ok nvm, the previous idea of mine looks like shrek...

whole steppe
#

I was able to change the icon before, but couldn't tell the editor about the change, so it could remember the set icon...

but with this method, I think it will get the necessary done!

#

I was only able to make the Editor remember MonoScript objects icons,
thanks for this, yet another internal methodcs internal static extern void CopyMonoScriptIconToImporters(MonoScript script);

prime anchor
#

!ide

grave hingeBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

narrow crystal
#

Hi. I'm wondering: How would I use a custom inspector script (let's say I made a fancy looking button) in multiple different scripts. As in, how would implement that custom editor script into a monobehaviour?

#

lets say i coded a fancy looking button, but now I want to use that button in 3 different monobehaviour classes. Sureley there's a better way then making 3 different custom editor scripts for those classes, right?

gloomy chasm
narrow crystal
#

So use the code in a static method, and call that in each monobehaviour's editor class.. makes sense

#

a lot simpler then I was thinking about it Ha

gloomy chasm
#

Just like you do GUILayout.Button(..) you can do MyGUILayout.FancyButton(..)

narrow crystal
#

yeah exactly.. I was overthinking it heheh

odd shore
#

hi, I think this is the right channel but does anyone know what this is called?

#

and the best way to build something like it?

real spindle
gloomy chasm
#

The AdvancedDropdown is also what the AddComponent button uses to show components you can add

odd shore
gloomy chasm
real spindle
#

Ah, makes sense that it looks a bit different from the previous question's screenshot then

alpine bolt
#

Any way I can access a stylePropertyName of a class (only have its name string) like you can get in TransitionEndEvent?

turbid spade
#

Hallo all! I'm looking for a way to automatically have the Unity Edtor start Play when the code is recompiled. Does anyone know of an extension that does this, or some other means of achieving it?

alpine bolt
turbid spade
#

Ah wait, it's probably called automatically through that attribute, right?

burnt dove
#

How can I read this value by code?

deep bear
burnt dove
#

Thanks

deep bear
#

That's surprising, and unfortunate :/

gloomy chasm
#

I think pivot rotation is that dropdown that you want

#

Yeah it is

burnt dove
#

Thanks, didn't know that was called "pivot"

whole steppe
crude forge
#

hm. get/set properties on a variable make it not-findable via 'FindProperty'... ie- I'm saving serializedproperties in the Editor, but I cannot use the property name... and the variable it protects is private... therefore what do I do?

visual stag
crude forge
visual stag
#

Show some code so it's clearer what name you should use and whether you're finding it correctly

crude forge
#
    public bool _filled = true;

    [field: SerializeField]
    public bool Filled
    {
        get
        {
            return _filled;
        }
        set
        {
            _filled = value;
            UpdateSprite();
        }
    }
#

filled = serializedObject.FindProperty("<Filled>k__BackingField");

visual stag
#

There is nothing serialized for get and set, they are just methods

crude forge
#

ah. I was hoping to make _filled private...

gloomy chasm
# crude forge ah. I was hoping to make _filled private...
    //public bool _filled = true;
    // Make it private, and add SerializeField so that it is still serialized
    [SerializeField] private bool _filled = true;

    //[field: SerializeField] // Don't need this any more since it isn't an auto property
    public bool Filled
    {
        get
        {
            return _filled;
        }
        set
        {
            _filled = value;
            UpdateSprite();
        }
    }
crude forge
#

that much I had before - but the issue is then how do I fill the serializedProperty? I'm serializing properties so I can tell when the value gets changed in the GUI Layout so I can trigger behavior for that.

gloomy chasm
crude forge
#

if it's private, it doesn't find it...

gloomy chasm
#

A C# property is not the same as a SerializedProperty

#

SerializedProperty finds anything that is serialized. This means either public fields, or private fields that have the [SerializeField] attribute, Auto properties count as the second option

crude forge
#

Just realized that, yes. Auto properties?

gloomy chasm
# crude forge Just realized that, yes. Auto properties?
[field: SerializeField] // This attribute is being applied to that backing field that is generated.
public bool Filled { get; set; } // It is called an auto property. Because it automatically makes a private backing field.
crude forge
#

saving that in my code comments - will be a useful reminder.

whole steppe
#

sry, just realized that the question is C# specific and isn't directly about editors...

shell beacon
#

Guys, where can I find a list of all builtin editor style names? I want to style a button like a list item (including alternate) and EditorStyle doesn't have it exposed..

gloomy chasm
shell beacon
gloomy chasm
shell beacon
#

Oh yea forgot that exists 😅 thanks

shell beacon
#

Say, how do I prevent a window from being docked?

alpine bolt
#

When dropping a visual element in custom uxml element, how do I make it so it goes straight to some content container inside rather than the root of that uxml element?

copper lynx
#

i have an object with a transparent shader. Is it possible to make it not be effected by light?

#

cuz right now its making a shadow

peak bloom
#

URP or hdr?

#

if URP you can disable it in your URP asset

visual stag
#

You can disable shadow casting on the renderer

#

Persisting Changes

If you're trying to set something from an editor context it needs to be dirtied.
The options in order of preference are:

  1. SerializedObject/SerializedProperty
    ApplyModifiedPropertiesApplyModifiedPropertiesWithoutUndo
    See SerializedObject: How-to for more info.
  2. Undo.RecordObject • (PrefabUtility.RecordPrefabInstancePropertyModifications also required for prefabs)
  3. EditorUtility.SetDirty (most lazy, doesn't record undos)

If something is changed and not dirtied, that change is transient and will be wiped.

When working with SerializedProperties, don't mix and match Undo or SetDirty unless you're familiar with applying or updating in the correct order.

External resources

gloomy chasm
gloomy chasm
tidal comet
#

Someone can help me with adding MySQLConnector?

foggy stream
#

I want to have the default inspector in a settings menu.
I'm trying to use something like the following

    static class LoggerSettingsUIElementsRegister
    {
        [SettingsProvider]
        public static SettingsProvider CreateLoggerSettingsProvider()
        {
            var provider = new SettingsProvider("Project/Game/Logger2", SettingsScope.Project)
            {
                label = "Logger",
                
                activateHandler = (searchContext, rootElement) =>
                {
                    
                    var settings = LoggerSettings.GetSerializedSettings();
                    InspectorElement.FillDefaultInspector(rootElement, settings, editor);

But I don't know where I can get hold of the editor of the Settings to submit to FillDefaultInspector. Anyone know if this is something possible?

gloomy chasm
foggy stream
gloomy chasm
peak bloom
#

is there a better way to detect if gameobject is deleted/removed in the scene and in edit mode other than subscribing to hierarchyChanged?

#

did not know that

mint sable
#

Hey guys, trying to extract prefab icon with PrefabUtility.GetIconForGameObject but returns an unreadable Texture2D

gloomy chasm
mint sable
gloomy chasm
mint sable
#

editor tool, save the result as PNG

gloomy chasm
#

Could try Graphics.CopyTexture

mint sable
#

eitherway PrefabUtility.GetIconForGameObject doesnt return the actual game object preview

#

oh, i managed with AssetPreview.GetAssetPreview, neat

gloomy chasm
#

AssetPreview is normally used for getting asset previews

mint sable
#

was using GetMiniThumbnail instead..

#

just using this for automatically generating sprites for my items, works for now, in the future i will probably want to take into account lightning and positioning but for now its ok

gloomy chasm
mint sable
#

well i can probably automate something for transparency through that as we have access to the texture itself (though lightning might be off)

#

will take a look into that utility

whole steppe
#

is there a way I could detect a state creation of the Animator window?
like a callback...

it's this window:

#

I was able to subscribe to this callback graphDirtyCallback from UnityEditor.Graphs.AnimatorControllerTool, but it gets called in different occasions too, like when selecting a transition...

shell beacon
#

Hi guys, I'm using EditorGUIUtility.ObjectContent(null, type).image to get component icons, but for some reason for modified script icons it returns null.. so I ended up writing a small function to get the icon from an asset file (idk if best practive..) and now I get the generic script icon (see picture)
How can I get the same icon for components same as how they're shown in the inspector?
My code:

        static Texture GetImage(Type type)
        {
            Texture image = EditorGUIUtility.ObjectContent(null, type).image;
            if (!image)
            {
                string[] GUIDs = AssetDatabase.FindAssets(type.Name);
                if (GUIDs.Length > 0)
                {
                    string path = AssetDatabase.GUIDToAssetPath(GUIDs[0]);
                    image = AssetDatabase.GetCachedIcon(path);
                }
            }
            return image;
        }
shell beacon
#

I'll use #if..

whole steppe
#

but Reflection is my friend!

#

here's an example

shell beacon
#

lol actually my project has a lot of reflections 🤣 we can cache it as delegate and reuse 🙂 thanks

whole steppe
#

segs 👍

faint pendant
#

for some reason, my visual studio 2019 isnt giving me errors for unity code, even though it was before. I do not know what i did to make it do that

shell beacon
grave mortar
#

Greetings!

I have an editor script, that helps a user create a script and writes it to file.

I then want to be able to add the new class to a gameobject in the hierarchy.

The issue I'm having, is for Unity to know about the new class, I need to run AssetDatabase.Refresh();

I've tried many different 'tricks', but I'm at the point now, that I feel its impossible to get any logic to continue after AssetDatabase.Refresh(); has been called.

Is my suspicion correct? or is there a way for me to get my logic to continue, and be able to Add the new components to my gameobject?

crude forge
#

Hm. so I can get shortcut bindings and Ids via ShortcutManager.instance.GetAvailableShortcutIds and that API. but what about 'click' related actions? ie- seeing if there's a 'shortcut' for alt-mousebutton0, or ctrl-mousebutton1, or behavior like that? Is there a way to check and see what a combination of provided buttons and keys would have behaviors assigned to them?

#

(I created something, for example, that takes the mods and reacts on a keyup in the Editor, printing any assigned name of a shortcut binding if one is available)

#

ie- Ctrl+s ==> Main Menu/File/Save

gloomy chasm
#

What are peoples opinions on loading UXML and USS by assigning them in the "default reference" in the script inspector vs loading them by path in code?

waxen sandal
#

I never use default references since they're so hard to find and it's not obvious how it's loaded

gloomy chasm
#

Yeah, that is true.

#

I am trying to set up some basic workflows and utilities for cross package editor windows. And coming up with a single utility method for multiple packages is hard :/

vapid prism
gloomy chasm
#

So if I have all of my UXML and USS inside of Editor/UI, then I can do something like this
LoadStyleSheet("Collections/StandardCollection.uss")

#

And it should work

crude forge
#

Hm. I am working on an editor gui, my string values are getting reset every time. it's likely because I'm feeding the values in through dropdown menus - my private ints defined in the editor are getting reset when I navigate away. here's the problem - the dropdowns are dynamic: they are fed the sorting layer name list. so I'm trying to save the names to the actual monobehavior (so if the layer count changes it doesn't nuke every game object)... but I'm not sure how to resolve the problem of the selection value saved by the dropdown menu from being lost every time and reset when the gameobject is visited again

gloomy chasm
crude forge
#

Yep it is the int of the selectable... But it's the structural problem I'm not sure about...

gloomy chasm
#

Could store them in SessionState? Again, I don't really get what you are doing though

crude forge
#

Ie not relying on the int from the popup but... Hm.

random glade
#

Hi, I'm using Visual Studio Code and I don't get the snippets here. I have the Package installed and also installed extensions. Still not showing here? Can someone help? I did all of the steps in the !vscode command but its still not working. Restarted my pc and so on. Nothing helped

real ivy
#

Hi all, anyone using ParrelSync?
Is it possible to disable opening code IDE when double clicking on console log entry, on the clone editor?

shell beacon
#

Can we use relative paths (to a local file) in HelpUrlAttributes?

peak bloom
#

@gloomy chasm is it possible to handle undo/redo ourselves(manually)? as in without using Binding and just events

#

also, it's for custom editors

gloomy chasm
peak bloom
#

it's a huge enough project that refactoring this can be a pain

gloomy chasm
peak bloom
#

yes

gloomy chasm
#

How are they doing it if they are not using binding properties?

peak bloom
#

callbacks

gloomy chasm
#

And setting the values directly instead of using SerializedProperties?

peak bloom
#

yes

#

exactly that 😄

gloomy chasm
#

It would be less work and better in every way to just switch to using serialized properties than trying to make it work with undo

#

Because when you undo, you have to manually update the values in every field 🙃

#

Assuming that undo was even registered

#

Literally one line fixes it myIntField.bindingPath = "_myInt"; 😛

#

Get rid of all of that callback stuff

peak bloom
#

man, this can take hella long time to finish kekwait

gloomy chasm
#

I mean, unless they are doing other stuff too in the callbacks. It shouldn't take more than a couple of hours to do depending on the size of the project I would think

peak bloom
#

yes, lotta things there.. I guess I've no other choice then kekwait

gloomy chasm
#

Have fun 👋

peak bloom
#

🥹

#

thanks! bro 👍

zinc wasp
#

I'm back with more GraphView questions
a) how do I get a selected node? how do I call a function each time this happens?
b) is there a way to highlight nodes? for example, if I have one node selected, I would like to highlight some other nodes instead of drawing more edges and making everything unreadable

peak bloom
peak bloom
#

@gloomy chasm pretty sure you showed a dude an api to check for duplicate names in edit mode, but I forgot what it was

#

again, sorry for the ping UnityChanOops

peak bloom
peak bloom
#

tring to avoid FindObjectsType here if I can

peak bloom
#

yeah, that's the api I was looking for, thanks!

peak bloom
#

@waxen sandal one more, proly you know how to have custom icon for objects in hierarchy?

#

what api should I take a peek?

#

the red color should be where the custom icon will be at

peak bloom
#

aight, thanks! 👍

peak bloom
#

thanks, once again! this it works 🙂

#

one question tho, it appears if I did this

        static GUIContent ChangeIcon(string txt)
        {
            var orangeGui = EditorGUIUtility.IconContent("d_Transform Icon" );
            orangeGui.image = Resources.Load<Texture>(txt) as Texture2D;
            return orangeGui;
        }
#

it would replace the built-in "d_Transform Icon"

#

is there anyway to assign the texture directly?

#

..

#

nevermind, found it 🙂

#

it is fixed now... apparently I did it wrong, needed to instantiate GuiContent directly instead of replacing the built-in

crude forge
#

Hm. So I'm trying to create an in-editor GUI so I can get some visual feedback based on tool-state (for debugging). This would run inside the unity editor, and in theory have some corner-text and shape/color information (not unlike a fps indicator). I know how to display text in the screen-space context, but nothing that will be locked to the actual scene view.

Is something like this feasible to accomplish? Or should I try and completely rethink an editor gui approach for debugging?

gloomy chasm
crude forge
#

I can make an indicator -in the scene-... but not something that would be locked to the scene view camera. without manually creating some shenanigans via EditorApplication.update and moving/resizing objects constantly. which I could do... but I was hoping to avoid that

gloomy chasm
crude forge
#

not the intended example there, but effectively what I'm trying to do. have text and symbols in the corner that will exist -within the editor mode- while I'm using the tools I am customizing. as a means of debugging behavior within those tools. that text will have to stay within the same position and size as I move the scene view camera around

#

the "styly" text and symbol is roughly what I'm trying to accomplish... in Editor

gloomy chasm
crude forge
gloomy chasm
crude forge
alpine bolt
#

I'm having some sync issues with my Transition Animations on the Editor side. I find that starting my transitions without the await Task.Yield() line are fallible. Sometimes they animate, sometimes they just skip to the end, instantly. I wonder if there's a proper way to sync this ```cs
private async void AnimatedBorderDepth1HighlightColorSwitch()
{
if (_doOnInitialization)
InstantBorderDepth1HighlightColorSwitch();

if (DataAssetObjectExists)
{
    _borderDepth1.RemoveFromClassList(_COLOR_DEPTH_1_ANIMATED_INACTIVE);
    _borderDepth1.AddToClassList(_COLOR_DEPTH_1_ANIMATED_ACTIVE);
}
else
{
    _borderDepth1.RemoveFromClassList(_COLOR_DEPTH_1_ANIMATED_ACTIVE);
    _borderDepth1.AddToClassList(_COLOR_DEPTH_1_ANIMATED_INACTIVE);
}
        
await Task.Yield();
        
if (_doOnInitialization)
  ResetBorderDepth1HighlightColorInstantSwitchClasses();

}```

zinc wasp
peak bloom
#

that's a matter of how you'd iterate over them and do your custom styling etc

#

you can do

foreach(var node in graphView.nodes)
{
    if(node.selected)
        //DO Blue color
    else
        //Do Red color
}
peak bloom
#

in the case of Unity, there's a chance your code would get executed twice at the beginning and end of invocation

#

you'd need to use CustomYield if you're planning to wait for next frame with async/await in Unity

#

and I'm not sure if CustomYield would work for custom editors due for a fact there's no concept of frame timing in it

zinc wasp
peak bloom
#

via uss/uxml

#

nodes in graphview api are just UIElements

#

or via Query and just modify the default color

var node = node.Query("border-selection").First(); // to get the border element
/// then do inline styles (c#)
#

border-selection iirc is the name of the border element, you should check

zinc wasp
#

oh no

#

its been years since i've messed around with css, and i have absolutely no clue how to write uss und uxml

alpine bolt
#

there's some small use cases where you do need to write, but it's mostly to cache reusable variables, but that's more ahead

alpine bolt
# peak bloom in the case of Unity, there's a chance your code would get executed twice at the...

Interesting. I'm glad I made that 'mistake' as the await Task.Yield was different for different transition types (opacity, translation, etc...). What I ended up doing was subscribing to EditorApplication.update event and respond to any visual update requests. I'm still testing, but it seems to work with the same visual outcome, but better, as there's no unnecessary multiple execution.

peak bloom
#

oh it's imgui

alpine bolt
#

UITK

peak bloom
#

and what kind of visual update request you're talking about?

#

in what context?

alpine bolt
#

adding or removing classes that have transition animations. They seem to require some sync with the Editor to work in Editor-mode.

#

So, whenever I want to make a class switch, I just mark it as "updateButtonVisuals"

peak bloom
#

transitions work fine in edit mode on my end

alpine bolt
#

I'm not having that experience when using a context menu, for example.

peak bloom
#

proly just a quirk with uitk version you're using... UItk kinda janky here and there but it's fine overall

alpine bolt
#

any sudden change is a bug, every smooth change is the intended behaviour

#

I'm using the latest 2022.2

peak bloom
#

did you make sure to cancel it (if there's any animation going on) before invoking the animation

alpine bolt
#

Cancel?

peak bloom
#

and don't forget to always schedule it

#

yeah

alpine bolt
#

I know there's the OnTransitionCancel event, but never figured out how to invoke it

#

I always thought it was something on the unity internals

peak bloom
#

yeah, it's not exist just yet 😃 .. unfortunately

#

I'm using a not splendid way to cancel it

#

are you fine with inline styles?

#

if so, you can just interpolates the style values

#

give me a sec

#

I see you're already using async/await in your code, so shouldn't be too difficult

alpine bolt
#

I removed all async when switched to EditorApplication.update -= OnEditorUpdate;

peak bloom
#

oh I'm using my own helper class for this, but if you're ok I can send you my tween helpers for uitk

#

it works in the edit mode and runtime

#

it's my git repo but wont link it here for my own convenience

alpine bolt
#

sure. I can read through someone else's code

peak bloom
#

aight

errant shale
#
  • I'm planning to start making an editor tool that is very similar to tilemap's grid editor. I wish to zoom in/out, move around, select and modify specific "cells" of the "grid". How difficult will this be to create, and what to search for? I don't have any experience with editor tools that respond to user devices input, just inspectors or gui windows for data editing
errant shale
#

- Doesn't matter, i can work with both. But i prefer imgui

gloomy chasm
glad pivot
#

is there any best practices when it comes to creating plugins that use scriptable objects as configs?

#

like as example best way to create a config to make sure there is always one in the project, or easy way to reference the config (should it have static elements, or always be referenced by loading it from resources/ dragged and dropped?)

gloomy chasm
glad pivot
#

yes catnod

gloomy chasm
#

Then no, there is not really a best practice. There is no way I would consider good to do it. But I would say probably create a singleton and on the get, you use Resource.FindObjectsOfType to see if one exists in the resources folder. If not, you create one. And inside of a #if UNITY_EDITOR you save it to the assetDatabase in a resources folder.

#

Unless you need multiple configs

#

Then it depends on how they are used, where, and when

glad pivot
gloomy chasm
#

If it is used in the scene and makes sense, you could have a component that references a config.

glad pivot
gloomy chasm
#

You could have a 'master' config that is a singleton that has a list of all of the other configs.

gloomy chasm
short tiger
#

The SettingsProvider and SingletonScriptable APIs could be considered best practices for exposing and storing custom project settings, but they are also editor-only APIs, so you would still need your own method for making it included and accessible in builds.

glad pivot
gloomy chasm
#

Though they are super nice

short tiger
#

You can also use PlayerSettings.SetPreloadedAssets to have some ScriptableObjects automatically load and wake up in builds.

#

The list is also exposed in Player Settings if you want to do it by hand.

crude forge
#

jumping back to an old thing - I know there's a way to get shortcut bindings. But I'm wondering about the bindings that use the mouseclick/drag.

#

I can get keyboard-specific shortcut bindings and Ids via ShortcutManager.instance.GetAvailableShortcutIds and that API. But it doesn't include mouse actions (click, drag, etc).

I'm using this, in general, to put together custom Unity Editor workflows... without overlapping what's already there. And understanding what IS there and what the context (name of function) is can help a lot. So I have a thing that always prints out the current keybindings when I press a key in the editor.
ie- Ctrl+s ==> Main Menu/File/Save

valid helm
#

Hey guys! Does anyone know how I create this horizontal line to separate sub-items generated by [CreateAssetMenu(...)]?

short tiger
#

So in this case, maybe Data Driven Architecture has order = 10, Folder has order = 12 and C# Script has order = 14

valid helm
shadow minnow
#

I wrote a shader for sprites that allows me to swap palettes, but the way the shader works requires the main texture of the sprite to become unrecognizable. This is a problem for tilesets since the tile palette window just displays the images of the tiles

#

is there a way i can change the material of the tiles displayed in the tile palette window?

#

and if i can't modify this window, is there a way i could realistically recreate the tile palette window to accommodate the changes i need to make?

#

for instance, is there a way via editor scripts to change the active tile brush? or to display sprites with a material applied?

azure coral
#

I think this would qualify as an editor extension question. Is it possible to access/expose the Transparency Sort Mode for sprites (normally found in the 2D Renderer Data) in the Universal Renderer Data asset?

#

I needed access to the Opaque and Transparent Layer masks found un the UR Data asset, but the project I'm working on uses tilemap and I need to be able to sort sprites automatically on Y axis

#

I've written a very simple script that does this without the renderer data asset, in literally 1 line of code. But I'm not sure if it will cause me trouble in the future

#

And I have to attach it do everything I want sorted on a specific layer

#

This is what I need.

#

But it doesn't appear here, Unless I'm not understanding how it functions with this renderer asset

peak bloom
#

is there any callbacks for when we're docking/undocking editor window?

#

well, GeometryChanged event seems work 🥹

gloomy chasm
peak bloom
#

when the nodes are massive tho...

#

if only just couple of them it's fine

gloomy chasm
peak bloom
#

yeh

gloomy chasm
#

That sounds sounding like you might be doing something funky, pretty sure ShaderGraph and the like don't do that. And I don't remember ever having an issue with it

peak bloom
#

I did bunch of Querying to each node in the graph and stripping off some of the default child elements, which I shouldn't 😄

#

as the graph grows, with bunch of nodes, docking/undocking can be painful

peak bloom
gloomy chasm
#

Sure thing, I would probably try to create a new graph window with nothing in it, and start adding stuff until ya find the thing that breaks it. Kind of annoying. But future you will thank you haha

peak bloom
#

@gloomy chasm while you're here
Here's the thing, I've a custom graph editor that can do addons, BUT what if I want to make an addon for it that requires external SDK(in this case it's Live2D sdk) that users MAY OR MAYNOT have them installed on their machine

gloomy chasm
peak bloom
#

exactly!

#

or just errors in general after installing my package in Unity editor

gloomy chasm
#

There is two ways to do it. One is to use defines. For example, if you are trying to do HDRP specific stuff, you would reference the HDRP assembly from your assembly, and the HDPR assembly has a HDRP_01 define (or something like that). So in code, you would do

#if HDRP_01
// some HDRP specific code
#endif

The other option is to put the addon in a unitypackage. And simply unpack it to add it. There is a number of ways to do this, could check for a type, have the user manually unpack it, or have a window where they can click a button.

peak bloom
gloomy chasm
peak bloom
gloomy chasm
peak bloom
#

OH! haha

#

oh yeah... holy.. I didn't think about that 🤣

gloomy chasm
#

LOL

peak bloom
peak bloom
#

lmao

#

marvelous! 👍

#

thanks a ton, bro! 👍 will go with that instead yeah! nice!

gloomy chasm
#

No problem! 😄

green owl
#

Yo!
How do I use isTrigger with the object still colliding?

green owl
#

never mind

peak summit
#

i have an object with child transfroms that I want to move and then the parent object executes a method when the child transform is moved in the editor.
would i have to create a special script to place on the children?

#

or is there a way for the parent to know when child objects are moved inside the editor?

#

or should I be using editor handles for something like that?

peak summit
#

how can i make the animator record a position change when I move a position with handle.positionhandle() ?

#

how do I find what the transform properties are called in strings?

#

trying to use serializedobject.findproperty

peak bloom
# gloomy chasm Sure thing, I would probably try to create a new graph window with nothing in it...

found the issue

        private GraphViewChange OnGraphChange(GraphViewChange change)
        {
            if(PortsUtils.PlayMode)
                return change;

            if (change.movedElements != null)
            {
                foreach (GraphElement e in change.movedElements)
                {
                    if (e.GetType() != typeof(VNodes))
                        continue;

                    var vp = (VPortsInstance)e.userData;
                    vp.vnodeProperty.nodePosition = e.GetPosition();

                    EditorUtility.SetDirty(PortsUtils.activeVGraphAssets); /// dumb shit
                }                
            }

            return change;
        }
#

next level of stupidity! 😄

gloomy chasm
charred inlet
#

does anyone know how to write a [CustomEditor] script that remains active when a child of the target type is selected in the hierarchy?
i think I've seen this in some package code of Unity but cannot find it again, it may involve manually creating an editor type (which was an undocumented method in some editor utility class if i recall correctly)

gloomy chasm
charred inlet
# gloomy chasm What do you mean "Remains active"?

I mean if I have parent selected, the custom editor is active. If I select one of the child game objects, then the parent's custom editor is disposed because the children don't have a MonoBehaviour of the custom editor type. Obviously I can also put a child custom editor that performs the same work as the parent custom editor but it kinda feels odd doing it that way.

#

Assume that parent has ParentMB and ParentMBEditor while children have ChildMB and ChildMBEditor.

rain beacon
#

how often OnInspectorGUI is actually called and when? I've put a log into it:

[CustomEditor(typeof(ConversionConfig))]
    public class ConversionConfigEditor : Editor
    {
        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();
            
            Debug.Log("lol");
        }
    }

and it seems like it gets called like 4 to 6 times whenever I click in the inspector window (with the corresponding asset selected)
and 8 times on creation (what?)
is there some clear info when and why and how often this method is called?

charred inlet
#

@rain beacon I assume it works the same way as OnSceneGUI meaning you'll get a call for various EventType. Try Debug.Log(Event.current.type) to see the different event types causing each call.

rain beacon
alpine bolt
#

How do I add a button either on the red or blue area?

gloomy chasm
# alpine bolt How do I add a button either on the red or blue area?

Reflection. Note that I didn't put any check is to make sure there is valid date, and did add any of the bindingFlags that you would needto get the fields and stuff.

var toolbarType = typeof(EditorWindow).Assembly.GetType("Toolbar");
Object toolbar = Resource.FindAllObjectsOfType(toolbarType)[0];
VisualElement root = toolbarType.GetField("m_Root").GetValue(toolbar) as VisualElement;

// Now use root like normal. You can open the UIToolkit Debugger in Unity to find the names of the elementsto query.

https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/GUI/Toolbar.cs#L56

#

Also I didn't test it since I just wrote it in discord.

alpine bolt
gloomy chasm
#

I think there is a github package someone made to do it if you want

rain beacon
#

is it actually possible to see which value was updated in OnValidate()? ofc I can keep current state of all fields and compare, but it's kinda dumb. it would be nice if unity sent me who was changed

austere pulsar
#

im making a custom editor, but when i do this

public override void OnInspectorGUI()
    {
        base.OnHeaderGUI();
        if (GUILayout.Button("Generate World"))
        {
            generator.Generate();
        }
    }

it hides all other attributes in the script like worldheight, width, etc

#

none of these fields are showing up

crude relic
#

You are calling base.OnHeaderGui instead of base.OnInspectorGui.

#

@austere pulsar

austere pulsar
crude relic
#

👍

rain beacon
crude relic
rain beacon
# crude relic What are you trying to accomplish

just an extension for editor's functionality which would basically do OnValidate() for a concrete field once it's changed, not running whole code, but just the code that is relevant to a specific field

crude relic
#

Ah, I see. Yah, no way around that one

rain beacon
#

and it seems like there's no other way than reinventing git and taking a snapshot of current state of the fields and compare it OnValidate()

crude relic
#

That really sounded like an x/y problem but you were actually trying to do exactly what you were asking about ahahaha

#

What is the situation this is used in? Attribute?

rain beacon
crude relic
#

If you control the lifecycle you can create serializedobject for whatever you're tracking

#

And then use that to measure changes

#

Thats what unity does internally

rain beacon
crude relic
#

Hmm, not sure how do describe that concretely. You need a point at which it makes sense to create a serializedobject before changes are made and then detect them after changes are made

rain beacon
#

yeah makes sense

crude relic
#

In the editor, this is done by creating a serializedobject before updating the inspector and then detecting/applying changes after the editor is finished (roughly speaking)

rain beacon
#

anyhow thanks for explanation

crude relic
#

Hmm, I could have sworn serializedobject exposed some way to get changed value information

#

Might be fulla shit 🤔

rain beacon
#

but I found nothing that would tell me who was actually changed

#

just has modified or doesn't have

#

what I ideally would like to achieve though is attribute
[ValidateWith("MyMethod")] applied to fields/properties
which would run MyMethod when I change value in inspector
🙂

#

but I don't see a clear way of doing this

#

other than going very deeply into the weeds of custom editoring
(or reinventing git)

gloomy chasm
#

You can also use ObjectChangeEvent for the same sort of thing. Downside is that it is a global callback

rain beacon
#

seems same as OnValidate()?

gloomy chasm
#

Except that it is only called once per frame per object, and won't be called for other things besides property changes

hard pine
#

Is there anything for sticky scrolling in unity?

peak bloom
#

just necroing, sticky-scrolling sounds like food to me 🤣

hard pine
peak bloom
#

I see 👍

peak bloom
#

@gloomy chasm is ScriptableSingleton saved as physical file somewhere in our project or nah ?

#

I always thought that FilePathAttribute tag actually does that but not quite sure

wintry wharf
#

is there a way to have different inspector icons for each copy of a scriptable object? I'd like to have my game items' images as icons on the scriptable objects
SetIconForObject changes the icon to the same image for every instance, which I don't want

gloomy chasm
peak bloom
peak bloom
#

Project

gloomy chasm
#

Just in the project settings then

peak bloom
#

oops wrong screenshot

#

there

gloomy chasm
#

YOUR_PROJECT/ProjectSettings/

peak bloom
#

oh! I thought it's a relative path of our main project

#

give me a sec