#↕️┃editor-extensions
1 messages · Page 93 of 1
the target character model & animation of the preview window will be defined in the EditorWindow which the preview is docked in
I would handle that by making the preview part that may or may not be toggle be it's own normal C# class, then. If you want it as it's own window you just create an instance of that class in the window and have it have a 'draw' method that you call. Same for if you have it as part of another larger window.
would i be passing in the vars in the Draw call?
I would do something like this
public void AnimPreviwer
{
public void SetAnimPreview(AnimationClip clip) => // Setup all the preview info in this method.
public void Preview(Rect rect) => // You would call this one in OnGUI and it would handle the actual previewing stuff.
}
You would call the SetAnimPreview when you change what clip you want to preview, you can change it to be a model or AnimController or whatever you need it to be. The point is to just call it once 'on setup'.
The Preview method would be the thing calling like the previewRender.Begin/EndPreview() and stuff.
That makes sense. I'll do that, thanks again.
Sure thing.
Haha, no I don't. I used to play the MechWarrior games a lot though.
I thought it might be the game, did you own any of the special mech warrior console controller things?
some of them got quite extensive
Not sure if this is the right channel for this, please direct me to the correct one if it isn't.
Can someone tell me how to install the Unity Runtime Scene Serialization package? I can't find it in the Unity Registry and I reallllly need it for something. Is there a git or tarball link I'm missing, or just a file I can download?
Add by name com.unity.runtime-scene-serialization
(I just guess on the name and it was right 😛 )
ah ok thanks
Does anyone understand how Undo.IncrementCurrentGroup actually works?
So far I have figured out that it does not seem matter if you increment before or after registering an undo. And the number of increments is not relevant if there are not more registers between them.
I've got this for creating the editor within the editorWindow```cs
public class MyEditor : Editor{
AnimPreviewUtil previewUtil = null;
AnimPreviewUtil previewEditor = null
OnGui(){
previewUtil = CreateInstance<AnimPreviewUtil>();
previewEditor = (AnimPreviewUtil)Editor.CreateEditor(previewUtil);
previewEditor.OnInteractivePreviewGUI(rect, BgColour);
}
public class AnimPreviewUtil : EditorWindow {}
Quite wrong. You are trying to make an editor for an EditorWindow and then trying to cast the editor back to an editor window.
Im not quite sure what the desired outcome is, so not sure how to advise.
i just realised it doesn't like the cast from CreateEditor
I want an editor inside of an editorWindow that displays an animation.
CreateEditor passes back an editor, which means I can't manually set an variables in the editor that it returns. I need to set 2 variables
Much like the animation inspector with the dockable preview animation at the bottom of it
Yeah, sadly the Unity Docs are really poor on this question. As best as I can tell, if you record objects one after the other it will all be considered part of one step, if you want a new step, then you should use that method and then further object recordings will be considered part of the next undo group. Unfortunately I can't actually know that because the unity docs don't tell me and I haven't experimented with it to know.
it seems through my testing that I'm not disposing of all my test windows, I now have about 50 of them active in the background and completely lost, lol
Isn't there some function to start recording of an undo group and stop recording, so lots of individual changes can be grouped together in an undo group
i mean, like GuiLayout.BeginHorizontal/EndHorizontal but for the undo/redo actions to be recorded in a group
I only read into the undo/redo stuff briefly
so, i think there might be something like a a BeginUndoGroup & EndUndoGroup
There is int undoGroup = Undo.GetCurrentGroup() and then there is Undo.CollapseUndoGroup(undoGroup) which combines all of the undo operations from the current undo all the way to the undoGroup.
that's probably what i was thinking of. using that, can i say move dozens of GO's and handle them all as a group for a single undo or redo action?
Yeah, I know how to use undo/redo. The funny thing is that even when you collapse undo operations, it doesn't change the undo index. I think there is like a second list of like object int range pairs or something.
Sure can. You could even provide 0 for the Undo.Collapse method and then every operation that has been done in the current editor session can be undone at once.
i was considering using the undo system myself. I wrote my own in the end, as i couldn't get my head round the group thing at the time
(Maybe not the fully session, I think there is a cap or maybe it gets cleared once in a while or something)
that's something my undo system doesn't have, i kept meaning to add it, but never got round to it, so technically, it'll save all undo's to file and eventually consume the entire file system, lol
What sort of undo system are you making... there is a reason people put a cap on the number of undos normally...
it wasn't anything fancy, it just records a list of gameObjects in a stack, then pops or queue's them
if you want the code, i can post it if you like
Nah, I'm good but thanks 🙂
i might change it to the unity undo system at some point, but really, what i have is better than great, it's good enough!
Yay! BSOD!
I'm tyring to work out how AvatarPreview class is initialised within https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/Inspector/AnimationClipEditor.cs#L483 I can see that it's initialised within the Init method, however how is Init called?
Init() is called in HasPreviewGUI(). ctrl + f is your friend when reading github source code.
i saw that, i'm not sure how HasPreviewGUI is called
If a call to OnInpspectorGUI is made, that explicitly calls Init(), but when OnInteractivePreviewGUI, how is HasPreviewGUI called?
It is called by Unity.
I've added an HasPreviewGUI fn to my code, but it isn't being called, are there some other stipulations that I am missing perhaps?
It is a virtual method in the Editor class.
I think...
It is either a virtual method or a 'message magic' method.
Either way it needs to be in a class inheriting from Editor.
i have all of that
it wouldn't be because of the [CustomEditor(typeof(AnimationClip))] perhaps?
@gloomy chasmI made a test class to demostrate this in an attempt to work it out https://hastebin.com/vatavuzedo.csharp
So what is it that isn't working?
HasPreviewGUI isn't being called
i'm wondering if it's because of the attribute, that when an animation clip is selected, it calls HasPreviewGUI automatically due to that
@snow bone If you are not using the CustomEditor part of the editor. It may be simpler to just not use the Editor class.
can i achieve the same result as the animation preview, but use OnInspectorGUI instead?
for the OnInteractivePreviewGUI, the docs read: " Inspector previews are limited to the primary editor of persistent objects (assets)" I'm thinking that this is directly related to having the attribute and why HasPreviewGUI isn't being called
as I'm not using it in inspect an asset in this way
ModelImporterClipEditor uses the AnimationClipEditor using it's OnInspectGUI, perhaps this is what I should be using instead
Ah, that may indeed be the problem.
I appreciate you patience. I don't know what i'm doing, I'm just working it out as I go along.
All good, I too once didn't know what I was doing with editor scripting 🙂
Can you tell me if this is the Header please?
You mean OnHeaderGUI? No it is not.
is it this part?
Sure is.
so AnimationClipEditor draws all this stuff as well?
Guess so.
I've been thinking that it draws only the anim preview at the bottom.
which does explain some of the confusion I've been experiencing trying to work some bits out, including the header
It must drwa that Loop time and stuff using some other component etc
Nah, that is all just in OnInspectorGUI 🙂
This is the part that I'm trying to make
I think that is displayed with OnInteractivePreviewGUI()
It does.
Why not just use the Editor for AnimationClip?
If that is exactly what you want.
which editor is that?
I think just doing this should work.
// Init somewhere
Editor animClipEditor = Editor.CreateEditor(animClip);
// In OnGUI of your window.
animClipEditor.OnInteractivePreviewGUI();
that throws a null ref exception.
Is the anim clip null?
no
i do checks to make sure it isn't and i double checked, stepping into the code
Debug.Log("Anim:" + editor.target.name); gives output in the console
If i provide a humanoid gameobject instead, that shows fine
Perhaps I can play the Animator on the gameobject to get it to animate the anim
@gloomy chasmThis will have to wait for another day, thank you for the assistance.
I dont get why the displaystyle is not updating properly?
Debug.Log("HandleDisplayWeapon: " + skill.weapon + " : " + weaponSpeedPenaltyPf.style.display.ToString());```
I did this everywhere and it worked fine. The difference is weaponSpeedPenaltyPf is defined in the uxml, whereas the working other stuff are VE created in C#
It's always late. Well, i had this problem before already, changed my way to this new one and it worked for everything. But apparently it's not for the uxml ones
How can I store a lot of data (>100MB) to make sure it survives a domain reload? Is there any built in editor function available of should I just serialize it to a file? It's not supposed to be editable by the user, I also can't store it in a scene.
Yeah I was looking at that just now, sounds like the solution I need!
I feel like I want to murder a Microsoft engineer right now. My computer bluescreened with something about threads and then refused to boot into windows, just the recovery environment. I tried everything and it would not recover, finally I tried the last resort of reinstalling windows while leaving my personal files untouched.... it deleted everything in both program files folders and moved out my appdata folder from my user folder.
So now, I get to reinstall all of my games from all the different clients, all the games installed into program files, all of my programs, all of my chocolatey packages, and pray to God that I didn't lose my unsaved notepad++ docs
Oh and all of my N++ plugins.
And the worst part, I have no idea what happened the first time that broke windows. Not even safemode loaded correctly.
Is it possible to reference a MonoBehaviour class from a ScriptableObject? I mean the class itself, not an instantiation of it.
I have a bunch of Monobehaviours implementing a common abstract monobehaviour. I want a dropdown of these monobehaviour in my editor. I don't want to use reflection because I want the list to be curated (drag and drop the monobehaviours reference into my SO)
if I make a public AbstractRootMono abstractRootMono in my SO, I can't drag the class file itself because it expects an instantiation. Using public Type abstractRootMono doesn't show up in the editor (maybe Type isnt serializble?)
MonoScript?
your the best @waxen sandal
does anyone know how to remove this warning?
Hi! any ideas why my window doesn't open?
https://pastebin.com/6RK9CpHr
(trying to open it at L230 here)
yeah, just resetted it, but nothing
weird thing is that it gets me errors from this window's script
it's executing the code somewhat, but... Not opening anything?
hmmm
That's something to investigate
any ideas why my property seems not set to an instance of an object l32?
no wayyyyyy
The whole function??
Possibly yeah
ok, unity didn't like that: Whenever i clicked any ui of the editor (not just mine), it logged that. Relaunching it
lol i can't even click the cross on topright 😭
it logs me an error too 😭
(not an issue, but seemed funny to me lmao)
something weird seems to be happening... The errors logs on the first time i try oppening the window, but not the other times...?
still not opening neither
What'd you change?
nothing, just put onEnable before Open
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditorInternal;
public class RequirementCW : ExtendedEditorWindows
{
//Just draw the requirement inspector...
private ScenarioLeaf leaf;
private SerializedObject soTarget;
private SerializedProperty reqSp;
private List<LeafRequirementSO> reqSos = new List<LeafRequirementSO>();
private SerializedProperty reqDisplay;
private void OnFocus()
{
Hydrate();
}
private void OnEnable()
{
Hydrate();
}
[MenuItem("Window/SCOL/Requirements Editor")]
public static void ShowWindow()
{
GetWindow(typeof(RequirementCW));
}
//[OnOpenAsset()]
public static void Open(ScenarioLeaf leaf)
{
RequirementCW window = GetWindow<RequirementCW>("RequirementsCustomWindow");
window.soTarget = new SerializedObject(leaf);
window.leaf = leaf;
window.Hydrate();
}
void Hydrate()
{
reqSp = soTarget.FindProperty("requirements");
for (int i = 0; i < reqSp.arraySize; i++)
{
reqSos.Add((LeafRequirementSO)reqSp.GetArrayElementAtIndex(i).objectReferenceValue);
}
reqDisplay = new SerializedObject(this).FindProperty("reqSos");
}
public void OnGUI()
{
if(leaf != null)
{
EditorGUILayout.LabelField(leaf.ToString(), GUILayout.ExpandHeight(true));
if(reqSp != null) EditorGUILayout.PropertyField(reqDisplay);
}
}
}
._.
yeah lol
Add if(soTarget != null) to OnEnable and OnFocus
true, true
no more errors now, of course 🥴
Still no openning though, what is this sorcery
What's ExtendedEditorWindows
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class ExtendedEditorWindows : EditorWindow
{
protected SerializedObject serializedObject;
protected SerializedProperty currentProperty;
protected void DrawProperties(SerializedProperty prop, bool drawChildren)
{
string lastPropPath = "";
foreach (SerializedProperty p in prop)
{
if (p.isArray && p.propertyType == SerializedPropertyType.Generic)
{
EditorGUILayout.BeginHorizontal();
p.isExpanded = EditorGUILayout.Foldout(p.isExpanded, p.displayName);
EditorGUILayout.EndHorizontal();
if (p.isExpanded)
{
EditorGUI.indentLevel++;
DrawProperties(p, drawChildren);
EditorGUI.indentLevel--;
}
}
else
{
if (!string.IsNullOrEmpty(lastPropPath) && p.propertyPath.Contains(lastPropPath)) { continue; }
lastPropPath = p.propertyPath;
EditorGUILayout.PropertyField(p, drawChildren);
}
}
}
}
Something i thought i'd use tbh 👀
Have you heard of Editor.DrawPropertiesExcluding
i may have not 👀
i'm not using this DrawProperties though
Try attaching a debugger and catch all exceptions
yup, was next step, really didn't want to go through that but 🤷♂️
thanks !
nothing is wrong on the debugger, lowkey kinda wanna die now
(Like this changed anything about that 👀)
What is the remaining issue?
my window isn't opening when i call "OnOpen"
(through the debugger, i can see it goes through OnOpen, Creates the instance of the window, but nothing happens in the editor)
Reset the layout

Is it possible to add a menu item to the "Edit" menu?
Sure, [MenuItem("Edit/Test")]
Yeah apparently I'm blind and didn't see my added item 😆
Thanks
Is it possible to add an item to this section of the context menu?
Adding it to the "Edit" menu doesn't populate it there
"GameObject/test"
With that way, the highest it can go on the menu is right under "Select Children" though
I want to group it with Cut, Copy, etc.
Ah not sure about that
No worries, its probably not possible :/
You might eble to cehck the reference source
How could I do that?
How is it possible to load asset from editor?
Somehow this
AssetDatabase.LoadAssetAtPath("Assets/Prefabs/GameObject1", typeof(GameObject)) as GameObject
returns null
I cant understand why
probably missing .asset
Assets/Prefabs/GameObject1.asset
So I see where they are creating the copy/paste menu items, its on the fly in the class SceneHierarchy.cs. So I don't think it's possible without modifying that class :/
well, it didnt help(
You need to include the file extension in the path.
Selecting the asset in the project browser will show its full path and extension in the bottom bar of the window. Also in the context menu for assets (right-click menu) there is "Copy Path" that copies the whole path that you can just paste in to the AssetDatabase.LoadAssetAtPath.
In UITK, I have a VE field class CollectionField : BaseField<LibraryCollection> {}, where LibraryCollection inherits from ScriptableObject, all should be fine.
However when I try to bind it I get a warning saying it is not compatible, any ideas?
Bit more googling revealed the answer to be that Unity doesn't do any sort of type conversion and so the bound type must directly be one of the base supported serializable types. In this case it must UnityEngine.Object.
I'm trying to play an animation on a character in the OnInteractivePreviewGUI```cs
private void OnGUI()
{
gameObject = (GameObject)EditorGUILayout.ObjectField(gameObject, typeof(GameObject), true);
clip = (AnimationClip)EditorGUILayout.ObjectField(clip, typeof(AnimationClip), true);
if(GUILayout.Button("Show Anim"))
{
if (editor != null || testEditorWindow != null)
{
DestroyTestEditorWindow();
}
else
{
showEditor = true;
}
}
if(showEditor && gameObject != null)
{
if (editor == null)
{
showEditor = false;
InitAnimator();
editor = Editor.CreateEditor(gameObject);
}
}
if (editor != null)
{
if(gameObject != null)
{
animator = ((GameObject)editor.target).GetComponent<Animator>();
animator.speed = 0f;
animator.Play("Default"); //Error: Game object with animator is inactive
animator.Update(Time.deltaTime); //Error: Can't call Animator.Update on inactive object
}
editor.OnInteractivePreviewGUI(PreviewRect, GUI.skin.window);
}
}
private void InitAnimator() //Creates the Animation Controller
{
var controller = AnimatorController.CreateAnimatorControllerAtPath("Assets/Test.controller");
var rootStateMachine = controller.layers[0].stateMachine;
var state = rootStateMachine.AddState("Default");
state.motion = clip;
state.iKOnFeet = true;
var animator = gameObject.GetComponent<Animator>();
if(animator != null)
{
animator.runtimeAnimatorController = controller;
}
}```
animator.Play() gives the error Game object with animator is inactive
animator.Update() gives the error Can't call Animator.Update on inactive object
Have you tried to make sure the GameObject is active?
i've read that I perhaps need to call Animation.Sample(), however I'm not sure how to get this
calling SetActive on the gameObject has no effect. I thought it had worked, but I added // instead of removing.
Several posts refer to doing Animation animation = go.GetComponent<Animation>(); but this always return null
I figured it out!
@gloomy chasm the docs for OnInteractivePreviewGUI https://docs.unity3d.com/ScriptReference/Editor.OnInteractivePreviewGUI.html say that the default implementation is a no-op, I'm assuming that If I want a zoom function, I'm going to have to write my own implementation for the Class?
is there a way to indent your editor of your custom script without making a script specifically allowing you to indent on your custom script?
What? I'm not exactly sure what you are wanting to do, but I am pretty sure the answer is no?
trying to organize my team's script, so heading in and adding headers, wondering if you can indent in the script without making a script specifically to indent in your editor. been looking around with no luck.
You could make a decorator attribute, and add it to your fields.
There is this which has a lot of pretty nice decorator attributes (Have not used it my self, but seems solid) https://github.com/dbrizov/NaughtyAttributes
So, it is either make a custom editor, or use decorator attributes, there are no other alternatives.
Okay, thanks for the help. Though I probably won't be able to use that Git link you sent since it's a school project and they want us to do it ourselves. Thanks for the info and link.
Ah, got it. It is just a simple decorator draw if you only want to indent stuff.
Has anyone experienced when all plugins fail to show up in the top menu
hmm it works in a new project
so I might have corrupted things
not a worry
If there is a compiler error and the code that adds the menu item is new, then it will not show up, idk if that could be the case for you.
Getting this error
Multiple precompiled assemblies with the same name Newtonsoft.Json.dll included or the current platform. Only one assembly with the same name is allowed per platform. (C:/Users/maxpl/Bug_Test/Library/PackageCache/com.unity.nuget.newtonsoft-json@2.0.0/Runtime/Newtonsoft.Json.dll)
Yeah, that would be an error that prevents compiling. Means you've got multiple assemblies... with the same name... in this case Newtonsoft.Json.
So I just delete one?
I'm just trying to get Quixel Importer into an empty URP project
anyway i realize this is probably the wrong channel
Hello there! How can i focus on the inspector window through script? basically open it?
thanks! What is the type of the Inspector windows though...?
it doesn't solve the problem, i need to have the window in a variable, how can i...?
like i gotta do inspectorWindow.GetType()
but i don't know how to get inspectorWindow
i'm suprised nobody asked it online 🤔
well, this dude had time to die 😳
it's not a problem, i'll just change my layout to have the inspector always visible, but that's a shame
System.GetType("UnityEditor.InspectorWindow,UnityEditor") or something like that
You can also find EditorWindows using Resources.FindObjectsOfTypeAll
Is there any way to solve this? :
https://forum.unity.com/threads/treeview-element.667324/
It says that i should be able to copy the thing
but it uses quite a few internal stuff
I don't understand why it is internal
Just give it a annotation that says that it is not finished
also how come it is not finished since like 2019
Hi! I've done a reorderable list in my custom editor, and i've put the OnItemRemoved Callback to this function: (In other words, when i click on the little "minus" icon, it's going to call this instead of a regular removing.
void RemoveLeaf(ReorderableList list)
{
ScenarioLeaf leafToDestroy = (ScenarioLeaf)pLeavesWindow.GetArrayElementAtIndex(focusedLine).objectReferenceValue;
SerializedObject so = new SerializedObject(leafToDestroy);
//Req.Remove(so.FindProperty("requirements"));
DestroyImmediate(leafToDestroy, true);
pLeavesWindow.MoveArrayElement(focusedLine, pLeavesWindow.arraySize);
pLeavesWindow.arraySize -= 1;
}
I want it to destroy the item i selected, and reduce the array size by one. It does it on the reorderable list (on the right), but then when i check on my array in the debug inspector, there are still missing elements (on the left)
(I feel like there is a lot of wrong this with this method lol)
https://pastebin.com/69UWCTgs
here is the pastebin of my custom window
Use arrayProperty.DeleteElementAtIndex(index) to remove an element from an array. If the property is of a UnityEngine.Object then you need to set it null first otherwise Unity will just set it to null instead of removing the element. (This bug was fixed in a new version of Unity, I just remember which one)
Not really a bug but rather a "feature"
Well it was under the 'fixed' section of the change log iirc.
And it feels like a bug, at least to me.
Yeah it does but I can see how it's a feature according to Unity at least
Should've been implemented differently though
Well, it doesn't matter anymore since they removed it! 😄
It's going to break some things at my last job 😄
oh well, they did remove it then, no?
oh, they removed the bug?
Hahaha, I made an extension method just because I found it annoy that it would set it null instead of remove the entry.
I don't remember what version though. 2020.3, or maybe 2021.1?
i'm going to tell you right now then :)
nope, still the same:
void RemoveLeaf(ReorderableList list)
{
ScenarioLeaf leafToDestroy = (ScenarioLeaf)pLeavesWindow.GetArrayElementAtIndex(focusedLine).objectReferenceValue;
SerializedObject so = new SerializedObject(leafToDestroy);
//Req.Remove(so.FindProperty("requirements"));
pLeavesWindow.GetArrayElementAtIndex(focusedLine).objectReferenceValue = null;
pLeavesWindow.DeleteArrayElementAtIndex(focusedLine);
DestroyImmediate(leafToDestroy, true);
//pLeavesWindow.MoveArrayElement(focusedLine, pLeavesWindow.arraySize);
pLeavesWindow.arraySize -= 1;
}```
Do you have both windows open at once when you remove it?
Shouldn't be, but they are using different SerializedObjects so if they are not updated they will get out of sync. You could try removing then switching to the debug inspector and see if you still have the problem.
wdym? I am on the debug inspector
I don't want them to go out if sync, how can i do so?
Well idk if that is the problem, so don't go trying to fix it if it isn't the problem 😛
Just close the debug inspector, remove the item in the normal inspector, then switch/open the debug inspector and see if the problem is still there. 🙂
Also, do you make sure to call ApplyModifiedProperties()?
IDK how to even phrase this question. I'll try my best. How do I create a scene type view in an editor window? Somewhere where I can do some mesh changing to essentially before I click to actually create this prefab and/or scene gameobject? At the moment I have a button that create something into the scene view where I check to see changes, then either delete or alter there, but, was thinking I could make my life easier if I just do it from the editor window I have open
Like, you just want to see a scene? So like using PreviewRenderUtility?
not necessarily. I just want to have a scene like view for I can do lets say some editing of a gameobject before I instantiate it into an actual scene. I'll check out that previewrenderutility and see if that is it!
You say "Editing of a gameobject", but what do you mean by that?
The only thing you can edit in the scene is the transform.
Everything else is done in the inspector or hierarchy.
uhhh so, if I want to view the length of a gameobject before instantiating it, and decide maybe I want it shorter or longer, possibly seeing that first
Ah, the PRU should work fine if you just want to see stuff.
yeah, thank you! https://docs.unity3d.com/ScriptReference/Editor.OnInteractivePreviewGUI.html might be exactly what I needed
@opaque zenithOnInteractivePreviewGUI is the bane of my life right now
Isn't OnInteractivePreviewGUI essentially a no-op component, meaning you can't do much with it
it has a bunch of built in functionality for panning, it will allow the viewing of a mesh and has some lighting, but you can't add stuff to it.
You can override and write your own editor script to implmenent OnInteractivePreviewGUI, but you have to then provide your own scene, lighting and rendering.
I'm trying to currently render an animated character to OnInteractivePreview, I can get it to display, but can't get it to animate
okay, I'm currently trying to see what I can do with it, I'll let you know. It might be easier to just have the editor create an editor scene that is temporary basically and just do things within that and have the scene displayed in the editor window, idk
do you want my script for displaying a game object and anim?
like, for example, I was looking into a way to add almost what the avatar configure does in an editor window
um, give me a few to see what I can do and I'll get back to, I mean, I'd LOVE to, but I also see messing with these things as sort of learning opportunity
like just found https://docs.unity3d.com/ScriptReference/SceneManagement.EditorSceneManager.NewPreviewScene.html which I want to see what I can do with
I've been looking at that today aswell
the key point is, if you do editor = Editor.CreateEditor(gameObject); you HAVE to do DestroyImmediate(editor); if you don't, you'll have up to 64 instances in unity floating around that you can't do anything about without restarting unity.
if you go above 64, good luck.
@opaque zenithAre you trying to write your own editor window using NewPreviewScene etc?
use a check, for example, in the interactivepreviewGUI
if (gameObject != null)
{
if (gameObjectEditor == null)
gameObjectEditor = Editor.CreateEditor(gameObject);
gameObjectEditor.OnInteractivePreviewGUI(GUILayoutUtility.GetRect(256, 256), bgColor);
}
looking at it right now. the page I linked doesn't have any examples of how to use it
more importantly, you need this cs public void OnDestroy() { if (gameObjectEditor != null) { DestroyImmediate(gameObjectEditor ); gameObjectEditor = null; } }
i was kind of hoping you'd found some nice pages that I could borrow from you to save me doing a more searching on it
This might be of interest to you, i found it earlier today and was cogitating it https://answers.unity.com/questions/900091/custom-scene-view-in-editor-window.html
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
I just started looking into this stuff so unfortunately haven't found much yet
I actually have that page opened right now haha
if you come up with a solution, please share it with me, i've been desperately banging my head against the desk for the last week on this subject
Awch, man I wish I could be more help to you but I would have to just spend a couple of hours looking at the source code and implementing it my self to be able to accurately tell ya how beyond "look at the source code for the AnimationClip editor".
no worries. I wouldn't expect you to. Unity implements it's own animator, which bypasses the default behaviour of using an animator on a gameobject
I've looked at a couple of examples from Animancer Pro and Motion Matching and they both seem to create their own scene and view it with a custom OnInteractivePreview or what ever they choose
You've already been of great help, i now understand much more about it than I did
@snow bone In broad strokes what I think should work is to create an instance of PreviewRenderUtility, add a gameobject to it that has an animator(animation? Whatever the component is called), and then using CreateInstance to create a animation statemachine and add the desired clip to it, and add the statemachine to the animator component, then play it. You may need to increment the time your self.
For testing and setting it up I would create a simple like "Cube moves up and down" animation and model. And for setting it up you can instantiate it in the main scene instead of the PreviewRenderUtility to more easily see what is going wrong.
Once you get it working in the main scene you can simply instantiate it in the preview scene instead.
i was thinking about that, it renders a mesh doesn't it, so i need to regenerate that mesh for each frame of the animation
What???
i might be confusing some other thing i was reading up on, i've read a lot of stuff about stuff
Basically what I said is all you should need to do. Maybe need also need to Repaint(), but that is trivial to figure out if you need to do 😛
my brain might be over-saturated with it. It'll sort itself out eventually as i work shit out
Well good luck!
i tried sorting the over-saturation out with beer & sambuca at the weekend, but i don't think it's worked
Ahahah, that's too bad.
Best advice is to simplify it down to it's most basic parts ti where it isn't even what you want, get that working, then build up to what you actually want.
that's been my approach so far, build a foundation, then I can expand upon it
Hello all. Is there a way to handle event, when i dropping asset/assets to serialized field in inspector?
I have this code for PreviewRenderUtility, which displays a character, only there's two of them, any idea why?cs private PreviewRenderUtility previewRender; private GameObject previewGo; private GameObject prefab; private AnimationClip anim; private Vector3 camPosition = new Vector3(0, 10, -10); bool showPreview = false; [MenuItem("Window/Preview Render")] static void Init() { var window = GetWindow<PreviewEditor>(); window.Show(); } private void OnGUI() { prefab = (GameObject)EditorGUILayout.ObjectField(prefab, typeof(GameObject)); anim = (AnimationClip)EditorGUILayout.ObjectField(anim, typeof(AnimationClip)); Rect r = new Rect(2, 80.0f, position.width - 4, position.height - 82); if (GUILayout.Button("Preview")) { if (!showPreview) showPreview = true; else showPreview = false; } if (showPreview) { if (previewGo == null) { previewGo = Instantiate(prefab); previewGo.hideFlags = HideFlags.HideAndDontSave; } if (previewGo != null) { BeginDraw(r); previewRender.AddSingleGO(previewGo); EndDraw(r); } }} void BeginDraw(Rect r){ if (previewRender == null) previewRender = new PreviewRenderUtility(); previewRender.camera.transform.position = camPosition; previewRender.camera.transform.LookAt(Vector3.zero, Vector3.up); previewRender.camera.farClipPlane = 30; previewRender.lights[0].intensity = 2.5f; previewRender.lights[0].transform.rotation = Quaternion.Euler(30f, 30f, 0f); previewRender.lights[1].intensity = 2.5f; previewRender.BeginPreview(r, GUIStyle.none); } void EndDraw(Rect r){ previewRender.camera.Render(); previewRender.Render(); Texture texture = previewRender.EndPreview(); GUI.DrawTexture(r, texture); } private void OnDestroy(){ if (previewRender != null) previewRender.Cleanup(); previewRender = null; if (previewGo != null) DestroyImmediate(previewGo); } private void OnDisable(){ OnDestroy(); }
I'm finally up and running enough that I can run Unity again, but when I try to open the project that I had open when the computer crashed, there's a lock on the SourceAssetDB file and it's not letting me unlock it.
@gloomy chasmAny idea why it shows two chars?
using github?
@ivory fulcrumdid you restart your pc also?
What do you mean two? How do you know there are two?
More than restarted it: My computer BSOD'ed and then refused to boot so I had to take the nuclear option of "Refresh my files" which deleted everything in "Program Files" and "Program Files (x86) which I'm VERY upset about but can't do a damn thing about
it happened while I was working on something in Unity and had the project open
@gloomy chasm there's two of them, I mean I could have double vision, but it's very unlikely
So Unity never "quit" to unlock it except for my computer hard restarting
Screenshot pls.
@ivory fulcrumthere's a post here about it, perhaps might help https://forum.unity.com/threads/unity-crashing-at-start.988481/
So now I've reinstalled some of my software and reinstalled Unity
it's weird, if i expand the window in any directions, they become one and scale together
RT?
RenderTexture
na, that's not it
I was rendering twice
previewRender.camera.Render();
and
previewRender.Render();
lol
Yup, that would do it, haha.
i made more progress getting that working than my previous attempt last week
on to animation
I to seemed to maybe be getting this working, but, now I need to add camera controls I think
what approach did you take?
I'm trying out the EditorSceneManager.NewPreviewScene() with PreviewRenderUtility()
did you look at my code above, it's a little dense, but readable. I don't think you need to create a scene with PreviewRenderUtility
Why are you doing that? PreviewRenderUtility already creates and has it's own preview scene.
I'll link my code, it's shows a gameobject
https://hastebin.com/gazibirigu.csharp in it's entirety
no idea, just an example I found. Does previewrenderutility also include the camera? Wondering why it was in there
It sure does.
yes, and lights too, that code i posted has some basic usage of all of them
2 lights to be specific.
oh okay, I'll check that out Exar
sets up camera & does some lights
is there some default camera control options with this previewrenderutility?
i haven't got the animation working yet though
it doesn't seem to have any cam controls
it just has a camera, i think they expect it to be DIY
yeah, that is not problem. I have a nice camera control script I made. I just didn't know if I was going to double down basically on using it lol
There's plenty of camera zoom & pan code in the unity github repo, i'm going to look at that after i get the animation working, see if i can get some cam controls too
just wondering if this helps, but, have you done any reanimation rebinds? I'm going to need to eventually figure this out also, so trying to look into now
note, you can either use previewRender.camera.Render(); or previewRender.Render(); the later has rudimentary scaling, the GO in preview shrinks when the window is smaller
reanimation rebinds, what do you mean by that?
like when my character dies, i can bring it back to life like the reanimator? 😄
I'll name him Frank of course
https://docs.unity3d.com/ScriptReference/Animator.Rebind.html
IDK if you need to use that with PreviewRenderUtility.DrawMesh
I've not used that before
i'm trying to make a character preview, so i can preview a character at a particular animation pose
void OnGUI()
{
if (m_clips != null)
{
GUILayout.BeginVertical();
{
foreach (AnimationClip anim in m_clips)
{
if (GUILayout.Button("Play " + anim.name, GUILayout.ExpandWidth(false)))
{
m_animation[anim.name].normalizedTime = 0;
m_playingAnim = anim;
m_time = 0.0f;
Debug.Log("Playing " + anim.name);
}
}
}
GUILayout.EndVertical();
}
}
void Update()
{
if (m_playingAnim)
{
Selection.activeGameObject.SampleAnimation(m_playingAnim, m_time);
m_time += 0.01f; //Update() is reportedly called 100 times per second
if (m_time > m_playingAnim.length)
{
m_playingAnim = null;
Debug.Log("Done playing " + m_playingAnim.name);
}
}
}
something I just found if that helps at all
and when you open the window, in onenable or somewhere have it populate an animationclip list
I tried AnimationMode.SampleAnimationClip(go, clip, time) but that failed for this approach, maybe that will have more profit
I'll try that, thank you
It wasn't the code I was looking for, however, it led me to the right destination, so that's fantastic!
I just added 1 line; anim.SampleAnimation(previewGo, time); and it works nicely
nice! GG
I think that snippet refers to an Animation, while I'm using an AnimClip, which still might be useful to me later, as I might need to use one of them also
was there anything in the post that suggested what these two vars are? Selection & Selection.activeGameObject ?
@opaque zenithDo you want the clip animation version with simple follow?
yes please
@snow bone just slapped this together with some copy and paste, could probably be a little better, but, just changed some of my in game stuff to events so a little sloppy.
Camera previewSceneCamera;
float minDistance = 0;
float maxDistance = 20;
float minXRotation = -90;
float maxXRotation = 90;
float zoomSpeed = 20;
float moveSpeed = 20;
float currentDistance;
float rotateX;
float rotateY;
Quaternion currentQuaternion;
Vector3 offset;
void CameraControl()
{
if (currentEvent.isScrollWheel)
{
currentDistance += (currentEvent.delta.x + currentEvent.delta.y) * Time.deltaTime;
currentDistance = Mathf.Clamp(currentDistance, minDistance, maxDistance);
}
if (currentEvent.isMouse && (currentEvent.button == 0 || currentEvent.button == 1))
{
rotateX += currentEvent.delta.y * Time.deltaTime;
rotateY += currentEvent.delta.x * Time.deltaTime;
rotateX = Mathf.Clamp(rotateX, minXRotation, maxXRotation);
currentQuaternion = Quaternion.Euler(rotateX, rotateY, 0);
}
offset = target.transform.position + currentQuaternion * new Vector3(0, 0, -currentDistance);
previewSceneCamera.transform.position = offset;
if (currentDistance != 0) previewSceneCamera.transform.LookAt(target.transform.position);
else previewSceneCamera.transform.LookAt(target.transform.position + currentQuaternion * new Vector3(0, 0, 1));
}
if you want to use for the camera in it
have
previewSceneCamera = previewRenderUtility.camera;
previewSceneCamera.transform.position = new Vector3(0, 0, -10);
previewSceneCamera.transform.LookAt(target.transform.position);
currentDistance = Vector3.Distance(previewSceneCamera.transform.position, target.transform.position);
in my OnEnable()
Something I'm trying to figure out now after messing with camera controls is the rendering distance with PreviewRenderUtility
it's almost worth writing a class specifically for the camera control
yeah possibly, I just through it into a separate function atm and called from ongui
you mean how far it can render before it starts to clip?
yeah
isn't that previewRender.camera.farClipPlane = 30;
ohh probably haha
let me see
I haven't done this much with camera through code, so forget about all those little settings
it just clips to a plane parallel to the screen at a distance
sweet! Changing that worked beautifully
i tried messing with the camera clip frustrum once, that was painful
Just put the farclipplane to whatever I allow the max distance in this
think I'll add some inspector type settings to this now to change the camera settings so don't have to do it through code
currentQuaternion I see you are bucking away from the trend instead of juust calling it currentRotation!
haha, not necessarily. I don't do comments a lot, which I know is booooooo, but, instead, I try to almost name everything for it's purpose. Since the Variable is a Quaternion and what I was editing, that is the name I ended with
oh I forgot that. In OnGUI I just have currentEvent = Event.current; and a field Event currentEvent
yeah, i figured that, i generally stumble my way through events for the gui
is the camera control in Update?
you could put it there if you want, I just put it in the onGUI also
it's doing weird stuff
I figured lateupdate sand stuff wouldn't matter
umm one last thing I forgot to mention
GameObject target; target = GameObject.CreatePrimitive(PrimitiveType.Cube); is how I have it setup in my test
need to make sure you have that set to something
so it targets
i set that to previewGo
uhhh only other thing I have repaint() called at end of ongui
not sure if that is needed or not tbh
I just kinda default put that in editor windows
I wandered about it being in Update as you have Time.deltaTime in there
OnGUI has a different refresh to deltaTime
deltaTime is between each Update as far as I know
Editor Update is quite quick in general
I might be wrong, as the renderpreview might be working on an Update as it has it's own scene etc, so it might very well be correct
haha, no idea. I'll look into that in a bit, though, if you make it better I wouldn't mind the share hehe
I think there might be some time differential as OnGUI definitely happens at less than Update.
@snow bone happen to find a way to make the background the gridbackground instead of EditorStyles.helpBox?
when you call previewRender.BeginPreview(r, GUIStyle.none);change the style from GUIStyle.none to what ever style you decide
I think there's a background texture you can set if you want something else
@opaque zenithI added a property named BgColour to the code i posted earlier, repalce GUIStyle.none with BgColour is one way
This is the best way I've found to handle stylescs GUIStyle bgColour; GUIStyle BgColour { get { if (bgColour == null) { bgColour = new GUIStyle(); bgColour.normal.background = EditorGUIUtility.whiteTexture; } return bgColour; } }
@opaque zenithI guess that with the DrawMesh function, you could draw yourself a nice floorplane and skybox also.
oh sweet, thanks for the BGColor. I'll see what I can do with the texture. I read somewhere about Drawgrid existing or something
@opaque zenith I think it's GUI.DrawTexture(r, texture); after the EndPreview(); while texture will be what ever graphics you want to add
i got a human character to draw by getting the textures from the skinned mesh renderers. normal meshrenderers would be used for normal stuff though
@snow bone I realized that I didn't need to restrain the camera like I do in my games, so I changed my camera control to
void CameraControl()
{
if (currentEvent.isScrollWheel) previewSceneCamera.transform.position -= previewSceneCamera.transform.forward * (currentEvent.delta.x + currentEvent.delta.y) * zoomSpeed * Time.deltaTime;
if (currentEvent.isMouse && (currentEvent.button == 0)) previewSceneCamera.transform.eulerAngles += new Vector3(currentEvent.delta.y, currentEvent.delta.x, 0) * rotateSpeed * Time.deltaTime;
if (currentEvent.isMouse && (currentEvent.button == 1))previewSceneCamera.transform.position += ((previewSceneCamera.transform.right * currentEvent.delta.x) + -(previewSceneCamera.transform.up * currentEvent.delta.y)) * moveSpeed * Time.deltaTime;
}
idk if you did something similar at all
so basically, scroll just zooms in and out regardless of target, left click rotates, right click moves
well thing is i don't touch the "normal inspector", just the custom window
Hi! Let me introduce my problem once again:
Here's my custom window script for visualising some object of mine more easily. I feel like i've got some problems, and i don't know where they are... For example, when i try to execute "AddLeaf", it appears my window and the object i'm inspecting are going out of sync 👀
Or remove leaf
hell, both of em
(knowing that Remove Leaf is the callback for the "remove button" of my reorerable list (aka this thingy at the bottom right:)
(and that technically AddLeaf too, but i created a custom button to encapsulate it further)
Well, first off you should apply your SO after adding or removing something
Keeping a shadow copy of Requirements is probably also something that's easily out of sync
Also, you're keeping a list to check whether items are expanded, you should not do this and use the isExpanded property on a SP
Again, you're doing a lot of bookkeepng yourself that will easily go out of sync, if you don't close all those possibilities it'll cause issues
This dynamic height thing also seems likely to cause issues
what i thought too, but it works strangely well.
Idk if it really is likely, because it's just calculating from the things i draw, so it's just on the custom window side
wdym shadow copy ? 🤔
oooooh, thanks!
wait, wdym...? You're talking about the boolean "show"*, right?
showActions[index] = EditorGUI.Foldout(ActionsFoldoutRect, showActions[index], "Actions");
yeah, what about this? Is there another way to do an easy foldout...?
Yes, e.g. actionsSP.isExpandend = EditorGUI.Foldout(ActionsFoldoutRect, actionsSP.isExpandend, "Actions");
actionsSP.isExpanded
What does that represent? What i'm trying to do is to draw a custom foldout, with all my actions drawn on ToString
Is ActionSP a new property i don't have?
would work like a charm, but the original issue of why i decided to go with an array was that i wanted each element to be independently foldable, here it seems if i open one, it open all :/
Not sure what you're exactly trying to do, but you've got a bunch of things that are not kept in sync properly with your serialized data
if you were talkiing about "Req", i just deleted it, i need to refactor my code, it's some kind of old remain
That array is one of them
basically:
- I open the window, with a ScenarioTree. This tree has a few things in him, including Leaves (-> in the reorderable list i'm doing). Those leaves have Actions and Requirements, both scriptable objects, that contains few things and a ToString override.
- On this window, i simply want to display the attributes of the tree, including a reorderable list of the leaves, customized, containing, for each elements (for each leaf):
- Requirements.ToString() + "Edit Requirements" button,
- Actions.TOString() + "Edit Actions" Buttons,
- other simple PropertyField displayed normally
(Buttons redirecting to other custom windows.)
problem is that it's partly in sync. And i either want it to be 100% sync'd, or even better, to just sync when i press the save button. But right now, it's doing bad lol
(Like maybe using pLeavesWindow to create the reorderable list, and hydrate back into pLeaves when i save)
(I feel like it was my primary intent, but got lost at some point lol)
still need help 🥲
my removing method is doing the same thing than yesterday (s/o here)
void RemoveLeaf()
{
ScenarioLeaf leafToDestroy = (ScenarioLeaf)pLeavesWindow.GetArrayElementAtIndex(focusedLine).objectReferenceValue;
SerializedObject so = new SerializedObject(leafToDestroy);
//Req.Remove(so.FindProperty("requirements"));
pLeavesWindow.GetArrayElementAtIndex(focusedLine).objectReferenceValue = null;
DestroyImmediate(leafToDestroy, true);
pLeavesWindow.DeleteArrayElementAtIndex(focusedLine);
//pLeavesWindow.MoveArrayElement(focusedLine, pLeavesWindow.arraySize);
pLeavesWindow.arraySize -= 1;
}
Has anyone released a new asset on the Publishing portal v1 recently. How long did you wait for verification?
I still can't figure out how to do a simple thing such as set the position of an EditorWindow (with UIElements/Toolkit content). Setting the "position" property seems to do absolutely nothing.
(This is Unity 2019.4.23f1 fyi)
perhaps you are using position wrong
if i have an editorwindow class and set it's position, it goes there
I’m not sure if it’s a UIElements thing somehow. I just set the position to make the top left be 0,0 for example and it makes no difference in the window position.
You are trying to set the position of an EditorWindow on the screen?
Ya just do window.position = new Rect(Vector3.zero, window.position.size);
You’d certainly think so, yes. And yet it doesn’t budge. I will dig a little deeper since at least from what I’m gathering from people here, it’s supposed to work that way.
Thank you
@snow bone how is your previewrenderutility things going today
so, trying to use HideFlags.HideAndDontSave; more in what I'm currently working on. If the user decides they want to "save" the things I'm using what is the best way to go about that? Iterate through the things with this flag and disable it? Just use PrefabUtility.SaveAsPrefabAsset?
Is it possible to have a BeginHorizontal start a new line when the contents are starting to overflow? I basically need a grid but it needs to be dynamic (I don't know the number of rows yet)
Invalid decorated editor instance. Something is screwed up
from LAM plugin , does anyone came cross same problem ?
If this is to do with an asset store plugin, use the developer's forums, this is not the place
what's editor type ? they embedded dead link , couldn't find anything about it in Google
Nobody knows
ah , something internal , only by using reflection a by code can expose it
Hello, i have a problem with my custom Attribute, when i assign my attribute along with other attribute like Range it seems to not identify the property in the CustomPropertyDrawer
Assign only custom attribute will work as normal
You can only have one PropertyDrawer at a time
does RangeAttribute use PropertyDrawer as well?
Yes
is there any other alternative?
Depends what you're trying to do
what im looking for is to Hide/Show properties on inspector if certain condition is true
I tend to write custom inspectors for that sort of thing personally.
I know others use Odin, which supports all sorts of handy attributes that can be combined.
I also think there's some implementations for combinable attributes like this one https://assetstore.unity.com/packages/tools/utilities/stackable-decorator-111270
Not sure if the latter has hiding built-in as I've never used it, but it could likely be extended to do the same
thanks
how do i get c# since i have visual studio 2017 on my mac
and does that support nested property drawers? If not, it's not gonna answer the question
I have genuinely no idea 🤖
uh my hierarchy window is kinda broken idk what happened , i cant interact with it anymore and bunch of errors popped up. any idea what could have caused it?
I am wanting to create a simple editor which lets me drag and drop a few prefabs onto an editor component and add them to a list of GOs (preumably held on the corresponding MB), but for the life of me I cannot work out how to correctly add to them in the editor, I assumed it would be something like:
var newPrefab = EditorGUILayout.ObjectField("Prefab Tile", null, typeof(GameObject), false) as GameObject;
if(newPrefab != null)
{gridTileset.Tiles.Add(newPrefab);}
It just keeps spawning more and more though, so is there a specific way to only add a prefab once its been dragged into the editor field or something?
Im trying to make a custom editor class for a class so basically it will only show certain variables depending on another variable. I have that working, but when i use that class as a field or list within another class the custom editor isnt showing. I added the serializable attribute as well. Is this possible? Or maybe im having a coding error, i can show the code if needed but didnt want to clutter the chat.
AssetPreview.GetAssetPreview is great but provides no way to change angles and all the modular tiles I show in there are basically a line... is there any way these days to change the angle of it or anything?
Nope, gotta generate a preview yourself. You can use PreviewRenderUtility to help do that.
ah ok
@queen echoyou want some code to display with PreviewRenderUtility?
It's fine I can Google it now I know what it's called, thing is I also use odin for some stuff and I don't think I can use it with that, it's a pain as all the tiles are just flat so you can't see them in previews, but not sur eif that's because the project is 2d (but has some 3d stuff)
PreviewRenderUtility is undocumented. Good luck
as with all good unity features
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
seems good enough
it's called looking a gift horse in the mouth
is there a way I can make drawsphere not drawspheres for all the children of my targetobject that also has this script?
nvm, figured it out with if (UnityEditor.Selection.activeGameObject == gameObject)
idk if there a method that extends void OnDrawGizmosSelected() to be exactly the selected?
you can provide id's to drawsphere's i think
@opaque zenithare you trying to allow the selection of a gizmo to select a gameobject or vice versa?
when I select the object make the gizmo appear
i think you want to just draw a gizmo on the current selected go don't you?
you just draw a gizmo sphere or what ever at the location of the selected game object
it sounds like you are on the right track
only, what if your activeGameObject is a child of the current gameObject? something to think about.
I actually redid my gizmo so that it wasn't included in build script anyways. New script seems to make it all work even better.
public class VerticeGizmo
{
[DrawGizmo(GizmoType.Selected | GizmoType.Active)]
static void DrawGizmoForMyScript(MeshEditor me, GizmoType gizmoType)
{
Gizmos.color = Color.yellow;
foreach (Vector3 v3 in me.GetComponent<MeshFilter>().sharedMesh.vertices)
{
Gizmos.DrawSphere(new Vector3((v3.x + me.transform.position.x) * (Vector3.one.x / me.transform.lossyScale.x), (v3.y + me.transform.position.y) * (Vector3.one.y / me.transform.lossyScale.y), (v3.z + me.transform.position.z) * (Vector3.one.z / me.transform.lossyScale.z)), .01f);
}
}
}
I just realized I'm not using the gizmotype param at all
not sure if I need to or not
so, I'm still messing with trying to do a coroutine in the editor
there is an API for progress bars now
summary of what I'm doing: this asset https://assetstore.unity.com/packages/tools/particles-effects/quick-outline-115488, which works great, has to calculate the shape of the mesh (including submeshes) that you want to glow
it has a "bake" procedure
for complex meshes, this can sometimes take up to several minutes and because it is just happening inside of the MonoBehaviour of the Outline component script, it freezes unity
I can sort of live with this, but it would be nice to not have this be such an interruption, especially because if those cached baked calculations get lost, the script tries to recreate them all at runtime....which can be really bad
I'm exploring what unity has to offer for solutions to this type of problem
since I'm sure I will run into an issue/situation like this again in the future, and regardless its a good chance to get to know how the unity editor works
(for me)
I like how unity does a lot of things for the most part, but it sort of feels a bit "tangled" for lack of a better word, in how this script can compute things at runtime, but ALSO in edit mode
there does appear to be coroutines for the editor, but they require you to use an EditorWindow
if this glow thing was something I was pretty serious about having for my project and I was constantly needing to bake complex meshes, I guess having an EditorWindow that was a "central process" of sorts that managed them all would be one approach
and the MonoBehaviour could probably communicate to that EditorWindow somehow to ask it to bake a mesh, which can then be done in a non-blocking way
is there a better approach to this than that?
I feel like the unity editor program has a shit load of "idle" time inbetween you working on various parts of the your game that it can use to do background tasks instead of blocking you out completely
There is the Editor Coroutines packages. In short all it really does is subscribe to the EditorApplication.update callback.
yeah, I've looked at editor coroutines
@gloomy chasm do those require you use an EditorWindow?
Shouldn't.
I removed the code that I had, let me find what I tried to plop in
it was basically something like this
using System.Collections;
using Unity.EditorCoroutines.Editor;
using UnityEditor;
public class ExampleWindow : EditorWindow
{
int m_Updates = 0;
void OnEnable()
{
EditorCoroutineUtility.StartCoroutine(CountEditorUpdates(), this);
}
IEnumerator CountEditorUpdates()
{
while (true)
{
++m_Updates;
yield return null;
}
}
}```
long story short EditorCoroutineUtility.StartCoroutine seemed to do nothing, inside of the MonoBehaviour anyway
The thing you pass in the EditorCoUtil doesn't have to be anything specific. It is just used to see if it has been destroyed/cleaned up by the GC. The code is relatively simple if you want to take a look at it that may help you.
The Util is literally just direct wrapper around the EditorCoroutine constructor.
so, are you saying I should be able to launch an editor coroutine from a monobehaviour?
You can launch them from whatever you would like, even a normal old C# class 🙂
hmmm yeah, it does seem to work! awesome
I must have just not been getting a life cycle method called that I was placing it in
so
unity seems to kill my editor coroutines when it reloads script assemblies 🙄
even if the change was in a totally different script
how do I make my own background task?
or alternatively....how to stop unity from killing coroutines when it reloads scripts??
100% not possible. The reason that it is killed is because it reloads all the data in the project, and static fields along with delegates are not serialized by Unity so they are reset to their default values.
You have two options, one is to keep track in serialized field of how far along the task was and what it had already done (for an index in a list or something). The other option is to disable assembly reloading until it is finished.
makes sense
Hey guys, is there any way of having a UNityEvent with both dynamic and static parameters?
I want to be able to pass some dynamic parameters to an event determined at runtime but I also want to be able to configure some of the parameters from the editor
I tried running a hello world code, but I keep getting this error, even thought I have the C# extension for debugging. How do I make the code run?
I'm working on a 3d tilemap editor and I want to draw the grid on the current working plane (to handle 3d there is an editor window to enter a y value to specify a plane to edit on) and a ghost of the tile the user would place on the grid under their mouse. What should I use to draw these things? Is it a bad idea to have my selected 3d tilemap visuals component drawing the stuff while the editor just tells it about where the mouse is and stuff?
I'm also having trouble making sure my tilemap3D is initialized. If I want my tilemap3D to function roughly like the 2d tilemap editor package in that I can just plop it into the scene and edit it, and the edits persist between editmode, playmode, and separate sessions, what should I use to hold the data? And how do I ensure that the 3d grid object is initialized and the data is loaded. Initializing in awake does work sometimes. but most of the time I find that my tilemap3d is not set up when I go to test it.
I was trying to use gizmos to draw when debug.drawline gets the job done. Now I can see what I am doing.
hey guys, in my mesheditor editor script I have this line
void OnSceneGUI()
{
meshEditor = target as MeshEditor;
for (int i = 0; i < meshEditor.MyMesh.vertices.Length; i++)
{
Handles.Label(new Vector3((meshEditor.MyMesh.vertices[i].x + meshEditor.transform.position.x) * (Vector3.one.x / meshEditor.transform.lossyScale.x), (meshEditor.MyMesh.vertices[i].y + meshEditor.transform.position.y) * (Vector3.one.y / meshEditor.transform.lossyScale.y), (meshEditor.MyMesh.vertices[i].z + meshEditor.transform.position.z) * (Vector3.one.z / meshEditor.transform.lossyScale.z)), "Element " + i);
}
}
Any ideas off top of someones head how to make it so if a vertice would have multiple elements to make them display on the GUI next to eachother instead of unreadable on top?
hmm nvm, I just realized I think I have elements being displayed I don't need to. I'm going to change instead of going based off the vertices, go based off the coordinates
I have all 24 vertices, for example, on a cube, instead of just the 8
ya
for (int i = 0; i < meshEditor.Coordinates.Length; i++)
{
Handles.Label(new Vector3((meshEditor.Coordinates[i].x + meshEditor.transform.position.x) * (Vector3.one.x / meshEditor.transform.lossyScale.x), (meshEditor.Coordinates[i].y + meshEditor.transform.position.y) * (Vector3.one.y / meshEditor.transform.lossyScale.y), (meshEditor.Coordinates[i].z + meshEditor.transform.position.z) * (Vector3.one.z / meshEditor.transform.lossyScale.z)), "Element " + i);
}
worked
Can someone please point me to how the heck you properly make asset icons?
Is there a way to define a custom operation for how something should be undone like file operations?
e.g. if a process creates backups of files and then saves new versions of them, when the user "undoes" it deletes the new files and replaces them with the backups?
No can do.
Hmmm
So I would have to create like a button to undo the file operation
and do it myself?
If it is just a file operation yes. Otherwise there is Undo.CreateObject()
It's not just a file operation, it's a change to several objects but it also changes files, but I want to make it so that it's "undoable".
Depending on what you are doing you maybe can get around it somehow.
Basically, it modifies a bunch of objects with a transform and sprite renderer, and then saves the changes to the sprites over the original sprite files, but after it's copied the original file to the same name.bak
Bu unless it is a Unity Object it cannot be undone.
hmm
Hey, so I'm new to customising the editor. I'm trying to replicate this interface from the sorting layer option, to the inspector gui of a monobehaviour. I know how to make buttons and stuff in the inspector gui, but not something like this. Anybody here knows how to do it (or have a tutorial / documentation that explains it) ?
Fear not, there is a class for that! It is UnityEditorInternal.ReorderableList
THANKS !
Sure thing! Let me know if ya have any questions.
It's looking real good! It doesn't do anything yet, but getting close :D
Well, at least I was able to undo the file operation with powershell
foreach ($filename in ls *.bak) {
$filename.FullName | sed -e "s/\.bak$//" | rm
}
ls *.bak | rename-item -NewName {$_.name -replace ".bak", ""}
Have fun triggering it with Undo/Redo operations.
I have no intentions of trying to do that in undo/redo.
Especially since that does it to ALL bak files
not just the ones relevant to my prefab
it worked though because I only have one prefab for now
Ah, got it.
I'm just glad to know it generally worked
Well nice job!
Yeah, I just wish powershell came with powershell named linux text tools
like sed, awk, grep, etc
I just discovered that unity doesn't have editor support for generic ScriptableObject fields... yay... time to make a custom field I guess...
This was supposed to be an easy thing!
It's never easy
It almost was 😛
The worst part is when you're in the part where you're stuck and burnt out on a project, and you have this cool idea for a new project, and you start it so that you can work on it next without forgetting what you were doing.... but you still have to make yourself come back to the project you still have to finish
SSSSShhhhhh
But I guess that just means that I'm getting better at managing my ADHD tendancy of starting projects and never finishing them
I feel like I've never finished a project before but that's not true.
I'm trying to wrap my mind around serialized objects and proprieties, it's all quite new to me. I have a serialized property that is a object reference. How do I get the serialized property of one of the property it points to ?
The way I did it, was (property.serializedObject.targetObject as ObjectClassType).property or you can do.... var x = property.FindProperty("propertyName") and then choose x.someProperty property to assign the property through SerializedProperty
So if it's an int, x.intProperty = 25 I think
The intellisense should be able to help you what types are available.
if it's an object, you want x.referenceProperty I think
I usually though just do it the former way
I tried var x = property.FindProperty("propertyName") and it tells me that the property is null, even though Debug.Log(((ObjecClassType)property.targetObject).properyName); prints a non null result
Did you receive the SerializedProperty as a parameter to an overridden method? or did you create one yourself?
What do you mean ?
I've noticed that certain things work if you are getting it as a parameter say in "OnGUI" or "GetPropertyHeight", but if you do SerializedObject.Create(), some of the stuff for "SerializedProperty" doesn't work.
Then no, you won't be able to use "SerializedProperty.____property"
You would want to cast the target object and treat it as the original object
(mySObject.targetObject as TargetObjectType).property
But then I can't create a propertyfield around it
So if I create a SerializedObject of a Texture2D, then I would do (mySObject.targetObject as Texture2D).width if I wanted the width property
Then you would want SerializedProperty property from the parameters
yes
Then you're not creating it, you're using one created by the engine, at which point you should be able to do either.
@lost dove Are you trying to get a property from a property for a UnityEngine.Object field?
I have a serialized list of objects, and I want the serialized property of one of the entries
so i tried making a serialized object of the entry, then finding the serialized property
Oh, you just do prop.GetArrayElementAtIndex(index)
Is that what you mean?
no, I'm sorry, I explain badly
let me try again
I have a list of serialized object, and I want to get the property of one of the values. I tried the GetArrayElementAtIndex, and it gives me a serialized property that is an objectreferencevalue, but I can't manage to get the properties of the object pointed by the objectreferencevalue. I tried converting the object pointed to a serialized object and using findproperty, but it gives me a null result (even though I checked that the property is not null)
Ah, I see... sort of. Creating a SerializedObject is the right way to go, I'm not sure why it would be null. I can try helping more if you want to share the code.
this is the code
SerializedObject element = new SerializedObject(Nodes.GetArrayElementAtIndex(index).objectReferenceValue);
Debug.Log((element.targetObject as PathingNode).Type); // this is not null
EditorGUI.PropertyField(
new Rect(rect.x, rect.y, 90, EditorGUIUtility.singleLineHeight),
element.FindProperty("Type"), //this is null
GUIContent.none
);
sry I don't know how to make the code pretty on discord
(Just add cs after the first 3 "`" without any space)
Is Type a c# property and not a field by chance?
Type is defined like this:
public abstract PathingNodeType Type { get; }
Well that would be the problem then.
Ah, I see what you mean
Unity only serializes public fields and private fields with the SerializeField attribute.
(SerializedProperty is really a bit of a misnomer imo...)
Yes, of course. I feel stupid now. I knew that. Oh well. Thanks for the help again ^^
No problem, I did that too a couple of times when I was newer to editor scripting.
I would forget that it has to be the field not the property.
Question: What is the name of the way to sort out certain bits of the project into their own assemblies or bundles, so that when I make a one line change to a shader, Unity doesn't reimport all assets for 20 seconds?
asmdef?
I think they only do incremental compile in 2021 though
And it doesn't count for shaders
Going to ask here again, does anyone happen to know the design guidelines for making asset icons? And also any idea how to have icons for both light and dark themes?
is there any way to use a script to extract a material from an FBX asset? the only way I can see to do it is by manually right-clicking the material and clicking "extract from prefab"
No guidelines, and for dark, it looks like '_d' no?
Well that is annoying. I know they used to have a "Human Interface Guidelines" site for UX/UI design stuff, but I think they took it down.
I guess I will just have to do trial and error until I get it looking right... :/
Oh I met you're right it is just magic 'd_'.
New question:
Any idea how to support undo/redo in a custom VisualElement that can be bound to a list? It seems Undo.undoPerformed is called before the serializedobject is updated so I can't really use that.
Can i do SerializedProperty edits through MenuItem ? Seems like nothing changed
You can, just gotta make sure to apply the changes.
Well... I finally got the Thumbnail system to work. Except I now have the temporary scene in the scene view.... or is it a render texture? I don't know
Got it. I had to set the hide flag on the prefab
Now I just need to get rid of the "black background" on the thumbnail
I think that's because I need to do a culling mask
So that I'm only rendering the object and not the background
Because setting the background to have a 0 alpha value isn't working
Are you using the PreviewRenderUtility?
No. I set up a scene pooling system, sort of.
It may be working, but you may not be drawing it in a way that supports it.
I have a single temporary scene, and I just remove the prefab objects, leave the light and camera, and then put the relevant prefab object into the scene and render
then reset to remove it
But I have a destructor that will close the scene
Sounds right.
That got around the "too many scenes" problem which then caused the whole thing to finally just work
But it's rendering a black background behind the object
Alpha is black. You need to render it in a way that supports alpha.
Well, here's how the camera is set up:
camera = EditorUtility.CreateGameObjectWithHideFlags("Preview Camera", HideFlags.HideAndDontSave, typeof(Camera));
light = EditorUtility.CreateGameObjectWithHideFlags("Preview Light", HideFlags.HideAndDontSave, typeof(Light));
if (Unsupported.SetOverrideLightingSettings(scene))
{
RenderSettings.ambientMode = AmbientMode.Flat;
RenderSettings.ambientLight = new Color(0.84f, 0.84f, 0.88f);
RenderSettings.fog = false;
RenderSettings.defaultReflectionMode = DefaultReflectionMode.Custom;
RenderSettings.customReflection = ReflectionProbe.defaultTexture as Cubemap;
}
EditorSceneManager.MoveGameObjectToScene(camera, scene);
EditorSceneManager.MoveGameObjectToScene(light, scene);
var cameraComp = camera.GetComponent<Camera>();
cameraComp.cameraType = CameraType.Preview;
cameraComp.enabled = false;
cameraComp.clearFlags = CameraClearFlags.SolidColor;
cameraComp.fieldOfView = 15;
cameraComp.renderingPath = RenderingPath.Forward;
cameraComp.useOcclusionCulling = true;
cameraComp.scene = scene;
// This line doesn't work, might need to use culling mask instead/ as well?
cameraComp.backgroundColor = new Color(0, 0, 0, 0.0f);
cameraComp.orthographic = true;
var lightComp = light.GetComponent<Light>();
lightComp.type = LightType.Directional;
lightComp.intensity = 1.0f;
lightComp.enabled = false;
lightComp.color = new Color(1.0f, 1.0f, 1.0f, 1.0f);
cameraComp.forceIntoRenderTexture = true;
And then the code that uses that also sets the render texture as the target texture
and then calls "render()"
You also need to make sure the rendertexture supports it.
This is my camera settings
_camera.cameraType = CameraType.Preview;
_camera.enabled = false;
_camera.clearFlags = CameraClearFlags.Depth;
_camera.fieldOfView = 15;
_camera.renderingPath = RenderingPath.Forward;
_camera.useOcclusionCulling = false;
_camera.scene = _scene;
And RenderTexture
GraphicsFormat format = _camera.allowHDR ? GraphicsFormat.R16G16B16A16_SFloat : GraphicsFormat.R8G8B8A8_UNorm;
var rtd = new RenderTextureDescriptor(res, res) { depthBufferBits = 24, msaaSamples = 8, useMipMap = false, sRGB = true, graphicsFormat = format };
_renderTexture = new RenderTexture(rtd);
_renderTexture.hideFlags = HideFlags.HideAndDontSave;
_renderTexture.Create();
_camera.targetTexture = _renderTexture;
What is occlusion culling?
Oh I created a temporary render texture
I didn't use "new RenderTexture()"
var defaultRenderTexture = RenderTexture.active;
if (_renderTexture is null)
{
_renderTexture = RenderTexture.GetTemporary(pixelWidth, pixelHeight);
_renderTexture.hideFlags = HideFlags.HideAndDontSave;
_renderTexture.Create();
RenderTexture.active = _renderTexture;
}
"Occlusion culling removes additional objects from within the camera rendering work if they are entirely obscured by nearer objects."
Do you make sure to set alphaIsTransparent = true for the texture that you render?
private static Texture2D Render()
{
int res = (int)Resolution;
_camera.Render();
var preview = new Texture2D(res, res, TextureFormat.RGBA32, false, true);
preview.alphaIsTransparency = true;
var oldActive = RenderTexture.active;
RenderTexture.active = _renderTexture;
preview.ReadPixels(new Rect(0, 0, res, res), 0, 0);
preview.Apply();
RenderTexture.active = oldActive;
return preview;
}
I fixed it.
It's the library provided "ToTexture2D" extension method for RenderTexture
His code created a Texture2D that was RGB24 instead of ARGB32
So by changing it to ARGB32, it preserved the alpha
I thought of it because you said to make sure the texture is set to "alphaIsTransparency = true"
I realized "wait a minute, is the "ToTexture2D" setting its temporary texture to be "alphaIsTransparency"?
Alright. Now I just need to create the importer/exporter
i am having an issue when downloading the editor application says "validation failed"
how do i fix this?
Has anyone gotten EditorXR to work successfully? I get a ton (over 137) of errors. Tried both 2019.4.25f1 and 2020.3.14f1
Is that still being worked on?
I only heard about it when vr was up and coming and never again
I don't know. I really need something like it though
all the errors are ImportFBX errors
.fbx files can't be read, hm
oh, there are also FreeType errors, .ttf file format unsupported
wait, this might be some kind of permissions issue
Yeah tht doesn't seem like an editor issue 😅
Forums might be a better place to ask as well
i'm thinking the .zip file I downloaded from github may have been corrupted
trying from scratch
oh no
the github repo uses GitLFS
and it seems corrupted
Icon seems fine to me
how did you download it?
FYI, I got it installed correctly (the zip file from github was corrupted)
BUT, it is using "input-prototype" instead of the new or old input system
so compile errors galore still
ok, turns out this is actually a git submodule in EditorXR, but it didn't automatically get included with git clone.
turns out this is mostly an exercise in fighting with git
I could have just used "Install from git url": "com.unity.editorxr" lol
EditorXR still hopelessly broken, oh well
Hey, I have this weird issue, where when some stuff is edited on my custom editor, the gizmos of the corresponding object isn't updated until I put my cursor on the scene. Does anyone know how to address this ?
Not sure what you mean exactly, but it sounds like you need to repaint the sceneview.
Is there a way to use EditorGUILayout.PropertyField(); on a property that is a scriptable object, but then show the contents of that object instead of a reference to it?
I tried PropertyObject but it gives the same output. It allows me to select a SO
Found the solution:
var editor = UnityEditor.Editor.CreateEditor(blackboardProperty.objectReferenceValue);
editor.OnInspectorGUI();
Follow-up. How would I go about showing the values of public properties on a class that is not serializable? I wrote something that appears to work, but it doesn't feel right.
Shouldn't use string comparison there but rather type comparison
Also be use to destroy the editor instance correctly
When using EditorApplication.EnterPlaymode(); is there a way of waiting for it to actual load into play mode?
Hi! Can i put a tooltip on a GUILayout button?
GUIContent
There is a callback, I think it is called EditorApplication.enteredPlayMode
@gloomy chasm thank you so much, it's PlayModeStateChange.EnteredPlayMode for future reference!
argh! Is it possible to have some with the GUILayout buttons though? 👀
(not the GUI Buttons)
Should do, it is easy to find out for your self 😉
wait, so now i need my GUIContent[] that has my button textures to have textures, and not guicontents! how shall i do that?
for (int i = 0; i < button_tex.Length; i++)
{
button_tex[i] = (Texture)AssetDatabase.LoadAssetAtPath("Assets/Sprite/EditorUI/" + (i + 1).ToString() + ".png", typeof(Texture));
button_tex_con[i] = new GUIContent(button_tex[i]);
}```
You need what?
oh wait a second 👀
(i basically needed to understand this code i once copied and that magically worked but i think "button_tex" are those textures 👀 )
yes it was, thanks dumb me 👀
Thanks it all works ! I have a functioning reordorable list with undo/redo and all that! It took me a few days but I learned a lot ^^
Hey, how do we access the inspector window ? I need to repaint it when I make sime changes in the scene, but I can't find on google the proper way (or anyway) to access it
Is it possible to use EditorGUILayout for property drawers?
No
Thanks.
i am having an issue when downloading the editor application says "validation failed" can I get some help with this?
*2020 version
Nvm
an NRE but it still works? 🤨
Kind of late, but if it is a custom editor you can just call Repaint. If you want to repaint the whole window you can get all open windows with Resources.FindAllOfType and pass it the inspector window type, and repaint each of them.
Hi! i would want to know if something is possible: i've got here several buttons to put animations on text; and i would want that when i hover over one, a little window appears, and shows a cool preview of what the animation looks like. Is that possible...?
You can show an editorwindow as a popup
ShowPopup
There's also a bunch of different show modes that you can use
thanks! i'll look into this right now :)
what should i do? A popup that shows a scene, a canvas...?
(because the text animation is in game, not in editor)
I mean... that's kind of up to you
You can render a scene to a rendertexture and show that in your popup
But I'm not up to date on all the embed scene things
that would be COOL AS FUCK, indeed
Sooo, i did that, and indeed, it's pretty damn cool
but i need it to be just like it was in playmode (even though it's not). How can i do that...?
What specifically?
I have a camera, filming this TextMeshPro. I'd want it to be play mode instead of like... Standard editor:
because thing is that this text can be animated in play mode (with a plugin i bought)
(I also have a text field that doesn't keep what i input it, in line line 288 here and idkwhat i'm missing https://pastebin.com/Pwrw1BEB)
(don't mind the mess 👀 )
I have a CustomProperty drawer for a struct. In another Editor class I want to call this property drawer. How can I do that ?
that's tricky. I think you need to checkout the CreateEditor thingys:
idrk how though, sorry i can't help more :/
I ll have a look. Thank toy anyway ! @tough stream
no prob! :)
Well this didnt solve my issue but I am not far. I want to get the property drawer from a field. ```cs
SerializedObject so = new SerializedObject(panelItem_SO);
PropertyDrawer pd = getDrawer(so.FindProperty("scene"));
pd.OnGUI(new Rect(10, 10, 150, 100), so.FindProperty("scene"), new GUIContent("Scene"));
if found this ```cs
static Func<SerializedProperty, PropertyDrawer> getDrawer;
public static PropertyDrawer GetDrawer(SerializedProperty property)
{
if (getDrawer == null)
{
var mtd = typeof(PropertyDrawer).GetMethod("GetDrawer", BindingFlags.NonPublic | BindingFlags.Static);
getDrawer = (Func<SerializedProperty, PropertyDrawer>)Delegate.CreateDelegate(typeof(Func<SerializedProperty, PropertyDrawer>), null, mtd);
}
return getDrawer(property);
}
Why not just propertyfield..?
it doenst display anything
SerializedProperty serializedProperty = so.FindProperty("scene");
EditorGUI.PropertyField(GUILayoutUtility.GetRect((float)Screen.width, EditorGUI.GetPropertyHeight(serializedProperty)),serializedProperty);
pass true as second param
I'm finding it hard to explain what I'm trying to do here but, is it possible to have an array of serializable classes where you can pick which class each element is?
so,
public class ParentClass
{}
public class A : ParentClass
{}
public class B : ParentClass
{}
public class Monoclass : MonoBehaviour
{
public ParentClass[] classes;
}
where then in the script component for Monoclass, for each element in classes you can pick whether it's A or B
There's probably a better solution to what I'm trying to do
Serialize reference and you have to make your own drawer for it
would you be able to explain what you mean by that? I haven't worked with drawers before
KaiDevvy: I would try creating an array of the parent class in the actual script for the object, then you can create property drawers for each child class and that might work. I don't know, I haven't tried it
but your classes need to be [Serializable] and your base classes should contain items that are [SerializeField]
You'll only need to create property drawers if you don't like how unity draws that class by default
Also for arrays, Unity doesn't do very well with that, but you can fix that by drawing your own property drawer for the array, but the way to do that is to create a ListOfParentTypes class that implements IList<ParentClass>
is there a way to make Gizmos.Drawline thicker?
other than something like
Gizmos.DrawLine(me.transform.position + me.Vertices[me.Triangles[i]], me.transform.position + me.Vertices[me.Triangles[i + 1]]);
Gizmos.DrawLine(me.transform.position + me.Vertices[me.Triangles[i]] + new Vector3(-0.001f, 0, 0), me.transform.position + me.Vertices[me.Triangles[i + 1]] + new Vector3(-0.001f, 0, 0));
Gizmos.DrawLine(me.transform.position + me.Vertices[me.Triangles[i]] + new Vector3(-0.002f, 0, 0), me.transform.position + me.Vertices[me.Triangles[i + 1]] + new Vector3(-0.002f, 0, 0));
Gizmos.DrawLine(me.transform.position + me.Vertices[me.Triangles[i]] + new Vector3(0.001f, 0, 0), me.transform.position + me.Vertices[me.Triangles[i + 1]] + new Vector3(0.001f, 0, 0));
Gizmos.DrawLine(me.transform.position + me.Vertices[me.Triangles[i]] + new Vector3(0.002f, 0, 0), me.transform.position + me.Vertices[me.Triangles[i + 1]] + new Vector3(0.002f, 0, 0));
Gizmos.DrawLine(me.transform.position + me.Vertices[me.Triangles[i]] + new Vector3(0, -0.001f, 0), me.transform.position + me.Vertices[me.Triangles[i + 1]] + new Vector3(0, -0.001f, 0));
Gizmos.DrawLine(me.transform.position + me.Vertices[me.Triangles[i]] + new Vector3(0, -0.002f, 0), me.transform.position + me.Vertices[me.Triangles[i + 1]] + new Vector3(0, -0.002f, 0));
Gizmos.DrawLine(me.transform.position + me.Vertices[me.Triangles[i]] + new Vector3(0, 0.001f, 0), me.transform.position + me.Vertices[me.Triangles[i + 1]] + new Vector3(0, 0.001f, 0));
Gizmos.DrawLine(me.transform.position + me.Vertices[me.Triangles[i]] + new Vector3(0, 0.002f, 0), me.transform.position + me.Vertices[me.Triangles[i + 1]] + new Vector3(0, 0.002f, 0));
just a tip, this code would look a whole bunch nicer (and marginally faster) if you cached the variables before repeatedly using them
var position = me.transform.position;
var a = position + me.Vertices[me.Triangles[i]];
var b = position + me.Vertices[me.Triangles[i + 1]];
Gizmos.DrawLine(a, b);
Gizmos.DrawLine(a + new Vector3(-0.001f, 0, 0), b + new Vector3(-0.001f, 0, 0));
Gizmos.DrawLine(a + new Vector3(-0.002f, 0, 0), b + new Vector3(-0.002f, 0, 0));
Gizmos.DrawLine(a + new Vector3(0.001f, 0, 0), b + new Vector3(0.001f, 0, 0));
Gizmos.DrawLine(a + new Vector3(0.002f, 0, 0), b + new Vector3(0.002f, 0, 0));
Gizmos.DrawLine(a + new Vector3(0, -0.001f, 0), b + new Vector3(0, -0.001f, 0));
Gizmos.DrawLine(a + new Vector3(0, -0.002f, 0), b + new Vector3(0, -0.002f, 0));
Gizmos.DrawLine(a + new Vector3(0, 0.001f, 0), b + new Vector3(0, 0.001f, 0));
Gizmos.DrawLine(a + new Vector3(0, 0.002f, 0), b + new Vector3(0, 0.002f, 0));```
okay, also, I just learned about Handles.DrawLine
I'm fairly sure you cannot set the thickness, though in the newer versions of Unity they've added some thickness settings with handles afaik
handles are editor-only, and afaik need to be called from OnSceneGUI
I went through the manual remembering there was other things like Debug.DrawLine and made me see what else there was
I have developed a simple tool that allows me to create and save textures; while the tool was still placed in the Assets folders I had no issues when I actually saved the file, but when I remade it into a .git package it wouldn't show the textures in the specified path unless I specifically called AssetDatabase.Refresh() after the operation.
The tool works either way, I'm just wondering what causes this quirk
I just figured that the SteamVR plugin has a bug with its settings because Resources.Load in DidReloadScripts does fail during import. Does anybody have an idea for an alternative to load a scriptable object that might work during asset import?
In an assetimporter?
No they are using DidReloadScripts which gets called during asset import but it does not work during import and returns null
Which in turn leads to them reacreating (overwriting) the settings asset file
So there either needs to be an alternative that works during import or some way to check if Ressources are ready to be loaded 🤔
using UnityEngine;
using UnityEditor;
public class EditorStuff : EditorWindow {
float value;
[MenuItem("3d multiplayer/Editor")]
private static void ShowWindow()
{
GetWindow<EditorStuff>();
}
private void OnGUI()
{
GUILayout.Slider("TimeScale", value, 0, 3);
}
}```
GUILayout' does not contain a definition for 'Slide
not sure about your question, but, you are probably looking for EditorGUILayout.Slider
as I've been delving more into handles, I'm confused on the difference between gizmos/handles/debugs? Like, some of them have different overloads and stuff, but, I mean, that aside, if lets say something between all 3 functioned the same, is there generally 1 you would want to use over the others?
If memory serves. Gizmos can be seen in the game view and cannot be interacted with.
Debugs simply draws visuals in the scene view.
Handles draws things in the scene view, and some can be interacted with.
I think Gizmos can only be drawn in the OnDrawGizmo method.
Generally Handles or debug is what you want.
thanks
okay, thanks for that clarification!
What do yall do for your editor namespaces? Like MyCompany.MyTool.Editor, or MyCompanyEditor.MyTool? Or do you just not have separate namespaces for editor only code?
We use Editor currently but it's kind of annoying
So thinking about using something else but don't really know what
It's annoying since you have to do UnityEngine.Editor instead of just Editor
Yeah, that is exactly what I am doing now and also the reason I was asking because I can't think of a better namespace. But it is annoying to use Editor.
as flat as possible, I'd say
Uh... I don't get what you mean by "flat".
does anyone know if/how I can slap a header on a field declared like this?
just the general idea of avoiding hierarchy I guess
you add the header in that field thing too
[field:SerializeField, Header("Speeds")]
thank ya
That doesn't particularly answer my original question. The 'problem' is what namespace to put editor code in. All it really is is a convention/naming question.
hm, I haven't written much editor code to give a meaningful answer I guess
I use MyCompany.MyGame/MyTool.Editor
i typically remove code when I have to type a company name to access it, though, unless it's a big deal to have
So you use .Editor as well. It works so well, yet is so inconvenient to need to do UnityEditor.Editor, haha 😛
Is it? Namespaces are usually mostly handled by the IDE anyway.
Only that when working with custom editors you need to do this.
using UnityEditor;
namespace MyTool.Editor
{
public class MyEditor : UnityEditor.Editor {}
}
You can just write : Editor
as long as you have using UnityEditor; at the top, which your IDE should do for you more or less automatically
and the namespace, well I have tooling to insert that based on the folder my script is in.
Nope, at least not in the latest version of Visual Studio Community.
Nope. Try pasting in the code in my codeblock.
See what your IDE tells ya.
It doesn't know if you mean the namespace or the class.
I usually put my custom editor classes inside the file they are a custom editor for, with #if UNITY_EDITOR stuff
Ew 😛
That bloats the files size so much, especially for larger classes and more advanced editors.
But to each their own.
My classes are usually pretty small anyway. It works for me ¯_(ツ)_/¯
Gues that's why I never ran into that issue then
I guess if I used a different strategy I would just name my namespace slightly differently.
Something like... Company.Product.DevTools
idk
Hi. Why does my profiler's editor loop kill my framerate?
test standalone game not in editor for performance testing as Editor will still do its things when you run in-editor
Ok, thanks. But what about testing the game in editor? With 120ms lags it's unplayable
Use profile editor and deep profiling
the later versions of unity, the profiler is now a external, so it shouldn't kill so many frames
with the earlier versions of unity, you can drag the window out of the unity window, which helps
I even stopped profiling and there are the same lags
I'm working on your standard ScriptableObject Variable system, and am making a window to more easily view the values in the project. But I'm not sure which layout is better, any thoughts?
A little explanation: The treeview is of folders that contain Variable SOs at any depth, and for clarity I would of course add icons.
The first one you would have to click on a folder (displayed in the treeview on the left) to see the values of the Variable SOs that are in the folder.
What is this error? I tried putting unity 2d extras in my editor and it's giving me this. I just copy pasted 2d-extras-master in my Packages folder, renamed it to com.unity.2d.tilemap.extras, and it is supposed to work like this. This is a new project, there is nothing in it
unity told me to go into safe mode
I guess the thing you copy-pasted is not compatible with that version of Unity or with another package version
i am using the recommended version of the latest unity hub
unity hub 2.4.5
unity version 2020.3.14f1
lts
and the package is not working right now
i tried redoing it
but no
it feels weird to switch out of a reccomended version of unity
should i try the latest and not the lts?
Did you follow the isntructions here? https://github.com/Unity-Technologies/2d-extras
e.g. Please use the 2020.3 branch for Unity 2020.1-2020.3 versions.
Welp
my bad i guess
i had used it before
and they changed how they install it now
woops
wait
no
no they didn't
@twin dawn
I am using the recommended branch and i put it in the project with that name
there is literally nothing else i am supposed to do
idk then ¯_(ツ)_/¯
Given that Unity Recorder's GIF encoding feature has been deprecated, is there a recommended GIF recorder for Unity, on the Asset Store or elsewhere?
I like making GIFs to share on social media because the format is widely supported and easy to share.
Not specifically for Unity, but my go-to GIF recording software is GifCam: http://blog.bahraniapps.com/gifcam/
Or ScreenToGif is a wonder (https://www.screentogif.com/)
I've found a multitude of programs that record the whole screen, but I liked Unity Recorder's ability to grab frames straight out of Play Mode.
Maybe I should just reverse engineer it xP
Yep, just use ScreenShots:
https://ngtools.tech/uv/UnityEditor.ScreenShots/
Internal API, simple as that
Seconding ScreenToGif, for GIFs there's no real need to record in-editor anyway as they get compressed
I guess he likes the way it is integrated, ease the life
But properly adjusted, this is exactly the same yep
well sorta
Unless there's some witchcraft involved, external software will capture at time intervals independent of Unity's rendering rate, whereas an editor extension can grab each frame as it comes, ensuring a smooth gif even if some stutter occurs during the recording process.
I guess for now I'll use version 2.5.5 until it stops working or a new equivalent shows up :\
I hate it when features I use get removed >.<
from this video's comment : https://www.youtube.com/watch?v=2HVhnh93JZY
It seems it is working no?
As of last Fall, yes. I was using it myself up until around a month ago, but last week when I updated the package the GIF feature went poof and started this whole thing xP
don't update then
That's basically what I said when I was going on about version 2.5.5 ;P
Or make your own using https://docs.unity3d.com/ScriptReference/Time-captureFramerate.html
It's the GIF encoding that would be the roadblock for me there.
I'm sure you will find your answers there:
https://www.google.com/search?client=firefox-b-d&q=c%23+make+gif
dude come on obviously I googled it first
And have you tried some?
Some third party software? Or cooking up my own encoder?
Maybe the latter is easier than I assume and there's some straightforward way to get an API like FFMpeg working but I'm not expecting much.
hmmm there, surprisingly, seems to maybe be a .NET API for it.
Does anyone know of any examples I can reference for an editor item list that can be be reordered by dragging items up and down?
ReorderableList?
Thank you I believe that's what I'm looking for
Any clue why this isn't being called?
internal class LibraryAssetModificationProcessor : UnityEditor.AssetModificationProcessor
{
public AssetDeleteResult OnWillDelete(string path, RemoveAssetOptions options)
{
UnityEngine.Debug.Log("Asset deleted");
return AssetDeleteResult.DidNotDelete;
}
}
Nvm got it working. Forgot "Asset" at the end and needed to make it static. I was sure that I had it working in the past... Ehh, it is working now though it would be nice if Unity changed how it handled it so it wasn't so magic... At least add support to VS like the Update/Start/etc methods have.
I wrote my own snippets in VS since Unity 4. Works seamlessly.
~\Documents\Visual Studio 2019\Code Snippets\Visual C#\My Code Snippets\UnityOnDestroy.snippet
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Unity OnDestroy</Title>
<Shortcut>OnDestroy</Shortcut>
<Description>Code snippet for OnDestroy Unity's event.</Description>
<Author>Michael Nguyen</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Code Language="csharp"><![CDATA[protected virtual void OnDestroy()
{
$end$
}]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
The VS Unity extension now supports all the built-in UnityEngine.Object inherited class message methods.
I should really make more snippets since they are so handy....
So why don't you have OnWillDeleteAsset? 🙂
Because AssetModificationProcessor doesn't inherit from UnityEngine.Object 😛
Then go write your snippets 🤪
Lol, maybe I will! But it doesn't change how janky it feels to use by default 😉
Yeah, the static design is kinda outdated, they can do better
I might say I would have prefered an attribute perhaps
Yeah, an attribute would be better than inheritance + static which just feels weird.
I understand why they pick static, easier, no need to instantiate
But it makes the code less robust
Yeah, it does limit it a bit.
Having to inherit from a class just to make a static method is strange to me. I think at least an attribute would be better than how it is with inheritance.
Yeah, the inheritance does not bring anything. No security, no scope, no feature
Or I don't see them
Yeah, it is an empty class as far as I know. Literally just there to find the message methods.
Yo, is it safe to use AssetDatabase.AssetPathToGUID with deleted paths from OnPostprocessAllAssets...? It works fine it seems...
Sounds like the DB is not updated yet, so I would say yes
but what are you going to do with deleted GUIDs?
Removing the asset from a list in all Collection ScriptableObjects.
I would have thought that it wouldn't have worked, but I'm not complaining. Makes things easier for me!
When adding an item to a ReordableList is it possible to have a selectable context menu show up? I want to add different subclasses to the same parent class array.
Thank you!
How can I add items to the dropdown? Sorry don't have a ton of experience with editor stuff
For anyone searching in the future, this is how to do it:
private void AddDropdownCallback(Rect buttonRect, ReorderableList list)
{
var menu = new GenericMenu();
menu.AddItem(new GUIContent("Item 1"), false,() => { });
menu.AddItem(new GUIContent("Item 2"), false,() => { });
menu.AddItem(new GUIContent("Item 3"), false,() => { });
menu.AddItem(new GUIContent("Item 4"), false,() => { });
menu.ShowAsContext();
}
Is it possible to show fields of derived classes?
public class ItemData : ScriptableObject
{}
public class SwordData : ItemData
{}
[System.Serializable]
public class Item
{
public ItemData itemData;
}
[System.Serializable]
public class Sword : Item
{
public int damage;
}
public class ItemDisplay : MonoBehaviour
{
public Item item;
// if item.ItemData is SwordData -> show 'damage' field in the inspector
}```
Using a custom editor it is.
Also, it isn't showing fields of derived classes, it is showing fields of UnityEngine.Objects.
How do I add an item to a ReordableList? I'm trying to do ReordableList.list.Add(), but ReordableList.list is null
You need to set the list to something.
What do I set it to? Do I just create a an empty list if its null?
Yup, it is just the list of items that you want to show in the ReorderableList
Okay do you know if it has to be a special type or is the type of my serializedObject?
How can I set the value of a custom SerializedPropperty?
No can do. Unless it is serialized by reference with [SerializeReference], then you use .managedReferenceValue which is write only.
So if I want to create custom object adds to a ReordableList, then they need to be references?
What?
I'm trying to create a dropdown to a ReordableList that allows me to add different subclasses to it
I don't want to add the parent class, which is what the default add does
Okay, I get what you are doing I think. But I think you need to show some of the code so I can understand better what part you are having trouble with.
Okay give me a second
namespace Agile.Events
{
public enum EventType
{
MoveCamera
}
[System.Serializable]
public class AgileEvent
{
public EventType Type;
public event StartEventDel NextEvent;
public delegate void StartEventDel();
internal virtual void Begin()
{
}
internal void End()
{
NextEvent?.Invoke();
}
}
[System.Serializable]
public class MoveCameraEvent : AgileEvent
{
public Vector3 position;
public MoveCameraEvent()
{
Type = EventType.MoveCamera;
}
internal override void Begin()
{
Camera.main.transform.position = position;
End();
}
}
}
These are the classes I'm serializing ^^^
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Here is my editor class
I'm stuck at line 55
What does the events field look like in the event manager? (Also either reply or @ me because I don't remember to check back, haha)
Its just a public AgileEvent[]
You need to make sure it has the [SerializeReference] attribute because without the attribute unity doesn't support polymorphic serialization.
