#↕️┃editor-extensions

1 messages · Page 39 of 1

proud yarrow
#

maybe an export html / export pdf too, not sure how hard it is to export a pdf tho

#

i wonder if i could have it embed youtube videos into help entries (optionally)

#

that might be kinda cool

#

i've seriously considered adding comment threads to them but that just seems like... too much

#

if anyone has any other feature suggestions let me know please

#

i think this is going to be the one... the first asset I actually release publicly

#

might try to sell it on the asset store, might release it freely, still considering my options on that

#

hey one of yall might know... is there a way for me to add my icon next to the standard blue help book on top edge of inspector window?

#

i mean i can draw it there, did that, but the foldout hotspot eats the mouse events there so the button doesn't fire, also it hides/shows when foldout is up/down which is weird, so if i put it there i think i'd need to find a less hacky way to do it

visual stag
#

I have attempted to replace the book's functionality (not possible) and during that time I may have attempted to inject my own in there. I have strong memories of everything being impossible

proud yarrow
#

yes, i tried setting GUI.depth to int.MinValue too, no joy

#

i could have swore i saw some custom component stick something up in there once but i don't remember for sure now

wispy delta
#

What's the best way to resize these icons to fit with the 'A' and 'N' buttons to their left? Right know the texture is a part of the GUIContent used by the button in the horizontal layout. Is there a better way to show an texture instead of text on a button?

#

I tried giving the textures read/write permission, but even with that it wouldn't let me go less than 8x8 for some reason; which was still too big, and felt icky

visual stag
#

for a start scale the buttons to the same size

#

then you may have to manually add padding to the textures themselves

#

I think you could do it in a GUIStyle but I tend to just modify the texture for the purpose because the less styles the better imo

wispy delta
#

I'm not changing the button size anywhere, I guess they default style just uses the content size?

visual stag
#

yeah 😃

#

I assume if you use the toolbar for this one (seeing as the content is small) then it won't

#

but I could be wrong

wispy delta
#

Yea, there's a fixedWidth and fixedHeight in a style, if it's 0 it'll scale to content size. The icons are gross, but it works 👍

visual stag
#

I almost always have to create a specialised scaled icon

#

it's one of the most difficult things and I get pretty proud when I create an icon that scales well

#

or has good scaled variations

wispy delta
#

Yea, I think I'm gonna have to hire someone to make the icons. While I'm not the worst artist/designer, I've put all my character points into programming

zealous ember
#

Hi guys, looking to display a scene into a custom windows, wondering if anybody can point me in the right direction. thanks

visual stag
#

wait, a scene view window? Or an object preview?

zealous ember
#

@visual stag
kind of integrate a scene viewer in to the UI. like the editor in below

visual stag
forest vortex
#

that page really needs a lot more elaboration

#

reading it i'd never know what it was used for

visual stag
#

agreed

forest vortex
#

editor scene

#

good to know

craggy sedge
#

You can also use PreviewRenderUtility for some of that stuff

#

Though I think that's more for the preview GUI

zealous ember
forest vortex
#

nice, have fun 😃

worthy swan
#

lol

gleaming zenith
#

How do I create multiple new scenes additively? I always get "Current mode does not support additive creation of new scenes."

worthy swan
#

how do I get the current open prefab

#

I see a prefabContentsRoot, is that the prefab or the actual root

#

nvm PrefabUtility.GetOutermostPrefabInstanceRoot() does what I need

worthy swan
#

actually seems like that's not working out for me

#

I'm trying to add the current open prefab to a list in an editorwindow

worthy swan
#

I guess it's not working well cause I'm trying to get the prefab variant

sonic wind
#

Is there a way to loop through all variable names in ENUM

#

found it

sonic wind
#

Having problems getting EditorGUILayout.Foldout working properly

#

Cant see a way to check when the label is clicked

gleaming zenith
#

I think that's by design

sonic wind
#

It has that last parameter and i have nooo idea what it does

gleaming zenith
#

Just set it to true?

sonic wind
#

Doesn't seem to do anything

#

Im quite confused

#

I can get it to open by clicking it now but cant get it to close 😄

#
        {
            if (fold1 == false)
                fold1 = true;
        }```
gleaming zenith
#

you know you have to use its return value?

#

item.Foldout = EditorGUILayout.Foldout(item.Foldout, new GUIContent(contentText), true);

#

you have to save it and reuse it in the next frame

#

fold1 = EditorGUILayout.Foldout(fold1, "name", true) in your case

sonic wind
#

Ah, that was it

sonic wind
#

When changing values from the custom inspector (below) it does not promt prefab changes (bold). Can i force it to check if the prefab is different?

worthy swan
#

is it possible to get a reference to the prefab variant opened in prefabstage?

dusky plover
#

@sonic wind You can use a EditorGUI.BeginChangeCheck to check if anything changed during the current drawing frame.

#

But the reason they don't become bold is likely because you didn't register with Undo.
You should use Undo.RecordObject on the object you want to change BEFORE changing it.
That registers it with the Undo system and causes the value to be persisted.

sonic wind
#

Thank you @dusky plover

#

Noticed something odd, After having removed the aboce part from the custom inspector the bottom part stopped prompting changes when typing the numbers. It still finds them when dragging the value up or down

#

Note it still says 'changed' after every number typed

        {
            Undo.RecordObject(Base, "Changes");
            Debug.Log("Changed");
        }```
sonic wind
#

Just using these to set and get the values EditorGUILayout.FloatField(title, value);

waxen sandal
#

You're better off using propertyfield

sonic wind
#

Cant make any edits now but i'll check those out

worthy swan
#

"is it possible to get a reference to the prefab variant opened in prefabstage?" -- nvm figured it out.

AssetDatabase.LoadAssetAtPath(stage.prefabAssetPath, typeof(GameObject));
gloomy chasm
#

After doing AssetDatabase.AddObjectToAsset(page, pages);. Is there a way to get all the objects saved to asset? So is there a way to get page from pages?

forest vortex
#

but know that array will be object references, not just names.

#

'pages' is actually a folder in the assets folder.

#

and 'page' is an asset object.

gloomy chasm
#

Thanks @forest vortex. LoadAll does exactly what I want! 😃

visual stag
#

@sonic wind you have to call undo.record object before you begin to make changes to it, not after

sonic wind
#

@visual stag Ill try do that later today. the reference i was linked had it afterwards so thought it should be that way

visual stag
#

If you notice the example on the scripting API, it does the change to the object after (but still uses a change check) 👍 it also mentions it records changes after the function

sonic wind
#

Seems to work fine after moving things around, now just wondering if there's a way to see which elements are overwritten

waxen sandal
#

Did you check the links I sent you earlier?

sonic wind
#

No, didnt do that. Ill check them

sonic wind
#

How would you set a value with these? Didnt find any tutorials on the subject either

#
   SerializedProperty serObjRes = serObj.FindProperty("maxHealth");
    
    if (serObjRes != null)
    {
        Debug.Log("Found " + serObjRes.floatValue);
        serObjRes.floatValue = Random.Range(1f,50f);
}```
gleaming zenith
#

You can just cast your serObj to the type it actually is like MyBehaviour and then set the properties manually

sonic wind
#

((body)serObj).

gleaming zenith
#

so body is your MonoBehaviour?

sonic wind
#

Yup, the class name

#

public class body : MonoBehaviour

gleaming zenith
#

I think you must use serializedObject.target or sth

sonic wind
#

seems to find that

#

If doing it that way i dont see a reason to use this over EditorGui

gleaming zenith
#

what is it that you're trying to accomplish?

sonic wind
#

Mostly to learn how to do custom inspectors and currently trying to list float array (size is determined by length of enum) in the custom inspector and allow changes from there to be applied to the prefab

gleaming zenith
#

by casting the target to your class you can modify it. From there you can do your own inspector and do more than the default inspector

#

in your case you should read the enum and do a for loop in the OnGUI based on the enum value right?

sonic wind
#

I got basically all that working but it was really fiddlish, then i was suggested serialized objects and trying to see what they are all about

#

body Base = (body)target;
and
((body)serializedObject.targetObject)
seem to do the same thing

gleaming zenith
#

Yeah I think they're the same thing but not sure about that

sonic wind
#

Somewhat confused about this description of SerializedProperty
SerializedProperty and SerializedObject are classes for editing properties on objects in a completely generic way that automatically handles undo and styling UI for Prefabs.
Cant see a way to set values via it

gleaming zenith
#

you can only set values on the direct object AFAIK

#

at least thats what I'm doing

sonic wind
gleaming zenith
#

you need a copy of the original object for this

#

but AFAIK you have to implement it yourself

#

this is a prefab only feature AFAIK

sonic wind
#
        var so = new SerializedObject(transforms);
        // you can Shift+Right Click on property names in the Inspector to see their paths
        so.FindProperty("m_LocalPosition").vector3Value = Vector3.zero;
        so.ApplyModifiedProperties();```
Found this in documentation
gleaming zenith
#

Try it

sonic wind
#

