#↕️┃editor-extensions

1 messages · Page 44 of 1

visual stag
#

and you can definitely create and attach a new script using this method

#

With the CreateScriptAssetFromTemplate method at the bottom there containing what I previously described

#

Maybe it's the AddScriptComponentUncheckedUndoable function we want

visual stag
#

ye

barren moat
#

YES!

#

Can I access that though?

#

internal

visual stag
#

Of course

#

Reflection

barren moat
#

Yeah.

#

cool 😃

plucky inlet
#

REFLECCIONEEE in Tiny Tina voice

visual stag
#

MethodInfo AddScriptComponentUncheckedUndoableMethod = typeof(InternalEditorUtility).GetMethod("AddScriptComponentUncheckedUndoable", BindingFlags.Static | BindingFlags.NonPublic);

barren moat
#

ooooooh

#

Saved me some time

#

Reckon I can set fields on it too?

#

haha

visual stag
#

No idea lol, see if GetComponent works immediately after you've added it

#

I think you're in new territory now 😛

barren moat
#

It worked!

#

I got my script attached

#

❤ ❤ ❤

plucky inlet
#

👍 surprising :-]

barren moat
#

Yes.

#

I have no means to call GetComponent directly though because I need a Type instance.

#

And the type doesn't exist.

whole steppe
barren moat
#

That would have saved me some time

plucky inlet
#

@barren moat I'd probably try to reflect the type from string to see if it's there on reload callback

visual stag
#

is the GetClass method on the MonoScript that you can now Load not initialised?

barren moat
#

It returns nulll

visual stag
#

Makes some sense

barren moat
#

yeah it does

visual stag
#

At this point we've gotta go through the reload

barren moat
#

Hey I can't work on this now, I'm at my job. 😃

#

Thanks for the tips though.

#

Yeah, I can still do that, will be easier though.

plucky inlet
#

you'd probably still need some reload syncing, anyway this should be half way there 0

barren moat
#

yep, def.

barren moat
#

oh, I got one!

#
void Reset() {
  if (_animator == null) {
    var animators = GetAllComponentsInChildren<Animator>();
    foreach (var a in animators) {
      if (a.RuntimeAnimationController.name == "theName") {
        _animator = a;
        break;
      }
    }
  }
}
#

boom, problem solved

#

I'll just add this to the generated script

random flume
#

Gais doing onHover.background =Texture2D.whiteTexture is not smooth and slow. I am trying to change the background color of my buttons

obsidian thunder
quasi monolith
#

hey guys any way to detect when the user is in right-click-rotate-view mode?

#

"flythrough" mode

#

ok apparently I can check Tools.viewTool

#

BUT this is always reporting as Pan view, never anything else

#

gotta be a bug?

dim walrus
#

Try to use Debug.Log all frames while moving the camera to check which are which tools

#

Like using Tools.current

gloomy chasm
#

I am having this bug where I have a custom class that stores a serialized property. I do some stuff with the class, pass it around a couple of methods. But when I do something with that serialized property it has lost it's connection seemingly to the original and so it doesn't effect the original if that makes sense. Any ideas what could cause it to lose the connection like that?

sterile spire
#

mmh... if I understand it right... when you modify the serialized property of your monobehaviour... the modifications seems to "not happen"? say..... if you have set serializedProperty.x++ from you editor script, the serializedProperty.x variable won't change it's value?

#

if so... it might be solved by registering your monobehaviour on the Undo before doing the changes

hot whale
#

reload.SpawnedArrow.AddListener(OnSpawnArrow); Its saying that SpawnedArrow is null although I am just trying to add a listener to the unityEvent

wispy delta
#

@hot whale This channel is only for editor scripting ie: extending the editor. You may have better luck posting in the #💻┃code-beginner channel.
@sterile spire any changes you make to a serialized property won'y be applied until you call ApplyModifiedProperties() on the serialized object that holds the properties

hot whale
#

😮 didn't notice I was in Editor scripting. my bad

wispy delta
#

no worries 👍

random flume
#

Oh hi @hot whale

hot whale
#

Hey whats up lol

random flume
#

We are not allowed to talk here man what is wrong with you @hot whale ??

novel heath
#

So i've got an stateBehaviour that takes in a SO and on update, updates my transition conditions on the incoming transition with an Editor script i built. these states that the behaviour is attached to are nested in a SubStateMachine. I'm grabbing a reference to the SubState by digging through the context and attempting to add an any state transition (substate.AddAnyStateTransition(currentState)) It wasn't working exactly... so i went to the docs and saw that description:

Utility function to add an AnyState transition to the specified state or statemachine.

The transition asset that is created is added as a sub asset of the state machine. Its important that AnyStateTransitions are added to the root state machine. AnyStateTranistions added to a sub state machine will be discarded at runtime. This function pushes an Undo operation.

Not sure i quite understand this and am wondering if someone could help me out? I'm actually seeing these transitions in the context object, but not seeing them drawn in the animator itself. So my immediate thought is, this wont work. Does this mean there is no way to add a transition in a SubState from the Any State to another State through script?

gloomy chasm
#

So I have a propertydrawer for a non-Mono class. I edit some values directly, not using a serializedproperty. But I can't figure out how to save the changes so that prefabs will respect and save the changes. Any ideas?

random flume
#

So when I close my Editor window the object I put in my ObjectField is gone. How to keep it?

visual stag
#

Serialize it somewhere

#

Scriptable object, component, put the guid into editor prefs, etc

random flume
#

Do you think I can use SerializedObject @visual stag ? Or that is not their use?

visual stag
#

Serialized Object is a representation of an already serialized object

random flume
#

I used Editorprefs and getinstanceid which seems to work @visual stag

#

Hopefully it is ok to do that

green shoal
#

I'm having trouble to find how to display a image in editor, like in shader editors for example, can someone give me a direction to where I can read about it?

visual stag
#

EditorGUI.DrawPreviewTexture

#

if you want to draw it transparent use this material:
new Material(EditorGUIUtility.LoadRequired("Previews/PreviewTransparent.shader") as Shader) {hideFlags = HideFlags.HideAndDontSave}

green shoal
#

thanks a lot, it helped me a lot 😄

green shoal
#

So, I'm trying to build a tilemap, is there a way to insteado of making objectfields and then drawing the tiles, I just make square fields that display the img instead of the tile?

#

Like, I tried drawing the img in the same space if the value was not null, but then I can't select the tile again :B

onyx harness
#

@random flume InstanceID won't work. It does not survive a process restart.

#

@green shoal Have you tried GUI.DrawTexture?

green shoal
#

I'm using the draw preview texture, it is working as long as you drag objects to it and I'm fine with it, I just wanted that small button to open the selection window

#

but the squares just gave me a massive bug and I have no clue to what happened ;-;

onyx harness
#

Dragging object to a draw preview texture? I don't understand

green shoal
#

it is an objectField, the draw preview is on top of it, so if you drag the object gets it

onyx harness
#

oh I see

green shoal
#

but as the preview is on top you cant click

onyx harness
#

That's strange

#

Drawing a preview does not catch any event

green shoal
#

maybe thats the bug I'm having and I didn't even notice before 😄

onyx harness
#

Just check what you are rendering.

#

Or use the GUI debugger

green shoal
#

I think I messed up while getting the rects and got some overlapping

onyx harness
#

I might say, you should think about not using ObjectField at all

green shoal
#

I have no idea how else to do this tho

onyx harness
#

DragAndDrop
And also Event.current.type using EventType.DragUpdated, EventType.DragPerform

#

When you drag an object, it is held by DragAndDrop

#

And you receive the events DragUpdated in your OnGUI

green shoal
#

yeah, I just drew in all my rects to make sure, they are ok, it is the object field trolling me .-.

onyx harness
#

When you finally drop the object, DragPerform is sent

#

I understand DragAndDrop is a bit cumbersome to grasp

green shoal
#

so, I check for the event and get the object from dragandrop, but how do I get if the mouse is over the rect?

onyx harness
#

You have your Rect no? How do you draw?

green shoal
#

well, till now Ive been drawing with the preview, is there some drawer that sents me a message when I mouse up on it?

onyx harness
#

No no

#

How do you draw your preview?

green shoal
#
Texture teste = textureFromSprite(myScript.TilesCorredor.Chao.sprite);
            EditorGUI.DrawPreviewTexture(myFirstGrid[1][2], teste);
onyx harness
#

myFirstGrid[1][2] is your Rect right?

green shoal
#

yup

onyx harness
#

myFirstGrid[1][2].Contains(Event.current.mousePosition)

#

It is that simple 😃

green shoal
#

wow, nice, I'll try it, thanks a lot for that walkthrough 😄

#

I'll test and finish it tomorrow, I have to sleep before checking through a lot of tile names

onyx harness
#

No problem, good luck

green shoal
#

so, I don't really have much Idea of what I'm doing

    Texture testee = EditorGUIUtility.whiteTexture;
        EditorGUI.DrawPreviewTexture(myFirstGrid[0][0], testee);
        if (Event.current.type == EventType.DragPerform)
        {

            if (myFirstGrid[0][0].Contains(Event.current.mousePosition))
            {
                Debug.Log("worked");
            }

        }

it should work like this right?

#

because it didn't and I don'tk know why

#

the EventType.DragUpdated works fine, the EventType.DragPerform is the one not being sent

#

worked with drag exited, its good enough for me, I think my field being an image it does not work, I now got I'll have to put a feedback with the DragUpdated and so the DragPerform will probably work

visual stag
#

You don't have anything else in the place where you're dragging?

#

just the texture

onyx harness
#

@green shoal Put a Event.current.Use() at the end of your DragPerform

#

Also I'm not sure 100%, but you need to set DragAndDrop.visualMode to something different than Rejected in your DragUpdated.

random flume
#

What do you mean a process restart @onyx harness ?

random flume
#

Oh man much thanks for that material thing @visual stag !!

onyx harness
#

Closing then opening Unity.

green shoal
#

I'm having an issue, only my first row works

#
//my draw line
EditorGUI.DrawRect(myFirstGrid[x][y], myCol);
//my line checking the mouse
if (myFirstGrid[x][y].Contains(Event.current.mousePosition) && DragAndDrop.objectReferences[0].GetType() == typeof(Tile))

//both of them in two equal for loops
#

I added this in the same place to debug it

if (myFirstGrid[x][y].Contains(Event.current.mousePosition))
                    {
                        Debug.Log("the current tile position is " + x + " " + y);
                    }

why is it saying it contains the mouse but then when I'm dragging it won't change?

