#↕️┃editor-extensions
1 messages · Page 10 of 1
full screen 😛
it's because your script is on a different assembly, and that assembly needs to reference your dll
so u need to reference it manually here
Its not selectable?
well u need to allow it to compile first
Ah nvm, I found it
Do complex selectors support pseudoclass modifiers
if so, how do they work? (it's hard to tell what happens if typeSel.classSel.NameSell:hover:active is defined as a multiple)
theoretically, it's possible but whether or not it's actually supported is what the docs don't clarify iirc
yeah it doesn't get clarified.
I can't find any specific docs right now through MDN on such an attributable behaviour of pseudoclasses
one of the levels of CSS W3C has specifications for might have the behaviour defined or at least denied but then that's the question of does USS use the same level of CSS as inspiration or is this just all esoteric?
yknow what i'll just skip this for now and come back to it when there's actually a need for the C# -> USS and USS -> C# interpreters to have it.
Hi, I have a problem with using vs code with unity. When I open vs code, it says “ Could not locate MSBuild instance to register with Omnisharp” and intellisense doesn’t work. What might be the problem?
Install the build tools for visual studio https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2022
The link is for build tools for visual studio, is it the same for vs code?
Yes
If that doesn't work, make sure you've installed everything mentioned in the install instructions, including the .NET 4.7.1 developer pack
After downloading, run it? It prompts visual studio installer.
Another thing is, one of my friends has this problem too, but his intellisense worked, but broke the next day he opened it
I would not recommend vs code for Unity as its debugger is deprecated and configuring it is a huge pain in the ass. If you have access to JetBrains Rider (students can get it for free) I would recommend that. Otherwise VS Community ships with Unity through the hub and is way easier to configure
I have a question. I am switching materials on selected objects by assigning a new list to renderer.materials, but I cannot undo this. I have tried using RecordObjects() on my list of selected gameobjects but I just can't get it to work.
void SwitchMaterial(Material source)
{
UnityEngine.Object[] objectsToRecord = Selection.objects;
Undo.RecordObjects(objectsToRecord, "Switch Material");
foreach (var mesh in meshes)
{
Renderer renderer = mesh.GetComponent<Renderer>();
if (renderer != null)
{
Material[] object_materials = renderer.sharedMaterials;
for (int i = 0; i < object_materials.Length; i++)
{
Material mat = object_materials[i];
if (mat == source)
{
object_materials[i] = targetMaterial;
Debug.Log("Switching material: " + source.name + " to: " + targetMaterial.name);
}
}
renderer.materials = object_materials;
}
}
}
I'm trying to calculate the height of a rect before drawing elements. I used CalcHeight on both the rect style and the two label styles but this doesn't seem to be accurate. I have the styles attached to BeginArea and both labels. What am I doing wrong?
You're modifying renderer so you need to record Undos for that.
The selection is likely storing GameObjects, and the GameObject is not changing
Oh of course! It's obvious now that you say that. Thank you very much 🙂
Ok so on further inspection
Section 3.5 of the Selectors Level 4 specification contains an explanation of pseudoclass behaviours
Like all CSS keywords, pseudo-class names are ASCII case-insensitive. No white space is allowed between the colon and the name of the pseudo-class, nor, as usual for CSS syntax, between a functional pseudo-class’s name and its opening parenthesis (which thus form a CSS function token). Also as usual, white space is allowed around the arguments inside the parentheses of a functional pseudo-class unless otherwise specified.
Like other simple selectors, pseudo-classes are allowed in all compound selectors contained in a selector, and must follow the type selector or universal selector, if present.```
Does Unity's USS follow the level 4 specification in this case?
Don't know if this is the right place; but how can make it so that the material doesn't cramp up like this on the sides?
result turned out to be. com.unity.ui has no native importer technically -> Uses ExCSS (or a modifiaction thereof).
USS is CSS3 derivative for anyone wondering
anyone knows how can I trigger assets browser for custom editor?
Had to resort to reflection and getting the objectSelector... it works now
if there's any way to do it without reflection I'm up for that
lol 🤣 .... aight changing to that instead 🤣
Also, can this be wrapped in a IMGuiContainer in uitk?
if (Event.current.commandName == "ObjectSelectorUpdated")
var obj = EditorGUIUtility.GetObjectPickerObject();
Of course, or just use a Button to call it
How to use it, it is kind of funky
aight! Thanks a ton! 👍
Changing my code now 🔥
np!
I found a way to add icons to scriptable objects in the asset viewer , here https://answers.unity.com/questions/1452924/custom-icon-on-scriptableobject.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.
How do I make all meshes in my scene readable, this doesnt seem to work... ```cs
private void MakeReadable()
{
#if UNITY_EDITOR
foreach (var filter in FindObjectsOfType<MeshFilter>())
{
//Exception for probuilder assets
if (filter.sharedMesh.name.Contains("pb_Mesh"))
{
return;
}
var path = AssetDatabase.GetAssetPath(filter.sharedMesh);
ModelImporter ti = (ModelImporter)AssetImporter.GetAtPath(path);
if (!ti.isReadable)
{
ti.isReadable = true;
EditorUtility.SetDirty(ti);
ti.SaveAndReimport();
}
}
AssetDatabase.SaveAssets();
#endif
}
does it log anything or just silently doesn't work? does it ever reach inside the if (!ti.isReadable)? how do you call MakeReadable?
No errors are logged, the code was executed
in play mode?
in the editor called from a MenuItem
have u tried AssetDatabase.ImportAsset(path, ..) instead?
not sure if importer.SaveAndReimport does that automatically
looks like it should work as it is.. my guess is it's gotta be something with refreshing.. check if pressing ctrl+S --> ctrl+R will finalize the changes
hmm maybe y
oh ffs
😄
hey Lyrc!
Hey, in an editor script I'm changing sprite names inside a texture. How do I apply those changes to the texture so it's actually being serialized back to the texture?
Well, the name in the metadata seems to get changed and saved. But it seems that the actual asset name doesn't change. Like, the name of the subsprites inside the multi sprite texture.
hey are you still on it?
yes
since 2 hours or so 😄
still no solution, since unity updates the wrong names and even after a unity restart all settings are undone
so how exactly are you changing the sprite names?
@eager shale have you seen this? https://forum.unity.com/threads/renaming-sprite-slices-in-script.345417/#post-3041862
well I retrieve all Sprite's via AssetDatabase.LoadAllAssetsAtPath and then change it via setting sprite.name
na that won't do at all 😛
oof.. sry I'm late xD
you can go with either a TextureImporter, or straight up changing the data inside the .meta file
check out the links, they contain both versions
it's okay, I'm currently a bit stressed out, so I'll check it later or tomorrow
I feel that
I've been reworking the entire core of my USS Interpreter to be USS-Compliant
Unity's documentation for USS plain sucks.
It's maddeningly confusing, gives little examples where they matter most
and expressly says "go to MDN" half the time
when MDN has things that USS doesn't support
and no matter what version of the manual you go to, it never really changes.
I think the reason Unity doesn't actually have a native USS importer is likely because they're still not done properly documenting it internally
what do you wanna do with USS and need Unity's support?
make a native USS Object Model
so that I can construct USS in C#
exporting works fine
I just need to rework Style Rule Values
to be more compliant
but that's hard to do when the data types themselves don't even know what compliancy they want to follow
CSS L3? CSS L4? USS Superset?
yeah in my mind everything Unity released after 2019.3 is beta stuff 😛
nested prefabs only recently escaped that conviction lol
ouch
I'm sat here
just trying to understand USS
it's not CSS3 compliant
despite it being a modified ExCSS importer
it's not USS compliant because USS doesn't have any definitive standard
It's not CSS4 compliant because that requires CSS3 compliancy
how did they manage this nightmare
I can only handicap it heavily.
and so all I can do
is do two value types
ValueType for any value type that isn't a keyword
and USSKeywords, a subtype of value type
are you just trying to understand the syntax of the 'language'? or
building an importer/exporter
so I can do this in C#
without ever having to touch this nightmare again
the exporter part works
you gotta know the syntax of the language for that xD
yeah and I can grasp CSS syntax
but USS syntax is halfway CSS syntax
and halfway a bottle of vodka still unfinished
your project sounds huge scoped, I'm surprised you're salty about it just now after weeks/months xD
everything else I understand fine
it's not even the majority of USS that's the problem
it's just what are the actual keywords
there's no examples for how this works.
no examples for how these work.
and I can't find any on MDN or W3C CSS Level 3 or CSS Level 4
not because I haven't tried but either Unity has renamed them from what they really are
or they just are under some module specification document that's extremely hard to find.
the only thing I can do for the first image is assume that's how they intend their documentation to be read for USS common properties
do you have EXP with CSS? HTML? WPF(XAML)?
(this is the 2023.2 documentation which is the most readable one)
yeah, a fair bit
CSS/HTML
just whatever Unity's doing
they need to take it back
and really rethink it
XAML looks to be the addition to USS in comparison to CSS
I get they use Yoga under the hood.
do u also want the UXML stuff?
can you please type full paragraphs, this is impossible to read and takes up so much screen space
I'm fairly aware of the nightmare that is UXML which is after this one unfortunately. All I can do in assumption to USS is make assumptions on what to support based on the keyword, providing a block of methods that automatically define things
Isn't all this just talking about the rest of the docs, like if you see justify-content: flex-start | flex-end | center | space-between | space-around then you know that it's a property where one of those options must be present
It feels counterintuitive to assume that at first glance because I thought these were all syntactic things I needed to bake in support for under the hood.
No, it's just talking about how to read the property docs https://docs.unity3d.com/2023.1/Documentation/Manual/UIE-USS-SupportedProperties.html
I am confused why that's not in the supported properties page itself.
2023.2 is the most readable iteration of the USS documents which were only made available halfway through my journey into USS, but even then it's questionable.
I find it fine personally. There's way worse docs out there, but they're consistently updating these and they're fairly thorough
Plus, the code has better highlighting than the scripting reference which is great
yeah the code highlighting I don't mind - that at least is extremely helpful in knowing when the USS Interpreter is actually working
and knowing most of it now for what the data types top section means is helpful - all I need to know now is the use of {A,B}
I think you're gonna manage, but it IS a big project, what you're doing. Pretty sure for UXML you're gonna have to get hands with it full-time just to get the grasp of it, nevermind the complete language 😄
But in the end it's YOUR app, you can support/not support any amount of syntax/features you want/don't want 🙂 Can't go wrong with skipping a few ;P Users could also request them later
it occurs at least A times and at most B times, which I'm assume is in reference to the use of top, right, left, bottom rules (e.g. how many of that specific overall category you've got)
It's just a shorter way of writing what the mozilla docs did:
When one value is specified, it applies the same width to all four sides.
When two values are specified, the first width applies to the top and bottom, the second to the left and right.
When three values are specified, the first width applies to the top, the second to the left and right, the third to the bottom.
When four values are specified, the widths apply to the top, right, bottom, and left in that order (clockwise).
I want to at least achieve some sort of parity with USS for my USS Object Model because I plan to release it to github separate of my editor framework once the academic period has passed. I'm just having to always double check what's supported from 2021.3 against what 2023.2 says.
as for that I'll check the MDN because they probably have the examples - unless they mean, more specifically, <length><length><length><length>
they mean exactly as it's written, you can include 1 to 4 lengths there.
Not 0 lengths, not 5 lengths
which is what I'm assuming it means but I thought at first it meant you supplied one length then used {1, 4} to determine which values apply to it
The only one I don't see is the use of "||" in any of these documents but maybe I've missed something
flex: none | [ <'flex-grow'> <'flex-shrink'>? || <'flex-basis'> ]
ok so this value properties thing isn't a simple affair that you can't exactly do enumeration to define the basis for, it's more of a per-case basis
@visual stag curious, you're working with USS/UI Toolkit or just know your CSS?
Both
would u recommend the UI toolkit as someone who's familiar with web dev then? For game production ofc
I hate UGUI and I refuse to use it unless I'm forced to, but UIToolkit is not really ready for runtime yet for many applications due to it lacking custom material support, it still being somewhat buggy, and some text features being missing
my main concern was that if I locked into it and later wanted help, it could prove hard to find someone specifically familiar with it.. but if web-dev ppl can straight up jump in (with some practice period maybe) it's another matter
If you have web dev familiarity it's a piece of cake imo, though you'd probably run into things that web can do that it cannot a lot, and that may be frustrating.
alright thanks, I think I'll stay away from it for now then.. IMGUI can indeed be a mess but at least it works 😄
I do prefer using UGUI/IMGUI for some things but despite how annoying USS is to read and understand at times. I see a lot of value and potential in it - I just don't like the fact there's no USS Object Model native to unity that allows me to completely write USS in C#.
I hate web dev too though, so I kinda wish they didn't rip from CSS, as what the hell is justify-content vs align-content vs align-items, it's just nonsense that you have to learn and remains unintuitive forever
hmm I think they specifically did a lot of stuff to enable web-devs to work with Unity
I mean, if you're making editor extensions stuff UIToolkit is ready and you should use it
oh.
you can embed IMGUI in UIToolkit easily if there's something it still doesn't support, so there's no downside
I'm pretty much just in a corner where what I want to do is only achieveable with USS/UXML or UITK and I've had a hazy past with UITK corrupting projects when I installed it so I steer clear of it unless it's directly baked into the version of Unity I'm using.
I forget when it stopped being a package, but it's been built-in for a couple of versions at least
Maybe around 2022.1/2022.2? - It corrupted work in 2019 and 2020 before for me. 2021 I wouldn't try out of fear of the same solution (same with why I won't use GraphToolsFoundation in part - the other part being GraphView is native since 2019 although experimental).
i am more confused than i was before
@simple cove in the end I'm just gutting out the original Style Rule idea. Due to all the intricacies with every type of style rule it's not the correct structure and it's better off being a generic string with unique constructors for every possible value that can be obtained.
all of it 😛 go with the other way tho imo, it's a 100% ready script
it's not as simple as replace old prefix with new prefix
yeah lol.. just make it work with what you know for now imo, rest can come later and/or upon demand
yeah, it sucks it has to be this way but it's such a wide scoped subsystem that already was just being converted to and created based on a string
i already have a_0_0, a_0_1, ..., a_1_0, a_1_1, ... and the new sliced pieces that i create are a_0, a_1, a_2, ... and need to be renamed to a_2_0, a_2_1, a_2_2, ...
because of how auto naming works with the sprite editor
so the sprites that need to be renamed and those that are already renamed share the same prefix
in the end it's just too complex and there's so many ways it could just cause worse import/export times. Keywords are going to be harder as some will likely be enums (see - cursor). There is a workaround at least. For any property that has only one of two possible values - e.g. width/height with <length> or auto, I can make the assumption that the value is intentionally auto if no numbers are supplied for the length.
so would be helpful for me to understand the general solution to the general problem so i can work out a specialized solution for my special problem
BOOM
@simple coveyou are my angel tonight
not my angle, because then you'd be the sine to my cosine (we belong together)
don't ask me, my brain was rotting in the last few hours
np 🙂 glad it worked lol
foreach (Sprite sprite in renamableSprites)
{
string newName = _texture.name + separator + newIndex.ToString() + separator + (i++).ToString();
var factory = new SpriteDataProviderFactories();
factory.Init();
var dataProvider = factory.GetSpriteEditorDataProviderFromObject(sprite);
dataProvider.InitSpriteEditorDataProvider();
var spriteRects = dataProvider.GetSpriteRects();
foreach(var spriteRect in spriteRects)
{
if (spriteRect.name != sprite.name) continue;
spriteRect.name = newName;
}
dataProvider.SetSpriteRects(spriteRects);
dataProvider.Apply();
var assetImporter = dataProvider.targetObject as AssetImporter;
assetImporter.SaveAndReimport();
}
had to do it a bit differently since the importer stuff seems deprecated nowadays
ah.. I don't think it's deprecated, but combining 2 solutions can be weird
you ended up with your custom one tho lol
well, the snippets didn't show how to instantiate the importer, so i figured to construct an importer and then set the spritesheet, but spritesheet property is deprecated
and the deprecation redirected me to use the sprite editor data provider
yeah rly cool, I didn't even know it existed
there's probably a more efficient solution that doesn't go through the whole spriterects array 20 times at most, but i'm happy to have a solution now
hold on, i can think of an improvement already
...
GetSpriteMetaData(out var dataProvider, out var spriteRects);
var i = 0;
foreach (Sprite sprite in renamableSprites)
{
string newName = _texture.name + separator + newIndex.ToString() + separator + (i++).ToString();
spriteRects.Where(sr => sr.name == sprite.name).First().name = newName;
}
SaveChanges(dataProvider, spriteRects);
}
private void GetSpriteMetaData(out ISpriteEditorDataProvider dataProvider, out SpriteRect[] spriteRects)
{
var factory = new SpriteDataProviderFactories();
factory.Init();
dataProvider = factory.GetSpriteEditorDataProviderFromObject(_texture);
dataProvider.InitSpriteEditorDataProvider();
spriteRects = dataProvider.GetSpriteRects();
}
private static void SaveChanges(ISpriteEditorDataProvider dataProvider, SpriteRect[] spriteRects)
{
dataProvider.SetSpriteRects(spriteRects);
dataProvider.Apply();
var assetImporter = dataProvider.targetObject as AssetImporter;
assetImporter.SaveAndReimport();
}
the .Where is still a bit ugly in the foreach but the array structure doesn't let me think of a better one
converting the array to a dict (key = name) might solve the problem but it works for now so eh
jesus christ, now it causes another bug to happen
now after executing the script, this happens
can't make any new rects
any ideas why this happens now? 😄
if i delete the rectangles that i renamed via the editor script, it works again 🤓
and its bound to those that i edited
im a bit exhausted rn, maybe tomorrow somebody either has some solutions or i have more energy for this shit
Is there a way to display the edit handle of a physics collider from a script? Because I am doing a custom asset and I won't to set the size of some colliders there
i have an editor window. there are two guilayout buttons, and i wanna change color on pressed. like if i click first button make it black other one is gray, if i click other button , make second button black and first button gray
Hello. I have an editor window used to configure/batch build a scene with different variants (long story. No, I don't have the time needed to make sane). The issue I'm running into at the moment is that there's no time between builds - it's just one long process that doesn't allow the script to go in and make changes. is there any way to make the builds not "batch" together? ae, wait for one to finish, do the next one, etc?
Relevant code:
foreach(TurnaroundObject displayObject in iterators)
{
modelViewer.turnaroundObjectToSpawn = displayObject;
UnityEngine.SceneManagement.Scene x = EditorSceneManager.GetActiveScene();
EditorSceneManager.SaveScene(x,x.path);
MakeBuild(displayObject.name);
SavePreview(screenshotter, displayObject.name);
}
The main issue here is that All the builds are made at once, leaving no time for SavePreview to go into the scene and save the preview for it.
Is there an easy way to stop the loop until the builds/screenshots respectably are done?
yeah, my bad. tired.
I know that the builds are getting batched together though, on account of them morphing into one massive loading screen instead of several smaller ones with interruptions between
there's also only one report at the end which is annoying if one in the middle fails.
For context:
private void MakeBuild(string nameToBuild)
{
Debug.Log("Making build for: " + nameToBuild);
BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions();
buildPlayerOptions.locationPathName = FilePath + "/" + nameToBuild;
buildPlayerOptions.scenes = new string[] { mainScene };
buildPlayerOptions.target = BuildTarget.WebGL;
buildPlayerOptions.options = BuildOptions.None; //TODO, add selections for this kinda junk in the window itself. Target platform especially.
EditorBuildSettings.scenes = new EditorBuildSettingsScene[] { new EditorBuildSettingsScene(mainScene, true) };
BuildReport report = BuildPipeline.BuildPlayer(buildPlayerOptions);
BuildSummary summary = report.summary;
if (summary.result == BuildResult.Succeeded)
{
Debug.Log("Build succeeded: " + summary.totalSize / 1000000 + " megabytes");
}
if (summary.result == BuildResult.Failed)
{
Debug.Log("Build failed! ");
}
}
With the above loop, I'll only ever get the "Build succeeded" summary for the last build in the loop, implying they're all batched together
this isn't really a big issue for me normally, as the builds still wind up in the right spot with the right files and everything, but now that I'm trying to automate the preview, there's no time between the builds to go into playmode for the screenshot
the screenshotting functionality naturally works fine outside the build loop
anybody knows whats the equivalent of deltaTime for custom editor?
I can inaccurately simulate this, but perhaps there's a built-in api for this
There's none
If it's Imgui, then be careful since it's called multiple times a frame
too bad 😢 .. it's uitk, aight wil just make a bogus deltatime then... thanks 👍
You can utilize System.DateTime.Now for your own timers
You gotta make your own using EditorApplication.timeSinceStartup.
Is there a way to draw an object's editor in a custom property drawer cleanly. Can't find a way to control the rect position of the editor instance, I'm currently calling _editor.OnInspectorGUI();
just wanting to say thank you again, I've found a solution that allows me to create this behaviour in C#.
for the custom value types, if they can be supplemented with auto
I have the object type for them have an "isAuto" boolean so that when you create one without a value (e.g. new Length() instead of new Length(200) for px) it'll assume the behaviour is intentionally auto.
I've got tons to do in terms of every possible native style rule but the structure for adding them is at least more extensible
I have a draggable grid in an Editor Window, found this code on the vast interwebs but didn't work fully. On the bottom and right side when the grid was dragged, it wouldn't draw fully. It was drawing one line too less, and wasn't drawing them long enough. I fixed this by adding gridSpacing to both the width and height.
Now, I know that the problem is that the full grid for the given width and height is drawn but the offset is causing it to be drawn off the screen on the top and left side. Math isn't my strong suit but is adding gridSpacing the ideal fix here or would it be better with a different offset? https://hastebin.com/share/qifebudaci.java
You need to be in at least unity 2021.
I don't fully understand, but I think what you want to do instead of the offset spacing thing is to simple draw an additional set of lines i <= widthDivs; (same with height)
That would work for the line amounts but not the lengths but really an additional set of lines shouldn't be necessary, right? The same amount of lines should always be visible, it just depends where the first line is drawn, in which currently could be off to the left or top out of view meaning there's one short. As for lengths, vertical lines never need to be offset up and likewise for horizontal. Sounds like bad offsetting to me but math 🥲
Making your own fluent extension with UITk is the best if you're doing full c#...
so you can do this
visualElement.Size(width, height, isDynamic).FlexRow().BackgroundColor(Color.blue);
so it won't get messy with boilerplate codes
here's a sample of mine
public static T Size<T>(this T visualElement, float x, float y, bool xdynamic = false, bool ydynamic = false) where T : VisualElement
{
var xlen = new Length(x, LengthUnit.Pixel);
var ylen = new Length(y, LengthUnit.Pixel);
if (xdynamic)
{
xlen = new Length(x, LengthUnit.Percent);
}
if (ydynamic)
{
ylen = new Length(y, LengthUnit.Percent);
}
visualElement.style.width = new StyleLength(xlen);
visualElement.style.height = new StyleLength(ylen);
return visualElement;
}
as for cloning, you can bisect the internal InlineInternalStyle class via reflection and clone it, that is if you're planning to do what folks do with clonetree in uitk
uss/uxmls can easily make lots of bloats to your project files, which I really hate
slef promotion: (I'll publish my fluent extenstion for uitk on github soon)
Bogus deltaTime 😃 at least my tweens are tweening smoothly now while in edit mode
var refValue = Screen.currentResolution.refreshRate;
oneFrame = (1d / (double)refValue) * 1000;
while (EditorWorkerIsRunning)
{
if (EditorTimeToken.IsCancellationRequested)
{
timeProp.Stop();
break;
}
timeProp.Restart();
await Task.Delay(TimeSpan.FromMilliseconds(oneFrame), EditorTimeToken.Token);
time = (float)timeProp.Elapsed.TotalSeconds;
timeProp.Stop();
}
UITK is hazy for some of my goals
IMGUI and UIE are my targets, UITK is somewhat... different
UIE ?
https://forum.unity.com/threads/renaming-uielements-to-ui-toolkit.854245/ UITK is UIE. Do you mean UGUI?
I mean, if that works for you, but something like this would work too 😛
float lastTime = 0;
void MyMethod()
{
float deltaTime = EditorApplication.timeSinceStartup - lastTime;
lastTime - EditorApplication.timeSinceStartup;
v = Mathf.Lerp(v, a, b, 2.0f * deltaTime);
}
I mean specifically the UIE element under UITK
UITK isn't my goal, I directly want to use UIE for compatibility between a wider versions bracket in tandem with some API that are experimental or otherwise
can you explain what UIE here? 😃 is it UIElement? isn't that UItoolkit too 😃
Yeah UIE stands for UIElements, which is what UIToolkit was originally called before it was renamed to UIToolkit. So UIElement is UIToolkit. 🙂
Aren't a bunch of controls still in teh UIE namespace?
Yeah everything is still in the UIE namespace. I asked them about it during one of the dev days and they said they sadly are not going to move them. The reason being is because of the way their updater works, it would require them to have a full second set of identical classes that they would have to maintain as well.
Either way
UIE/UITK
Im just targeting specific aspects
They will be aspects compatible from 2019+
I'm not positive this is the right place to ask, feel free to redirect me. How can I access an array of classes for the Editor?
In the OnInspectorGUI in the editor script, I have
Debug.Log($"{usedModules.isArray}");```
And in the ScriptableObject I'm acessing I have
```public Module[] UsedModules;
public class Module
{
public string ExampleString;
}```
If I change it from `public Module[]` to `public string[]` or any other type it works, but with `public Module[]` FindProperty only returns null. Is there something I can do to access my UsedModules variable?
It looks like I just needed to add [System.Serializable] to the line before my class.
yeah this is a very useful thing to know, serializing structs and classes is very handy
Is there a way to check if a string is a valid script name? (ie: doesnt start with numbers or has illegal symbols or spaces in it, etc) I remember vaguely coming across something that suggested this type of validation in the API before but I cant remember which part of the API might have had it - im trying to build a custom editor window that uses script template files (similar to the MonoBehaviour that gets generated when you click "Create > C# Script", but with my own templates instead) and want to validate the name, I can do it manually but if theres already a way, might as well use Unity's approach
That sounds familiar.... Can't remember what though. You can check the ProjectBrowser to see what it does when you rename a asset.
Thats a good idea, ill give that a try
How do I draw labels sideways like this in IMGUI?
haven't done it actually but word is that's it
I see
looks like ultimately it uses this https://docs.unity3d.com/ScriptReference/GUI-matrix.html
Ok great thanks
the best version is this yes 😛 Didn't recommend matrix stuff out of consideration xD
I tried searching both here and on google and came up with nothing.
I want to be able to add information to the inspector window when you choose a folder in the project files section. Does anyone have some information on where I could do this? Thanks!
[CustomEditor(typeof(MyBehaviourClass))]
public class MyEditorClass : Editor {
public override void OnInspectorGUI() {
// Show / hide some thingies depending on other thingies
}
}
So I know that I can create custom editors like this, where MyBehaviourClass is a MonoBehaviour class and I can hide/show fields within MyBehaviourClass.
The thing I don't know how to do is to do this kind of thing for struct / non-MonoBehaviour Serializable class fields, nested in a MonoBehaviour class.
For example class MissileSpawner : MonoBehaviour has:
public enum Pattern { Line, Circle, Square, Puppy, ... }
[Serializable] public struct AttackType {
public Pattern pattern;
public T param1; public T onlyWhenLine; public T onlyWhenCircle;
}
[SerializeField] private AttackType[] attackTypes;
So I basically add more attack type structs to the list from the inspector and depending on the chosen pattern enum different fields would pop up.
Can someone explain how can I do this?
You can get the target object with var myClass = (MyBehaviourClass)target
Then check its attackTypes variable and do your logic accordingly
It's actually not recommended to directly access the target as it makes it harder to properly support undo/prefabs/some other things
If you just want to access field in a non monobehaviour class/struct then you can use something like serializedObject.FindProperty("attackTypes").GetArrayElementAtIndex(0).FindPropertyRelative("pattern")
You can also create a PropertyDrawer for your class/struct instead of an Editor for the Monobehaviour
PropertyDrawers are kind custom editors but for non unity classes
@ornate oriole ^
I was thinking more just for reading the list's values but I guess FindProperty is the proper way then
Sure, it can work for just reading things however you might also run into syncing issues where values are updating in the SO but not in the instance yet
While we are on the subject, how would you go about drawing the elements in a list differently based on something in the parent class?
Say I have a planner MonoBehaviour that has a list of Conditions (structs), which I made a property drawer for:
Currently I'm just storing the success state of that condition in the Condition itself and drawing it with red/green accordingly in the PropertyDrawer, but I would like to not have that data there but in the parent class instead
Yeah that gets more difficult
Usually the solution is to draw it all in the custom editor
Rather than in a property drawer
How finnicky does it get if I still want the nice List UI?
Theoretically, you can go to the parent property in your PropertyDrawer and modify/read it
But that's kind of hacky
I'm not sure on the latest API changes for reorderablelist but this is how it used to work https://blog.terresquall.com/2020/03/creating-reorderable-lists-in-the-unity-inspector/
It's fairly easy but has a bunch of boilerplate
Ty, will take a look 👍
if it's ListView in UItk you can just do listv.Rebuild() and it will sync up the changes automatically
Howdy folks! I'm stuck on how to create a custom class in an Editor script.
In my main script I have:
public int ModuleQuantity;
public Module[] UsedModules;
[System.Serializable]
public class Module
{
public int ExampleInt;
}
And in the OnInspectorGUI in my editor script I have:
moduleQuantity.intValue = EditorGUILayout.IntField(moduleQuantity.intValue);
SerializedProperty usedModules = serializedObject.FindProperty("UsedModules");
usedModules.arraySize = moduleQuantity.intValue;
for (int i = 0; i < usedModules.arraySize; i++)
{
SerializedProperty module = usedModules.GetArrayElementAtIndex(i);
EditorGUILayout.PropertyField(module);
}```
Nothing I have tried seems to work to let me acess or modify `UsedModules`. How could I do this? Thanks!
Okay I was looking, it does appear that my above code can modify the array UsedModules. However, I'm still struggling to figure out how to access one of the Modules to see what is inside from the editor script, which is important because I need access to the variables within Module
At the moment my best way of testing is using target, which from what I've heard you generally shouldn't use, but feel free to correct me if I'm wrong
Okay I finally figured it out. To access a variable within a Module, I can use module.FindPropertyRelative("ExampleInt").intValue within the for loop.
one thing you might want to do, for your sake. Create an extension script that just does "Find" instead
example (without error handling) ```c
/// <summary>
/// A Shorthand Expression for finding an underlying SerializedProperty within another SerializedProperty.
/// </summary>
/// <param name="property">The SerializedProperty to find the target in.</param>
/// <param name="targetPropertyName">The name of the target property to find.</param>
/// <returns><see cref="SerializedProperty"/></returns>
public static SerializedProperty Find(this SerializedProperty property, string targetPropertyName) => property.FindPropertyRelative(targetPropertyName);
That is for the project window, I am trying to add it to the inspector window like such
I'm not sure if this the right channel, but I'm making a simple node editor and you're able to drag nodes, and drag the window. Dragging the window applies the delta to the windowOffset and each node's position. This is fine, but when it comes to saving the graph asset, I don't want to save nodes with the window offset applied.
I made an attempt to resolve this by subtracting the window offset from each node, saving the asset, and adding the window offset back.
However, it saves with the offset applied for whatever reason. I've used Debug.Log to make sure the values are what they should be, and they are.
I'm unsure what the issue is.
public void SaveGraph()
{
for (int i = 0; i < graph.nodes.Count; i++)
{
graph.nodes[i].Drag(windowOffset * -1);
}
EditorUtility.SetDirty(graph);
AssetDatabase.SaveAssets();
for (int i = 0; i < graph.nodes.Count; i++)
{
graph.nodes[i].Drag(windowOffset);
}
}
I'm getting the feeling the saving occurs on the next frame. Removing the second loop, and it will save the values as it should. Either that, or it's asynchronous?
in grapgview api you can't change the position of elements consecutively in single frame... do schedule.Execute to delay a tick
I'm trying to create a custom editor with an animation preview, but one that can have multiple actors in it at once. Not sure how that could be implemented. Would using timelines be the thing I should be starting with? "Powerful Preview" plugin seems to be able to achieve this, but I'd like to write my own implementation
Unity documentation for USS specifies that -unity-text-outline can take <length> or <color> as a shorthand for -unity-text-outline-width and -unity-text-outline-color
does it actually mean it can take both or just one or the other? (there's no || but I'm assuming you might be able to?)
well with the common properties reference it seems that it's both
so I'm assuming it's meant to be and-or
You can use PreviewRenderUtility to do it. Though it is undocumented unfortunately
oh wow, I never knew this... I used the janky asset preview or some sort 😭
time to update
yeah this article mentioned that it's undocumented https://www.blog.radiator.debacle.us/2016/06/working-with-custom-objectpreviews-and.html
like, why Unity?
Unity doesn't document some things
then there's just Internal
Internal is probably documented only in internal handbooks or stuff
Btw, a good way to see how to use it is both to look at its source code, but also where it is used. The GameObject editor uses it, along with the mesh asset editor (and others).
Tbh, probably not. Maybe some of it is, but not most of it... at least that is the impression I get
Not if you are 10th level black magic wizard or higher!
you could create a full on horror game about debugging a game engine's internal namespace
actually we could create an in-engine plugin that turns Unity Engine into a horror game
and you have to debug the full game engine, passing through mystic cryptid secrets
that would be scary (to an extent)
So like... just normal editor scripting?
Thanks, I’ll take a look at it!
Hey, i need a little help. I know this isn't related to coding but I couldn't find any other channel to post it in. I recently upgraded from 2021.3.4f1 to 2021.3.21f1. For some reason, my main colliders on prefabs are showing in scene view, but the colliders connected to child objects are not showing. I looked through my gizmos to verify that box colliders are turned on, and they are. Is this an issue anyone else has experienced before? How can I get the collider gizmos to show up in scene/game view, because before I upgraded everything was fine and visible.
I need some help figuring out how to convert my existing code to the experimental Graph View editor.
My Node Editor currently looks like this
And I want to have it look like this
For that I am following this tutorial https://www.youtube.com/watch?v=6vVqBt_5nbs&list=PL0yxB6cCkoWK38XT4stSztcLueJ_kTx5f&index=8
In this video we'll be creating our basic, non-styled, Node.
They will end up acting as our dialogues, including their data and their connections with other dialogues.
Timestamps:
00:00 Introduction
00:21 How is the node structured?
03:44 Adding the base UI
08:45 Drawing the node in th...
And am I making it while using my own code
But now I am sitting with errors I have no clue about how to fix.
The top and the bottom error are the exact same just on different lines of code.
In Rider it tells me this
So it would be awesome if I can screenshare my code or get some help figuring this out.
I am following a intermediate coding course in which I build these RoomNode's and I have some Okayish coding experience at least good enough to follow the course and understand what I am doing but not good enough to convert it properly to look similar to what I want it to look like or at least I can make it look like it but can't make it work.
Another issue is that of right now my Nodes from my old system don't work anymore.
If you can help me please then do tag me as I am on a single monitor and am coding at the same time too.
what is the class signature for RoomNodeSO?
A Node which is necessary to make the Graph View understand that I am adding a note, I still have to update the RoomNodeSo name to just RoomNode as it used to be a Scriptable Object and I still want it to use the Scriptable Object logic but work as a node too.
But Node does not inherit from UnityEngine.Object, so you cannot use it in the SetDirty method
I see, how do I change this then to make it work?
I'm not sure you can. I think you will need to save the data yourself (maybe in a SO) and then build everything on the fly
basically you cannot save a Node. But you can save the underlying data from which a Node can be created
Mhmm okay, then I go with the old system but is it possible to use the Graphview Gridbox background?
I basically created this script:
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEditor.Experimental.GraphView;
using UnityEditor.Graphs;
using UnityEngine.UIElements;
namespace NodeGraph.Editor
{
public class RoomNodeGraphView : GraphView
{
public RoomNodeGraphView()
{
AddManipulators();
AddGridBackground();
CreateNode();
AddStyles();
}
private void CreateNode()
{
RoomNodeSO node = new RoomNodeSO();
AddElement(node);
}
private void AddManipulators()
{
SetupZoom(ContentZoomer.DefaultMinScale, ContentZoomer.DefaultMaxScale);
this.AddManipulator(new ContentDragger());
}
private void AddGridBackground()
{
GridBackground gridBackground = new GridBackground();
gridBackground.StretchToParentSize();
Insert(0, new GridBackground());
}
private void AddStyles()
{
StyleSheet styleSheet = (StyleSheet)EditorGUIUtility.Load("RoomNodeSystem/RoomNodeGraphViewStyles.uss");
styleSheets.Add(styleSheet);
}
}
}
To do my Graph view
Then I got this for my Editor
That looks very simplistic. My Graph view stuff is much, much more complex than that
In here I basically call the AddGraphView(); and AddStyles();
and then I got this final code
I think you have a long learning curve ahead of you
I think so to, I use Unity since 4.11 but started coding about half a year ago.
I know pretty much everything else on Unity.
Needed to do some of the optimisation, Old UI building, Scene Build and Other related tools for my work.
GraphView is not fun, it takes a lot of effort to learn and use. That said, when it works it's brilliant
Anyways the moment I put the AddGraphView(); method and AddStyles(); method in onEnable() my whole logic for the nodes breaks.
If I remove those two the stuff works but then the background is gone.
This is what it looks like when it works
wait one
And this is what it looks like when I add the background changes in.
Then the nodes are gone and I cant make them either anymore.
Now I don't know if putted the code on a wrong point which may gets executed first or if I do something else wrong but I been playing around with this for the past few hours.
I got a lot of cool stuff going like the manipulators and stuff but this is kinda like a difficult one because I like the grid box background over a one color background.
How you mean wait one?
I also kinda do like to know if its possible to create input and output ports without using the Graphview window for my nodes because then the connections make much more sense.
I mean wait a moment, I want to show you something
Oh yes that's fine, you can also DM me if you do prefer and then I can just send you the code.
I am building this as a game that I later want to convert into my own asset for on the Asset Store with it's own art and these kind of things.
All my code is commented line by line and I write documentation as I progress in my scripts for each bit of code.
So I been making sure things are easily readable. I have only not commented the GraphView script yet as I am still working on this.
I'm just trying to let you know what you are getting into
This is a simple Database creation/modify tool made in graphview based on data stored in an SO
it contains more than 50 custom scripts
nothing is simple when using grahpview
and it's still experimental which means all of the existing code can become worthless overnight if Unity so wishes
I see well that looks really cool.
Yeah it did be probably easier for me to show you my scripts but since its directly the source code of my game I kinda don't wanna put that all in here.
I got pretty much like 20 or 30 hours in my project in terms of code writing but everything works and it's not only this window the code also makes changes to things happening in the Editor and for the data that it does store.
tbh, unless you really need to use graphview I would steer well clear of it
Yeah for me the three things I wanna use from it are the Gridbox Background, Manipulation of the Editor window and the Input/Output Pins/Ports for the rest I am not planning on using stuff.
Maybe over time adding in a sidebar inspector window to create stuff more easily but not currently my goal.
I just overall dont like the way my editor does look right now and I know people already been making graph based editors before those experimental tools got introduced take Bolt as an example.
So my goal is to have it look better.
If I can do so then that would be great but right now I just have some issues with it.
Do you know if I can use/add these three things without using the graphview?
no you cannot. I/O Ports is specific to graphview
if you want my advice, stick with what you have for the moment and wait until graphview becomes production
unity tell me it wont be that long to wait
Will do and but what about the manipulation of the window and the gridbox background?
That maybe OK using standard UIToolkit, you would need to experiment
but I suspect that the manipulators are specific to graphview
Would you also know why the moment I call AddGraphView()
and the other one it does not work?
wdym? they will definitely deprecate GraphView in favor of GTF
as said by the staff himself
What is GTF?
Mhmm I am gonna look at that
@short venture I have send you a message, if you are okay I send you my code in a private DM.
I basically just still need to figure out how to add the gridbox from the GraphView into my personal editor.
Currently it is still using the experimental stuff.
I do it now like this but that does not work with Scriptable Objects as you say so I have to figure out how to make it work in my script.
Integrations of external scripting tools are broken
I got these 2 methods
But then when I call them in the Editor Script all my nodes are gone.
did anybody face that ctrl+s(VisualStudio) opens save window instead of just saving changes?
i restarted VS, Editor and PC
only regenerating of VS project files is helping for a shot time
I dont have this issue since I work in Rider
Hey @tawny tangle, I disagree with some of what Steve said. GraphView can be a lot to setup. But it definitely can be worth it, and less work than doing the same thing manually.
Also, ignore GraphToolsFoundation (for now), the package is deprecated as it is moving to the core engine, but it won't be in until at least 2024.
Can you summaries what your current issue is? It has been a bit since I used GraphView but would be happy to help as best I can 🙂
I am finishing up diner but I have added you as friend. If you did be okay I love to send you the info plus my code via DM.
Okay let me create a thread on this.
someone know why Bolt setup dont finish?
if i click generate it doesnt work and in visual scripting appear this
yeah I'm using GraphView
but that's purely for version compatibility between 2019-2023
that and it's baked into Unity Engine still, via Experimental so for those versions if you want something that you know is in there it's there
GTF right now is a package that I believe you install instead and it can be hazy whether or not someone has it installed
Please forget that GTF is even a thing. For all intents and purposes it does not exist.
#763499475641172029 would be the appropriate channel for this question. Good luck!
w- whuh?
like legally, metaphorically or is it just a pain?
I took one look into the documentation
NOPE
ill just- just take my chances with graphview.
Better to use GraphView yeah.. GTF will be way too long before it finally be official
I'mma be honest
Graphview is a very funky api in Unity but it's not all that bad
Translating MDN CSS is hard enough before I even get onto doing GraphView stuff
but translating the GTF documentation
The GTF package was originally released in a experimental state. But they changed plans and decided to make it a core part of the editor since it would speed up development for them and it will be used all over the place. As such the package has not been update for like 2+ years, and I suspect the built-in version is going to be a good bit different of an API.
At the soonest we would see GTF build-in would be 2024.
Additionally, the API for GTF is just really bad. Lots of boilerplate.
even the internal namespaces are terrible
I will state right now
I regret trying to translate background-position
a good portion of dealing with background-position is just the infinitessimal possibilities for it to mess up
No, it is "we will see it as a built-in part of the engine in a year or so". The devs said a month or so again that ShaderGraph is currently being moved to it.
feels like they're were experimenting back then and were like Yes! lets use this
Yeah, they also used terminology like View, ViewModel, and Model. The whole thing felt very 'un-Unity'
either way I'd feel hesitant using GTF
and I don't know how long it'll be before they fully just yeet GraphView experimental API
No, don't feel hesitant! JUST DON'T USE IT!
It is not meant to be used. It is deprecated!
I'm not saying GTF as in the package
I'm saying GTF as in the thing that'll materialize in a year
it will not
I have no idea what they'll call it in a year specifically
Ahh, no that should be 100% fine to use!
whether or not it'll replace GraphView, the Experimental thing or it'll be it's own namespace
GraphView took years to reach the current state
Also, I said 2024 at the soonest. There is no official word on it. That is just my own guess
Also, GV is basically in maintenance mode and will eventually be replaced with GTF
also are there any specific restrictions to how Unity's USS handles background-position
or is it all just CSS for anything not in Unity's USS pages
What do you mean "background-position"?
I don't think there is support for that in USS...?
USS Supports background-position, a CSS value
it's in the reference pages
just it links directly to the CSS page
Ahh it was added recently
huh
wait
it's been in since 2022.2?
I thought it was in 2021.3
oh bother
these are the values I've yet to add support for: background-position background-position-x background-position-y background-repeat background-size border-bottom-color border-left-color border-right-color border-top-color letter-spacing text-overflow text-shadow word-spacing
some have been in for ages
some haven't
I'm gonna just wrap a preprocessor directive around it for 2022 or newer
welp i started writing background-position, might as well finish the fight
ended up just doing them all - every single one has been carefully checked and wrapped around #if UNITY_2022_2_OR_NEWER statements
Don't currently plan to support the global keywords that CSS has as I don't exactly know how to integrate them without issues in some cases
Hey there! Is there a way for me to position nodes automatically in GraphView? To over simplify, I have a bunch of nodes that have connections. I was looking to create a visualizer for these nodes. I've gotten as far as creating a graph view, populating it with nodes, but I don't really know how I would go about automatically laying out the nodes.
Given an arbitrary number of nodes with connections between them, how would I lay them out automatically on a graph view in a relatively good looking way (doesn't need to be perfect, just avoid overlaps as much as possible)
could do this: foreach (var node in nodes) { node.position = ..; } (?)
the 'good way' to position them will have to be your own algorithm
Just general talking and off topic stuff is not allowed on the server fyi. Best to do that sort of thing in DMs 🙂
first I've heard of that rule, didn't see it in the rules channel
Hmm, they might have removed it, my bad
It's alrighty
I can see why it was a rule - I'd just be wary of who I'd DM purely because of the unsolicited DMs rule - I'll move those types of messages into another channel if there is a more relevant social channel.
So I have a list of strings being drawn in a SettingsProvider OnGUIusing EditorGUILayout.PropertyField
Is there any way at all to "lock" the first few elements of this list? In this screenshot I want the first 3 elements to appear grayed out and not editable by the user (and not rearrangeable either). The rest of the list should be freely editable and rearrangeable. How would I approach this? I'm kind of assuming I won't be able to use EditorGUILayout.PropertyField directly.
Honestly I'm trying to recreate something like the built-in layer editor
Would need to use the ReorderableList instead of PropertyField. As far as I know, there is no way to prevent reordering of only certain elements.
I can think of a few ways you might be able to do it sort of. But it would be ugly and funky and far too much work 😛
Thats good. Then ReoderableList is where it is at.
In the draw row callback, just check the index and do GUI.enable = false; PropertyField(); GUI.enable ' true;
It's been some time since I used it... where can I find some examples?
I see there's a ReorderableList class but it's a little unclear how to draw one in IMGUI
Do I want to be using GetReorderableListFromSerializedProperty?
The heck is that? Never seen it before.
idk haha
here is a wrapper a made for it some time ago that lets you just give it a property and then call on the instance DrawLayout() https://gdl.space/ramewijube.cs
Might be too much going on to get a good idea of how to use it idk.
Seems like you just make one
and call DoLayoutList or DoList to draw it?
(after setting callbacks etc)
Yup
How would I make a Visual Element take up 100% of the screen height?
height: 100%?
Tried that, but isn't that 100% of the container?
I have a Visual Element with a ListView Inside + another VisualElement inside. I want everything to be 100% height, so I set them all to 100% but they don't strech all the way up
(Sorry, should have added this information in the original question)
@mint plaza listView.style.height = new StyleLength(new Length(100, LengthUnit.Percent)))
the shorthand new Length() would work too and much simpler
just make sure the parent is already filling the whole screen
if the parent actually smaller than your screen size, detach it from that parent and do position.absolute
Right I was doing that through the UI builder, and had the parent also at 100%. Ideally I wanted to avoid absolute positioning elements
Yeah even though I set it at 100% like you suggested, but using the UI builder, it doesn't seem to grow to 100% the container size
oh wait, that's c# I posted haha my bad 🤣
No worries haha
Also, curiously in the UI builder it shows up at 100% size as expected
pretty much the same
But not in the window itself
which does make me wonder if I'm just being a dummy or if something sketchy is going on
I have a GameObject which is a prefab instance and one of its children has a CustomEditor button which allows to delete one of its children properly. But when trying to do it I get this error, any ideas how to get over it?
InvalidOperationException: Destroying a GameObject inside a Prefab instance is not allowed. UnityEngine.Object.DestroyImmediate
It is a prefab instance. That means it has a set structure which you cannot remove from or reorder.
To be honest it sounds like a poor setup overall, having a parent GO delete a child GO in editor.
unpack the prefab then destroy?
Could you suggest a better one?
Not without knowing what the reason is for what you are doing, the goal, etc.
Basically recreating this asset https://assetstore.unity.com/packages/tools/utilities/node-map-97266 but trying to make it more extensible. Currently there are "agents" which are those who navigate the map and I'm trying to create my prefabs as their children to do what I want
I see. So what is the child you are trying to destroy from what?
So I added the feature to choose what prefab your agent will have under it via popup. Basically I'm destroying the existing prefab instance and creating a new one
Any clues why this method would never get called?
[CustomEditor(typeof(MonoBehaviour),true)]
public class DataBasedComponentDrawer : UnityEditor.Editor
{
public override void OnInspectorGUI()
{
//code
}
}
Perhaps because you are trying to add a custom editor for MonoBehaviour?
Only spawn it at runtime is what I would say.
Doesn't sound designer friendly to me
I don't really understand the use-case so it is a bit hard to say.
I need it for my use. I googled and people suggested this..
Modelling levels fastly
Try Component instead of MonoBehaviour
But I mean why does the agent need to be visible while designing the level?
huh that worked, tyvm!
It is because MonoBehaviour already has a custom editor.
oic
That should be done on the prefab it is instantiating, no?
You can't see the whole level when editing a single agent
Why would you need to see any of the level when editing a agent...?
To adjust it to the level
For example colors combination might not be satisfying
#🖼️┃2d-tools is the channel you want I think 🙂
Ok, sorry
Can you change which type it is at runtime?
No
Then don't use prefabs like this. Have a base prefab, and then create variants of it, one for each type. Then add the 'type' prefab that you are instantiating right now as a child to the prefab variant.
Does that make sense @wintry trout?
Trying to read it correctly
Base GO
Base GO Dog Variant
> Doggy
Base GO Bee Variant
> Bee
Ah it appears this doesn't work either:
[CustomEditor(typeof(Component),true)]
public class DataBasedComponentDrawer : UnityEditor.Editor
{
public override void OnInspectorGUI()
{
}
}
I had a debug point but it was getting called from an AudioListener which is not monobehavior :(
So, you have an Agent base prefab, right? Then you create a variant of that prefab. Call it something like AgentDoggy and on that variant, you add the Doggy prefab. So you don't use that dropdown any more, instead you have a prefab variant for each agent type
Yeah, AudioListener is a component
Yeah but this editor is not called from classes that derive from monobehavior :(
Agent itself is plain GO with Transform and Agent scripts only even without being a prefab. Because there is no need for it to be a prefab.
GameObject newAgentGO = new GameObject();
newAgentGO.name = "Agent";
Agent newAgent = newAgentGO.AddComponent<Agent>();```
So just add the agent component to the Doggy prefab then and call it a day?
How would I change doggy to something else then?
You wouldn't
You would have one prefab == one type.
You are trying to have a prefab, which is a static template, but then also change it. Which is counter to the point of a prefab.
You can't have something static and dynamic at the same time
What's your suggestion for changing the agent's template then? Adding it by hand each time?
Yeah
Or you could have a window I guess that has the dropdown which you can use to swap it out
I have another idea
I will supply a clear map, then you can create agents as you want
Tho it has another limitation...
Does anyone know whether this behaviour got changed? http://answers.unity.com/answers/1251668/view.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.
It's so frustrating googling for 30 minutes and all you see are answers from 2016 that no longer work :(
Is it possible to modify built-in editor windows? In my case I want to add a "Label" (Similar to event but just act as timestamp) to the animation dopesheet.
Is it possible? No, but sort of yes. Basically what you would need to do is to register a callback for when any editor window opens, if it is a Animator window you can add a visual element on top of what is already there. Basically you can only overlay elements on top of the window, and you have to manually position them.
So with some hackery and headaches it is possible to sort of modify them, but only sort of.
Yo, I'm playing around with Custom Property Drawers, how do I set up the bloody rect position properly for my properties 🥹
When resizing the inspector it seems like the input boxes just stay on the same spot on the screen (more or less) and try to readjust themselves to the changing inspector window size
You use the width of the rect that is given in the draw method?
// public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
EditorGUI.BeginProperty(position, label, property);
position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);
Rect initialRect = position; {
initialRect.x = 30;
initialRect.y += 20;
initialRect.width = 200;
initialRect.height = EditorGUIUtility.singleLineHeight;
}
// Pattern Property
SerializedProperty patternProperty = property.FindPropertyRelative("pattern");
Rect patternRect = initialRect;
patternRect.height = EditorGUI.GetPropertyHeight(patternProperty);
patternRect.width = 290;
EditorGUI.PropertyField(patternRect, patternProperty, new GUIContent("Attack Pattern"));
Here's the piece of my code up to the first property (please keep in mind that I just started playing around with this and I have close to no idea what I'm doing)
Why are you using a prefix label, do you know?
This
initialRect.width = 200;
And also this
patternRect.width = 290;
are why you are having trouble. Don't hard set the width like that.
Idk what PrefixLabel exactly does, but it was in a few tutorials and without it my Element 0 label goes away, so I left it there
Oh, so that's the problem... I was trying to set the width of the input box, but now I guess that's not how I do it..
And yes, removing initial.width = 200 does kinda resolve the problem, because it just uses the full available width
I was trying to achieve something like having a hard set width of label + input area as a whole, which would just readjust it's position to left/right depending on how I resize the inspector window
^ like this
where the size doesn't change when I resize the inspector window
So you don't want the size to change when you resize the inspector?
Nope, I want to have one set width for them
basically so it would look nicer instead of having the full width of the inspector
purely aesthetically
A PrefixLabel is a label that is focusable basically. An the rect is the field rect. The docs have a decent explanation https://docs.unity3d.com/ScriptReference/EditorGUI.PrefixLabel.html
So, isn't that what you had originally by setting the width? What was the issue with that then? I guess I didn't understand
The problem was the X position of the property in the inspector
it wouldn't move right with the inspector being resized to a smaller window / or left when being resized to a larger window
it would just stay in place with it's "right border" being dragged around right and left
the label adjusts it's position, but the boxes stay in place and only get bigger (or smaller and even negative in size)
here's a short video
I have a custom editor which when I click a button gathers some data into the inspected GameObject. But even though I see that data, it doesn't get saved after I press Ctrl+S. Once the game is launched values disappear. The same happens when I restart PC, reload scene or relaunch Unity. Tho if I change some OTHER values in the inspector some of the unsaved once will become available for saving. I don't understand why.Any ideas how to fix it?
Basically I want a hard set distance from the label to the input box so it wouldn't (hopefully) behave in such a way
Saving editor data
Well, saying this out loud certainly did help.
Oh odd. I feel like I should know why, but it isn't coming to me atm, and I don't have time to figure out right now sorry. I would start by making a dummy class with a single field, and get that to behave how you want.
Welp, I solved it somehow so it's ok now, thanks anyways
I love it when that happens haha
I can finally go to sleep.
I started getting dizzy but a man can't just leave a piece of code unfinished.
Someone suggested to use a callback for when any editor window opens and overlay it with my own UI to "modify" existing windows.
Is there already an existing callback for that or do I have to use something like EditorApplication.update and EditorWindow.focusedWindow?
Anyone here familiar with Handles.DrawBezier? I'm trying to use it to draw lines in a custom editor, but when I assign the texture it comes across as two very thin lines, rather than the texture appearing in a recognisable way. Thoughts on what might be happening?
okay I tried a different texture and it shows a weird streaky effect (the edge of the pic on the left, the editor window and line on the right)
okay I changed the texture mode to 'Editor GUI and Legacy GUI' and now the twin lines appear a lot thinner
I don't know what you're expecting. I don't think it uses anything but the y axis and X 0 swept across the uvs
A typical use case is a 1x2 texture, not something big
I was hoping to make the arrows tile in the direction of the line
Does anyone happen to have any good guides on using the IMGUI system?
I'm getting negative values on position.width's print. -288.8f. The Inspector window is plenty wide atm
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);
var buttonRect = new Rect(position.position, Vector2.one * WIDTH);
position.position += Vector2.right * WIDTH;
position.width -= WIDTH;
if (position.width < 0)
Debug.Log(position.width);
}```
well, try fixing your WIDTH variable? 😛 What are you actually trying to do?
mind you're not using the buttonRect at all in shown code
WIDTH is a constant float of 20f
I know
ah, I know
you're actually using this as position position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);
that's pretty small
I have no clue how the -288.8f can happen though
this is the property. As you can see, it's looking good. However, it prints negative width values sometimes
It's actually ruining some TextArea height calculation in a similar property drawer
sry I can't figure out why this may happen :/ I blame unity's strangeness
however I could help you fix the height thing if u want, lol
I'm trying to draw a plane that 'highlights' the forward plane of a box collider. It's not working and I'm not sure why...Can someone take a quick look? https://hastebin.com/share/vunununici.java
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I only set the value if width > 0 (that is the fix), but this issue baffles me
you could use a smaller version:
void OnDrawGizmos() {
if (!this.TryGetComponent<BoxCollider>(out var box)) { return; }
Gizmos.Color = Color.green;
Gizmos.DrawWireCube(box.bounds.center, box.bounds.size);
}
I see these potential issues there:
- you're using localToWorld but still using
transform.rotation - no normals are defined on the Mesh
This is what I did. 20f being the WIDTH. Hope this helps.
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
using (new EditorGUI.PropertyScope(position, label, property))
{
position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive) + 2, label);
Rect popupRect = new Rect(position.x, position.y + 1f, 20f, position.height);
Rect fieldRect = new Rect(position.x + 20f, position.y, position.width - 20f, position.height);
// 0 == true, 1 == false;
bool result = EditorGUI.Popup(popupRect, useConstant.boolValue ? 0 : 1, _popupOptions, Styles.PopupStyle) == 0;
EditorGUI.PropertyField(fieldRect, property.FindPropertyRelative("_variable"), new GUIContent());
}
}
Ah, the first one is an easy fix. How do I define the normals?
per vertex :p
something like this?
mesh.normals = new Vector3[]
{
Vector3.forward,
Vector3.forward,
Vector3.forward,
Vector3.forward
};
yup! but with proper directions
also, you use box.size twice
since it's local, in DrawMesh you just gotta pass Quaternion.identity as rot and Vector3.one as size
not sure if box.center is local also
why do you use this line actually? 😛 Gizmos.matrix = transform.localToWorldMatrix; // following Gizmos will be drawn in this transform's local space.
I used to handle this by drawing a line, I just forgot to take it out
I'm not sure how to handle the directions for the normals.
try skipping them, maybe normals aren't needed in your case and the issue was just the localToWorld
call some of these too 😛 after creating the mesh
maybe this as well https://docs.unity3d.com/ScriptReference/Mesh.UploadMeshData.html
OK, recalculatenormals worked, but the normals are drawn the wrong way
Change the winding order of the indices
yea that may or may not work out of the box depends on how lucky u get assuming indices order xD
Oh dear, I am not sure how to do that...
wait, I think I have it
ok, last question. When I draw this mesh, it it lit as if it was in the scene...how do I make it unlit (like most gizmos)?
Nope :p
Why not Gizmos.DrawCube?
Size.y can be 0.01 to make it look like plane
Because I want it to be backface-culled.
For context: I am trying to create a one-way trigger in 3D. I'm wanting the gizmo to represent visually which side actually detects collision
Could you guide me through the process? Debug.Logs are still triggering. Is this normal?
protected const float WIDTH = 20f;
protected const float HEIGHT = 20f;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);
var buttonRect = new Rect(position.position.x, position.position.y, WIDTH, HEIGHT);
var fieldRect = new Rect(position.position.x + WIDTH, buttonRect.position.y, position.width - WIDTH, position.height);
if (fieldRect.width > 0)
PropertyWidth = fieldRect.width;
else
Debug.Log(fieldRect.width);
}```
What is it logging?
-288.8f
Hmm.. debug.log the width at the top before modification, and after the PrefixLabel. As far as I can tell it should be all working just fine...
prints either 1 or 621. The inspector window is pretty wide right now
the 1 is constant between different widths
printing before prefix label
oooh, does the last width debug.log you have print every frame?
I might doing some poo poo here tho. This is a BasePropertyDrawer class that is to work with BaseReference classes. Both are abstract and base to concrete classes like SpriteReference, etc...
what do you mean?
// Change this:
if (fieldRect.width > 0)
PropertyWidth = fieldRect.width;
else
Debug.Log(fieldRect.width);
// To just this:
Debug.Log(fieldRect.width);
the Debug was right after the opening bracked of OnGUI
printing 1 and whatever width my property had in the inspector
now it prints the negative value (1 - PrefixLabel.width - WIDTH) and (RealValue - PrefixLabel.width - WIDTH)
Working now! Even added an arc without much issue. Thank you!
On the Derived classes I tried a clean OnGUI print, same results: 1 and whatever width it has in the inspector window
If you don't cache this you have a massive memory leak
a Mesh is a UnityEngine.Object that exists in native memory, it has to have Destroy called on it manually
I have a debugging package that can do this sort of thing easily without leaks https://github.com/vertxxyz/Vertx.Debugging
Thanks for that! adding a mesh to the gizmo may just be more trouble than it's worth.
Writing custom inspector. I forgot how to check which scene event type the draw is during this draw frame. I'm not really sure how it's called, so I apologize if I am butchering my question...
Scene Draw phase or Editor Draw phase? Scene Draw (aka Scene Rendering) is after LateUpdate, as this graph shows. https://docs.unity3d.com/Manual/ExecutionOrder.html
Hi everyone, I've been looking into making an inspector for a scriptable object asset. This would be for generating some form of mesh, I've got this working with the PreviewRenderUtility to display the mesh, however I want to also be able to interact with this. I'm wondering, how do we use Handles with this? Is there a way to do it directly within the same editor script that creates the render or would I need to set add a component to the object I am rendering within the scene that separately controls this?
IIRC there is a class called something like Drag2D. I would look at the source code for the GameObject inspector to see how it handles showing previews 🙂
Thanks, I'll have a look ^-^
Hey everyone, how can I free the memory of an ongoing web request before a domain reload causes the release of an invalid GC handle?
Here is the relevant code:
private static List<(UnityWebRequestAsyncOperation, Action<AsyncOperation>)> webRequestSubs = new();
[InitializeOnLoadMethod]
static void OnInitialize()
{
EditorApplication.delayCall += OnDelayedCall;
AssemblyReloadEvents.beforeAssemblyReload += OnBeforeAssemblyReload;
}
private static void OnBeforeAssemblyReload() // Trying to clean up all the web requests <-------------------------
{
AssemblyReloadEvents.beforeAssemblyReload -= OnBeforeAssemblyReload;
for (var i = 0; i < webRequestSubs.Count; i++)
{
if (!webRequestSubs[i].Item1.isDone)
{
webRequestSubs[i].Item1.webRequest.Abort();
}
webRequestSubs[i].Item1.completed -= webRequestSubs[i].Item2;
webRequestSubs[i].Item1.webRequest.Dispose();
}
webRequestSubs.Clear();
}
In OnDelayedCall:
UnityWebRequestAsyncOperation webRequestOperation = webRequest.SendWebRequest();
...
webRequestOperation.completed += HandleCompletedRequest;
webRequestSubs.Add((webRequestOperation, HandleCompletedRequest));
Is there an error in the transition documentation for USS?
it says for "transition" that the first time value is for the delay and the second is for the duration - which, if only one is supplied means that the transition delay is supplied and not the duration (meaning a transition will wait n seconds and take 0 seconds to change between values)
CSS documentation states that the first time value is for transition-duration, not transition-delay
link?
the MDN CSS documentation has a conflict with which order it goes in: "zero, one, or two <time> values. The first value that can be parsed as a time is assigned to the transition-duration, and the second value that can be parsed as a time is assigned to transition-delay."
This is admittedly not my area of expertise. But I am not sure I understand what you are wanting to do. Would you be able to explain differently what you are wanting to do?
I mean, the quickest way to find out would be to write the uss and see what it does 😉
I'd try but I don't have any examples to build up for a USS editor window
this is genuinely the final style rule I've got to do as well
wait what @ unity
nvm
it is probably an error LOL
I didn't even need to look far
(I reported this error an hour or so ago under incorrect/confusing information on the page)
so that feels vindicating
it's probably duration, delay
and it's the way everything else generally fits together
so I'm very sure it's either an error or something not fully explained why
It would be really confusing to have delay over duration
I'll just keep it as duration, delay in the docs
and if it ever needs changing I'll revisit it
just no point over semantics with it because if it's wrong, at worst it's five minutes fixing
MDN CSS vs Unity USS documentation feels like playing "who's right, mom or dad?"
I want to do some web requests from an editor script which doesn't inherit from any class.
When a domain reload is triggered while a request is ongoing, there seem to be some resources which aren't cleaned up, which trigger a invalid GC handle exception.
I just modified my code to use an editor coroutine instead of callbacks for the webrequests but that didn't fix the exceptions.
I'll try storing a reference to the coroutine and stop it on beforeassemblyreload. Maybe that will work 🤷♂️
That didn't work either, next I'll try using EditorApplication.update to manage the webrequest
Is there any way I can add this little lock to my own Editor Window? It updates everytime I select something new and I want to be able to lock it from updating, same way as the Inspector works. Seems neater to use the lock if I can rather than making my own radio button.
void DrawStateWindow(State state)
{
Vector2 contextButtonSize = new Vector2(20, 20);
Vector2 position = new Vector2(stateObjectSize.x - contextButtonSize.x, 0);
Rect contextButtonRect = new Rect(position, contextButtonSize);
if (GUI.Button(contextButtonRect, GUIContent.none))
{
Debug.Log(state + ": Context button clicked");
EditStateMenu(state).ShowAsContext();
}
/*
Right click to show context menu:
* Add transition
* Delete state
*/
}
This function runs inside GUI.Window. The button appears and can be clicked, but the code inside the if statement doesn't run. Any idea what's happening?
Also figuring out how to display the standard editor view for a value, but inside another editor window
PropertyField/Editor.CreateEditor
cheers thanks, that works now. Although I'm getting a weird problem where I can't edit anything in the windows
Show your code
@waxen sandal The GUI.Button and the OnInspectorGUI display properly, and show the correct values, but don't respond in any way outside of animations when you click on them
DrawStateWindow runs inside of GUI.Window
You have to cache the instance of the CreateEditor
What does that accomplish? I'll presumably have to make an array of them because it runs that function each time for an array of states
No idea why your button doesn't work
It recreates the editor each frame, which means it's recreating the serializedObject each frame, which means changes never persist
Nor does the editor get disposed and thus you also have a memory leak
okay screw that I'll draw the editor somewhere else then
I was hoping I could make it be drawn in the inspector when I click on it, but I didn't figure out how to do that
but if I do that I can just have one editor reference to cache, that changes when I click on it
@waxen sandal the function from which DrawStateWindow is run (as the 'function' parameter), in case this is screwing up:
void DrawDraggableWindow(ref Vector2 position, Object objectWithPositionStored, Vector2 size, int id, GUI.WindowFunction function, string name)
{
Vector2 offset = -size * 0.5f;
Rect windowRect = new Rect(position + offset, size);
windowRect = GUI.Window(id, windowRect, (i) =>
{
GUI.DragWindow();
function?.Invoke(i);
}, name);
Vector2 newPos = windowRect.position - offset;
if (newPos != position) // If position is changed, confirm value and record in undo history
{
Undo.RecordObject(objectWithPositionStored, "Set position");
position = newPos; // Update value to save change to the node's position
EditorUtility.SetDirty(objectWithPositionStored);
}
}
Looks fine to me but its been a long time since I looked at windows
Could try using guiLayout.Window and use GUILayout.button and see if htat works somehow
tested, I need to use GUI.Window so I can use GUI.DragWindow() and change the positions easily
But does it work
nope, makes it really weirdly small for some reason
but I'm going to try limiting the drag zone to a small section
@waxen sandal solved it, the problem was the draggable hitbox overlapping with the other buttons
Also @waxen sandal creating the editor on the spot doesn't stop the values from being edited
although yeah there's also the optimisation thing
Is there any way I can hook into an asset duplication event?
I want to change some serialized fields to be a different value when something is duplicated
Ideally I want to have access to the original asset as well as the new one
thanks @waxen sandal
Anyone know if there is a way to see the inside faces of a Handles handle? Specifically the SphereHandleCap?
Wasnt sure where to ask this, is it a known issue that when changing the swizzle of a unity tilemap and using gameobject rule tiles that the swizzle is not applied to the gameobjects correctly?
I found this which seems to be an old mention of it but cant seem to get the solution to work and the post seems quite out of date: https://github.com/Unity-Technologies/2d-extras/issues/201
What is the code running when you click this button?
Is there something off about my calculation for scene view camera to the object?
how do I recreate that "enable constrained proportions" lock button?
in a custom property drawer
so that it'd be next to these animation curves
🤷 look at the source https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/Inspector/TransformInspector.cs#L98
https://github.com/Unity-Technologies/UnityCsReference/blob/cf0545699c3656babdff41124680a038fbbcef4e/Editor/Mono/Inspector/ConstrainProportionsTransformScale.cs
Though I imagine your implementation could be a lot simpler, just find the icon they use, draw it as a toggle, and implement the constrain logic
hrm, how would I find the icon? I often want to find one but I don't know how to.
and usually google isn't very helpful
Presumably the icon/style is in the source code I linked
ok, thanks
Seeing as it's UI Toolkit it's probably also in the style and you can use the UIElements Inspector to look at the element.
I'm not going to do any more poking around, but it could also be in defined the styles they add to the field https://github.com/Unity-Technologies/UnityCsReference/blob/963b05b9d90f9876da8897d75842010603ad6727/Modules/GridAndSnap/LinkedVector3Field.cs#L48
ok, anther question then. I get this error when I try to maximize in play mode:
it pauses the game.
I'm drawing the curve like this:
x.animationCurveValue = EditorGUI.CurveField(position, new GUIContent("X", "the curve of the x value."), x.animationCurveValue, Color.red, new Rect(0, 0, 1, 1));
I am attempting to add new element to the SerializedProperty with using
private void OnClickB()
{
Debug.Log(levelDatas.arraySize);
levelDatas.InsertArrayElementAtIndex(levelDatas.arraySize);
var a = levelDatas.GetArrayElementAtIndex(levelDatas.arraySize - 1);
a.managedReferenceValue = Activator.CreateInstance(typeof(PuzzleCreator.LevelData));
Debug.Log(levelDatas.arraySize);
}
``` but this give me error like this
```InvalidOperationException: Attempting to set the managed reference value on a SerializedProperty that is set to a 'LevelData'``` any explanation how should i dot it?
managedReferenceData is for SerializeReference, if you're not using that then you cannot set a serialized value as a whole, only by its individual element properties
I have no evidence other than that error but I think unity cannot open a curve editor window when the player is maximized
We have a custom build script and want to enable Custom Main Manifest for Android from it, but this flag doesn't seem to be exposed?
ok then, how should i do it??
the class are like this
https://pastebin.com/pFLfbpEN
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.
does anyone know how I can check if a unity event serialized property has any functions added to it?
I've tried directly reading it as an array and checking it's array size, but that (somewhat obviously) doesn't seem to work
After a long while, it's working now and has been released under MIT license. It'll have a few issues and some things are currently in development (ExportSelector & ExportSheet Attributes are being tested rn).
it does work and you can alter the style sheet at will, it'll just overwrite anything.
Congrats on the milestone!
Yeah it's scary but
How big do the sheets tend to get?
well not big
here's a quick change in C#
The sheet only takes up the lines it needs
in a human readable format
one sec
What surprised me most was, there's never been a *publicly released USS Object Model before, as far as I know?
so the one I released has been the first one on github which is a bit huh
It is in works-in-progress but I can send the link to you if you want it
There a ridiculous amount of things that can possibly be created.
We have but scratched the surface. And most people tend to spend their energy in a direction they feel is the most worth while.
So congrats on probably being the first ^^
I think what I did was worthwhile
Do you plan to expand this to CSS?
depends
I possibly could
but Iroquois USS Object Model is focused on USS - there is an unused attribute which doesn't go used right now called "CSSCompliancy" (in the public version).
It's meant for an editor window, like Unity's UI Elements samples, which allows you to view all constructor samples & their compliancy to the specifications
I went from no knowledge of USS or CSS to a fairly decent understanding of USS, CSS, the specifications and the requirements between them.
there might be some issues but compared to USS Interpreter (the previous one), the USS Object Model is a lot easier to use.
The original USS Interpreter took so much longer to write a sheet for - so I just tore down everything and started from scratch with what I learnt
Good stuff. I haven't worked much with CSS since 10+ yrs.
It's a bit more complicated today, so I can imagine this type of thing being viable.
That said, for not too complex layouts, the declarations can be mixed and matched like components, by simply adding classes to selectors
Just need an understanding of how the stylesheet file is read by the system
semantics
I'm not too sure what you mean in the last part of that
I don't know about USS; but in CSS
.Alice { font-size: 10 }
.Bob { font-color: #000000 }
.Alice, .Bob { padding: 0 }
Syntax of the example might be wrong.
But the idea is that one selection can be added to multiple scopes
oh, yeah, you can do one-lines in both I think
only thing is, each declaration has ';' after it
other than that, I could totally add a one-line option to USS Object Model
(well, anyone can really - just fork and go)
have you linked it in here?
yeah, in work-in-progress
sorry, was just making dinner
here too
I'm also adding issues I notice as I go along testing it out
the style rule constructors for "transition" may be incorrect and need testing - duration and delay are swapped from the USS documentation but will be swapped back if they are meant to be like that
Setting the inspector to Debug might show the fields, I don't remember. But you can also just take a look at the source code https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/Export/UnityEvent/UnityEvent.cs#L748
Do you intend to replace strings with Enums?
for USS Variables and Native Properties?
yes, everything
kk
everything is documented in XML too.
here's an example of a keyword replacement
https://github.com/neopolitans/USSObjectModel/blob/main/USSObjectModel/StyleRule/Constructors/BackgroundImage/BackgroundPosition.cs & https://github.com/neopolitans/USSObjectModel/blob/main/USSObjectModel/StyleRule/Constructors/_Global/AlignmentValue.cs
I'll read after food and stuff. I'm too tired to read this right now 😆
Generally, the enumerators are kept with the style rule constructor that needs them - reason being is that it's harder (and arguably worse) to have one large enum for keywords that need to be prevented or whitelisted for each constructor than it is to have multiple ones at once for each rule. Any style rules that have keywords which overlap 1:1 share the same style rule (AlignmentValue as an example).
Some of the groundwork for Importing Style Sheets is also laid down in the USS Object Model too.
The strength is in the lookup, and not having to memorize the API, or keep a reference next to the screen.
If you want to group enums, maybe consider nesting them in different classes.
for a single enumerator or multiple ones?
I found that just having a single enumerator would require much, much more work and with all the keywords that CSS and USS share... - I learnt the hard way with the USS Interpreter because it was just genuinely a pain to try cram everything together.
I was just thinking if you wanted to avoid one large enum (I don't think that's bad btw)
then you can "group" them to a more logical structure. Or just make similar prefixed Enum names.
if all the relevant 'Variable' enums are grouped in a single class, lookup will be easy
both have their downsides and the way I chose has it's own limitations for sure.
generally they are too
I can't really say if the same way you're describing is the same way I did it
I'd suggest looking through the USSOM and finding out
I did add XML commenting for most of every enum value possible too for each enum type, though I know one or two are missing.
Honestly, I might not touch USS until 2023 is close to LTS.
But when I do, I'd prefer
Rules.Variable("grid-background-color", new ColorHex(0x2B, 0x2B, 0x2B)),
// This -->
Rules.Variable(Var.GridBackgroundColor, new ColorHex(0x2B, 0x2B, 0x2B)),
xD
Yeah I'll do those
in fact, what I'll do is not even that
that would be pointless ngl
Rules.Variable("grid-background-color", new ColorHex(0x2B, 0x2B, 0x2B)),
// This -->
Var.GridBackgroundColor(new ColorHex(0x2B, 0x2B, 0x2B)),
might as well do it this way
That seems legit
just as a double check, could you also post the issue to the git so that it's easy for me (and my tutors) to see
I'll totally do that though, that would save time for both of us and anyone using the USSOM, especially for GraphView tutorials
Done. FYI I am moving away from that github account.
Alrighty and thank you!
Good stuff and good work so far.
I'm totally dead on energy right now. Might have some comments later. Seeya o/
see ya and get some rest o7
Its gotta be a bug. It happens after I open the curve window by clicking on the curve field. If i reset the layout it stops happening until i edit the curve again.
found another messup I did that I need to rectify too - forgot to add a data type for "var()".
I am attempting to raycast at a prefab preview in editor using Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); However, its retuning colliders of the scene instead of the preview. Anyone have some thoughts on how to make this work? I'd like to raycast against the prefab and ignore anything else
Most strategy games does this: Middle click -> Look around, Right click -> Pan camera.
Unity does the opposite.
It wasn't a problem for me until I make my own strategy game.
Now switching between play mode and edit mode makes me go crazy because these 2 controls are swapped between scene view and in my game runtime.
Is it possible to swap middle click and right click inputs in Unity Scene View?
How do you get intellisense to work for visual studio code? I've followed every step on visual studio code's website, but for whatever reason the intellisense still isnt working, even with the developer pack and regenerating project files
I also have the modern net setting off
It's broken beyond Unity 2020.3, so if you're on 2021 or newer that might be the problem.
One of the steps is to restart the PC. Did you do that?
(Reboot is not necessary though, just kill explorer.exe and open it again)
Oh crap
thats annoying
Yea i'm on 2022.2.1f1
It should still work to some degree, but more than one person said it didn't work no matter what they did, and one day it just worked.
To be fair I didn't restart my pc so that might be the issue
Visual Studio Community is much better, unless you're restricted by hardware capacity.
just open Task Manager and kill the explorer.exe process
and use Run to start it again
both actions would trigger the update of the %path% environment variable
@tawdry kraken I've finally been testing the USSOM with GraphView and it's working pretty consistently thankfully. I'm just recreating UE4-style bluerpint nodes with it
Complex and Selector lists are matching, they're just not "working"/displaying with the UIToolkit because Unity-default .uss files are overriding them
(this isn't even USSOM-related, I just have a USS-related skill-issue because I forgot to check selector precedence when applying USS to visual elements)
turns out achieving node design like this is surprisingly hard almost.
is there a way to re-use this interface for adding components to something?
I want to have a list of a certain kind of class, and I want to be able to add new instances of said class to the list.
I think so, if it's in UI Toolkit
just using the regular unity editor code
you- you mean Immediate Mode GUI? (IMGUI)
Here's a funny issue
It wanted a "number"
what it really wanted was a length (in em, ex or rem according to CSS).
at least ExCSS caught it
I can't really tell if this is being addressed by Unity so I can't explicitly change it - but I'll mark it as an issue on the USSOM for later on
Intriguing, thanks
Hey peeps.
I have no idea what channel to put this question in, so ill give it a go here.
Im trying to create a Scene template.
However when im trying to select what dependencies to clone or reference, the editor wont allow me.
I keep ticking things off, and then, as soon as i scroll down to untick more dependencies they get ticked back again.
It is super frustrating, i have no idea what to do...
Oh, and im running 2021.3.20f1
!vsc
it is not, if you're using uitk... You have two options, either with the old Mesh api or the latest Vector Api which basically a wrapper for the mesh api
I think they sorta followed SkiaSharp with the new Vector API, they're quite similar from one to another
Can't get past this ambiguous methods error, I think its mad at a reference, so I tried deleting package cache, and removing the references, but no luck
Hey everyone, I spent the past week developing a tool for Unity which utilizes the OpenAI API.
There are already published assets on the store which rely on the OpenAI API and a corresponding API token from the user.
But this statement has me scratching my head: https://unity.com/legal/provider
5.10.1 Provider shall not distribute via the Asset Store any Asset, including a software development kit, that enables the delivery of services.
I wrote an email to assetstore@unity3d.com to ask them about this, but I haven't gotten a response yet.
Is there a better way to reach the Unity Asset Store team directly as a publisher about this sort of stuff?
im not too sure what im doing wrong. im having an issue with recording undo's. as i should im using serialized objects to do most of it for me. But i have a case where i want to call a method to set a variable and have it do some other commands as well at the same time every time the variable is changed. so becasue its not a serialized object i have to do it manually, but for whatever reason doing it this way wont register any undos
public override void OnInspectorGUI()
{
MyClass _example = target as (MyClass);
// ...
bool VariableAState = EditorGUILayout.Toggle( "Variable A", _example.VariableA);
bool hasChanged = _example.setVariableA(VariableAState); // SetVariableA both sets the variable and does extra operations when the value has changed
if(hasChanged)
Undo.RecordObject(target, "Variable A changed on MyClass"); // This does not record any undo's for whatever reason.
}
Ya gotta read the docs. You need to call before setting the value.
Also if you are using serialized object (good!) then at the start of your OnInspectorGUI method you need to call serializedobject.Update(); so that it looks at the data and is up to date on it.
thanks! you are completely right, i was looking at the docs but I guess I completely missed that it was being called before the value changed. and ill add that update as well 👍
ok so i changed it to this which also seems to not do anything
// ...
bool _CurrentStateOfA = EditorGUILayout.Toggle("Variable A", _example.VariableA);
if(_CurrentStateOfA != _example.VariableA)
{
Undo.RecordObject(target, "Variable A Changed on MyClass");
_example.setVariableA(_CurrentStateOfA);
}
Uhh, you might need to either use RegisterCompleteObjectUndo, and or, increment the current group before/after recording the undo
oki thanks, ill have a look into that
Fair enough, my bad
The api is very simple and easy to use to draw custom shapes https://forum.unity.com/threads/introducing-the-vector-api-in-unity-2022-1.1210311/
yeah, it's a cool api to make custom geometry
I can see lots of folks would make their own custom controls and selling it on assets store with it
💰
Yeah but- I dont have any clue why that came up over AdvancedDropdownMenu
Hahahaha... making custom controls for UITk that are good enough to sell on the asset store.... lol
Tbh id take USS/UXML over it
One thing that UITK doesn't want you to do, make high quality custom controls
I'd be surprised if that were the case
I'm also on my way making my own 🤣 ... not to sell, it's mit
you sorta can
Yeah, only sort of 😛
different concept.. you're working with a predefined properties with uss/uxml... and if you want more, you need to make your own
No custom viewData, no pseudo states, no inheriting from the CompositeFieldBase like VectorNField does, etc.
I actually don't think you can even make proper composite fields without reflection...
another weird decision by them is why they made this internal
internal InlineStyleAccess inlineStyleAccess;
/// <summary>
/// Reference to the style object of this element.
/// </summary>
/// <remarks>
/// Contains data computed from USS files or inline styles written to this object in C#.
/// </remarks>
public IStyle style
{
get
{
if (inlineStyleAccess == null)
inlineStyleAccess = new InlineStyleAccess(this);
return inlineStyleAccess;
}
}
What?
I don't know whats going on
Why is that weird?
Slim just kinda going on stuff
That looks like how it should be.
surely weird, it sorta cock-blocked inlinestyle modification .. by that I mean via c#
lemme guess to force people to use uss/uxml 😅
cloning is impossible without reflection inlinestyle in uitk
Not really, you are only meant to modify the values. Not set the whole thing
And yeah, you are meant to use USS 😛
what if I want a similar behavior to cloneTree? but full inline?
WHY would you do that!?
I'm making my own fluent extension 😃 .. full c#
Idk why people complain about using USS. Its like complaining about using multiple components per game object
Like, yeah you can just have one. But wtf is wrong with you 😛
what I'm complaining is how my projects will bloats with tons of uss/uxmls.. like heck tons of them
Why would you have tons of them?
due to the scale of the project and mostly due to small things that need different style
Ahh yeah. I know another guy that did that! They put it on github.
You mean for Runtime? Or still editor stuff?
Idk, like you either bloat the code base per file or bloat the number of files. Personally, I prefer the latter if it keeps the code cleaner.
Plus, doing stuff inline screws others over. Just saying. Like, it makes theming the editor basically impossible...
thus I need this to be accessible #↕️┃editor-extensions message:smiley:
so I can just move the style around like a template
How does that fix anything?
Does setting them in that make them not inline?
oh I mean it was for my extension that is 😂
yes I just realised this after reading it... hmmmmm
as a matter of fact that's very true, yeah.. why didn't I think about that before I started the project 😂 lol
lol
😂
Gotta use USS I guess! Oh well! What a shame!
I will be a good editor extension dev and say that if you really want to do fluent in C# (EW! USS is nice!). You can probably find the source code for where they apply the inline stuff and the style sheets and might be able to interject it with certain styles. Like require the element to have a name, and use that to apply the C# style to just that element.
Of course, with lots of reflection I assume 😂
but I really hate looking at my projects with tons of uss/uxmls 
Just organize it better 😄
oh neat, who?
man all I did was just write a USS object model to get around using USS directly
this is how I got the GraphView group to look like a UE4 Comment
They might not have released it separately it seems. But I think it is here https://github.com/neon-age/Smart-Inspector
noice
I'll have a look in a bit, thanks for sharing
As for USS, Mech
I no longer hate it or dislike it or any of that
I actually understand it well enough and feel comfortable using .uss files and C#.
It was one hell of a journey but WOW the things you can do
being able to go from A to B using UI Toolkit Debugger was a major reason why it clicked too
Anyone has some good way of collapsing multiple changes into one Undo group in a way that it is also Redo'able?
I see this as some common problem on Redo not being able to recreate anything more complex than single operation/change.
Huh, if only there was some sort of an API that would let you CollapseUndoOperations, that would be handy!
...
Oh wait!
int undoGroup = Undo.GetCurrentGroup();
// Any and all undo related things here..
Undo.Recordobject(target, "Recorded a changed");
// here we actuall make a new group so they will be sepereate undo operations.
Undo.IncrementCurrentGroup();
// Works with serializedObject too!
serializedObject.ApplyModifiedProperties();
// And we collapse!
Undo.CollapseUndoOperations(undoGroup);
Hope this helps! 😄
https://docs.unity3d.com/ScriptReference/Undo.CollapseUndoOperations.html
I have a headache, and I'm 100% sure it's because I don't understand GUI / GUILayout / GUIEditor. I'm trying to create multiple boxes, each with buttons above and below, inside of an EditorWindow. I started with buttons above for now. The result? All boxes display fine, but only the first button group appears. Anyone know what it is I'm messing up on? https://gist.github.com/Tencryn/06c64ca5abe978644eadc8573f43bf63
You are trying to use GUILayout and GUI at the same time. The Layout system doesn't know about any of your GUI code, and other way around.
Unless you have a particular reason you are wanting to manually position things. I would just use the layout system with GUILayout
Something like this. You can wrap it all in a GUILayout.Group if you want to position the whole set manually. Still recommend using GUILayout for that instead though. You have GUILayout.Space(n) and GUIlayout.FlexSpace()
using (new GUILayout.HorizontalScope(GUILayout.Width(GetWidth())))
{
using (new GUILayout.VerticalScope())
{
GUILayout.Button("Button Above");
GUILayout.Label(GetTitle());
GUILayout.Button("Button Below");
}
// Repeat above code here...
}
Though really, I would recommend looking in to UIToolkit! It is great for styling and layout things out! 😄
yeah I can attest to UI Toolkit
for all the hesitation I have
it does do things better than IMGUI in ways that just
past the Web-dev like languages, it's pretty helpful
also here's a fun one for the books Mech
I wondered why my USSOM was having problems with complex selectors and pseudoclasses - turns out I was just doing "SimpleSelector.name" and not "SimpleSelector.Name()"
No clue what that is referring to. But oof!
oh right the USS Object Model - the Interpreter I was working on for C# -> USS
I meant the .name vs .Name()
ohhhh