Looks like you can change the values like this

        {
            serObjRes.floatValue = Random.Range(1f, 10f);
            serObj.ApplyModifiedProperties();
        }```
sonic wind
#

Any ideas on how to get value of the float array?
float value = soArray.GetArrayElementAtIndex(i);

#

SerializedProperty soArray = so.FindProperty("resistances");

#

Found it
Debug.Log(soArray.GetArrayElementAtIndex(0).floatValue);

waxen sandal
#

Yeah you're support to apply it on the serialized object

lucid hedge
#

@wispy delta thank you again for drag and drop snippet, I'm getting somewhere 😃

wispy delta
#

Looks awesome! Glad to help 👍

lucid hedge
#

anyone got tips when making rects responsive to the dimensions of your editor window?

#

because I don't think this is the way to do it

#

I'm basically getting the width of the window and then determining how many columns/rows there should be and then moving the rects

surreal quest
#

lol, it looks like you're not resetting the x

lucid hedge
#

yeah I'm not, I will but I'm just wondering if there is like an elegant way to do this

#

I might just get some paper and do this properly

#

lol

forest vortex
#

you've invented a new puzzle game

lucid hedge
#

:p

wispy delta
#

@lucid hedge maybe GUILayout.SelectionGrid

#

Not sure if you know this, but Screen.width/height doesn't just apply to the game. You can use it for editor windows as well. You'd probably need the width to calculate xCount

lucid hedge
#

Victory!

#

I'm gonna check out selectiongrid too ty

#

added a 'plus' slot instead of the bottom bar

#

I'm done for the night

#

good night ❤

wispy delta
#

looks awesome 👍

wispy delta
#

I'm continuing work on drag n drop gui and got it working for any Object. I'd like to add an option to allow/disallow assets scene objects.
Since the method works with any Object I figured I can't just use PrefabUtility.IsPartOfAnyPrefab() as that wouldn't work with textures, audio, scriptable objects etc.

The only other methods I found that seemed helpful were AssetDatabase.IsSubAsset() and AssetDatabase.IsMainAsset().
Do I need to check both methods or is there a better way to check if an Object is an asset or in the scene?

wispy delta
#

tldr: I'm creating a drag n drop field and want to add an option to disallow scene objects, whats the best way to check if a UnityEngine.Object is in the scene?

grim monolith
#

@wispy delta You can use AssetDatabase.Contains(obj) it will return true if it's on the project

wispy delta
#

Perfect, thanks!

grim monolith
#

np

lucid hedge
#

If I have an editor window open then close Unity, open Unity again, the editor window will be still open

#

what method will be called?

#

OnEnable?

#

Because I'm having an issue where my prefab list 'forgets' the prefabs in it when I close and reopen Unity

#

so it shows up as empty slots

#

so I want to 1) Remember the prefabs OR 2) clear the lists

#

okaaay

#

clearing the list in OnEnable() worked

wispy delta
#

Sounds like you got it to work, but if you ever need information to persist in a window it's best to store the info in a scriptable object

lucid hedge
#

Yeah I do use scriptable objects, but the prefab list only gets stored in the scriptable object when the user presses a save button, when he just adds prefabs but forgets to save it, it doesn't get put in a scriptable object so when closing/reopening Unity they are forgotten

#

probably should add like some info when they forgot to save it

#

or a warning or something

wispy delta
#

I believe there's a way to intercept when Unity quits but I am not sure

lucid hedge
#

Yeah I don't think I want to do this, messages that pop up when you want to close stuff are annoying imo, just gonna add an indicator icon in the UI that shows if the prefabs were saved or not

lucid hedge
#

nice method, ty

wispy delta
#

Also @lucid hedge I don't think you necessarily need to save it yourself. Just write to it and mark it as dirty. If it's dirty I'm pretty sure the new data will be saved when the project is saved. You may need to test that tho

forest vortex
#

it should be, yes

lucid hedge
#

never used 'dirty', will add it to list of things to check out

#

ty

wispy delta
#

Obviously the original file still needs to be created, but once you have a reference to it you should be good to go

forest vortex
#

but having your tool hook that event and just save on exit would work

#

you don't really have to have it prompt the user

lucid hedge
#

hmmm I want to register a mouse click within a rect

#

with this

#

if (r.Contains(Input.mousePosition) && Input.GetMouseButton(0))

#

but it doesn't seem to be doing much

wispy delta
#

You have to use Event.current in editor stuff for input

#

In general Input is for runtime Event is for editor

lucid hedge
#

if (r.Contains(Event.current.mousePosition) && Event.current.type == EventType.MouseDown)

#

works

#

ty for the tip

wispy delta
#

You can do if (Event.current.button == 0) as well

#

well this is the full thing you need to do

var e = Event.current;
if (e.type == EventType.MouseDown && e.button == 0) 
{ ... }
#

If you just check if the event type is mouse down. someone could middle mouse click or any other mouse button. That may be what you want, but it's good to know you need to differentiate between different mouse buttons

lucid hedge
#

selecting stuff feels super slow

#

I'm gonna try some optimizations

wispy delta
#

feels slow frame-rate-wise?

lucid hedge
#

there is like a delay

#

after I press

#

between the button press and the blue selection indicator

wispy delta
#

it may just be you need to call repaint

lucid hedge
#

lol dude

#

that fixed it

#

tysm

#

so smooth now ❤

wispy delta
#

np. repaint set me back so many times. i could never figure out why the gui wasn't updating, but it was just that it wasnt repainting

indigo kiln
#

Im creating a very basic idle game, and would like a little help with the auto add function. So i need to add a number every second to a count variable. Would i use delta time to add it to there or WaitForSecond, or something else for the delay between adding it?

wispy delta
#

Are you doing this in the editor or at runtime?

indigo kiln
#

I want the timer to start when the program starts. so im pretty sure the timer is running in runtime.

wispy delta
#

Ok then #💻┃code-beginner would be the correct channel. This channel is for extending the editor, but no worries I can still help :)
You could use a coroutine like so:

float delay = 1f;
int count = 0;

private void Start ()
{
    StartCoroutine (AddRoutine ());
}

private IEnumerator AddRoutine ()
{
    while (true)
    {
        yield return new WaitForSeconds (delay);
        count++;
    }
}

Or you could keep track of time yourself like so:

float currentTime;
float delay = 1f;
int count = 0;

private void Update ()
{
    currentTime += Time.deltaTime;
    if (currentTime >= delay)
    {
        currentTime = 0f;
        count++;
    }
}
indigo kiln
#

And the count ++ is what is getting added to the count, right?

lucid hedge
#

yes

#

count++; is equivalent to

#

count = count + 1;

#

or

#

count += 1;

gleaming zenith
#

@indigo kiln by idle game you mean, when you close the game it continues in the background?

indigo kiln
#

Okay, that makes sense to me. Thanks for all the help so far guys, i very much appreciate it.

#

@gleaming zenith i want it like that in the future, but right now im alright if it just counts when its open.

gleaming zenith
#

I think you can easily do that without much hasle

#

but you have to do it from the start on correctly

#

save a timestamp when starting the "game" or "profile" of the game status

#

and use it to calculate your current time

#

thats the best way you can to that

indigo kiln
#

really? so it would be the difference between when the game opens for the first time, and current time?

gleaming zenith
#

because you cannot run a coroutine or whatever when the game is closed

#

if you start the game the first time at 08:00 and close it at 08:30 you have 30min time

#

when you reenter at 10:00

#

you want the time to be 2:00h right?

indigo kiln
#

okay, well i need to start work now, so i have to go. But yeah, thats how i would want the game to work.

gleaming zenith
#

Save a timestamp at 08:00 and then you can always "calculate back in time"

indigo kiln
#

I need to start work, but if you comment stuff here, i can look through it. You dont have to comment the code, because i kinda want to figure it out, but thanks for idea.

#

that does make sense for me.

gleaming zenith
#

yeah if you have any questions or such you can dm me if you want

#

im going to sleep now xD

indigo kiln
#

thank you so much. Good night.

left gate
#

I instantiate a scriptable object, to use as a temp object for an editor.

However as the object is in memory unitys Garbage Collection will destroy the object at various times (e.g. going into play mode)

Is there a way to stop the GC on this object?

#

Writing the object to file does prevent it, but it also has other draw backs. I would rather keep it in memory

gleaming zenith
#

is it static?

#

Static variables shouldn't get cleared AFAIK

left gate
#

it is not static

#

i will try that, thank you

#

@gleaming zenith , no unfortunately it still gets destroyed

gleaming zenith
#

Maybe save it when OnDisable and load it OnEnable?

left gate
#

saving it to a file introduces a lot of other bugs ☹

gleaming zenith
#

that doesn't sound right

left gate
#

the bugs are with the flow of the code, and the asset managment with that new file

gleaming zenith
#

Maybe you code got too complex?

left gate
#

yup. its fine if the object could remain in memory

#

but writing to file, serializing fields, creating sub-assets, is just a pain

#

when you work from a file from disk

gleaming zenith
#

You should only need to save the scriptable object right?

left gate
#

hmm?

#

rather than sterilizing the fields? probably, but i wouldnt be supprised if i had to do that too

gleaming zenith
#

If you use a scriptable object you just have to save the object right? Every field gets automatically saved

left gate
#

it depends at which point i save the object

#

If i
save
make edits in code
those edits only exist on the SO thats in memory

gleaming zenith
#

you know when you make edits in your code -> your code gets recompiled and refreshed

#

EVERYTHING from your code gets thrown away and re-initialised

left gate
#

not for editors

#

they exist between compiles

gleaming zenith
#

Thats not my experience

#

only the serialized objects get saved

#

but your code gets a refresh

left gate
#

no private varibles get saved too

#

you have to mark it with [system.nonserialized] for it not to persist

gleaming zenith
#

Then I dunno bro

left gate
#

gloomy chasm
#

@lucid hedge That prefab painter is pretty cool and I think I may end up using it.
Was working on my own thing and ended also making a grid thing. Thought you might like it.

lucid hedge
#

Nice! thank you for showing me

#

do you have a twitter I could follow?

gloomy chasm
#

Yeah, it's the same as my username here. Though been a bit quite because I have been working on stuff.
Do you have one?

lucid hedge
#

yep

#

just followed you

gloomy chasm
#

Is there any way to get a display like this? Both name and image. But more specifically the image. If I use OnPreviewGUI the object is much darker.

cinder cloak
#

what are the drawbacks of writing to file..? , what temp editor are you creating , why is it temp? not judging , just curious ..

#

i use SO for a spine and path tool I built , I only have to create save reload once .. after that any changes in the inspector of that object are automatically serialized

#

for interest sake do you load the saved asset after creating it , habit i formed a while back , might be overkill , cant remember how I came to this pipeline, maybe the examples in the docs? all i know is I always do it for any created assets

#
        directortPath += "/";
        string splineDataPath = EditorUtility.SaveFilePanelInProject("Save Spline Data", "newPath.asset", "asset", "enter the name for your new path and save it", directortPath);
        if (splineDataPath.Length == 0) return;
        AssetDatabase.CreateAsset(target.splineData, splineDataPath);
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
        SplineData splineData = AssetDatabase.LoadAssetAtPath(splineDataPath, typeof(SplineData)) as SplineData;```
#

@left gate im interested to know why your editor SO must be memory only and what the serialization issues are..?

left gate
#

@cinder cloak I am handling assets and sub-assets. if the object is in memory I can simply do AddObjectToAsset, however you can not do that if it belongs to another Asset. My object in memory is a temp object, as I do not want the changes to be applied across until the user clicks a button

#

I have to instantiate the sub-asset, re-name it, re-link it to the Saved SO

#

previously I could simply call CopySerilizedValues then call AddObjectToAsset on any sub-assets. and it would work perfectly

#

when working with the file object there is also a notable performance difference of a few seconds, when creating/saving the temp obj

cinder cloak
#

interesting , i have never had the experience of adding same sub assets to multiple assets so I cant give you any input there.

#

at most the only sub assets i ever add to existing assets is mesh objects, because although they do save as part of the scene without being serialized , you cant create a prefab of that object and export it as a package .. the imported object will be missing the mesh