green shoal
#

I think I figured it out, kinda, EditorGUILayout.GetControlRect reserves a space, as I was getting all the rects based on the first and not using this, it didnt reserve space for them, and then only REAALLY drew the first row, the other were still on the first roll as I didn't get them

#

editor often is really confusing for me

onyx harness
#

@green shoal if you know your Rect, you don't need GetControlRect

#

If you draw something below your pictures using EditorGUILayout. Then use GUILayout.Space()

#

To 'reserve'

green shoal
#

thanks for the help 😄

green shoal
#

Ok, So, I'm using the transparent material, but I wanted it to have a "faded" color so the user knows it is not a tile he selected, is there a way to do so using the material?

random flume
#

What do you recommend then @onyx harness ?

onyx harness
#

@random flume Unsupported.GetLocalIdentifierInFileForPersistentObject

random flume
#

Oh wow

#

Works for prefabs too @onyx harness ?

onyx harness
#

It can

#

But a Nested Prefab is a bit more tricky to handle, depending on the case

random flume
#

I just need to know the gameobject put in object field

onyx harness
#

If it is the root GameObject of a nested prefab, yeah it should work as expected

random flume
#

Won’t work if it is a child?

onyx harness
#

It is a bit more complex than that

#

If it is the REAL child of the prefab, yes.

#

If it is a child coming from a Prefab Stage, it will not really work

#

Because in a prefab stage, the GameObject is a copy/instance, and therefore not persistent by definition

random flume
#

I am sorry but what do you mean by prefab stage?

#

Also the main question

#

Will it work on old unity versions @onyx harness

green shoal
wicked hornet
#

I just made a script that is supposed to restart the level when you enter a trigger hitbox, but it doesn't work and I don't know why, any help?

onyx harness
#

It will work on older versions, it depends when the method above have been implemented

#

@random flume

random flume
#

I couldn’t find any documentation on it

onyx harness
#

Google Unity api versioner

#

It will help you

random flume
#

Ok

green shoal
#

btw, is there a way to remove those weird cuts you can see in the image I sent?

bronze mountain
#

a gameobject is not the same as a transform @wicked hornet

onyx harness
#

@green shoal how did you generate your Rects?

random flume
#

It is a 2019 thing @onyx harness

#

Guess I am stuck with instance ID

wicked hornet
#

yeah but I changed the Transform to a GameObject, and vice versa and either the code doesn't run or it still doesn't work

green shoal
#
//for the first rect in each row
Rect BasePosition = EditorGUILayout.GetControlRect(true, size, GUILayout.Width(size));
//for the other ones
Rect toReturn = BasePosition ;
toReturn.x += x * size;
//size being screen.width/5f;
onyx harness
#

@random flume before 2019,there is an equivalent, it is named almost the same

#

I don't remember the name exactly

#

But it loses half the accuracy

random flume
#

Oh well instance ID works lol

onyx harness
#

I won't go into details

#

Well, xD

random flume
#

So I will just go with it

onyx harness
#

If it works, it works

random flume
#

Yeah xD

onyx harness
#

@green shoal GetControlRect from Editor GUI will induce some margins. Use the one from GUI utility

wicked hornet
#

Hey, this script I wrote compiles but doesn't work and I don't know why. It's supposed to reload the scene when the player goes into the trigger hitbox

bronze mountain
#

That has nothing to do with the editor :P and maybe put some debug output in the trigger callback to see if it fires at all.

green shoal
onyx harness
#

The argument provided perhaps

#

Or just calculate the Rect yourself X)

green shoal
#
Rect BasePosition = GUILayoutUtility.GetRect(size, size, GUILayout.Width(size), GUILayout.Height(size));

yeah, if I force it to have the size it works perfectly, thanks a lot

whole steppe
#

I"m trying to make a world streaming system that will let me cruise around the game world in the editor. I'm having the problem that I haven't figured out how to reliably get the position of the editor camera that a script depends on to know when to change the active world segments. The code I have now gives me errors that the statement I'm using to grab the camera position doesn't reference an instnace of an object, yet if I move the gameobject the script is attached to the camera location variable gets updated in the inspecor. Any advice?

bronze mountain
#

Do you want to move around with the game window/camera?

visual stag
#

@whole steppe you could make a script that [InitializeOnLoad]s and subscribes to SceneView.onSceneGUIDelegatewhich will pass you a SceneView class that contains everything you may need

whole steppe
#

@bronze mountain Yes. While it's in the editor the script shoul use the editor camera and while in game it should use the players camera.

whole steppe
#

@visual stag I'm using 2019.1 and don't see that function in the documentation. Was it renamed?

visual stag
#

it's been renamed

#

duringSceneGui

#

as you can also use beforeSceneGui

whole steppe
#

@visual stag How do I use SceneView.beforeSceneGui? It's an lvalue so I can't assign anything with it, and even though I don't think it does what I want, I'd like to learn about it anyway.

visual stag
#

this is just hand written so it might be slightly different, but:

[InitialiseOnLoad]
public static class CameraSubscriber {
    static CameraSubscriber () {
        SceneView.duringSceneGUI -= DuringSceneGUI;
        SceneView.duringSceneGUI += DuringSceneGUI;
    }

    private static void DuringSceneGUI(SceneView sceneView) { ... }
}``` @whole steppe
random flume
#

I am trying to create a box like this that has enable/disable toggle that can enable/disable my variables. Any thoughts?

whole steppe
#

@random flume what does bool do?

random flume
#

Wat?

whole steppe
#

nevermind, i misinterpreted your goal

random flume
#

I want the variable to be there

#

I just want to disable them when the toggle is off

whole steppe
#

I'm still looking to see if there is an easy way to do it for individual variables. But this lets you make groups of options that get dimmed and disabled when the toggle is turned off.

onyx harness
#

There is no easy way, you need to use PropertyDrawer

random flume
#

Alright

onyx harness
#

I can drop you some code from NG Tools if you want to achieve this task

random flume
#

So far I managed to load the icons but I can’t make them all line up like in the pic @onyx harness

onyx harness
#

What pic?

random flume
#

@onyx harness

#

You see how the drop down arrow is next to the C# icon next to the toggle button

visual stag
#

@random flume EditorGUI.InspectorTitlebar

#

You can look at the source if you want to make one manually

random flume
#

I looked at that but it won’t let you add the C# icon etc @visual stag

#

Oh how I can look at the source?

visual stag
#

it automatically gets the icon from the object provided

random flume
#

I specifically need the c# icon

visual stag
#

right

random flume
#

So yeah not sure how to make it use the c# icon

visual stag
#

well, you can see how they did it, just do something similar and replace the icon

random flume
#

Aight

onyx harness
#

@random flume hum... There is a hidden method to fetch icon based on a file extension

#

I'm not home, I can't drop the code

random flume
#

I already have the icons

#

Lining them up is what’s confusing me

onyx harness
#

Lining them you mean grouping them

random flume
#

Tried horizontal group and everything but they don’t line up like in the pic

onyx harness
#

?

random flume
#

Yes

onyx harness
#

Or indenting them?

random flume
#

Grouping them

onyx harness
#

To group you need advance PropertyDrawer knowledge

random flume
#

Wait what do you mean group lol?

onyx harness
#

If you toggle a fold, fields are showing up or not

#

Same as disabling them

random flume
#

Ah that is grouping

jolly delta
#

Anyone knows if the code for the HDRP/Lit shader custom inspecor is available somewhere ?

visual stag
#

On your hard drive. YourProject/Library/Package Cache/com.unity.render-pipelines.high-definition...

jolly delta
#

Thank you ! i'll look this way

visual stag
#

You can use one of the debuggers to find what code draws that inspector. Either the UIElements Debugger (which is exposed under the analysis menu) or the IMGUI debugger

#

I'm not sure which one would be required, and it might depend on your version

#

You can add the IMGUI debugger via the pinned link, or the pinned instructions for developer mode

jolly delta
#

I found the code files i was looking for, but i guess it's a bit too complicated for me to guess how to apply the same custom inspector to a shader graph based material ^^'

stark geyser
#

@coarse hull

using UnityEditor;
using UnityEngine;

[CustomPropertyDrawer(typeof(ReadOnlyAttribute))]
public class ReadOnlyDrawer : PropertyDrawer {

    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
        GUI.enabled = false;
        EditorGUI.PropertyField(position, property, label, true);
        GUI.enabled = true;
    }
}```
and attribute itself
```cs
using UnityEngine;

/// <summary>
/// Usage [ReadOnly] attribute for the inspector fields
/// </summary>
public class ReadOnlyAttribute : PropertyAttribute { }```
coarse hull
#

I've never understood customeditors or propertydrawers, for a scriptable object how would I use custom stuff like greyed out variable fields?

coarse hull
#

How would I make this in a custom editor script?

    [Space(10f, order = 0)]
    [Header("Overrides", order = 1)]
coarse hull
#

nvm got it

smoky radish
#

Hey guys,
Is it possible to get a value of the property which is a custom class and it doesn't inherit Object class ?

smoky radish
#

Do you know guys, how I should make editor field for FieldInfo ?

bleak furnace
onyx harness
#

@smoky radish You can access 'target' from the SerializedObject, from it get the property's valur

#

What do you want to show about a FieldInfo?

smoky radish
#

In a dropdown in inspector, I want to select one of the items in a dropdown and then show its public fields in inspector and can modify those fields. So I find that selected type fields in dropdown by reflection.Then I want to show those fields in inspector and can modify them.

#

@onyx harness

onyx harness
#

By any chance, is your object potentially static?

smoky radish
#

No

#

I can get and set fieldinfo value.

onyx harness
#

You will have to recode your own 'inspector' and manually draw each Type from fields

smoky radish
#

But I want to know if I check the fields type and then use proper EditorGUILayout or I can use something genersl like PropertyField

onyx harness
#

PropertyField relies on what is serializable, if your target is not, you can't

smoky radish
#

Yes, I know. Just trying to find something general :D

#

So I should show them according to their types ?

#

Like int, float string snd so on ?

#

And I should use Undo.RecordObject ?

onyx harness
#

Yep, everything manually.

You can't use Undo since it is based on serializable Object

smoky radish
#

@onyx harness Yup, you are right. Then what I should do ?

onyx harness
#

By hand, everything X)

onyx harness
#

For every public fields found in your object, regarding the Type you will display Int/Float/etc.

#

@smoky radish

#

Generally, if you want to handle almost all the types, it's about a dozen 'custom drawers'

smoky radish
#

Thanks. I think I almost figure out what you mean.
Just what is the hand way to make a snapshot ? (Instead of Undo.RecordObject) 😄

onyx harness
#

Unfortunately, Ctrl-Z is catched higher in the process

#

You need a custom Undo, which is not relying on Ctrl-Z

#

Or make a button

smoky radish
#

😦

#

Do you think there is another way to achieve what I want ? Conditional type based dropdown menu

#

@onyx harness

onyx harness
#

Of course, use attribute

#

(I'm AFK for an hour)

smoky radish
#

It is late here 😄 I should sleep. If you are online tomorrow I will ask about more information because I don't get it exactly 😄

onyx harness
#

@smoky radish ask ask, I will answer tomorrow

bronze mountain
#

Or somebody else will and steal your thunder, muhrhr!

random flume
#

Man @onyx harness I can’t seem to get it

onyx harness
#

Wait what?! 🤔

random flume
#

Lining these icons

#

This is how they look

#

@onyx harness

bronze mountain
#

For one you are using the wrong style. :P

random flume
#

Maybe @bronze mountain lol

#

Care to elaborate more?

onyx harness
#

@random flume the foldout that you see is just an illusion.
You can to draw the foldout with no label, then draw the icon, then the text

random flume
#

BeginHoeizontal @onyx harness ?

#

Cuz I did that and it didn’t work

#

Or maybe because I am using a label to draw the icon?

#

GUILayout.Label(EditorGUIUtility.IconContent(“the icon”)

onyx harness
#

No no

#

Get your Rect from EditorGUIUtility

#

With GetControlRect

#

Then manually draw everything

#

No need for a begin

random flume
#

Oh man I am confused now sorry 😦

onyx harness
#

Using a Rect, you can draw things on top of each other

random flume
#

I have a beginners

#

BeginArea

onyx harness
#

BeginArea allows you to use GUI Layout

#

Using GetControlRect you can then use EditorGUI

#

It's a way to switch between both worlds

random flume
#

So I don’t need the area thing too?

onyx harness
#

No need

#

I might even say, this is mandatory

smoky radish
#

Hey @onyx harness
Yesterday I was sleeping when you sent me the message :D
My question is very general 😄 what do you mean by attribute ? You mean make property drawer for it ?

onyx harness
#

@smoky radish you asked for a conditional type based dropdown.
I understand the dropdown is filled with fields meeting a condition.
Condition that can be an attribute.

smoky radish
#

@onyx harness I might name it incorrectly. I mean when I select an item in type based dropdown then I want to show public fields of that item in the inspector.

whole steppe
#

hey guys how do i have an OnSceneGUI in a static class

visual stag
#

SceneView.duringSceneGui += YourGUIMethod;

onyx harness
#

@smoky radish there is a thing a bit strange in that sentence.
From what do you fill the dropdown? 🤔
You said a type based, who provides the types?

smoky radish
#

For getting the selected item type

#

Then find the fields of that type

Type propertyType = Type.GetType(property.stringValue);
FieldInfo[] fields = propertyType.GetFields(BindingFlags.Public | BindingFlags.Instance);
object instance = Activator.CreateInstance(propertyType);```
vestal perch
#

then custom inspector maybe?

onyx harness
#

Well that seems about right

#

Where do you block?

smoky radish
#

Yup

#

No where actually 😄

#

I was asking for better approach

#

Because it has so difficulties 😄

#

I should control the Undo part manually. As you said

#

For each type different EditorGUILayout

vestal perch
#

well unity is going to do simpler editor extensions pipeline soon

smoky radish
#

I hope so. They always say soon 😕

onyx harness
#

@vestal perch do you have a source?

vestal perch
#

source?

smoky radish
#

So I have to go with this approach or there is anything else ?

onyx harness
#

Source of your information

vestal perch
#

I heard of some tool, Odin or smth, didn't use it and maybe it's payed

onyx harness
#

It sounds correct to me

vestal perch
#

well I read roadmaps, so probably there

smoky radish
#

Yup, I don't want to use Odin, prefer learn editor thingies.

#

@onyx harness About what you said about Undo part, I can't use Ctrl + Z then ?

vestal perch
#

"UIElements for Editor Extensions" this one I guess

smoky radish
#

I think that is for the appearance.

vestal perch
#

hmm actually it says it is already in 2019.1

smoky radish
#

Yup

#

I've used it before. UI for editor

onyx harness
#

UI Element is for rendering GUI more efficiently

smoky radish
#

It is for Editor. Am I right ?

onyx harness
#

Yep, if you try to catch undo/redo, you won't exactly have this input

#

But a 'command' perhaps

#

Like copy, paste, select all

#

They are all commands

#

Look at validate command in GUI

#

It is for editor but I heard they plan to use it for in game

smoky radish
#

Hmm, so I can implement it by commands.

#

Nice

#

Thanks

vestal perch
#

well old editor ways were alright until you use GUILayout tools, the precise positioning of elements is a pain

onyx harness
#

@smoky radish double check for undo/redo, I'm not sure it is the same for them

smoky radish
#

Okay, thanks.

vestal perch
#

I hope my old wpf background will help me with new uielements

onyx harness
#

I never use GUI layout, it induces performance decrease and garbage

vestal perch
#

well you are a publisher as I see from the role, for small homebrew tools it's ok to use whatever

onyx harness
#

Yeah you are right, it is superb for prototyping fast :)

random flume
#

@onyx harness Any thoughts on how to create like a pop up with all keycodes ?

onyx harness
#

EditorGUILayout.Popup?

#

Using Enum.GetNames(typeof(KeyCode))?

visual stag
#

it's an enum, so it just works in a property drawer?

random flume
#

Ah will try! Much thanks man!

#

Oh keycodes are enum?

#

Thanks @visual stag @onyx harness

visual stag
#

Yeah, I mean just exposing one publicly turns it into a dropdown

random flume
#

Awesome

#

That did it!

onyx harness
#

good job

random flume
#

Though there is something called EnumPopup

onyx harness
#

Yep

random flume
#

Use that instead of Popup?

visual stag
random flume
#

That is very nice

#

Ok so now the serious questions lol

#

How can I make what I choose to be used in my script?

visual stag
#

what do you mean, just expose a public Keycode myKeycode in your script... and use it

random flume
#

I mean what I choose in my editor window

visual stag
#

Oh, just make a change checked scope, and when it changes, assign it to what you want

random flume
#

Using .FindProperty?

visual stag
#

Or just record an undo and assign it

zealous coral
#

since u are going to assign the new KeyCode value to some variable in ur script in the end, that means there is already an existing variable of KeyCode type from the beginning
u can just do EditorGUILayout.PropertyField(serializedObject.FindProperty("myKeyCodeVariable"));
undo/redo will be handled automatically
(but u still gotta wrap that line inbetween serializedObject.Update(); and serializedObject.ApplyModifiedChanges();

random flume
#

I never really understood serializedObject @zealous coral

#

Like what is this object?

zealous coral
#

i assume u are making a custom editor for a MonoBehaviour, yes ?

random flume
#

Yes

zealous coral
#

in that case, serializedObject will be the "data object" of the instance currently selected

random flume
#

Can I choose my serialized object?

#

Like I have an object field

visual stag
#

It's a serialized representation of a Unity Object

#

it's got nothing to do with object fields

random flume
#

I meant the object in my object field

visual stag
#

If you want to create a serializedObject from an Object you can just use the constructor

zealous coral
#

i usually have something like this as a base

public class MyClass : MonoBehaviour
{
    public int A;
}

[CustomEditor(typeof(MyClass))]
public class MyClassEditor : Editor
{
    public override void OnInspectorGUI()
    {
        serializedObject.Update();

        //insert code here

        serializedObject.ApplyModifiedProperties();
    }
}```
#

u dont need to "pick/choose" the serializedObject

random flume
#

Let us say I do want to pick

zealous coral
#

u basically chosen it the moment u click on the gameobject(which has this monobehaviour attached to it) in the hierachy window

random flume
#

Can I do myGameobject = serilaizedObject

visual stag
#

What does that even mean?

random flume
#

Alright I think I get it

visual stag
#

The inspected Object or Objects are under the .targetObject(s) property if that's relevant

random flume
#

I need to findproperty of the gameobject I put in my field

zealous coral
#

as a starter, u dont have to care about "setting serializedObject"

visual stag
#

Then just create a new SerializedObject using the method I said a minute ago

random flume
#

Ah nice!

#

Cool

zealous coral
#
public class MyClass : MonoBehaviour
{
    public int A;
}

[CustomEditor(typeof(MyClass))]
public class MyClassEditor : Editor
{
    public override void OnInspectorGUI()
    {
        serializedObject.Update();

        //insert code here
        EditorGUILayout.PropertyField(serializedObject.FindProperty("A"));

        serializedObject.ApplyModifiedProperties();
    }
}
#

u can do it this way , the EditorGUILayout.PropertyField line

#

the sad thing is u will have to rely on strings to access those variables, instead of the normal way we code
myclass.A = 10;
^ serializedObject doesn't do this

random flume
#

Alright much love everyone

green shoal
#

Is Tile serializable? I'm havin trouble making it save, will I have to create a new class like you need to serialize dictionaries?

visual stag
#

It is serializable

green shoal
#

so, just to make sure I'm not doing something wrong,

Undo.RecordObject(myScript, "Tile changes");
//then
myscript.tilearray = thisCodeArray;

I'm saving like this, should I do something more?

#

is not really like that as the array size sometime varies, and the code is way bigger

visual stag
#

Seems fine

#

They're ScriptableObjects, so they're definitely serializable

#

Generally as assets

green shoal
#

I'm using this to better organize it, nothing wrong here too right?

    [System.Serializable]
    public struct TilePackage
    {

        [SerializeField]
        public Tile PortaFrenteAberta, PortaFrenteFechada;
        [SerializeField]
        public Tile[] PortaFrenteFechando;

        [SerializeField]
        public Tile PortaEAberta, PortaEFechada;
        [SerializeField]
        public Tile[] PortaEFechando;

        [SerializeField]
        public Tile PortaDAberta, PortaDFechada;
        [SerializeField]
        public Tile[] PortaDFechando;

        /*
         * F : final
         * E : esquerda
         * D : direita
         * C : centro
        */
        [SerializeField]
        public Tile
        Chao,        
        TetoFE, TetoC, TetoFD,
        ParedeFE, ParedeC, ParedeFD,
        ParedeTetoE, ParedeTetoD,
        ParedeFrenteE, ParedeFrenteD,
        TetoQuininhaE, TetoQuininhaD,
        TetoE, TetoD,        
        TetoQuinaE, TetoQuinaD;

    }
#

sorry if it is way too big, I'm kinda desperate right now

visual stag
#

I don't think SerializeField is applied to every field if you use a comma

#

but I'm not certain on that

green shoal
#

Oh, I'll try and change that then, thanks

visual stag
#

Actually, I may be wrong there? It seems to work for HideInInspector

#

Perhaps that's a special case, I'd have to look it up

green shoal
#

well, thinking again

        [SerializeField]
        public Tile[] PortaDFechando;

is the one I'm testing on, so this wouldn't be the issue

visual stag
#

It doesn't look too wrong

#

Seems fine to me 😛

#

You can tell it works fine by exposing one in the inspector

#

if it appears then it's working fine

#

(which it does)

#

You can probably even remove the [SerializeField] attribute

green shoal
#

well, on debug it appears, but as soon as I close the unity all info gets lost

visual stag
#

it works fine for me, must be an issue with you improperly dirtying that object somehow

#

Or not saving the scene or something

zealous coral
#

how are u making the changes in ur editor ?

green shoal
#

it is changing an scriptable object, it holds the tiles for a level and their respective map building color

#

should I use something like AssetDatabase.SaveAssets() as well?

visual stag
#

it should be dirtied fine with an Undo or SerializedObject functions I think

#

You would need to save your project before restarting Unity

#

it's something that can just not happen for some reason sometimes

green shoal
#

ok, so I just wrote the AssetDatabase.SaveAssets() at the end and as soon as I saved the collab gave the notification about the changes, wich it wasn't before, but restarting unity made the tiles vanish anyway

zealous coral
#

made the tiles vanish as in, the asset itself ?

green shoal
#

no, the reference was jsut set to null again

zealous coral
#

🤔

#

do u mind showing part of ur code which shows "how do u make PortaFrenteFechando ,or maybe even the whole TilePackage itself edittable "

green shoal
#

ok, let me just find my github password as it is kinda messy

#

I just opened unity one more time without even changing the code and this time it worked, I'm so confused right now

zealous coral
#

so, it worked ?
problem solved 😄

green shoal
#

I just noticed that half my interface is in english and the other half is in portuguese 😄

zealous coral
#

If it is not a problem for ur team, then it's not a problem xD

green shoal
#

its the easiest thing I had to fix today, so I'm quite ok with that

random flume
#

@zealous coral so I dragged my gameobject to my object field

#

Now how can I access the script attached to it and get the float variable

#

Or wait

#

Can I do like CustomEditor(typeof(MyScript));

zealous coral
#

U can use serializedObject.FindProperty

#

Oh wait, r u trying to make a 'detect object field changed, and then change float variable value' ?

random flume
#

No get the float value from the script attached to my object field gameobject

visual stag
#

You can use Editor.CreateCachedEditor to create editors for other objects

jade lance
#

a script I'm using was using "var size = EditorPrefs.GetInt("TerrainBrushSize");" to get the size of the terrain painter before, but now it only returns 0 with the new terrain brush system. is there any way to get brush size now?

quiet urchin
#

@jade lance is this with or without the terrain tool package?

jade lance
#

@quiet urchin without tool package, on 2018.3.0f2

zealous coral
#

@jade lance hey there, i did some digging and i found these
https://github.com/Unity-Technologies/UnityCsReference/blob/master/Modules/TerrainEditor/PaintTools/StampTool.cs
https://github.com/Unity-Technologies/UnityCsReference/blob/master/Modules/TerrainEditor/PaintTools/TerrainPaintTool.cs

it seems like there is some sort of 'brushsize' value available in this two virtual function inherited from TerrainPaintTool

public virtual bool OnPaint(Terrain terrain, IOnPaint editContext);
public virtual void OnSceneGUI(Terrain terrain, IOnSceneGUI editContext);

the brushSize value exists in IOnPaint and IOnSceneGUI
to have a better look at it in visual studio, u can just type UnityEditor.Experimental.TerrainAPI.StampTool in any of ur editor script, and go to its declaration
i am not sure how ur tool work/worked because i dont use terrain tool, that's all i got, hope it will aid u in solving ur problem

jade lance
#

thank you very much @zealous coral , may take me a bit to figure it out but that looks like the right direction

hoary surge
#

I'm sure this has been asked before, but is there anyway to resolve draw order problems with multiple unity OnDrawGizmos() calls happening? I see a ton of z-fighting which invalidates the visuals I'm trying to do.

onyx harness
#

@hoary surge I almost never use OnDrawGizmos, but if I had to handle order calls, I would use a manager

#

Like your script is un/registering to the manager using a priority, and you draw once from the manager

subtle path
#

Hello folks. Does Unity have a Gizmo/Handle for what's used to edit BoxColliders? I want to make my own BoxCollider and editor.

subtle path
#

I'm not able to draw two Handles. What am I doing wrong?

[CustomEditor(typeof(BoundingBox)), CanEditMultipleObjects]
public class BoundingBoxEditor : Editor
{
    BoundingBox BoundingBox;

    void OnSceneGUI()
    {
        BoundingBox = (BoundingBox)target;

        Vector3 bottomLeft = BoundingBox.transform.position + new Vector3(BoundingBox.X, BoundingBox.Y);
        Vector3 newBottomLeft = Handles.Slider2D(0, bottomLeft, Vector3.forward, Vector3.up, Vector3.right, 1, Handles.CubeHandleCap, new Vector2(1, 1));

        Vector3 topRight = BoundingBox.transform.position + new Vector3(BoundingBox.X + BoundingBox.Width, BoundingBox.Y + BoundingBox.Height);
        Vector3 newTopRight = Handles.Slider2D(1, topRight, Vector3.forward, Vector3.up, Vector3.right, 1, Handles.CubeHandleCap, new Vector2(1, 1));

        Debug.Log($"bottom left: {newBottomLeft}");
        Debug.Log($"top right: {newTopRight}");

       
    }
}
#

Only the first one gets drawn. When I comment out the first call, the second handle still doesn't get drawn.

subtle path
#

Okay. Something fixed this problem.

#

Is there a way to draw a filled RectangleHandleCap?

zealous coral
#

maybe u can use DotHandleCap and change Handles.Color before the line drawing the handle

#

or u could make 2 handles call at the same time , one using RectangleHandleCap, and another using DotHandleCap

float size = HandleUtility.GetHandleSize(something.SomePos) * 0.5f;

        EditorGUI.BeginChangeCheck();
        var oriColor = Handles.color;
        Handles.color = new Color(1, 0, 0, 0.5f);
        Handles.Slider2D(something.SomePos, Vector3.forward, Vector3.up, Vector3.right, size, Handles.DotHandleCap, 1f, true);

        Handles.color = oriColor;
        var newPos = Handles.Slider2D(something.SomePos, Vector3.forward, Vector3.up, Vector3.right, size, Handles.RectangleHandleCap, 1f, true);
        if (EditorGUI.EndChangeCheck())
        {
            Undo.RecordObject(something, "Change Look At Target Position");
            something.SomePos = newPos;
        }
#

in this example, the line using DotHandleCap serves more as a "draw a filled area", while the one using RectangleHandleCap is the one actually functioning as a handle

subtle path
#

DotHandleCap is exactly what I was looking for. Thank you ❤

#

I just got into editor scripting, and my life has been a waste before this.

zealous coral
#

i just realized it will ALWAYS face toward to "camera" though, unlike RectangleHandleCap 😅

subtle path
#

I am making a 2d game, this is what I want.

zealous coral
#

i first got into editor scripting a few years ago, i improved over time SLOWLY

#

right now i am still learning, we dont use everything available to us afterall 😃

subtle path
#

This completely changes the workflow for me. Before this, I would rely on Unity's components. Now I can make my own. For instance, I'm making my own box collider and my own platformer physics, but still taking advantage of the GUI.

zealous coral
#

yeah, making customized tool helps ALOT

waxen sandal
wicked hornet
#

Why can't I do this? Stripe.Text = "Striped Balls Scored: %s", m_StripedBallsScored;

#

I know I could use "" + (string) but strings are immutable so that would take up more memory

stark geyser
#

use StringBuilder to not generate garbage

wicked hornet
#

Sounds good, will do!

zealous coral
#

@waxen sandal thanks ! that's very nice !
this makes me wonder, why isn't this class grouped together under Handles ?

heavy swift
#

Is it possible to make a custom transform inspector when there is a certain component in the gameobject?

cloud wedge
#
    [PostProcessBuild]
    public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
#

where does that second argument get set?

#

i want to change it

zealous coral
#

that's most likely the location u choose to "Build" ur project ?

#

u know, when u go to Build Settings > Build, u are being prompted to choose a location

cloud wedge
#

i think you're right

#

how do I change it though?

#

oh the build button does that

#

that's not very obvious to me

zealous coral
#

i believe it's some sort of prefs value that is being set automatically whenever we do a build 😅

#

anyway, [PostProcessBuild] marks the function to be called automatically whenever we make a build, so it definitely is gonna be whatever location we just chose to make a build
maybe there isn't even any value saved anywhere in our computer

zealous coral
#

@waxen sandal i tried the BoxBoundsHandle, is it proper to use if(GUI.changed) to get the latest value of the handle ?
i did that because i dont see the DrawHandle function returns any value, unlike functions in Handles

visual stag
#

Looking at the ArcHandle they use a changed check block. I'd use a ChangeCheckScope over manually checking GUI.changed in all instances though

zealous coral
#

cool ! that's much better, thanks vertx !

frail phoenix
#

Are there any good examples of UIElements anywhere?

frail phoenix
#

I found the shader graph git repo

#

it's quite complicated

zealous coral
#

Shader graph is most likely not a good starting point 😅

frail phoenix
#

it's like the only thing made in UI Elements

zealous coral
#

I did some experiment on it but it's not available online. Maybe u can look for some unity video on it, iirc there's some

frail phoenix
#

there's like two of them

#

I've watched them over and over

zealous coral
#

Just to learn the basic 😂

visual stag
#

The EditorWindow and PropertyDrawer documentation pages have examples too

frail phoenix
#

are those made in UI elements?

#

I thought they were UGUI

visual stag
#

They can be either, as of 2019 the docs have shifted to UIElements

frail phoenix
#

ohhh.. docs!

zealous coral
#

oh wow, i totally didn't know that !
thanks alot vertx !
learning time

#

oh, my, god
u are telling me we dont have to deal with Rect in PropertyDrawer anymore ?!

visual stag
#

Yup

frail phoenix
#

Thanks vertx

zealous coral
#

did i do anything wrong ? i am getting No GUI Implemented in both Inspector and EditorWindow

zealous coral
visual stag
#
• UI Elements: Colors for the top/left/right/bottom borders can now be assigned different colors.
• UI Elements: Extended Image class and background-image property to support SVG image assets```
Some nice things coming down the pipe (just released in 2019.3.0a8)
lucid hedge
#

Asset store packages are nice

onyx harness
#

OH

waxen sandal
#

Exciting stuff

valid sonnet
#

svg image assets are nice too!

fresh yoke
lucid hedge
#

this looks guuud

onyx harness
#

I need to test that... 😵

fresh yoke
#

it's not good :/

#

I mean, it's better than the asset store ui which is bloody slow

#

but I was hoping they'd actually move asset store assets into new upm packge setup

#

this is still the old import into your assets folder crap

#

at least this is WAY faster to use than the asset store

#

downloading and updating the cached unitypackage is now a lot faster operation

#

but I really wanted to get similar packages as with Package Manager normally uses

#

as they are awesome and don't bloat the Assets folder

#

this doesn't solve that at all :/

#

they also reuse Package Manager icons so that same icon has totally different meaning here

#

that is super bad UX

#

you should never do that

#

when you use the "My Assets" view on PM, you see the checkbox if you've downloaded the asset on local machine cache (that hidden asset store folder), I repeat, the checkbox doesn't mean the package is installed on your actual project at all, like with regular packages on the same tool

#

it just means it's ready to "import"

lucid hedge
#

oh wow that's weird that it comes into the Assets folder

onyx harness
#

It will happen guys, this is just an alpha * crossed fingers *

visual stag
#

It's pretty awful to combine non package stuff with packaged stuff unless is extremely well bookmarked in my mind

#

I don't really want to see any non-package assets when I open the PM

fresh yoke
#

I'm now pretty afraid that this was what they were planning all along 😄

#

I hope it's just some intermediate phase, or backup plan for older assets and that new assets will work like in regular PM

#

because then I'd be totally fine with this setup

onyx harness
#

First it will ask all publishers to convert their assets to packages.
Yeah they definitely need some transition X)

visual stag
#

I can't imagine everything is package manager relevant. Code-based assets, yes

#

But otherwise, you'd think there'd be no need for change? Does anyone know differently?

#

I know there's that example deployment feature

#

Perhaps (3D) assets would just work fine in packages. Seems odd though!

fresh yoke
#

you can use sounds, meshes and textures in packages just fine

#

it's just a container

#

only thing you can't use directly from these packages are scene files

#

I think it's because these packages need to be read-only

#

but the workaround for that is to copy the files to the Assets folder then for these, like if you've seen some Unity's packages with samples buttons on PM, this is what they do

lucid hedge
#

When you go into the packages folder in windows file explorer, you can just add files there

fresh yoke
#

2019.3 PM also has option for your to create your own packages now

#

it's under that +

lucid hedge
#

there is the 'develop' button right

#

to make a local copy of the package

#

copy in your assets folder I mena

#

mean

fresh yoke
#

oh, that's new as well

onyx harness
#

Lol, just installed U2019.2.0b7, double clicked on any folder in Assets, get exceptions... XD

fresh yoke
#

but I meant the "create package" option from + -menu

#

@onyx harness this is in a8 😃

#

2019.3 that is

#

but yeah, PM is bit error prone

#

I love the concept tho

plucky inlet
#

well I don't think it makes sense for asset store packages to be downloaded per project so the central location for them will stay

#

probably

#

and they certainly need to be handled differently from 'normal' packages due to being imported from .unitypackage (and decrypted first but that's not that relevant here)

frail phoenix
#

@fresh yoke There are so many assets in the asset store that are so low quality that you need to access their source code and fix it in order to use them. If the assets downloaded outside of the assets folder that would just be so much harder

fresh yoke
#

oh, it definitely can't be automated easily, at least reliably

#

but if you maintain asset actively, moving it to package manager format is not that hard task

#

I've done this myself for like dozen 3rd party assets myself

frail phoenix
#

I just think there have been a lot of assets on the asset store that started out from someone that knew how to solve a problem well but then when they realized the cost/benefit ratio they pretty much abandoned the asset. Those same people would be highly inclined to obscure the code as a form of DRM, and would jump on anything that made that more possible. So I think that for a lot of assets allowing people to obscure them more would lead to a less functional asset store in general.

umbral sparrow
#

is there a way to enforce that a particular field has a unique value for each object of that type in the scene? i.e. i have a name field, and i want every object with that script on it to have a unique name

#

maybe an attribute? can't find anything like that in the docs, and i'd hate to re-invent the wheel if there's a good solution out there

onyx harness
#

It's like an ID, create it, register it.
Whenever you create, you check the name and set it something unique

random flume
#

Anyone knows how to create an animator window inside my editor window?

waxen sandal
#

That's not very easy, you can try using CreateEditor on the animator but I'm not sure that'll work

random flume
#

Ah

zealous coral
#

novabot are u trying to "extend the animator window" ?

onyx harness
#

An Editor is the drawer of a Component.
A PropertyDrawer is the drawer of a Type.

You need to use an EditorWindow to draw an... EditorWindow.
But I don't expect it to be easily feasible.

#

You look at the source code of the Animator window

random flume
#

I decided to just not do that lol

zealous coral
#

good choice, it's complicated

limber cairn
#

i dont have a script editor whats a good one 😦

visual stag
#

But your options are basically VS Community

#

VS Code

#

or Rider, which is paid (it has some discounts depending on your circumstances)

limber cairn
#

ok and sorry

dim walrus
#

Anybody knows how to draw an editor like if Inspector is in debug mode?

#

Like Editor.DrawDefaultInspector() but for debug mode

onyx harness
#

@dim walrus i never tried, but you could right before drawing, set the Inspector in Debug mode and restore the state after. That could be a way

tough fjord
#

so i was looking at a tutorial and noticed that the guy in it got these little definition bubbles while im not, anyone know how to get these

kind carbon
#

In visual studio I believe if you hover over something it pops up

#

with default settings ofc

tough fjord
#

Didn't work for me

kind carbon
#

are you using monocode or visual studio?

tough fjord
#

@kind carbon visual studios

kind carbon
#

does anything pop up if you hover over a line? even if it says "class System.string"

tough fjord
#

Nope only time somthing pops up it just brings up the auto complete list when typeing part of the word

kind carbon
#

Very weird, I'm honestly not sure then

stark geyser
#

You want to make sure that Unity plugin working properly. You can try reinstalling it. Also deleting and letting Unity regenerate VS solution and projects files if that doesn't help, they may have corrupt references.

tough fjord
#

@kind carbon so I think I figured out out, while we were talking I was downloading a bunch of those extensions that it asks if you want to download when you first get MVS which I didn't do at first, now that they are downloaded it's working

kind carbon
#

@tough fjord late response but ya that should fix it, there should be an option for "Game development with Unity" down below

tough fjord
#

so i just downloaded a bunch of tools and features and extensions because i figured the more the merrier and now im getting a bunch of errors i wasnt getting before especially ambiguity errors, anyone know how to fix that
the ambiguity errors dont seem to be a problem but its annoying to see a bunch of red squiggly lines everywhere
wondering what the hell i downloaded to make visual studio freak out over ambiguity

#

i would rather not have to put a underscore with every variable to stop getting ambiguity errors

tough fjord
#

oh god im a fool as well as unity is a jerk, turns out that for some reason somehow two versions of the same file were made

#

but now i guess i know how to deal with ambiguity errors

onyx harness
#

Ambiguity errors dont seem to be a problem? Really?

#

Ambiguity is simple, it means the compiler can't tell if it should use one over another

tough fjord
#

well unity wasnt telling me they were an issue just MVS

#

but at least i figured out the issue

#

and now intelisense is actually doing its job, kept watching tutorials where they were getting these detailed autocomplete options where i wasnt, now im getting them

wary raptor
#

Super silly basic question but I somehow can't find the google results to tell me the solution.
Looking to use a script from a forum (see: https://forum.unity.com/threads/replace-game-object-with-prefab.24311/ )
Only don't quite know how to "run" the script from within Unity. Only ever added scripts as components to GameObjects. Can you run a script that makes editor changes like new windows from somewhere?

#

Or am I supposed to just make an empty GameObject with the script as a component and play once? 🤔

visual stag
#

you could make an Editor Window and put some UI in it (buttons, etc)

#

You can run code with an InitializeOnLoad attribute (and you could register some callbacks from there)

#

There's lots of methods for running code from the editor without having a component

#

You can see people have used MenuItem further down the thread

wary raptor
#

The script I want to use is using MenuItem I see

visual stag
#

They are using it to open their editor window though, but that's one of the concepts 😃

wary raptor
#

Yep. But it's supposed to add a new menu item in the "Window" menu yet I don't see it.
Is that because it does that on Unity startup or because I simply copy/pasted the .cs and .meta file of the script in my project folder?

#

Sorry for the stupid questions, haven't used Unity much >.<

visual stag
#

You want the script underneath a folder called Editor, but that's all you should need

#

if it compiles, it should show up

wary raptor
#

Ah I placed it somewhere else

visual stag
#

I don't think not doing that will cause it not to work though, it just means you wouldn't be able to build later

#

(because you would have editor code in your runtime assembly)

#

The MenuItems seem to be creating a new menu called Tools though

wary raptor
#

I thought the issue was that I have the code but was more or less looking for the "compile" button to launch it

visual stag
#

unless you've copied another one

#

Unity automatically compiles

wary raptor
#

I probably copied another one. But there's a LOT of versions on that thread.

#

Oooh didn't know

visual stag
#

You want one of the latest ones

#

Because there's been a lot of changes to the prefab APIs

wary raptor
#

Although... I do remember it giving me errors immediately after I changed something one time so that makes sense.

visual stag
#

If there's errors then you'd have to solve them before anything would show up

wary raptor
#

No errors on this one though and it's one of the most recent versions. Think I'll (hopefully) manage now.

#

Also, forgot to mention and unsure how much changed between versions but my project uses 5.4.5 and I don't see an "Editor" folder in the project itself so... maybe a lot changed? ^_^;

#

Oh! Found it under Tools after restarting.

#

Thanks for the help vertx 🙏

visual stag
#

You have to create your own folder called Editor anywhere in the project and put your editor code under it (if you want your builds to work :P)

#

There's an exception to that with Assembly Definitions, but most people don't use them

wary raptor
#

I felt like there was a 50% chance creating your own folder would break things and it was supposed to be auto-generated

visual stag
#

Oh your project uses 5.4.5? Ancient times 😛

wary raptor
#

Yeah, it's a project from yore. Ye olden days.

chrome reef
#

Hey guys

#

I've recently downloaded unity for my linux machine

#

(the offically supported version that's available for ubuntu)

#

and unfortunetaly, whenever I boot up the editor, this is what it looks like :

#

my computer screen is not very big and the text is incredibly small/borderline unreadable

#

I was wondering if there was any setting I could tweak to make the text look bigger or perhaps an editor extension that could do that

#

I've really enjoyed unity while using windows and it would kinda pain me not being able to use it just because of my OS

simple urchin
#

Try changing your screen resolution

chrome reef
#

I've already tried it unfortunetaly, but the thing is, all applications are displayed fine with the exception of unity

#

Plus as you can see the application header has a reasonnable font size

simple urchin
chrome reef
#

I think what you posted has more to do with the ui of the game you make while I'm struggling with the editor of the unity application itself... 😥

simple urchin
#

Oh

#

@visual stag

#

Maybe you can help him

visual stag
#

Please don't tag me. If I can or want to help, I will

simple urchin
#

@stark geyser

#

Sorry

chrome reef
#

Oof

lucid hedge
#

So I sometimes use built in styles

#

public readonly GUIStyle m_LODSliderRangeSelected = (GUIStyle) "LODSliderRangeSelected";

#

like this one 'LODSliderRangeSelected'

#

is there a way for me to see where this style is defined and what it looks like?

lucid hedge
#

Also I do have an issue

#

in the inspector I draw a material editor

#

with this code

#

but when I try the same in an editor window

#

the expanded section just gets drawn above the header

#

instead of nicely below it

#

how should I avoid this?

onyx harness
#

@lucid hedge you can Google Unity editor styles viewer

#

How a DrawHeader can be drawn after the InspectorGUI... I need to see your code

#

To see how a style looks like, just draw it manually

wary raptor
#

I have a question. I am using a script to replace gameObjects with a predefined Prefab.
I only tried to add a line that would take the tranforms (translation specifically) of the "mesh" component of the gameobject.
But somehow this breaks the script. Does my code have some implicit meaning I'm not seeing?

newObject.transform.localRotation = go.transform.localRotation;
newObject.transform.localScale = go.transform.localScale;
 //newObject.transform.localPosition = go.transform.localPosition; <---- THIS WORKS FINE BUT I WANT THE MESH TRANSFORMS INSTEAD OF GAMEOBJECT
newObject.transform.localPosition = go.GetComponent(typeof(Mesh)).transform.localPosition; // <---- THIS BREAKS THE WINDOW UI AND HAS WEIRD BEHAVIOUR
}```
#

I don't think GetComponent would create a new object

visual stag
#

There is no different transform for the mesh component

#

They are the same transform

#

Also, Mesh isn't a component

#

You should generally use the generic version of GetComponent too, e.g. GetComponent<MeshFilter>()

wary raptor
#

Hmmm. Maybe I'm not using the right terms then.
The transforms in the "Imported Object" settings that you can't directly edit because it's based on your import settings. The transforms of this "Mesh" variable within the GameObject (that has 0,0,0 as translation).

#

I did do that at first actually.

visual stag
#

There is no transform in the mesh asset, only coordinates

wary raptor
#

This was how I tried it at first and I think it worked but it also broke the window and would keep creating new prefabs to replace the gameobject with.

visual stag
#

Add I said, Mesh isn't a Component

#

It'd return null and you get an NRE

wary raptor
#

Then I'm not sure what these transforms belong to. This is all in the "model" tab of my import settings. How would I acess that if not through Mesh?

#

(sorry for badly painted out object name =p)

visual stag
#

That is the imported object, which is the model prefab that is the origin of the imported model. Changed in the model itself via a modelling package or you can use the ModelImporter's settings to modify some things like scale

#

That transform isn't any different to the one that is used in the instanced version, they are the same logical object

#

(Different instances though)

wary raptor
#

Mmmm I understand it being the imported model from the 3D package's transforms.
But when you make an instance of it in the scene by drag/dropping and give it 0,0,0 as transforms in the scene when the imported object transforms were for example -50,0,0 you'll still see the object at -50,0,0 in the scene in the end.
Because the instance in the scene is a parent to this one, right?

#

Since I'm trying to replace a large amount of assets that were exported with non-0,0,0 transforms from the 3D package and turn them into separate prefabs at 0,0,0 (the good way to build up a scene rather than one huge prefab) I need to be able to give the new smaller prefabs within the scene the transforms of the gameobjects that were exported from the 3D-package which I believe are in mesh.

#

Hooooping this is kinda making sense. If not, I still appreciate the valiant attempt at making me understand Unity >~>

crystal raven
#

The prefabs transform should be the same as is in the 3d package

#

If I understand your problem correctly, you should be able to write an editor script that sets the transforms to zero if they are not a child of another object

wary raptor
#

Don't think that's quite it.
Issue is if I have my model prefab in the scene at a specific transform position and I create a cube with that same position they are not actually in the same spot. Which I believe is because the model was originally exported in a position different than 0,0,0 in the 3D package.
So there's an extra offset. But I'd need my cube to also get that extra offset somehow.

#

At least that's what my tests have pointed towards.

lucid hedge
#

@onyx harness

#

this is my OnGUI code in my editor window script

onyx harness
#

@lucid hedge comment one, test, comment the other one, test.

#

Uncomment both and add DrawHeader() again after OnInspectorGUI().
Test.

lucid hedge
#

this is DrawHeader without inspector, the arrow to expand does nothing here as expected, when I draw the inspector alone without header, nothing is shown. When I draw both, the header gets drawn as in the screenshot but when I click the arrow, the inspector gets drawn at the beginning of the editor window (the top) and disregards the other UI elements that are drawn already.

#

and this

#

results in this

#

and when I expand with the arrow, this happens again

#

it's like when I call OnInspectorGUI, all the rest gets ignored

#

and it's weird because when I do the same in a custom inspector, I am able to draw several elements first, then draw the header+editor

#

fixed!

#

simply wrapping it in begin/end vertical fixed it, draws nicely now

onyx harness
#

@lucid hedge wth...xD
Good job

lucid hedge
#

super happy that it works lol

#

Is all of this stuff different with UI Elements

#

?

#

for this new project I'm going to switch to UI Elements soon I think

onyx harness
#

I am wondering if it is due to UI Element

lucid hedge
#

I just want to prototype some stuff first before I move

rocky thunder
#

I created a custom Unity package that I share between multiple projects. When I have two of those projects opened at the same time in two different Unity Editors, simply switching between the two triggers a script reload/recompile. Any idea why?

onyx harness
#

Check the logs

rocky thunder
#

Unfortunately, logs are not helping me figure out what triggers the reload/recompile

onyx harness
#

@rocky thunder Recompilation always outputs the reasons behind.

rose mirage
#

How can I display multiple ReorderableList in the same UI while not having copy of the last on ine the next one ?

#

I tried trick with Dictionary and propertyPath, but either I am doing it wrong or that don't work

onyx harness
#

@rose mirage show us some code, your question is not clear enough

rose mirage
#

that is the point of this problem - it is not clear 😄

#

but it seems Dictionary trick did work

#

that is - for multiple ReorderableList to work properly in the same UI I needed to store them in a dictionary while using propertyPath as a key for the object I displayed in ReorderableList .

#

Confusing part was, that when I created new list to display it was already populated with data from pervious list (visually), taht was not there, but if I cleared that new list right after creation it was working fine and there was no extra data in it

onyx harness
#

What means multiple ReorderableList in the same UI?

rocky thunder
#

@onyx harness Here is what I get when switching from one editor to the other. My custom package is the one I obfuscated to XXXXXX in the following log.

Refresh: detecting if any assets need to be imported or removed ...
Refresh: elapses 0.526958 seconds

Hashing assets (204 files)... 0.042 seconds
  file read: 0.007 seconds (2.588 MB)
  wait for write: 0.000 seconds (I/O thread blocked by consumer, aka CPU bound)
  wait for read: 0.000 seconds (CPUT thread waiting for I/O thread, aka disk bound)
  hash: 0.004 seconds
Connect to CacheServer localhost:56591
- Starting compile Library/ScriptAssemblies/XXXXXX.Framework.Runtime.dll
- Starting compile Library/ScriptAssemblies/Unity.TextMeshPro.dll
- Starting compile Library/ScriptAssemblies/Unity.Notifications.Android.dll
- Starting compile Library/ScriptAssemblies/Unity.Notifications.iOS.dll
- Starting compile Library/ScriptAssemblies/Unity.PackageManagerUI.Editor.dll
- Starting compile Library/ScriptAssemblies/Unity.AssetBundleBrowser.Editor.dll
- Starting compile Library/ScriptAssemblies/UnityEditor.StandardEvents.dll
onyx harness
#

What happens if you disable the cache server?

rocky thunder
#

Same behavior, but I haven't look at the logs when disabled. I'll redo the test and post the logs here.

onyx harness
#

Even obfuscated, a DLL should not trigger a recompilation every time you alt-tab to the Editor

rocky thunder
#

Oh I just modified the log I posted so the name is not in there 😃

#
Refresh: detecting if any assets need to be imported or removed ...
Refresh: elapses 0.495455 seconds

Hashing assets (204 files)... 0.041 seconds
  file read: 0.006 seconds (2.588 MB)
  wait for write: 0.000 seconds (I/O thread blocked by consumer, aka CPU bound)
  wait for read: 0.000 seconds (CPUT thread waiting for I/O thread, aka disk bound)
  hash: 0.004 seconds
- Starting compile Library/ScriptAssemblies/XXXXXXXXX.Framework.Runtime.dll
- Starting compile Library/ScriptAssemblies/Unity.TextMeshPro.dll
- Starting compile Library/ScriptAssemblies/Unity.Notifications.Android.dll
- Starting compile Library/ScriptAssemblies/Unity.Notifications.iOS.dll
- Starting compile Library/ScriptAssemblies/Unity.PackageManagerUI.Editor.dll
- Starting compile Library/ScriptAssemblies/Unity.AssetBundleBrowser.Editor.dll
- Starting compile Library/ScriptAssemblies/UnityEditor.StandardEvents.dll
#

That's when cache server is disabled

lucid hedge
#

I have a ScriptableObject that stores a list of objects like this

#

public List<CycleSection> sections = new List<CycleSection>();

#

Right now CycleSection is just a regular class but I'm having some issues with references etc seemingly dissapearing when I press play

#

So I thought about turning the CycleSection into a ScriptableObject as well

#

but I don't want the CycleSection to appear as an asset in the project folder

#

what are my options here?

#

can I just serialize a class?

onyx harness
#

Just fix your bug. X)

#

You said it is a regular class, but is it serializable?

lucid hedge
#

it was not ...

#

I fixed that and now the references are showing up nicely in my scriptableobject inspector as well

#

that should do it

#

thank you!

lucid hedge
#

I do have another question

#

are Materials serializable?

#

because right now I am creating new Materials in a script and I'd like to store them in a ScriptableObject, but based on the errors I'm getting (Type Mismatch) I think (?) that if I create a Material that gets stored in a ScriptableObject, that Material has to exist as an asset in the project folder?

onyx harness
#

Possibly

#

You don't exactly store à Material in a SO (even if it is technically possible), I think you want to store a reference to it.

lucid hedge
#

but if the SO stores a reference, where do the materials live?

onyx harness
#

Nowhere if you didn't save it in the project

lucid hedge
#

because in theory I'd like to maybe send the SO to another person to use in his project, and he would have all the materials there

#

I see

#

then I'm going to create some materials 😃

onyx harness
#

He will have a SO full of missing references

lucid hedge
#

and you say you could technically store a material in a SO by storing all the material properties, their names + values

#

and then build the material from those values when you need it

#

right?

onyx harness
#

If you want to keep everything in one asset you need to use AssetDatabase.AddObjectToAsset()

#

You don't store the content of the Material, you save the whole Material asset embedded in your SO

lucid hedge
#

Alright I'll test out some thigns

#

things

#

thank you again

barren wadi
#

I have a small script called 'EnumVariableTest' that has a view variables so that I could test out inspectorGUIDrawing. It's set up so that it only shows certain variables depending on an enum. If EnumVariable is a monobehaviour, it works. But if I remove the monobehaviour inheritance and make turn it into a normal class with [System.Serializeable] then it just shows all variables, no matter what the enum is. Here's the editor script I use to draw everything:

#
public class TestPropertyEditor : Editor
{
    public SerializedProperty
       state_Prop,
       valForAB_Prop,
       valForA_Prop,
       valForC_Prop,
       controllable_Prop;

    void OnEnable()
    {
        // Setup the SerializedProperties
        state_Prop = serializedObject.FindProperty("state");
        valForAB_Prop = serializedObject.FindProperty("valForAB");
        valForA_Prop = serializedObject.FindProperty("valForA");
        valForC_Prop = serializedObject.FindProperty("valForC");
        controllable_Prop = serializedObject.FindProperty("controllable");
    }

    public override void OnInspectorGUI()
    {
        serializedObject.Update();

        EditorGUILayout.PropertyField(state_Prop);

        EnumVariableTest.Status st = (EnumVariableTest.Status)state_Prop.enumValueIndex;

        switch (st)
        {
            case EnumVariableTest.Status.A:
                EditorGUILayout.PropertyField(controllable_Prop, new GUIContent("controllable"));
                EditorGUILayout.IntSlider(valForA_Prop, 0, 10, new GUIContent("valForA"));
                EditorGUILayout.IntSlider(valForAB_Prop, 0, 100, new GUIContent("valForAB"));
                break;

            case EnumVariableTest.Status.B:
                EditorGUILayout.PropertyField(controllable_Prop, new GUIContent("controllable"));
                EditorGUILayout.IntSlider(valForAB_Prop, 0, 100, new GUIContent("valForAB"));
                break;

            case EnumVariableTest.Status.C:
                EditorGUILayout.PropertyField(controllable_Prop, new GUIContent("controllable"));
                EditorGUILayout.IntSlider(valForC_Prop, 0, 100, new GUIContent("valForC"));
                break;

        }


        serializedObject.ApplyModifiedProperties();
      //  serializedObject.
    }
}```
#

and here's my EnumVariableTest script:

public class EnumVariableTest
{
    public enum Status { A, B, C };

    public Status state;

    public int valForAB;

    public int valForA;
    public int valForC;

    public bool controllable;
}```
visual stag
#

If it's a plain serializable class you need to make a property drawer, not a custom editor

barren wadi
#

How should I go about doing that?

visual stag
#

Google "Unity Property Drawer" and look at the results

fleet summit
#

it's possible to hide title bar and menu bar from unity editor on windows?

hoary surge
#

Are there any sort of general standards for editor only monobehaviors with [ExecuteInEditMode] on them to live? Seems a shame to package them up with the final game distributable

visual stag
#

@fleet summit no, but it may get better in the future apparently

onyx harness
#

@visual stag oh, how come? Where did you read that?

visual stag
#

One of the things that's been mentioned during the editor UI refresh conversations

simple urchin
#

@shadow violet Hi bruh, I know what you are trying to say, but actually the assets that are not loadable and after an hour of two of load, it says that the asset got errors, And those tutorials that are pinned on this channel themselves use those assets, so obviously I need to download them to understand things step by step perfectly.

fleet summit
shadow violet
#

@simple urchin Uhh, could you remind me what your referring to? Assets for what? What assets aren't loading? And where are you pulling them from?

whole steppe
#

someone that could help me with edys vehicly physcihs please? I am prepared to revenue share and have a place in the credits

DM me asap

lucid hedge
#

@whole steppe why not contact the creator?

whole steppe
#

He wont answer today

simple flax
#

anyone know why this is creating an infinite loop?

#

there's pretty much a guarantee that the rendere exists, right?

#

unless mesh renerer is a different thing?

candid cipher
#

@simple flax You're checking gameObject every time, not the passed in parent parameter

#

so the object you're checking is never actually changing

proper dawn
#

He's accessing the gameobject from the child of the current gameobject though, which would make the variable passed to the method change to the child's gameobject though, no..? @candid cipher

#

Not sure what you're trying to achieve exactly, but wouldn't a gameObject.GetComponentInChildren<Renderer>() work for you? @simple flax

candid cipher
#

That would be the case if he were using parent at all, but he's not - so whatever child he's passing into Find_Children_Renderers isn't being used, and the only object checked is the same base parent

proper dawn
#

OH LOL

candid cipher
#

if (!parent.gameObject.GetComponent<Renderer>())
Should fix the whole block

proper dawn
#

I just noticed what you meant 😂

#

Yeah that makes a lot of sense lmfao, he's using gameObject.GetComponent instead of parent.GetComponent hahah

candid cipher
#

Yeah, easy mistake to miss when double checking code back!

proper dawn
#

But yea, I'm pretty sure gameObject.GetComponentInChildren<Renderer>() does exactly what he's programming there starletLul

#

Unless he really really just wants to check for the first child, and not support multiple children

candid cipher
#

Yeah, it'd do the job better than what they're doing at the moment, since it's only ever going to check the first linear hierarchy down and no siblings

proper dawn
#

I'm wondering btw if it's an okay thing to post the question posted on the forum here in the Discord instead. Since this might be way more active / easier to respond to by the community dernerThink

candid cipher
#

I don't believe there's any issue with posting forum questions for additional eyes

#

May want to double check with a community mod thoguh

#

May want to double check with a community mod thoguh

#

May want to double check with a community mod thoguh

proper dawn
#

<@&502884371011731486> , do you by any chance have time to answer my question right above Joeb's last messages? Also, it's okay to tag community moderators like that for questions right? Or should I send a pm instead the next time? dernerThink

#

<@&502884371011731486> , do you by any chance have time to answer my question right above Joeb's last messages? Also, it's okay to tag community moderators like that for questions right? Or should I send a pm instead the next time? dernerThink

stark geyser
#

@proper dawn It's not ok to tag anyone out of the conversation or send unsolicited DMs. If someone can or has the time to answer your question, they will. Otherwise have some some patience.

proper dawn
#

I meant whether it was okay to tag you to ask about whether it was okay to post something in the Discord which was already posted on the official Unity forums. To get those types of discord rule questions answered 😄 @stark geyser

stark geyser
#

Don't tag anyone, just post a link to the forum with short description.

proper dawn
#

God I suck at explaining starletW

#

But the " just post a link to the forum with short description" answered my initial question, thank you!

candid cipher
#

@stark geyser Their question was whether or not you (community moderators) were the people to tag to clarify rules - in this case, whether or not posting forum questions to the channels here is allowed or not.

#

Their DM question was an extension of that, whether they should instead DM you to ask such questions, or if tagging you in the channel is fine.

stark geyser
#

Sure, if you have any Discord related question, tag an active moderator in the general channel.

proper dawn
#

Hahah thank you for clarifying @candid cipher , and thank you for answering 😄 @stark geyser 😄

#

So... Does anyone here have an idea of how I can solve my issue described here on the forum post?
I also don't know if it's an actual bug or not, it feels like it is, but maybe it's all done intentional for whatever reason. So maybe I should create a bug report instead? Maybe some people here can give me some insight / tips.

https://forum.unity.com/threads/scriptableobject-gets-destroyed-in-editor-when-created-in-onenable-from-another.708983/

stark geyser
#

@proper dawn CreateInstance is used to create Scriptable Object memory instance for the scene objects. I don't think you can reference it in the asset. You need to create asset for it to work like that.

proper dawn
#

But in my code, I specifically need a new instance from the scriptable object. So if I were to have, lets say. 10 variables like that in my script. For every instance of my container I'd create, I would have to create 10 assets in my assets folder which aren't useful there at all, which I would also have to manually create, delete, and assign? starletDerp That defeats the entire purpose of what I'm trying to do starletFBM

stark geyser
#

You can turn Container script into a MonoBehaviour instance then it will work just fine.

proper dawn
#

My container script needs to be a scriptableObject. It needs to exist in the assets folder starletDerp

stark geyser
#

Make Child class pure data then. Why do you need it to be a Scriptable Object if you don't use its serialization feature.

#

SO only useful as file assets.

proper dawn
#

In my case:
Container = FloatVariable : ScriptableObject
So I can assign that ScriptableObject as a reference in scripts in the scene, and they all point to that same variable.

#

I can't do that when the container isn't a ScriptableObject instance in my Asset folder.

#

Gonna look up the reason(s) why (in my mind currently) the new instance (A game event), must be a ScriptableObject. And why it can't be something else. Maybe that's where my brain died a bit. Will get back to you on that one dernerThink

stark geyser
proper dawn
#

I watched the Unite Austin one, that made me start working on all of this 😄

stark geyser
#

It has a project example with additional stuff in the description

proper dawn
#

Just trying to add more possibilities than what it currently has. Especially in the editor. All the stuff I'm doing works 100% in runtime, just the editor stuff that's a bit an issue 😄

#

So I'm adding to the original project example which is in the description from the Unite Austin video

stark geyser
#

I didn't quite understand your second test at runtime. You can't create assets at runtime.

proper dawn
#

dernerThink What do you mean?

stark geyser
#

You can't create assets because program folder is immutable. Even any changes you do to SO data at runtime will be reset next session.

#

SOs are best used as visual data templates.

#

If you need to construct data from scratch at runtime you are better off using custom classes. You can even serialize them if you want to troubleshoot them in the inspector.

proper dawn
#

I'm not creating assets in my assets folder during runtime. If that's what you were aiming at dernerThink

stark geyser
#

On the forum you were testing asset creation at runtime

proper dawn
#

You mean " _child = CreateInstance<Child>();"?

stark geyser
#

yes

proper dawn
#

These things happen in editor mode, not in runtime, the last message there "press play" is when we enter runtime.

#

Oh.

#

The " _child = CreateInstance<Child>();" is completely valid. Just creates an instance like any other. 100% supported by Unity. It's just not stored in the assets folder, which I'm also not trying to do

stark geyser
#

SO asset can only reference other assets. It seemed like you were expecting it to create assets to hold. Never mind.

proper dawn
#

You're right though about questioning my need of the "Child" to be a scriptable object. It's too late for me now to dive into that, my brain is going all over the place hahah. I think I might've just tried to be consistent while it's actually a different case entirely, making it useless to use a scriptable object. Which would solve all my problems :D
Thank you for thinking along! @stark geyser 😄

#

And good night!

lucid hedge
#

@proper dawn from where is that last screenshot? Seems like it is relevant to some stuff I'm trying to do

lucid hedge
#

nvm got the forum post

proper dawn
#

@stark geyser Looks like I indeed didn't need the actual scriptable object for that specific case. But using the response I got on the forums, I was able to make it work while still using them! Changed it so that it doesn't use scriptable objects right now, but it's nice to know for the future 👍

proper dawn
#

Now I'm trying to figure out why "there are 2-3 instances of my monobehaviour" Only one has the valid event calls, but the others still exist somewhere, hidden.. In the darkness starletPanic

onyx harness
#

Just print a debug in OnEnable

proper dawn
#

OnEnable is only called once starletDerp It's about the constructor's , destructors being called and stuff. Complicated stuff and things starletDerp @onyx harness

stark geyser
#

Debug.Log has object context variant, if you use this in the parameter log will point to your duplicate on the scene when selecting it.

proper dawn
#

Ohhh that's very interesting for sure, thanks for that tip! Can't be used in my destructor though, just because Assertion failed on expression: 'CurrentThreadIsMainThread()' starletDerp

#

This is the kind of stuff I'm dealing with. This happens when I press play.

#

This is with 1 gameobject with 1 SliderSetter component attached to it in my scene

#

I think there's just something that's maybe referencing the SliderSetter somehow, preventing it from being garbage collected or something? I'm not sure, I'm hella confused.

#

This is with a clean project, which is kind of the logs I'd expect.

#

Constructor is called twice there (probably cause of Unity reasons), but the Destructor from one of them is called as well, to clean everything up. So if it'd do the same in my scenario, my stuff should work fine. But nooooo starletLul
Ohhhhh I hate debugging sometimes starletW

onyx harness
#

@proper dawn did you just assume I was a beginner? While you did not understand my answer XD...

proper dawn
#

I think I might've not understood your answer, @onyx harness 😄

onyx harness
#

Fogsight gave you the 2nd part ;)