#
 PrefabUtility.CreatePrefab(finalPrefabPath, targetCast.gameObject, ReplacePrefabOptions.ConnectToPrefab);
            AssetDatabase.SaveAssets();
            savedPrefab = AssetDatabase.LoadAssetAtPath(finalPrefabPath, typeof(GameObject)) as GameObject;
            AssetDatabase.AddObjectToAsset(meshFilterCache.sharedMesh, savedPrefab);
            PrefabUtility.ReplacePrefab(targetCast.gameObject, savedPrefab, ReplacePrefabOptions.ConnectToPrefab);
            AssetDatabase.ImportAsset(finalPrefabPath);```
#

why not use two linked SO one is the actual final values , the other is for editing?

#

For example Blender actually does this when you enter edit mode , it duplicates all the data of the object and you actually edit the duplicate, only when you exit edit mode ( same like a user saving ) does it copy the data from the duplicate to the real and trash the duplicate..

#

it does have drawbacks as well , because if you have a high poly model in the scene and enter edit mode .. it duplicates that hi poly model .. not the best for performance either

#

but it is a needed evil because for some operations that require mouse movement like translate or scale etc .. you always need to maintain the original value to use in the constant calculation using the current mutating numbers..

#

i have personally had more issues with doing in memory or scene serialized things, that now I rather always save thing to disc, have not had any issues with that but then again I have never tried to do what you are doing 😉

lucid hedge
#

@gloomy chasm you could just add a label below the rect right?

#

and you use onpreviewgui but I don't

#

I use AssetPreview.GetAssetPreview

#

and EditorGUI.DrawPreviewTexture

#

I have a question

#

So when I implement a scrollview in the editor window

#

it will only take into account the EditorGUILayout stuff

#

and not the EditorGUI.DrawPreviewTexture I'm using for the prefabs

#

how can I implement a scroll view so that it also takes into account the prefab list?

gloomy chasm
#

@lucid hedge The problem with onpreviewgui is that there is no lighting so they look dark grey instead of white. I will try those two options.

I ended up using GUI.BeginScrollview and GUI.EndScrollview for scrolling.

grim monolith
#

@lucid hedge what I used on mine is that I calculate how much vertical space it will use and add a Space(height); inside the scroll view

lucid hedge
#

aah yeah that seems like a nice solution

#

ty

left gate
#

@cinder cloak sorry for the late reply.
Yes from what I understand that idea I am trying to accomplish. Where the temp object is the duplicate.
Although it would be possible to correctly copy the data back and forth,(I.e. Saving) it's just much more of a pain than having the object in memory.

Having to manage the creation and deletion of assets / sub assets, correctly linking the sub assets. And the performance. It's just much more hassle 😜 especially as the editor is done (would have been much easier if I wrote it this way to begin with)

cinder cloak
#

hope you getting it sorted 😉

gleaming zenith
#

Is there a way to rotate a Handles.DrawWireCube(center, size) ?

gleaming zenith
#

Any more infos about that?

waxen sandal
#

I mean, you set the matrix and everything is translated/rotated/scaled by that matrix

gleaming zenith
#

Not working

#
Handles.matrix = Matrix4x4.Rotate(Quaternion.Euler(0, (float)(Mathf.Rad2Deg * obj.Hdg), 0));
#

Does not do anything

#

obj.Hdg is something I can edit live in the inspector

#

I would expect

Handles.DrawWireCube(
                new Vector3(
                    origin.x,
                    origin.y - (float) (obj.Height / 2 + obj.ZOffset / 2) + height / 2,
                    origin.z
                ),
                new Vector3(
                    (float) obj.Width,
                    (float) obj.ZOffset,
                    (float) obj.Length
                )
            );

to rotate

waxen sandal
#

That's how I did it when I used it 🤷

#

With Matrix4x4.TRS that is since I needed both of those as well

gleaming zenith
#

Nah not working. I probably have to write my own DrawWireCubeWithRotation method

wispy delta
#

test

#

even tho im not dming anyone

#

anyways, here's how i draw a cube with handles. you'll have to change some stuff that's missing, but it may save you some time https://pastebin.com/Q45TK2AC

gleaming zenith
#

Yeah but actually I don't want handles

#

I just want to show some debug bounding box

#

Nothing to edit (just for testing I can do it from the inspector)

wispy delta
#

thats what this is, there's nothing to grab. its the equivalent of doing it with debug.drawline

#

there isnt even the handles implementation here, you could change Line with Debug.DrawLine

#

just has the boilerplate for drawing between the corners

gleaming zenith
#

ok I check that

#

Ok it works but it rotates around the center far away.

#

Doing it like this:

Bounds(new Bounds(origin, size), Matrix4x4.Rotate(Quaternion.Euler(0, -(float)(Mathf.Rad2Deg * obj.Hdg), 0)));
#

Only on the object when hdg = 0. When hdg = PI its at maximum distance

wispy delta
#

you need to do Matrix4x4.TRS it's expecting a full transformation matrix

gleaming zenith
#

ok

wispy delta
#

offset the position in the matrix

gleaming zenith
#

it got even further away 😦

wispy delta
#

show me the code that calls the method

#

and your version of the method if you made significant changes

gleaming zenith
wispy delta
#

set the center to Vector3.zer, the offset is done through the matrix

gleaming zenith
#

the offset should always be zero

#

I just want to rotate the object around its own axis

wispy delta
#

where in the scene do you want to draw the cube?

gleaming zenith
#

At the origin position

#

with size size

#

with rotation Quaternion.Euler(0, -(float)(Mathf.Rad2Deg * obj.Hdg), 0)

#

Sorry not too much into vector math^^

wispy delta
#

no worries. try
Bounds(new Bounds(Vector3.zero, size), Matrix4x4.TRS(origin, Quaternion.Euler(0, -(float)(Mathf.Rad2Deg * obj.Hdg), 0), Vector3.one));

gleaming zenith
#

@wispy delta You're a king^^

#

I would've just tested around with the parameter otherwise^^

wispy delta
#

haha glad to help. if i wasnt playing anthem rn id try to explain matrices better

gleaming zenith
#

it's ok. Keep looting and leveling^^

wispy delta
#

ok im switching games so i can try and explain it rq.

multiplying a point by a transformation matrix returns a point relative to that "transform"
so in ur case you are creating bounds at 0,0,0 but then making that 0,0,0 relative to origin via the matrix. the same applies to the rotation and scale.

It's how child transforms in the scene have relative positions, rotations and scales.

gleaming zenith
#

Ok yeah I will work with vector math in the future so I probably get to that anyway^^

barren siren
#

guys, im new, need some help, what does private, public, float and private float mean?

wispy delta
#

those are "access modifiers", they just define what scripts have access to the variable or function. private means they can only be accessed from within the object they are defined in. public means they can be accessed from anywhere

gleaming zenith
#

I think you should go through the basics of programming first

wispy delta
#

^

gleaming zenith
#

Don't try to rush this stuff as it takes time

#

first video i found about basics

barren siren
#

ok ty

#

@gleaming zenith is coding for 2d same as 3d?

gleaming zenith
#

As programmer most of the time

#

As when you program in 3d you only have to add one more axis

#

math might get more complicated

#

but just for beginning I personally think 3d and 2d does not much differ. I saw many people think 2d is easier but then were suprised that 3d isn't much harder

#

It depends on how fast you understand stuff especially thinking in a 3d / 2d perspective

wispy delta
#

i started in 3d before unity had 2d mode. it's really not much harder if you have any familiarity with x,y,z. If you have zero experience with any 3d applications, 2d might be a tiny bit easier

barren siren
#

ty guys

gleaming zenith
#

btw these are more of "general-code" questions 😉

barren siren
#

ok osrry

leaden oar
#

Hello everyone !
Do you have tips, video, ressources to learn how to use the new UIElement system, the new way to do editor script ?

I found this: https://docs.unity3d.com/Manual/UIElements.html
But it's still tagged as experimental and it's rough to read.

wispy delta
#

not a lot of resources on it yet, but the examples along with a basic understanding of html/css should be enough to get started

leaden oar
#

#

Yes there is not so much things about it right now. That a bit sad for those who want to learn more about it.

wispy delta
#

unity doesn't like to invest too much time into making learning resources while things are experimental b/c they'll have to recreate all of them if anything significant changes

gleaming zenith
#

Unity was always pretty slow when it comes to documentation. You can learn most about new stuff in videos

gleaming zenith
#

Does anyone know how I create multiple scenes additively in the editor? I always get InvalidOperationException: Current mode does not support additive creation of new scenes. and I don't find anything useful to it in the internet.

#

I want to create multiple scenes at once (or with delay I dont care) that have different purposes

leaden oar
#

@gleaming zenith can you precise your problem ?
Creating scene and adding them additively to the current scene are two different things

gleaming zenith
#

In the Editor i want to create two scenes at the same time via

EditorSceneManager.NewScene(NewSceneSetup.Empty, Single);
EditorSceneManager.NewScene(NewSceneSetup.Empty, Additive); // throws exception
#

#pseudoCode

leaden oar
#

The process to create a scene and add it additively you must:

  • Create the scene
  • Save it as an asset
  • Add it to the list of scenes in build in the build settings
  • Instantiate it additively
scenic elbow
#

@gleaming zenith are you trying to do it in play mode?

gleaming zenith
#

@scenic elbow No this is an editor script.

#

@leaden oar I'm going to give this a try tomorrow. I probably have to save it as asset as I cannot have multiple unnamed scenes?

scenic elbow
#

weird, thought maybe the error implies it's not supported in either edit/play mode

#

should be in edit tho

leaden oar
#

@gleaming zenith You probably can't indeed

#

@gleaming zenith

Create

Scene newScene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive);

Save

EditorSceneManager.SaveScene(newScene, "Assets" + path + _name + ".unity");

path: "/Scenes/";

Add to build settings

public void AddSceneToSettings()
{
   List<EditorBuildSettingsScene> newSettings = new List<EditorBuildSettingsScene>();

   newSettings = EditorBuildSettings.scenes.ToList();
   
   EditorBuildSettingsScene sceneToAdd = new EditorBuildSettingsScene("Assets"+path + Name + ".unity", true);

   newSettings.Add(sceneToAdd);

   EditorBuildSettings.scenes = newSettings.ToArray();
}

Load Scene

EditorSceneManager.OpenScene("Assets" + path + _name + ".unity", OpenSceneMode.Additive);

path: "/Scenes/";

Bonus, remove scene

public void RemoveScene(string _name)
{
   if (SceneManager.GetSceneByName(_name).isLoaded)
   {
       EditorSceneManager.UnloadSceneAsync(EditorSceneManager.GetSceneByName(_name));
   }

}
#

Just extract that from one of my project. Should work 😃

gleaming zenith
#

I would have get that my own :p I already got that for in parts but not in combination with multiple scenes. Thank you anyway^^

drowsy maple
#

Hey there. I'm having trouble finding actual documentation on nested prefabs.
It seems like PrefabUtility.IsAnyPrefabInstanceRoot(..) should return true for roots of nested prefabs, even on an instantiated copy of the source prefab.
i.e. if the first child of a GameObject is the root of a nested prefab, these asserts would pass:

GameObject prefab = LoadAsset(..);
GameObject nestedPrefabRootInPrefab = prefab.transform.GetChild(0).gameObject;
Assert.IsTrue(PrefabUtility.IsAnyPrefabInstanceRoot(nestedPrefabRootInPrefab));

GameObject instance = GameObject.Instantiate(prefab);
GameObject nestedPrefabRootInInstance = instance.transform.GetChild(0).gameObject;
Assert.IsTrue(PrefabUtility.IsAnyPrefabInstanceRoot(nestedPrefabRootInInstance))

Is this understanding correct?

drowsy maple
#

It looks like that's incorrect. Experimentally, IsAnyPrefabInstanceRoot(..) only seems to work on objects returned by PrefabUtility.InstantiatePrefab(..).
I'm trying to make bulk changes to the non-nested parts of prefabs, and edits to prefabs instantiated this way cannot be saved, so this is inconvenient.
I can try to solve this by iterating both the PrefabUtility prefab and an instantiated prefab at the same time, but that approach won't work well as the number of prefabs in my project increases.
Is there a better way to determine what part of an editable prefab is in nested prefabs, or a way to save changes to a PrefabUtility prefab instance?

drowsy maple
#

My problem was trying to use AssetDatabase.LoadAssetAtPath(..) and PrefabUtility.SavePrefabAsset(..). Using PrefabUtility.LoadPrefabContents(..) and PrefabUtility.SaveAsPrefabAsset(..) made this much simpler.

barren siren
#

after coding my player mvmt , it only goes right and down

lucid hedge
#

@barren siren this is probably not for editor scripting?

barren siren
#

k

gleaming zenith
#

@leaden oar FYI: I just checked it. You have to save the scenes before you can add more "temporary" scenes. It's not possible to have multiple "unnamed" scenes

worthy swan
#

is it possible to draw an objects custom editor inside of an editorwindow? my attempts have been crashing the editor so far 😛

wispy delta
#

I use Editor.CreateCachedEditor
Then you can just call OnInspectorGUI on the ref'd Editor. Just remember to dispose it @worthy swan

worthy swan
#

@wispy delta ah thanks, now I'm drawing a propertydrawer instead which works fine too 😄

dusky plover
#

I'm trying to use Unity's ReorderableList class, but can't seem to be able to, well, reorder the elements.
Items clicked don't get highlighted so I can't really do anything other than to add and view items.
I'm using it on a custom inspector of a scriptable object.

Any ideas?

wispy delta
#

Not sure. Post whatever code you can and I'll see if anything looks funky

#

If you add three backticks on either side of the code it'll give it code formatting. A lil easier to read

#
Code
dusky plover
#

I take it it's not those ><

wispy delta
#

Yeah not single quotes

dusky plover
#
        {
            drawElementCallback = drawAction,
        };
        m_ActionList.DoLayoutList(); ```