proper dawn
#

Okay so.. "Print a debug in OnEnable", I added a debug log in there already, but.. How does that help me figure out what's happening exactly? "if you use this in the parameter log will point to your duplicate on the scene when selecting it." --> OnEnable and Awake are only called once. Meaning, it'll only show me a debug log from the object that's active in the scene, while there's still an object somewhere in memory which is printing the [Constructor] debug log message.

#

So basically, the print screen where you see [Awake] SliderSetter created, can be selected when adding the ,this in the debug log call. But it's effectively useless, since I need to know "where the other object is". Which is "invisible".

#

Maybe I'm missing another part of the answer though dernerThink

onyx harness
#

No no, I said that only because you wrote 'but others still exist somewhere, hidden'.
OnEnable is an easy way to locate the assets :)

proper dawn
#

Ohhhh yeah! It would certainly be useful to locate it, but OnEnable isn't called, that's part of the issue starletDerp

onyx harness
#

And also who created it by reading the stack trace

#

Oh crap

#

Do the same in awake (well you did it already)

proper dawn
#

So there is a constructor called for the monobehaviour. Twice, one for the object in the scene, and one for 'some invisible object'. The awake and onenable are called for only the visible object, and not the 'invisible object'. However, since the destructor is not called from the second 'invisible object', it's still alive there.

#

I've managed to reproduce the issue in a new project, with some less code, and it seems like it's one hell of an edge case. starletDerp

onyx harness
#

Can you show me the code of your class?

#

Because... Unity is forbidding us from writing a constructor

proper dawn
onyx harness
#

Unity never sent you warnings? 🤔

proper dawn
proper dawn
#

So. Fun fact about this. If I remove the _someScriptableObject.SomeEvent += SomeMethod; from the OnAfterDeserialize, the Destructor from the 'invisible monobehavior' is called. 👍 But.. I need that event bound.. dernerThink

#

Another fun fact is, I can keep that event there.. However... I need to remove the bound event from the UnityEvent in the Inspector, which is currently set to NewBehaviorScript.enabled.

#

I can also keep a Unity event, but then I can't reference any of the methods from the NewBehaviourScript, binding an event that, for example sets the gameobject name to something random, like this. Will also make the destructor be called. (and so work)

onyx harness
#

Read the answer in the link above

proper dawn
#

Will do!

onyx harness
#

You are not suppose to use the constructor

#

It is as simple that, and I don't think the answer changed between Unity 5 and Unity 2019

proper dawn
#

I'm "not using the constructor", I just "used the constructor to debug my issue"

#

So in the actual use case, I don't have a constructor or destructor in my code.