wispy delta
#

👌

dusky plover
#

There we go

#

Basically it's just the most basic code. But I'm getting this awful feeling that it's not working because it doesn't support selection for non-serialized property lists? =\

wispy delta
#

So i think the issue is you are recreating the list Everytime it needs to be drawn which is likely messing up any persistence. Create a field for the list and call the constructor in OnEnable. Then you can just call DoLayoutList in OnInspectorGUI

#

Also setup the delegates in onenable

dusky plover
#

Oh shit, that was a good catch my man. Works now.

#

Thanks a lot 😃

wispy delta
#

Np 👍

gleaming zenith
#

@dusky plover Btw don't do hungarian notation. It's ugly.

wispy delta
#

What's that?

grim walrus
#

m_SomeVar

#

byBits

#

g_OtherVar

#

lpszAwkwardString

#

You either provide their access_ or their types in lowercase and the rest pascal case

wispy delta
#

Ah, yeah haha I feel like the only people who use that notation are people over 30 years old, or students of people who are over 30 years old. But at the end of the day it doesn't really matter 🤷

grim walrus
#

Depends where you work. Some places have their own managed standards that require you to use it

wispy delta
#

Yeah, as long as everyone who's working on a project can agree to a convention it's fine.

grim walrus
#

It’s helpful in COM but it’s becoming dated

wispy delta
#

I just do variableName for fields and VariableName for properties and statics. Havent really run into any issues doing that

#

I can ways fallback to _variableName if I need to

#

But if I ever need more than 2 things with the same name I'm probably doing something wrong

grim walrus
#

I get to _variableName if i use property backing

visual stag
#

I’ve moved to the .NET naming standards

#

I used to do what unity did, but I heard they were migrating

wispy delta
#

I should do that

grim walrus
#

Think i do that without noticing

wispy delta
#

If I got rider it would make transitioning easier

grim walrus
#

im close to buying it, whether id be able to switch to it in work i dunno

reef crane
#

Your personal license lets you use it at work too, but there's also a business license so i dunno

#

Also, i'm 29. But I feel like i'm nowhere near that hungarian notation cutoff 😛

#

You mean people who have been coding for 30 years??

wispy delta
#

Haha yeah that's probably more accurate

#

30 and 40 look the same from 20

grim walrus
#

Well I wouldn't be sharing it with these degeneratesfine programmers so I should be alright with the personal license

reef crane
#

ooof

#

hobbles back to his retirement village

wispy delta
#

Haha the future is now, old man

gleaming zenith
#

@reef crane No you cannot use a personal license for work at your company. What's the purpose of company licenses then?
@visual stag Nice to hear that they're finally doing something in a standardized way 😄 Where did you hear that? I think this can cause many issues if not done correctly by unity because of the serialization and refactorings (you know)
@grim walrus Rider is defenitly worth the money!

grim walrus
#

Would literally be using it at work, since it wouldn’t be distributed anywhere else and then when I’m done it would be uninstalled/caches cleared etc and just use it at home

gleaming zenith
waxen sandal
#

You can use your Rider license at work

#

They literally say you can do it in a FAQ

gleaming zenith
#
A Personal license is an option for private individuals who purchase a license with their own funds, and solely for their own use. Personal licenses are not to be purchased, refunded or in any way financed by companies. 
waxen sandal
#

Yes, you can use your personal license at work as well as at home. You can use it working on your personal projects as well as your projects in your company. Our EULAs do not restrict this.

gleaming zenith
#

@waxen sandal Thanks I found this entry just yet damn

waxen sandal
#

You can't purchase a personal license as a company though

grim walrus
#

It’s usually “if a company has purchased it for you that’s a nono”

gleaming zenith
grim walrus
#

Means they would have to justify buying rider for myself or others. We are already using the “free” visual studio license

gleaming zenith
#

"free" VS license?

waxen sandal
#

Community

#

Or bizspark perhaps

gleaming zenith
#

But you're only allowed to use that if your Company does not make more then 500,000$ sales / year

reef crane
#

Yeah, the "refund" terminology seems like it's there to block you from buying it personally, using it at work, then having your company give you a bonus to the same value of a license

grim walrus
#

"free"
allegedly we make more then that per year

#

Projects go around £80-100k
But the new product/project thing has been £750k and another sat around £2.5million

#

Our studio as a whole gets like 10% of that because this company is ass

#

But its still the company that has the revenue

gleaming zenith
#

So you're probably not allowed to use Community^^

grim walrus
#

Nah probably not, thats their issue to sort though

#

If i switch to rider id be immune to it schemes in the background

gleaming zenith
#

As employee you're always immune to a lawsuit :p They company is responsible for correctly holding their licenses

#

The only thing they could sue you for is that you didn't mention it to them

#

but as far as I can tell your company is too stupid for that

grim walrus
#

Yup

#

The bigger projects are done in unreal, i dont even think they have paid royalties

gleaming zenith
#

😆

nova scarab
#

Any reason that GUILayoutUtility.GetRect passing GUILayout.ExpandWidth(true) doesn't expand the width across the entirety of the area?

waxen sandal
#

MaxWidth is set?

#

Use the IMGUI debugger if you want to know more info

fast helm
#

Upgrading from 2018.1 to .3, have hundreds of models that now have a "Fix Now" for blendshape importing. We use AssetImporter scripts to handle fixing this kind of stuff usually, but for some reason the bool that's associated with it in the ModelImporter class, bool legacyComputeAllNormalsFromSmoothingGroupsWhenMeshHasBlendShapes is set to internal so we can't auto-fix this issue with our importer (without whipping up some reflection) and have to manually go through the import settings. Just curious if there is some reasoning to having that property hidden from scripters before I go ahead and reflect it... The GUI fix button code merely set it to true, so I'm not seeing any special reason for it being so.

waxen sandal
#

You can probably access it with a serialized object

fast helm
#

That's not really accessible from the context of AssetPostprocessor and ModelImporter class. I can access it fine using a few simple lines of reflection, was just curious if there was an editor dev here that could give some insight into a decision like that

waxen sandal
#

Can't you make a SO from the ModelImporter?

#

I think I've done that before to access a few things

fast helm
#

Both of the related editor class for the ModelImporter are also internal. Not really looking for a solution here, I have one, just wondering about why the restricted access.

nova scarab
#

Are foldouts width restricted or something?

grim monolith
#

What you mean with restricted?

nova scarab
#

No matter what width I specify in the size, it stays the same. I am using a custom GUI style but that style has "fixed width" set to 0 and "Stretch Width" to true.

#

EditorGUI.Foldout(new Rect(nRect.x, nRect.y, 1000, nRect.height),descriptor.Expanded, descriptor.Description, true, RunicSystemStyle.Instance.ListItem);

waxen sandal
#

Override the style should fix it

fresh shell
#

I am trying to make a tool that will log when something is duplicated, I know I can use HandleHierarchyWindowItemOnGUI and Event.command.commandName == "Duplicate" but I'm not finding a way to find which gameObject was duplicated or the newly duplicated GameObject. Does anyone have any advice?

visual stag
#

Cache selection, previous selection is duplicated, new is duplicate. If I'm correct about what happens when you duplicate (I'm very far away from a unity instance right now)

fresh shell
#

Oh right! Thank you I dont know why I didnt think about that!

leaden oar
#

Or just the actual focus object?

gleaming zenith
#

When I instantiate a new prefab via var instance = (GameObject)PrefabUtility.InstantiatePrefab(prefab, scene) in the editor and trying to set its parent via transform.SetParent(parentTransform) or transform.parent = parentTransform it does not work. Anyone knows why?

#

Doing a "delayed" invoke seems to fix this issue. Again some strange Unity behaviour

#

Delayed in this case means saving all instances in a list and iterating over them as soon as all prefabs are instantiated. WTF

lucid hedge
#

Question

#

this error

#

I 'kind of' know why I'm getting it

#

but not sure how to fix it

#

it has to do with me changing GUI elements at the wrong time

#

the error is point me to this

#

in OnGUI I'm doing this