onyx harness
#

And the issue is 'why is it called many times?' right?

proper dawn
#

I was curious why it was called many times, but that's just the way Unity does things, as explained in the link you posted.

onyx harness
#

Without your debug, you wouldn't see as an issue no? Since it wouln't be output-ed

proper dawn
#

But the issue is, that the object gets created, deserialized, resulting in my event being bound. But then never being destroyed anymore after. Resulting in an event being bound by the invisible object that was supposed to be destroyed

#

Normally, the destructor is called, resulting in my event being unbound

onyx harness
#

Can you remove the event keyword? Just for a try

proper dawn
#

Sure

#

And so my issue comes when the event is basically invoked, for example, like this:

#

And the method is called twice, instead of once

onyx harness
#

Put a debug in OnBefore/AfterSerialize

#

See if they are outputting as expected

proper dawn
#

Not sure about OnBeforeSerialize, but OnAfterDeserialize should be called right after the constructor logs

#

Those are the results ^

fresh yoke
proper dawn
#

Any ideas left by any chance? starletLurk @onyx harness

proper dawn
#

@visual stag I'll take a look at OnHeaderGUI, thanks for the suggestion!

visual stag
#

Actually, that is if the script is drawn outside of the hierarchy apparently...

#

I'm trying to poke around the code and figure out when that's ever called 🤣