#
                {
                    selectedPrefab = prefabs[i];```
#

so assigning something to 'selectedPrefab'

#

but I'm also doing this in OnGUI

#

if (selectedPrefab != null) selectedPrefab.displaySettings();

#

so during the mousePosition event I'm assigning something to selectedPrefab, making it not null, calling displaySettings() which adds GUI elements

#

so how would I fix this?

#

nvm fixed it

#

by doing so Event.current.type = EventType.Layout checks

wispy delta
#

@gleaming zenith is there an error?

gleaming zenith
#

@wispy delta No it's just not working

#

@wispy delta Like it ignores the calls at all

wispy delta
#

But adding a reference to the object in a list and setting it's parent through there works?

#

Are you anything between instantiation and list iteration?

gleaming zenith
#

I instantiate them and want to set their position and parent directly afterwards. But none of both work (order doesn't matter as well)

#

As I said the workaround works. Also commented with a WTF Unity

wispy delta
#

Very strange. I haven't used the prefabutility version of instantiate. Maybe you could try the normal instantiate method and just see if it works @gleaming zenith

#

Just to see if the problem has to do with prefabutility

gleaming zenith
#

that might work yeah but I need the InstantiateAndConnect feature

lucid hedge
#

ScriptableObject icons ❤

dusky plover
#

So another ReorderableList question. Anyone has an idea how to enable multi-element selection? And if copy/pasting is in any way possible as a built in option?

wispy delta
#

You'd have to handle multi selection on your own. It's not too hard I should think. You can plug into the selection delegate and check if the shift key is pressed via Event.current

#

@dusky plover same for copy pasting. You'd have to handle that yourself

dusky plover
#

Yea, already implemented copy paste since I asked haha

#

Multi selection is a bit more worrying though, as it has some edge cases with the inherent drag and drop of the elements.

wispy delta
#

Have you tried only doing it if the mouse delta is below a theeshhold?

dusky plover
#

I meant about the part about dragging a group of elements rather than just 1 at a time.

wispy delta
#

Ah I see

dusky plover
#

Guess there's no getting around figuring that one out though 😃

wispy delta
#

Pretty sure someone figured it out on github

#

I forget the repo name tho

#

I believe it's this ^

dusky plover
#

Yea, and it looks good, but I have a typing limitation in my code that I can't use a serialized property for these, and all the extensions that I found many people do only support the serialized property interface and not the list one.

wispy delta
#

Yeah, no need to use his system but maybe you can see how he does element selection

meager copper
#

hey guys, is there a way to store values in an array in the editor/inspector script?`

wispy delta
#

Just define an array in a monobehaviour or scriptableobject that is public or has the serializefield attribute

#

@meager copper

meager copper
#

@wispy delta so i have to create the array in the normal game script, even if i just need them for the editor?

wispy delta
#

If you just need it in the editor create a scriptableobject that holds it and load it from the editor

#

You dont have to load the scriptableobject at runtime

meager copper
#

maybe i should give u more input, i think there is a better solution, i using a array so save some UI data for a char creator menu, and if the user edits the panel count to a lower count, it should save the values that will be deleted in a 2nd array, if the user set the size up again, the old values shoudl be displayed

visual stag
#

If you don't need it persistent put it in the Editor. If you need it persistent put it on a ScriptableObject or on the inspected Object. If you did put it on the Object you could exclude it with preprocessor ifs

rustic remnant
#

Does anyone know if it's possible to run unit tests from editor code?

barren siren
#

how to set rigidbody to dynamic with a if statement

wispy delta
#
if (something) rigidbody.isKinematic = false;

@barren siren

#

Yes you can @rustic remnant

errant finch
#

how do you edit the inspector for scriptableobjects?

wispy delta
#

What do you mean? @errant finch
You can create a custom editor in the same way you would for a monobehaviour

errant finch
#

I just realized what I was trying to make an editor for what not actually a scriptable object, but rather a field on the object

#

not good

wispy delta
#

I'm still not very sure what you are stuck on, but if you want a custom Editor for a variable use a PropertyDrawer

errant finch
#

k wait let me explain
So I've got this scriptable object which basically holds an ability
it has a public variable called Selector
and this selector has a whole ton of properties
I want to make a custom inspector for the selector specifically
so it shows up on the scriptable object
is that a thing I can do?

#

I want to edit the region in yellow

wispy delta
#

Yes use a property drawer

errant finch
#

I have never done editor scripting

#

can you explain it like I'm 5

#

oh wait do I just extend from propertydrawer as opposed to editor?

#

and do custompropertydrawer?

wispy delta
#

You cannot create a custom editor for arbitrary classes and structs, only monobehaviours and scriptableobjects. Custom editors are for inspectable things. You aren't inspecting the SelectorData you are inspecting an object that encapsulates a selector data instance. If you want to override the default way Unity draws a serializable class in an inspector you must create a property drawer for it in the same way you'd create an editor for a monobehaviour or scriptableobject

#

It's basically the same thing as a custom editor, but it's for arbitrary classes. Look it up and you'll find plenty of examples

errant finch
#

ya I found some

#

ty

#

wait just to make sure

#

do propertydrawers needs to be in an Editor folder?

wispy delta
#

Yes

#

Any code that uses anything in the UnityEditor namespace needs to be in the editor folder

errant finch
#

doesn't seem like anything I do changes the inspector

#

ooooh wait

#

nvm

#

errr is there any better way than giving a string to FindPropertyRelative?

#

that's pretty gross

wispy delta
#

It is a serialized property so strings are to be expected

visual stag
#

Gross is the way to go

errant finch
#

😦

wispy delta
#

And it's editor code so the level of acceptable grossness is much higher

errant finch
#

who needs clean code anyway

#

good god

#

man I just want some new things to appear when I select a certain enum

#

y dis gotta be so complicated

wispy delta
#

What do you mean

#
if (property.enumValueIndex == whatever)
   DrawConditionalGUI ();
dawn thistle
#

sounds exactly like what i said a few days ago

#

ill go write up some actual code for this for you

visual stag
#

these properties are often private so they need to referenced via string

errant finch
#

oooh that makes sense

dawn thistle
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public class EnumTest : MonoBehaviour
{
    public SomeEnum someEnum = SomeEnum.OptionOne;
}

[CustomEditor(typeof(EnumTest))]
public class EditorEnum : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        EnumTest enumTest = (EnumTest)target;
        switch (enumTest.someEnum)
        {
            case SomeEnum.OptionOne:
                EditorGUILayout.LabelField("Option One is selected");
                break;
            case SomeEnum.OptionTwo:
                EditorGUILayout.LabelField("Option Two is selected");
                break;
            case SomeEnum.OptionThree:
                EditorGUILayout.LabelField("Option Three is selected");
                break;
        }
    }
}

public enum SomeEnum
{
    OptionOne,
    OptionTwo,
    OptionThree,
}

very messy but this does what im guessing you want

visual stag
#

Oh is it highlighted but my iPad doesn’t do it

errant finch
#

oh um, I'm doing a propertydrawer

wispy delta
#

You can always sacrifice the ease-of-use of serialized properties/objects and do all the undo/multi selection support yourself. It'll be more explicit and you can modify properties instead of fields, however youll likely end up using a ton of linq and writing a ton of repetitive code

#

Yeah there isn't code formatting on mobile for some reason

visual stag
#

Sucks

errant finch
#

mobile trying to keep the coding man down

dawn thistle
#

i dont think that property drawers are much different. are they?

wispy delta
#

Different from what?

dawn thistle
#

Igotlazy says that they're using a property drawer, unlike what i shared

errant finch
#

wait but the thing is that I need to redraw the whole inspector

#

it's just some things I only want to show up during certain conditions

wispy delta
#

He's not using it for just the enum. The enum is drawn in the drawer

visual stag
#

Property drawers are just editor styling for fields that use EditorGUI.PropertyField to draw

wispy delta
#

Check out my snippet above if you are using serialized properties for the enum @errant finch

errant finch
#

oh shit boys

#

I think it's doing a thing

#

oh here's a question

#

how do you represent a sprite as it's actual sprite

#

instead of the name

#

you know what I mean?

#

which method

dawn thistle
#

like... do you want to draw a sprite in the inspector?

wispy delta
#

DrawRect with a guicontent that holds the texture I think

#

Haven't had to do that before

#

Nope, not that

visual stag
#

The source code for the editor is your best friend

errant finch
#

k so this isn't working

wispy delta
#

You are setting it to null constantly

#

Assuming the property has a serialized SelectionType field you'd wanna use that

errant finch
#

also getting these

wispy delta
#

What line does the error point to, if any

errant finch
#

this is very unintuitive

#

the editor one makes significantly more sense

#

whats my version of "target" here?

#

still not working

#

error on the enumpopup line

wispy delta
#

The property is your target

errant finch
#

ok

#

so what am I doing wrong in the pic

wispy delta
#

Probably won't fix the error, but you are completely sidestepping the serialized property. I'd advise you accept the sin which is using strings, otherwise you might as well not use serialized properties. I'm on mobile so I don't want to type up how serialized properties should be used. Just look at any of the editor source or documentation

#

You'll notice 99.9% of editor code, written by Unity, that draws the editors you use every day, use serialized properties and strings

errant finch
#

do I cast it or something what is this

wispy delta
#

Look at examples or documentation. You're asking me to reexplain something that you can find on your own easily

digital void
#

First of: in propertydrawers you cannot rely on the GUILayout-mechanisms, so your enum-GUI wont work at all right now. You have to do layouting yourself based on the provided position-Rect (you can set a requirement on height for this rectangle through overriding GetPropertyHeight). Just manipulate the position rect and/or create new rects as needed within OnGUI.
In terms of using serializedProperty correctly, you're best of trying to avoid casting the property back to it's original type, and rather work on the raw serialized data:

            var selectionTypeProp = property.FindPropertyRelative("selectionType");
            //either of these should do: 
            UnityEditor.EditorGUI.PropertyField(someRect,"Some Label", selectionTypeProp);
            selectionTypeProp.enumValueIndex = UnityEditor.EditorGUI.Popup(someRect, "Some Label", selectionTypeProp.enumValueIndex, selectionTypeProp.enumDisplayNames);
#

then to do the checking you can do this:

switch((SelectorData.SelectionType)selectionTypeProp.enumValueIndex) {

    case SelectorData.SelectionType.AoE:
    //doStuff
    break;
    case SelectorData.SelectionType.AreaPick:
    //doStuff
    break;
//... etc.

}
wispy delta
#

I think it would be really cool if I could override hover-tooltip GUI. It would let me have super informative in-editor documentation. If I was a better programmer I could do something cool like make hovering over a property show it's markdown documentation.

visual stag
#

As in do more than show text?

#

I haven't yet done tooltips in UIElement, but if they are limiting I plan on making something to inject modifications into them

#

So remind me in 2 weeks time :P

wispy delta
#

Ok haha

#

I wanna learn more about this injection you are doing. Sounds really powerful. Does it only work if the gui being injected into is drawn with UI elements?

visual stag
#

No, it would only work by injecting uielements

#

My kittens thing could put cats in tooltips

#

So I figure I can adjust the tooltip window panel size and put my own stuff in there

#

It would be painful to get the hover event and to associate gui with it in imgui though

lyric tide
forest vortex
#

yeah this group is about coding editor scripts, not about general scripts

#

might want to ask in general-code

lyric tide
#

Sorry about that. Will relocate.

meager copper
#

hey guys may u can help me, i have a dropdown in a custom inspector and i use a private bool for it

#

with the attribute [SerializeField], i dont change the value in the code (just with the foldout click) but if i switch the gameobject its get false again, how can i save the last state of the bool?

forest vortex
#

so you want the editor to show the same value for the foldout, but no matter which object you're editing?

mental wind
#

if that's what you're looking for, you should make it static

meager copper
#

it should keep the value if i open all things in the treeview, and change my object just to came back to it, it should be still open, actual the bool gets false and the dropdown closes

#

static will help?

mental wind
#

oh i see

meager copper
#

ahh

#

thanks works 😄

mental wind
#

oh! great lol

meager copper
#

are u suprised? xD

#

it was ur hint 😛

mental wind
#

well you were trying to do something different than i thought but i'm glad that worked lmao

meager copper
#

😄

#

omfg i tried this since i think, 45 minutes

#

didnt thought about to declar it as static

mental wind
#

yeah i guess static variables in custom editors are serialized more reliably than other ones

meager copper
#

ohh u solved a 2nd issue with that 😄

#

thanks again 😛

mental wind
#

no prob

visual stag
#

Static variables are not serialized, but are persisted. It will mean all the inspectors share the same value. If you wanted it per-object you were probably not dirtying with an Undo or SerializedObject functionality and it never registered the change

craggy sedge
#

Note: static variables are only persisted until a script recompile, or until you enter/exit play mode