#

Perhaps it's for ScriptableObjects or something, just not components

#

That would probably make a lot of sense

proper dawn
#

Yeah me neither starletW

#

Eh, it's not a big deal, would've been nice if it worked. Won't spend more time on something so small lol

dense plaza
#

Is there a way for a script to detect if the editor is built or closed?

#

I have a script that's logging things while working in the editor and I'd like to keep a Filestream open but if the editor rebuilds it will try to create a new Filestream which causes problems

waxen sandal
#

There are events to see when it recompiles

silver owl
visual stag
#

EditorApplication.quitting

#

and IPreprocessBuildWithReport ?

dense plaza
#

which might be what i want

visual stag
#

Ah, yeah that is probably what you need

barren moat
#

Hm...

#

What am I doing wrong here?

void OnValidate() {
  for (int i = 0; i < _flashCurve.length; i++) {
    Debug.Log($"BEFORE {i} -- time={_flashCurve.keys[i].time} value={_flashCurve.keys[i].value}");
    _flashCurve.keys[i].time = Mathf.Clamp01(_flashCurve.keys[i].time);
    _flashCurve.keys[i].value = Mathf.Clamp01(_flashCurve.keys[i].value);
    Debug.Log($"AFTER {i} -- time={_flashCurve.keys[i].time} value={_flashCurve.keys[i].value}");
  }
}
#
void OnValidate() {
  for (int i = 0; i < _flashCurve.length; i++) {
    var prevKey = _flashCurve.keys[i];
    var nextKey = new Keyframe(
      Mathf.Clamp01(prevKey.time),
      Mathf.Clamp01(prevKey.value)
    );
    _flashCurve.keys[i] = nextKey;
    LogKey(i, "PREV", prevKey);
    LogKey(i, "NEXT", nextKey);
    LogKey(i, "[i]", _flashCurve[i]);
  }
}
#

Oh I see

#

lol

#

Just a weird API

visual stag
#

.keys is a property that will duplicate the entire keyframe list

barren moat
#

Ugh. Stoopid

#

I should have known, can't cross into C++ land with a struct mutation I guess.

#

Still, I blame the API design!

visual stag
#

Yeah, similar API to the mesh .vertices, etc

barren moat
#

Yup.

visual stag
#

I agree, it should be better labelled

barren moat
#

.GetKeys() .SetKeys(keys)

#

I think this is how Texture2D works

visual stag
#

It's really a garbage collection conspiracy

#

where they want you to iterate over these arrays recklessly

barren moat
#

Ah, true. Yes, like my code that does curve.keys[i]

#

Making curve.length copies of the array

#

Ends up being O(n^2) instead of O(n) for linear scan

#

Ooh, this works so nicely!

#
void OnValidate() {
  var keys = _flashCurve.keys;
  for (int i = 0; i < _flashCurve.length; i++) {
    keys[i].time = Mathf.Clamp01(keys[i].time);
    keys[i].value = Mathf.Clamp01(keys[i].value);
  }
  _flashCurve.keys = keys;
}