mental wind
#

gotcha. interesting! makes sense that static variables are persistent.

meager copper
#

ahh nice to know

#

static is enough for my usage 😃

dim walrus
#

Is there any way to check if the scene is right now a prefab preview?

#

I'm doing stuff with scenes in the editor with code and opening prefabs and changing the scene looks like a bad idea

meager copper
#

Someone may has an idea why it just skips over the AddListener and gives no error? btn has the right value, i checked it in the debugging

    void Start () {
        
        for(int i = 0; i < colorButtons.Count; i++)
        {
            int cI = i;
            btn = colorButtons[cI].GetComponent<Button>();
            btn.onClick.AddListener(() =>
            {
                UmaCharacterCreator.characterEditor.OnUmaColorButtonClicked(colorButtons[cI].umaColor, colorName);
            });         
        }
    }
#

sorry wrong channel

fresh shell
#

Does anyone know a workaround to make a menu item hotkey just a single letter without having it interact with trying to type( ie if you have a hotkey for P or shift+P you can no longer type that letter or the capital for the latter)

forest vortex
#

you'd have to make it something you don't usually type

#

like Ctrl-P or Shift-Alt-P

wispy delta
#

I'm getting an error saying I shouldn't be accessing the targets array from within OnSceneGUI, but I'm not touching it anywhere. Any ideas?

#

It's triggered when i click on an object with handles whose colors are loaded from a scriptable object singleton. ie: if it doesn't exist, one is created in the project. The error only occurs when one has to be created.

red gorge
#

@wispy delta I would try to ensure the settings asset has been created before OnSceneGUI is run. Perhaps in OnEnable(). Creating the asset in that method must be accessing the targets array.

wispy delta
#

Bummer. Guess I'll have to add EnsureSettings()to roughly 40 custom editors

red gorge
#

Is there really a need to dynamically create the asset?

wispy delta
#

When else should I create it. Lazy instantiation seems fine?

red gorge
#

If it just exists in your project, you don't need to worry about that

craggy sedge
#

What if you had one of those InitializeOnLoad tags on a function in the class that creates it? So it gets created on script recompile if it doesn't exist already

#

I think at that point it would run even before OnEnable

wispy delta
#

I should consider that @craggy sedge, but that would present an issue if the user accidentally deleted the asset. It wouldn't be recreated until the next time code is recompiled. And it's in an asmdef, so tmk they'd specifically have to change my editor code since it doesn't have any dependencies. For what it's worth, this is a tool that I plan to sell. If I was the only one using it I wouldn't mind recompiling

red gorge
#

Another option would be setting a flag that the asset needs to be created in OnSceneGUI and using a default value, then creating the asset in the editor update loop if the flag is set

#

Probably prone to some visual weirdness if OnSceneGUI isn't called often though

wispy delta
#

I think the best option may be to create it in an InitializeOnLoad method, and if the edge case where the asset is deleted occurs my singleton may throw an error when it creates the asset but who cares.

wispy delta
#

How do I move a menu-item "folder" further down it's list of menu-items. I know how to change the priority of the "leaf" item, but not it's container item

craggy sedge
#

I think the priority is set as a 'whole', if that makes sense

#

So set the priority much higher on the inner items, and it should move the folder down

#

You may have to restart Unity to see that effect

wispy delta
#

That did it, thanks. Would be cool to see something similar to the Script Execution Order window. Might be overkill, but everyone's menu items are scattered amongst the Unity ones.

visual stag
craggy dock
#

Is there a way to make a button fill a percentage of the available space in the inspector? What I want to do is make a horizontal row of three buttons all 33.333% wide no mater the text inside them.

#

that way multiple rows of three buttons would line up

wispy delta
#

@craggy dock There may be a better way, but you could reserve the total space you want the three buttons to fill with GUILayoutUtility.GetRect. Split the returned rect into three parts and draw your buttons inside them.

#

This should give you a container rect to split that stretches to fill the width but has a predetermined height

var containerRect = GUILayoutUtility.GetRect (1, buttonHeight);
craggy dock
#

Thanks @wispy delta !

wispy delta
#

np, lemme know if it works 😃

craggy dock
#

Ok I have been reading the docs ect... how do I split the containerRect put the buttons in it?

wispy delta
#

@craggy dock

int padding = 2;
// Get the container rect and reserve it's space in the layout
var container = GUILayoutUtility.GetRect (1, 50);

// Set the left, right and middle rects equal to the container to start
var leftRect = new Rect (container);
var middleRect = new Rect (container);
var rightRect = new Rect (container);

// Calculate the two x positions that create the three-way split
// one third across
var middleLeft = container.xMin + container.width * (1f / 3f);
// two thirds across
var middleRight = container.xMin + container.width * (2f / 3f);

// Make the right side of the left rect flush to the left split
leftRect.xMax = middleLeft - padding;
// Make the middle rect flush to the split on it's left and right
middleRect.xMin = middleLeft + padding;
middleRect.xMax = middleRight - padding;
// Make the left side of the right rect flush to the right split
rightRect.xMin = middleRight + padding;

// Draw the buttons on their rects
GUI.Button (leftRect, "Left");
GUI.Button (middleRect, "Middle");
GUI.Button (rightRect, "Right");
craggy dock
#

Wow thanks @wispy delta Unity editor GUI scripting is a whole different animal than the WPF and XAML I do for my day job.

visual stag
#

Come to UIElement in 2019 and then It’ll be very familiar

wispy delta
#

@craggy dock Np. It's weird but once you get a basic handle on the weirdness it's fast to get stuff up and running

#

If I ever need help with WPF or XAML I'll ping you haha. I've never touched those in my life

craggy dock
wispy delta
#

very nice 👍

craggy dock
wispy delta
#

happy to help 😃

craggy dock
#

those unaligned buttons were driving me nuts! Now to fix the rest of my buttons lol.

wispy delta
#

@craggy dock If you want splitters that are a solid color/line I've got a method that makes it easy to draw. (vertx actually wrote this, but I tweaked it a bit) If you set wideMode to true the splitter will stretch completely across whatever window it is drawn in rather than it's enclosing layout rect.

public static void Splitter (float padding = 3f, bool wideMode = false)
{
    GUILayoutUtility.GetRect (1f, padding);
    var rect = GUILayoutUtility.GetRect (1f, 1f);
    GUILayoutUtility.GetRect (1f, padding);
    if (Event.current.type != EventType.Repaint)
        return;
    if (wideMode)
    {
        rect.xMin = 0f;
        rect.xMax = Screen.width;
    }
    var color = EditorGUIUtility.isProSkin ? new Color32 (30, 30, 30, 255) : new Color32 (153, 153, 153, 255);
    color.a = GUI.color.a;
    EditorGUI.DrawRect (rect, color);
}
#

If you like your splitters, that's fine - just thought I'd show you another easy option

craggy dock
#

oh that is nice!

dim walrus
#

@visual stag Thanks that's exactly what i was looking for

peak lava
#

@craggy dock sorry for the ping. But do you use any packages in wpf, like Fody, for auto triggering property changes?

gloomy chasm
#

@craggy dock If you want another way to do it. I do GUILayout.width(Screen.width / 3)

wispy delta
#

You could do that but I don't believe you can do padding easily

craggy dock
#

I ended up making a function that will return me a row with how ever many columns I want even does padding! Thanks @wispy delta for the inspiration.

    private List<Rect> GenRow(int columns, int rowHeight = 50, int vertPadding = 2)
    {
        List<Rect> row = new List<Rect>();
        int padding = 2;
        //Vert Padding
        GUILayoutUtility.GetRect(1,vertPadding);
        // Get the container rect and reserve it's space in the layout
        var container = GUILayoutUtility.GetRect(1, 50);
        float colWidth = (container.xMin + container.width) / (float)columns;

        for(int i=0; i<columns; i++){
            Rect tmp = new Rect(container);
            if(i>0) tmp.xMin = i * colWidth + padding;
            tmp.xMax = (i * colWidth) + colWidth - padding;
            row.Add(tmp);
        }

        return row;
    }
#

to use it you just call


        List<Rect> row = GenRow(3);
        GUI.Button(row[0], "B1");
        GUI.Button(row[1], "Button2");
        GUI.Button(row[2], "Test B3");
craggy dock
#

Buttons are so so so much tidier than before!

craggy dock
wispy delta
#

Very nice, well done !

zealous ice
#

Any idea how to add rich text to help box in custom editor?

weak cove
#

You would need to change gui style richText property GUI.skin.GetStyle("HelpBox");

zealous ice
#
var style = GUI.skin.GetStyle("HelpBox");
style.richText = true;
EditorGUILayout.HelpBox(text, MessageType.None);
```Like that? Never knew there was such option
#

I've added one line to make it "safe"

var style = GUI.skin.GetStyle("HelpBox");
style.richText = true;
EditorGUILayout.HelpBox(text, MessageType.None);
style.richText = false;
weak cove
#

I just wanted to write that you can restore it to be safe ;d

zealous ice
#

:P I was faster

digital void
#

alternatively you can also avoid editing the skin altogether by doing something like this:

    public static readonly GUIStyle richTextHelpBox = new GUIStyle("HelpBox")
    {
        name = "richTextHelpBox ",
        richText = true
    };
// ...
    public static void NonFocusStealingHelpbox( string text, MessageType msgType )
    {
        //HACK - helpbox steals focus when disabled/enabled (i.e. if it's drawn within an if-block), this will prevent it
        GUILayout.Label( EditorGUIUtility.TrTextContentWithIcon(text, msgType), richTextHelpBox );
    }
#

then again, you might not want to define new static styles all over the place, but I still found this one very useful as it also solved an issue for me with focus-stealing helpboxes earlier

gloomy chasm
#

Is there a way to enter Prefab Mode from script?

wispy delta
#

@gloomy chasm I believe you want PrefabUtility.LoadPrefabContents() or PrefabUtility.LoadPrefabContentsIntoPreviewScene()

gloomy chasm
#

Hmm, thanks @wispy delta.

What I was hoping to do is use the Prefab Mode view to edit a scriptableobject with some handles. But I guess I would be surprised if that was really possible.

wispy delta
#

ScriptableObjects arent prefabs so that wouldnt really make sense

#

You could make a script on a prefab store a unique copy of a scriptable object if you wanted to, but at that point you're kinda sidestepping the entire point of scriptable objects

gloomy chasm
#

Yeah, I have a pretty niche use for it.

#

Using scriptable object as a 'mesh shape' that I extrude along a path. So the scriptable object has verts that I want to be able to move around

wispy delta
#

Hmmm. If the shape's points are in 2d I'd consider just making a custom window for moving and adding points

#

You could probably even do 3d in a custom window, but I'm not familiar with how

gloomy chasm
#

Oh, you know what. That would be easier 😛

#

Thanks

gloomy chasm
#

I was wondering. How does one make a custom Handles.CapFunction?
Mostly asking for the functionality of the drawing settings in it. So I could use Handles.FreeMoveHandle that had a custom 2D image instead of the normal ones.

wispy delta
#

It's a delegate so just make your own function with a matching signature

#

If you scroll up a bit, @lucid hedge and I made a simple "hack" to draw our own controls over a previously made cap

gloomy chasm
#

I was figuring it was a delegate. I'm sorry I don't understand how to tell it what it looks like though.
I couldn't find when you and Alexander were talking and figured this out. Maybe I didn't scroll high enough?

wispy delta
#

@gloomy chasm when i don't know what arguments a delegate requires i just create an anonymous method and add arguments until the errors go away. Then I can mouse over the temporary arguments, see what type they are, and rename them
So i'd do
handleCap = (a) => {}
If there's an error
handleCap = (a, b) => {}
If there's still an error
handleCap = (a, b, c) => {}
repeat until no error and then you can hover over to see the argument types
There's definitely a better way to see delegate types out there. But this gets the job done for me 🤷

#

in the case of the cap function the signature is (int id, Vector3 position, Quaternion rotation, float size, EventType eventType)

forest vortex
#

all the cap types are defined under Handles

gloomy chasm
#

@wispy delta What I am wanting to do is instead of draw say a cube, or a circle. To draw a custom image/icon.

indigo briar
#

Hi. I have a little problem: My Unity does not detect my skripts as mono behaviour anymore.

forest vortex
#

what makes you say that

#

if you mean the text view on the right, that's just a preview of the contents, that's normal

#

if you want to edit the properties, the scripts have to be on a gameobject in the scene, or on a prefab in the assets

#

you can't get the component menu from clicking on the script directly.

indigo briar
#

yes. but they works no more. the error message is up right.

wispy delta
#

you have a variable with the same name as the class

forest vortex
#

yeah i couldn't see the error since it was so tiny

#

but that error usually means the class name has a problem

#

it can also happen if your class name has a space in it, or doesn't match the filename of the file

#

but the error is clear there's a variable named spawn inside Spawn Class

#

it's the red error lower left that matters

wispy delta
#

@gloomy chasm you'll likely have to delve into the Graphics class

gloomy chasm
#

Oh, okay.

forest vortex
#

until you fix all red errors, it can't compile

indigo briar
#

what can be wrong at the file names? they dont have a space charakter. they have worked before, but now not.

forest vortex
#

it's not filename

#

in this case

#

you have a class named "Spawn" and it contains some variable named "Spawn"

#

you can't use the same variable name as a class name

#

unless it's a reference to that class heh

#

when you open Spawn in Visual studio it should highlight the problem.

indigo briar
#

ok, but the other scripts dont work too.

forest vortex
#

yes need to fix each one

#

that's what the console is for

#

to show you all the warnings and errors

#

for now just worry about errrors

indigo briar
#

Assets\Scripts\Spawner1.cs(41,49): error CS1061: 'GameObject[]' does not contain a definition for 'Lenght' and no accessible extension method 'Lenght' accepting a first argument of type 'GameObject[]' could be found (are you missing a using directive or an assembly reference?)

forest vortex
#

Lenght is probably a misspelling for Length

#

and not sure about the other

#

just open the files and the problem wil be in red

#

or i guess that is all one error, i thought it was two at first lol

wispy delta
#

if you double click an error in unity it will take you to the line where the error is. double check your spelling and you'll fix a lot of errors

indigo briar
#

moving and killing are the scripts, that are assigned to the gameobject "Ghost". They have worked before few days.

#

ok, i wlill try that.

forest vortex
#

well someone must have changed them because they have misspellings and other errors that would never compile

indigo briar
#

Thank you very much, guys, IT WORKS NOW!!!!

visual stag
#

That's good 😌 next time #💻┃code-beginner is the correct place for such questions. This channel is for extending the Editor 👍

indigo briar
#

Ok.

wispy delta
#

The error takes me to a EditorGUILayout.Space() call right after I draw the toolbar buttons.

#

The only thing I can think is that the toolbar is the first time a Scope is used after drawing the reorderable list. Would an exception in the list gui cause a scope to not be disposed or something?

#

But to my knowledge there aren't any scopes drawn in the list so idk

visual stag
#

It’s the classic pain that is returning in the layout phase before the repaint

#

If you return before all the controls are layouted when it comes to repaint a layout will not have been registered for the following controls

#

Sometimes this means you don’t return in layout, other times it means you if else instead of returning... it’s a weird scenario

#

I think there is also an EditorGUI.ExitGUI or something similar that is undocumented that is intended for use in this circumstance

#

If you understand the issue as I’ve described it you can probably find a solution that works for your specific code

#

(I’m currently on a plane so I can’t be of more help lol)

wispy delta
#

Thanks for the explanation! I guess I'm still confused as to why double-clicking the object field causes the error, but manually selecting the game object (that double-clicking the field would have selected) doesn't? I guess it means the error issue is in the property field for the list element?

visual stag
#

I’m not sure without a deeper dive, sorry. But it should be to do with an incomplete layout phase, or a mismatched one. Sometimes I’ve had circumstances where I feel it’s unity’s problem and I just suppress the error sadly.

#

But more often than not it is me that’s the problem of course

wispy delta
#

Yea I'm sure it's something I've done wrong. It must have been a change I made relatively recently because it hasn't been a problem till today. I'll look through my commit history and see if anything looks fishy. I appreciate the help as always 😃

visual stag
#

As long as you have that concept of two passes that I’ve previously mentioned. One being layout, the other repaint. And understanding that guilayout calls need to be the same across both you should be able to understand the issue

#

No worries 😃

wispy delta
#

I'm pretty sure I understand it - tho I'm not sure of how often that would come in to play. Is OnInspectorGUI called twice and all the Unity methods do layout stuff in one and drawing in the other? If so, I can't think of a scenario in which anything would change between calls.

visual stag
#

If you have a button that adds content, or returns, or removes

#

You may get the down event in layout, then modify the collection you're drawing the gui over, then repaint happens and there's a difference

wispy delta
#

I see. It would make more sense to me for any input to only be read in the draw phase, but I have a limited understand of the system and I'm sure there's a good reason for it not to be

wispy delta
#

Long story short, the problem was I foolishly added a try catch (Exception e) around the list gui and there was an important error happening in there that I didn't know about.

#

Short story long, I'm running into issues with list serialization again. @visual stag we were able to detect changes made by the drag n drop gui and force the serialized object to update since all that code was in the Deformable editor, but now I'm running into the same issue when adding elements to the list from an external custom window. I don't have access to the Deformables custom editor from the window, so I can't force it to update. Right now I'm just doing this brute force solution and the problem seems to be solved

serializedObject.SetIsDifferentCacheDirty ();
serializedObject.Update ();
deformerList.DoLayoutList ();

Is this bad?

visual stag
#

Beautiful. My inflight WiFi ended and now I'm on a bus. Hm, seems not great. I'd try a bunch of stuff to attempt to trigger the change, or perhaps make a static bool where you can dirty it for the editor

wispy delta
#

Ok, will do. This whole list serialization has really becoming *become (I literally cannot spell) a pain in the ass. Is it worth filing a bug report over, or do you think it's intrinsic to how the whole thing works?

visual stag
#

If you can make a good test case, yeah, definitely. If it's not a bug it'd be great for the devs to explain the exact issue

wispy delta
#

Ok cool. I'll make a reminder to myself to put together a simple test project to make it easy to see.

visual stag
#

I have multiple simple bug reports that bounced back at me because I haven't provided code, and some are too complicated. So whilst the QA people are great I feel without a succinct report and example the pain of reporting can be great

wispy delta
#

Yea. I'm worried about this one b/c I understand the issue but it's kinda hard to explain

visual stag
#

I usually make an editor windows with multiple buttons, one that's how it should work, and the other with the correct code but the broken behvaiour

wispy delta
#

problem solved 😑

list.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) =>
{
    try
    {
        // 30 lines of ui code
    }
    catch (NullReferenceException)
    {
        list.serializedProperty.serializedObject.SetIsDifferentCacheDirty ();
        list.serializedProperty.serializedObject.Update ();
    }
visual stag
#

Oh yeah that was one of our solutions hah

wispy delta
#

but now im doing it in two places lmao. i still have to do it where you did it haha

#

im gonna vomit

visual stag
#

It's beautiful because it works

grim monolith
#

Anyone knows how to set the inspected entity? I want to show the same thing the Entity Debugger window shows when you click an entity

ancient sable
#

Hi everyone, as it relates to building a .net3.5 library release, is it even remotely possible to exclude a script from the exported dll even when code in the class library is dependent upon the code i want to exclude from the released library build.

The dll would require access to script that was excluded so i have that script in my Unity project and the dll will also be in the project.

craggy sedge
#

I'm not sure I entirely understand your question, but I think the answer there is 'no'

#

It's easy to exclude code from a compile via use of #defines and such, but if some of your code is referencing what you want to exclude, it won't compile

forest vortex
#

i think it could be done if both sets of code were compiled into separate dlls, then you could supply just one of the dlls

#

but i have no idea how to wrangle it into doing that

#

i'm not sure if namespaces create separate dlls, or asmdef files could induce it, or you might have to compile the code externally. hopefully someone else well versed in how compilation works will happen by

craggy sedge
#

asmdef files will create separate dlls, yeah

#

You can compile them externally but it'll probably be easier to use the asmdefs -then you can easily control inside of Unity which asmdefs reference which other ones

#

And you can catch cross-referencing issues pretty quickly

#

If you bring in an externally-compiled C# dll, I think Unity will always include it in your build

forest vortex
#

so he could put most of his code into one folder with an asmdef, and the one other piece outside that folder, and split it up that way as two DLLs

craggy sedge
#

Yeah

#

Ruchmair's question sounded more like they wanted to exclude small, specific sections of code

forest vortex
#

yeah but if they just put the code they want to exclude into one file, i think this could work

#

well one or more files

#

each group can be as many files as they want

craggy sedge
#

Yeah depending on the exact rquirements I agree that would be easier

ancient sable
#

two deparate dlls would work , i would just add a reference the libraries as is necessary. however since the dll would still be referenced in the other dll . the dll that uses the reference would not work in unity since unity will say that the referenced dll is not found ( while writing , i think i figured out a way to make it work)

asmdefs, I've never looked deeply into that 😬 I will do that.

craggy sedge
#

Yeah, you have to make sure to write the code such that the other dll could be removed without issue

#

In general the more you can keep code dependencies one-way only, the better

forest vortex
#

oh i thought he didn't want it to work unless they are given the second dll lol

#

but yeah if you want it to still function, i think you have to give them source code so they can compile out any missing parts using #ifdefs

#

or do some really ugly stuff

craggy sedge
#

Ohh, huh

forest vortex
#

like use reflection! dun dun dun

craggy sedge
#

I'm certain you can load dlls dynamically, but yeah that's a bit more complex

#

And depending on your target platform, may not actually be possible

#

(can't load code dynamically in iOS, for instance)

forest vortex
#

yeah there are ways to do it

ancient sable
#

its as Giometric said, i only want to exclude some code. the excluded code is already in Unity. so the solution i thought of is , compiling two dlls but the referenced one will have a single enpty code in it. then i place both in unity. Unity wont say that the referenced dll is not found.

#

its not the most beautiful solution but i can make use of the second dll later on

craggy sedge
#

When you say exclude code, do you mean exclude it from builds only?

ancient sable
#

correct 😬

#

i will give it a try now

#

will let you know if it works

craggy sedge
#

I think an #if might work depending on just how much code you're talking about

#

For example,

// This part will not be compiled into the build at all, but will work in-editor
#if UNITY_EDITOR
public void FunctionToExclude()
{
    // Do some editor-only stuff
}
#endif

public void SomeOtherFunction()
{
    // Do some stuff

    #if UNITY_EDITOR
    FunctionToExclude();
    #endif
}
#

Alternatively,

// This function will always be run, but the #if UNITY_EDITOR part specifically will be excluded
public void FunctionToExclude()
{
    #if UNITY_EDITOR
    // Do some editor-only stuff
    #endif

    // Do some other stuff
}

public void SomeOtherFunction()
{
    // Call this function in both editor and non-editor
    FunctionToExclude();
}
#

UNITY_EDITOR is a define that Unity itself sets while the game is in editor-mode, and will unset when the game is put into a build. There are a variety of other ones you can use (like checking for a specific version), and you can also #define your own stuff

forest vortex
#

oh yeah, if you're just trying to not add stuff to builds, this is the way to go

#

that or put the code in the Editor folder

craggy sedge
#

Yeah, if you're wanting to do entire scripts that way, putting them in the Editor folder would work

#

(though in either case, if you happen to incorrectly reference stuff that was editor-only in some normal code, you won't find out it's busted until you try to build 😛 )

ancient sable
#

my idea most definitely .... didnt work 😂, i forgot that not only does a dll compiled with a reference still depend on that dll reference even when the necessary code exists in unity , but it also will ignore the code in unity that is the very same code in its referenced library.

#if wont work for this either. i will just go with full source code inclusion in unity

river bolt
#

not up on web archive either

forest vortex
#

interesting, never saw one of those. i'll have to try it

river bolt
#

yeah I really should have one saved by now, the default editor camera speed is unbearable for working on anything less than 1m in size

#

makes VR development really unnecessarily difficult

forest vortex
#

yes I've had a lot of problems positioning in small increments. should be handy.

visual stag
#

2019 has the setting built in now 😃

whole steppe
#

Hey, does anybody know, if it is possible to draw GUI elements over the Animator window like you can do it with the SceneView?
Thanks.

wispy delta
#

Turns out HandleUtility.GetHandleSize() is affected by the Handles.matrix and Handles.DrawingScope so if you want the size of a handle, pass the point relative to the current matrix, not relative to standard worldspace

#

This should be relevant to @lucid hedge as I now know the ladder handle I wrote for you calculated it's size incorrectly

lucid hedge
#

@whole steppe you can draw GUI elements anywhere in the Unity Editor

#

Ty @wispy delta for letting me know!!

waxen sandal
#

It's not really that easy to hook into another window to draw in there as well

grizzled minnow
#

@whole steppe Unfortunately, unlike the project and hierarchy window, the animation window doesn't seem to have any GUI callbacks to hook onto

whole steppe
#

@lucid hedge @waxen sandal @grizzled minnow Thank you for your answers! 😃

ancient sable
#

here is a quick tip.

If you have an editor window script whose editor window you wish to launch from a function call in a dll. you must reference the necessary assembly. e.g EditorWindow.GetWindow(Type.GetType("myNamespaceIfAny.MyEditorWindowClassName, Assembly-CSharp-Editor"));

wispy delta
#

I'm messing around with extending the transform inspector. There's an internal class, TransformRotationGUI that is used to draw the rotation property gui in the standard Transform editor. Is there a way to create and use an instance of the class via reflection?

forest vortex
#

not sure, I know this addon modifies the transform inspector

#

but i don't see mention of that class in it

visual stag
#

you can instance any class you want by using Activator.CreateInstance

#

so you'd get the type with something like Type.GetType("UnityEditor.TransformRotationGUI,UnityEditor")

#

then use the activator to create an instance

#

and call any methods after you've retrieved them like: type.GetMethod("RotationField", BindingFlags.Instance | BindingFlags.Public)

#

in some cases (like method overloading) you may need to provide an array of types to GetMethod to specify exactly which one's relevant

wispy delta
#

thanks @forest vortex I'm gonna try and get it to work with reflection first so I can learn more about how it works and then I'll check out the repo. If it draws a rotation field without weird quaternion to euler shenanigans I'm going to be very happy.

thanks @visual stag I didn't know about the activator class. I think I've got the gist of how it works, but Type.GetType is returning null. Any ideas? According to the cs reference, the class is in the UnityEditor namespace just like you put, so I'm not sure what it's unhappy about

#

here's the stripped version of my custom editor with the relevant bits

private object rotationGUI;
private MethodInfo rotationGUIOnEnable;
private MethodInfo rotationGUIRotationField;

private void OnEnable ()
{
    if (rotationGUI == null)
    {
        var type = Type.GetType ("UnityEditor.TransformRotationGUI");

        rotationGUIOnEnable = type.GetMethod ("OnEnable");
        rotationGUIRotationField = type.GetMethod ("RotationField");

        rotationGUI = Activator.CreateInstance (type);
    }

    rotationGUIOnEnable.Invoke (rotationGUI, new object[] { properties.Rotation, Content.Rotation });
}
visual stag
#

provide it as I have specified

#

Type.GetType("UnityEditor.TransformRotationGUI,UnityEditor")

#

which includes the Assembly

wispy delta
#

Ah, I assumed that was a misspelling lol. I guess there's another class with the same name b/c now it is throwing AmbiguousMatchException: Ambiguous match found.

visual stag
#

that's probably RotationField

#

as I said, it's overloaded

wispy delta
#

Gotcha, I'll use the overload with the types array 👍

#

I assumed it would pick the version without any arguments if you didn't specify but I guess not

visual stag
#

you ask too much 😛

#

if things just worked as expected there would be no work to do

wispy delta
#

haha you're absolutely right

visual stag
#

and now you can do anything with your new reflection knowledge

#

ignore the "internal" keyword just by simply typing 100 lines of verbose string-referenced code

wispy delta
#

lol yea. there's a whole new world of builtin editors to ravage

forest vortex
#

so what does that do, make the rotations whole numbers only?

wispy delta
forest vortex
#

i see. I'm guessing that tweaked inspector i linked to does it the quick and dirty way

#

i haven't extensively used it but it looked neat with all the added features

#

but if it's going to make everything 89.9999 i probably don't want it 😛

wispy delta
#

yea it looks like it just changes the euler angles :(
the extra features look nice tho!

forest vortex
#

make a hybrid 😛

wispy delta
#

yea I guess that's the move haha. i've been grinding hard for too long on my main project so I've been enjoying taking small breaks to do simple projects that I can finish in like a day. i think this will serve that purpose

forest vortex
#

if you finish it i would love a copy 😃

wispy delta
#

yea i'll throw it on the hub

wispy delta
#

Is there a preferred/clever naming convention for storing method infos or is it whatever? im not sure if its too explicit to include the name of the type of object the method is from in the variable name

visual stag
#

I dunno, I just go MethodNameMI or PropertyNamePI

#

and ClassNameType

wispy delta
#

ok cool i'll stick with on of those

verbal wyvern
wispy delta
#

It's 7am and i never actually went to bed. i got kinda obsessed with adding the features in the repo @forest vortex linked while minimizing clutter to the editor.

I moved the "random rotation" and "snap to ground" buttons to the context menu which cleans it up a bit, but the part I'm most proud of is using reflection to draw an invisible float field over the "Scale" label so you can drag to change the entire scale vector.

grizzled minnow
#

Full disclosure: the lifetime and fading thing took 2 days 😂

craggy sedge
#

Nice, I've wanted to do something like that

forest vortex
#

@wispy delta yeah the scale label trick is pretty nice. Great job 😃

ancient sable
#

question. I have an Array of Components on a gameObject and an Array of MethodInfo for C omponents[0] for example.

what is a nice way to draw out each arrays content in a dropdown. similarly to the way it appears in the UnityEvent UI in the inspector ?🤔

#

i was thinking of pushing each Component and MethodInfo name into a string list or array which can actually serialize and using a EditorGuiLayout.Popup to draw out each component name and meThid name but i would end up with four different arrays. i would prefer to just use two

edgy aspen
#

hello, how can I add a tooltip to Editor Button?

#

I can add tooltip to the variables but not to the EditorGUILayout items?

#

When I hover to the GUILayout.Button("Add Upgrade") I want a little box appear

#

ok nvm I found the answer : I used GUIContent content = new GUIContent("Button", "Info Pop-up");

#

and put it in the GUILayout.Button(content)

ancient sable
#

any info on if we will be able to use a .net framework higher than 3.5 for managed libraries in unity ?

grim monolith
#

You can use GenericMenu and do your own dropdown logic. That way you don't have to make them serialized if you don't want

ancient sable
#

@grim monolith I'll give that a try, it looks very promising

#

also, Bunny83 (dont know his real name ), wrote a nice little SerializableMethodInfo.cs that i will be making use of later on

bronze mason
#

Hi, does anyone know if there is an event that gets fired when a material is dragged onto an object from the project window to the scene?

#

(or any similar event)

forest vortex
whole steppe
dusky plover
#

Anyone knows how to use the built-in shaders package you can download from the Unity archive?
When I move it to my project I get a few errors about seemingly missing API

#

Looking at the Unity source code repository, both of those missing properties seem to be internal scoped, and given their assembly is the Editor assembly, shouldn't I be able to see them if these scripts are placed inside an editor folder?

#

Actually, scratch that last remark, since the assembly defined by Editor folders in your project is a separate assembly than the actual UnityEditor.dll

In that case how are the built in shaders even meant to be used?

visual stag
#

@whole steppe change checks are for wrapping GUI controls to see whether they have been modified, it will not be helpful for capturing a drag-drop

whole steppe
#

Yeah, you are totally right. I've mis-read the question.... Didn't read the part where it said "scene" 😣

visual stag
#

(unless you have access to that control and scope of course, which in this case they don't) 😉

#

also ya'll can wrap links in < > to remove the pesky preview

#

I can help you there, give me a moment

#

Is the question still relevant, you deleted it....

whole steppe
#

Sorry, my post got deleted. it might have been considered as spam when I wanted to paste my shader :/

visual stag
#

which is an extension that adds disqus comments to the Unity docs

#

I have a comment on Graphics.DrawTexture that answers the question

#

If providing your own Material - it will not be clipped under other GUI elements.
To fix this provide a Shader with the following layout additions:

sampler2D _GUIClipTexture;
uniform float4x4 unity_GUIClipTextureMatrix;

struct v2f {
    float2 clipUV : TEXCOORD1;
}

v2f vert (appdata_t v) {
    float3 eyePos = UnityObjectToViewPos(v.vertex);
    o.clipUV = mul(unity_GUIClipTextureMatrix, float4(eyePos.xy, 0, 1.0));
}

fixed4 frag (v2f i) : SV_Target {
    col.a *= tex2D(_GUIClipTexture, i.clipUV).a;
}```
#

you can find an implementation in builtin_shaders\DefaultResourcesExtra\Internal-GUITextureClip.shader

whole steppe
#

First off: Thank you for your quick response! :)
So you suggest, that I add the lines above to my shader?