#archived-code-advanced
1 messages · Page 76 of 1
but it method is void
should I make async void?
because it is called like regular function
The problem is that Unity is asking for a lot of samples from your callback when you create the audio clip, and on the main thread. If those samples aren't ready, like if you're still downloading or processing them, Unity will stall.
Yeaah. exactly
You are doing it wrong, using (var res = await synthesizer.StartSpeakingTextAsync(speakMessage))
I think creating audio clip should be done on another thread but have not tried it yet. will it be better to use Unity Jobs System? or regular c# threads
Ok, let me correct,thanks
Tbh this is basic async/await, you should take time and properly learn it.
So I would suggest you download the data into your own MemoryStream, wait until you have a decent amount of samples, then create the AudioClip where you copy from that memory stream in your callback. Best case scenario, your buffer will always have the amount of samples Unity asks for so it doesn't need to wait at all.
if I do .Result in using() it works, not here
res is already the result, you don't need .Result anymore...
Ok, thank you very much for advice!
ok
?
but now I see:
UnitySynchronizationContext.ExecuteTasks() [Invoke]
1481.71ms
But I saw this yesterday too.
with that code before changing
Read Data takes time I think
But, how to solve that UnitySynchronizationContext.ExecuteTasks()? weird
If the stream is from a web download that is still downloading, then there's no amount of await that will solve this.
Unity is calling your callback on the main thread, waiting for it to finish giving it all the samples it needs. If they're not ready, it will have to wait and stop the whole game until it's ready.
Aha. but for downloading should not be used another thread?
Why it freezes unity by blocking main thread, it is async
It might, sure. But then the main thread is waiting for that thread.
Ah. Maybe
Unity wants those samples now. You can't tell it otherwise. It ought to be asking for it in a separate thread, and I think it might for following calls to the callback, but just creating the AudioClip will invoke your callback on the main thread.
So you better have those samples ready to go when you call AudioClip.Create
Maybe try logging the audioChunk.Length to see how many samples Unity is asking for initially.
Or a breakpoint.
Aah, may be. very clever!
I will try some stuff and tell how it goes. Thank you very much for advice!
Huh, does StartSpeakingTextAsync not have the entire thing ready by the time it's done?
// Starts speech synthesis, and returns once the synthesis is started
This is for an AI character, so low latency is crucial.
Yes, it has but auciocllp is not created
and creating it takes time as I see on profiler
var readBytes = audioDataStream.ReadData(audioChunkBytes); this line
and am trying to make this work on different thread and wait or something
Makes sense.
The data isn't ready. It wouldn't take this long to copy some samples. The AudioClip creation is taking a long time, but only because it's waiting for your callback, while it's waiting for the download stream to accumulate enough samples to return for this initial callback.
Ah, you mean this>
FromResult is not ready yet
But how can it return unready value since it is synchronous?
So you mean doing this
Reads audio data from the current position in the audio data stream. Waits if no data is available.
This AudioDataStream is managing its own buffer, so you can just use it instead.
You can use the audioDataStream.CanReadData method to check if it has downloaded enough bytes. You shouldn't create the AudioClip until it has enough so that it doesn't need to wait when you create it.
Ah. Let me check
How many bytes you need to wait for depends on how much Unity is asking for initially, which is why I recommended logging/debugging to see how big the audioChunk.Length is for the first call.
Ok, I will log it
I have no idea how to thank you man
Let me try
There is nothing like that array, only this
Is that not audioChunk.Length?
I know, Unity is giving you this array to fill it in. You want to know how big of an array Unity is giving you, so you know how many samples you need to preload before calling AudioClip.Create.
This is just a temporary log to see what the number is.
Debug.Log(audioChunk.Length), inside the callback.
Ah, I was confused sorry. Ok 1m
4096
audioDataStream.CanReadData(4096);
while it is not true
Ok, so you need 4096 samples. It looks like you're getting 16-bit audio samples, so that's 4096 * 2 bytes.
wait yes?
Ah ok
So I have to modify this function to be coroutine and yield return null untill it is not true?
I would add this wait in your synthesizeSpeech async method.
any help?
Is the synthesizeSpeech method called in a separate thread?
Ok, since you have it set up like this, you can just add another WaitUntil there. You just need to make some method in the speechSynthesizor class that calls the CanReadData method.
Or nevermind, I guess synthesizeSpeech is creating the AudioClip.
Ah, I tried it and Unity does not freeze!
BUt
it does not talk either
;d
Maybe The problem is found but I miscommented some code or something
Let me check
sometimes it is not 4096 is it ok?
Yes. Those four calls might be all part of the initial creation, so you may actually have to wait 4 times longer.
There's many different ways you can wait without blocking the main thread. I don't really want to walk you through that process, you can Google it if you don't know.
No no
It worked
everything
You are amazing man!!
Thank you very much for your time, I appreciate it
Have a beautiful day. I was stuck around 2 days for this
Just make sure to check that your latency hasn't gotten worse after this change.
You might need to use Type.GetType specifying the assembly name where UnityEngine.Transform is located
Hi, I am trying to skew a UI panel by modifying the vertex positions with
protected override void OnPopulateMesh(VertexHelper vh)
But this only seems to affect the vertices of the image that the script is on, how could I modify as well the vertices of all the child UI elements?
If you could help me, I would be very pleased.
Problem Description:
You have a Unity project with a MyScript component containing a public UnityEvent EHello and a public void Hello() method. You're trying to create an Editor script that opens a custom window allowing you to assign the MyScript component to a GameObject and add its Hello method as a callback to the EHello event. However, despite adding the callback through the Editor script, you're unable to see the callback listed in the UnityEvent's callback list when looking at the GameObject in the Inspector.
Steps Taken:
You created an Editor script named MyWindowEditor.cs that opens a custom window named MyWindow.
Inside MyWindow, you added an ObjectField to select the target GameObject with the MyScript component.
You provided a button in the MyWindow GUI to add the Hello method as a callback to the EHello event of the selected MyScript component.
You utilized EditorUtility.SetDirty(myScript) to mark the object as dirty to ensure the change is serialized.
Remaining Issue:
Despite successfully adding the callback through your Editor script, the callback is not visually listed within the UnityEvent's callback list in the Inspector of the selected GameObject.
you want to add a persistent listener
Thank you, I will check it out now..
I works! Thank you so much..
Is there any source about Unity's scene description code? My goal is to write a scene without using unity editor.
I'm looking to speak to someone whose written a code generator from scratch in unity.
The problem I'm faced with, is that when I generate code on the backend based on existing user types (using reflection), whenever the user deletes that type, like a struct, the type obviously no longer exists. So errors now occur on the code-generated backend. When there's errors, the assembly obviously doesn't get rebuilt, and therefore I'm stuck with old reflection data telling me that types exist (when they don't).
How is this mitigated?
Whenever the editor recompiles, I could have it automatically go through and delete all generated code, let it recompile, generate new code, and recompile again, but that's super icky
My current solution uses a really limited code analyzer that I wrote that literally parses specific files for structs, etc but it's a massive pain in the ass to use, and I would rather just use reflection.
DOTS related question here (hope its ok to ask in here rather than making a forum post, if not I'll copy it over 🙂 )
Do bakers get executed at runtime against objects that are instantiated?
DOTS has a general discussion
it's hidden by default for some reason though
Hm I can't find it in the channel browser. I can see the archived (locked) dots channel?
Unless you mean its hidden behind a Dots roles?
Oh its a forum, thanks 🙂
Accually I won't get it. Can you write a simple project which is explain your problem? Than publish it on github. Maybe we can discuss it on github and implement a solution.
I've never actually done code generation, but I always have been under the impression that it is done by first building the user code, then building the generate code as a second step.
Yeah, that sounds like the only possible way for this to work
gonna be slow as hell but thats alright
Yeah, usually do not want to delves into code generation. There might be a better approach for what you are doing if you want to elaborate.
Dynamically creating ECS dynamic buffers. The type has to be known at compile time
Ah, just a tool for reducing boilerplate code then.
correct
I understand, there is no other approach then code generation.
Personally, I would just gave up. Pretty sure you can write a few line of boilderplate code. However, I understand your wants.
Are you using an editor script to generate code or a source generator?
editor script
Yeah that’s basically the downsides of code generation via editor script
You have to tab back into editor for them to run, but editor has to first compile other scripts; you have to manually manage generated scripts including deleting no longer necessary ones; and then after generation there’s another compilation step to compile freshly generated code.
It’s really bad DX comparing to source generators, where there’s no need to tab back into editor for them to run, and it runs directly in your IDE whenever you change code; it won’t actually generate physical files that pollute source control; managing generated files is automatically done for you so you don’t need to worry about deleting old files.
Downside is you have to write your code generation using syntax based API, rather than reflection based.
Yeah, that's whats off putting to me. The main issue with the editor script generator is really just figuring out how to solve the infinite loop issue
and figuring out when new code needs to be generated
It gets even worse if you want to edit the editor script that does the code generation, because your project would be in a broken state and wouldn’t recompile to trigger the new generation 😅
Tbh this sounds like source generator is the better way to go than editor scripts.
I'm just wondering how people did this before source generator compatability was introduced to unity
afaik it's pretty new?
just cs files
I need to generate stuff that can't be done via reflection. Like dynamically creating ECS buffers of different types
Could it work if I only generate code when the play button is pressed or before actual build compilation?
probably not since that's still gonna leave room for errors when the user modifies the code on his end
I meant like, you generate code based on some other code right, so let's say you generate some code based on Foo.cs and Bar.cs, do you put the generated code in Foo.g.cs and Bar.g.cs, or do you put them all in one file like ECSGenerated.g.cs?
They can each be separate files
that's how I'm designing it
the generated code also has a generated header and footer, so it knows what it needs to wipe
Yeah I would suggest put them all into one file, so dealing with deleting old generated code is easier since you are just repeatedly overwriting that one file.
Do you have any ideas of dealing with the infinite loop though? I was thinking doing something with comparing the Assembly ModuleVersionId's
and storing it in a txt file somewhere after each generation
That's a bit too complicated, the easiest way is to make your editor script generated code stable. Eg if code generated based on Foo.cs will never change unless Foo.cs changes.
Prior to source generators, the biggest challenge of making editor script based code generation works, is that every step has to at least compile, in order for editor script to be able to receive the new assembly to generate new code.
Take an example of Foo.cs:
public partial class Foo
{
[GenerateHelper]
private float _value;
}
And your code generation wants to generate this based on the above:
partial class Foo
{
public float Value => _value;
}
The editor script would:
- Every time assemblies change, scan all assemblies to find usages of
GenerateHelper. - Generate code, and write them to
GeneratedHelper.g.cs. - Recompile (if
GeneratedHelper.g.cshasn't changed, Unity won't do anything, so you can freely always write to it as long as your code generation is stable)
The workflow for adding a new Bar.cs/adding new fields to Bar.cs:
- Add
Bar.cs, but only the fields with[GeneratedHelper], and do not write any code that requires using those generated helpers yet. - Tab back into editor, it should compile first for
Bar.cs. - And then it should compile a second time triggered by your editor script code generation, and writes to
GeneratedHelper.g.cs. - Now you can tab back into your IDE and start writing code that uses those generated helpers.
The workflow for editing/removing fields or Bar.cs entirely:
- Remove fields/
Bar.csthat use[GenerateHelper]. - Go into
GeneratedHelper.g.csand change all of those generated helpers' implementations to throw (so that you don't need to change your existing code that are still using those helpers) - Tab back into editor, it should compile first for both
Bar.csandGeneratedHelper.g.cs. - And then it should compile a second time triggered by your editor script. This time all the generated helpers are gone and your existing code that still using them will fail to compile.
- Tab back into IDE, you can now refactor all the code that are still using the non existent generated helpers.
As you can see these workflows suck and are super fragile, if you ever get into a situation where "I've changed some code but it wouldn't compile and thus the editor script can't see new assemblies" then you are going to have a fun time to get yourself into a temporary state to compile first, just so your editor script can see the new assemblies to regenerate the correct code.
alright
Yeah, I'd say if you are considering dealing with the above workflows, then just use source generators instead so you don't have to.
yeah I'll probably be switching over to a proper source generator
Editor scripts generating code based on non code assets (eg Translations.json): good.
Editor scripts generating code based on existing code: bad, terrible, painful DX.
Source generators generating code based on existing code: good.
Source generators generating code based on non code assets: works but not worth the effort.
Hey, I'm trying overlap capsule in job using dots. I'm constantly getting this exception on line containing overlap.
AssertionException: Assertion failure. Value was False
Expected: True
Fragments of code...
[UpdateInGroup(typeof(FixedStepSimulationSystemGroup))]
>in Update
CollisionWorld collisionWorld = SystemAPI.GetSingleton<PhysicsWorldSingleton>().CollisionWorld; //passed to [ReadOnly]
CollisionFilter collisionFilter = new CollisionFilter()
{
BelongsTo = ~0u,
CollidesWith = ~0u,
GroupIndex = 0
};
>in Job : IJobEntity >>> Schedule()
NativeList<DistanceHit> overlapHitNativeArray = new NativeList<DistanceHit>(Allocator.Temp);
CollWorld.OverlapCapsule(start, end, radius, ref overlapHitNativeArray, CollisionFilter);
Any help, can't find anything helpfull online
How unity terrain works? do it uses splat map or UV?
Every single rendered thing uses UVs as far as I know, Unity or otherwise
Not if you use triplanar for example
even then 🙄
How triplanar needs uv?
UVs are a core part of rendering
or world space texturing
No, UVs are optional. You can sample textures using anything you want.
But the UV is generated on shader
UVs on meshes, that is. Sure, you have to specify a texture coordinate to sample a texture, which you could also call UV.
But you don't need textures to render something
Unity terrain uses splat maps.
if i use WorldSpace X,Z object position as UV does it counts as mesh UV
But it also uses UVs, generated on the terrain mesh
I see, and does it uses Mesh UV in any way?
Humm
Are not splatmaps heavy? big ram usage and all?
Depends on the resolution and the size of the terrain.
aren't splat maps just materials that utilize UVs and parameters? 😛
A splatmap doesn't need to be super high resolution. The tiled textures revealed by it hide the low quality.
you paint some part with a specific 'brush', then the terrain renderer runs the shader to color that part
You're painting a mask texture, which the terrain shader samples to figure out which texture to blend in.
Is it scalable at all for a big open world game?
Won`t it need a lot of splatmaps or big splatmaps?
Since there are only four channels in the map, if you go beyond four different textures in one terrain section, performance can drop significantly, because it needs to draw that section multiple times.
Unity's built-in terrain is definitely not meant as a drop-in solution for big open world games.
the more materials u use, the more textures you load, so yeah in this way the more ram will be needed
I see
for big open world games you'd be better off with some custom chunking solution
-- and load/unload resources on runtime on demand, including HQ/low-LOD textures
is this the only way to have terrains? splatmaps?
Is there any other way? is v-rising using splatmaps?
I think what was mentioned before was very confusing xD this is #archived-code-advanced so no need to simplify or sugar coat
you paint with brushes --> brushes are mapped to a material --> the material uses a shader and some parameter presets --> the shader MAY OR MAY NOT process 0-XX textures
you can choose to paint with a brush that modifies the mesh without use of any textures if u want -- just plain math
or you can reuse the same texture for different materials and only load them once, but process them differently in each shader
this looks more scalable
yeah but it's also much more difficult to pull off 😛 which makes it less scaleable unless you have a technical art team
for big open world games you should definitely use chunks, but there's nothing stopping you from using a whole Terrain object as a chunk
That doesn't solve blending, like this.
Unless you mean using vertex color instead of a splatmap and have a very dense terrain mesh
don`t you need density only where it intersects?
meaning you can load/unload the whole terrain object including its resources, and render it on demand
Yes
well yeah there is an additional shader (terrain shader) that processes all the shaders indeed.. I get where you were going now with it using splat map
i think it is a good tradeoff
but limited to 4 textures if using vertex color, right?
Yes, unless you also include an additional base map for black color and blend the four splats on top of that.
The same limitation applies to a splatmap, unless you have multiple splatmaps or do some remapping to split each channel into two or more ranges.
Microsplat has support for 256 textures with a single splatmap
"Features Added:
- Extends the maximum texture count from 32 textures to 256, storing this in a single splat map instead of requiring one splat map for every 4 textures used."
My new shader system, coming to the asset store soon, which supports up to 256 textures at once in a single splat map shader, with the same performance as a 3 layer splat shader.
You can see this is relying on vertex color in some way. Perhaps combining a splatmap with vertex color to multiply the number of permutations.
But it can have even 256 textures with a single splatmap
I think it store the texture index + weight on a single float
He explains the limitations of his approach in the video above.
But this is an early video, so it might be different now.
Here we go, it's explained in detail here:
https://docs.google.com/document/d/1vD_LY5zxA_C78pDNdsC8xoA4HOezzPsVk9pz7ER9Gso/edit#heading=h.sv2wbughpick
MicroSplat 256 Textures Overview The 256 Texture module allows you to work with up to 256 unique textures on a terrain or mesh. It is based on a fundamentally different way of storing splat map data, and is called the MegaSplat Technique because the technique was first introduced in my older as...
so -- what I had in mind before was the 'paint details' part, not 'paint textures' 😅 so yeah oops
This playlist includes chunking as well: https://youtube.com/playlist?list=PLS7jk2aVN8G4gjIPTeyVhK0HYEbVY7xSa
Ty, i`m using dots to create a terrain engine for my game so this is all useful
anybody know how to disable the assembly csharp reference?
in assembly definition inspector unity
If you mean how to prevent Assembly-CSharp from referencing your assembly automatically, you can do that by disabling "Auto Referenced".
what would be the impact? if i disable those
It means all the predefined assemblies will not reference it, like Assembly-CSharp, Assembly-CSharp-Editor, the firstpass variants.
Since there's no way to specify which assemblies those predefined assemblies should reference, "Auto Referenced" is the only way to do it (or disable it)
Do anybody of you guys know why sometime a scriptable objects loses its reference on play mode? Like when i referenced a vector 2 of a gameobject in hierarchy, when i pressed play mode, it misses the reference
Because a scriptable object is an asset, which doesn't exist in any scene, and assets can't reference scene objects
They can reference them temporarily, but Unity can't serialize it, so as soon as it's reloaded from disk, you'll lose the reference.
tldr; attatch it to a scene object and then drag the object into the inspector of the gameobject you attatched it to (is that the problem?)
so i have a gameobject (Tutorial Manager) that would contain a list of Tutorial Behaviours SO. The SO would contain a vector variable that would reference an object in the hierarchy (as i remembered, I made the object into a prefab and attach it to the SO but still loses its reference) but when in playmode its missing
is there a solution?
Do not use SO for logic handling. (In this particular case)
Use a component in the scene
You could always use a component in the Scene than reference it through static variable or GameObject.Find
SO does not have the concept of a scene. It lives outside of it.
so even though i reference a prefab in the SO it still lose it refence? I want to optimize some stuff, so gameobject.find wont be my key
GameObject.Find is fine in the case that you are doing it once or twice and doing it in loading.
SO shouldnt lose reference to a Prefab. You are probably still referencing the scene object.
probably yes, ill do it one more time to check it again
I'm struggling to add a source generator to my unity project
I am trying to follow this microsoft tutorial: https://docs.unity3d.com/Manual/roslyn-analyzers.html
I got up to making the test script in my unity project, but my unity project does not acknowledge ExampleSourceGenerated as a thing, nor ExampleSourceGenerator as a namespace.
One thing I noticed is: since I'm on mac, my VS does not have a Batch Build menu item
And when the tutorial says to add the label "RoslynAnalyzer" and it is case sensitive, Unity automatically makes that label lowercase when I put it in
You can build with dotnet CLI instead.
If you want to verify if it's correctly added, open your .csproj and see if there's an <Analyzer Include="..." /> pointing to your SG dll.
So how does something like Roslyn actually work? Is it literally just parsing the raw IL text?
or is something happening at the lower compiler level?
Roslyn, or just Roslyn analyzer?
The analyzer
should I do that instead of building normally? Is that the step I have totally wrong?
You get back the syntax tree of your .cs sources, not the IL.
You can explore syntax tree with https://sharplab.io, change the "results" dropdown to "syntax tree."
ah alright
where do I find this?
this is what I'm looking at rightnow
For regular C# projects, you can do everything in CLI rather than using IDE's GUI. I'm only mentioning this because you are using VS on Mac, which isn't the same thing as VS on Windows (I've heard VS on Mac is pretty bad)
Your .csproj should be generated at project root, you should have a few like Assembly-CSharp.csproj, ones for editor script assemblies, etc.
I got access via plain text editor
<Analyzer Include="/Applications/Visual Studio.app/Contents/MonoBundle/Addins/MonoDevelop.Unity/Analyzers/Microsoft.Unity.Analyzers.dll" />
<Analyzer Include="/Applications/Unity/Hub/Editor/2022.3.2f1/Unity.app/Contents/Tools/Unity.SourceGenerators/Unity.SourceGenerators.dll" />
<Analyzer Include="/Applications/Unity/Hub/Editor/2022.3.2f1/Unity.app/Contents/Tools/Unity.SourceGenerators/Unity.Properties.SourceGenerator.dll" />
I take it all these .dll files are standard, and I just need to add a path to my dll in my source generator project's .dll?
No, you need to do it like the Unity manual tells you to, by adding the dll and adding the RoslynAnalyzer label.
Editing .csproj doesn't do anything, .csproj is generated purely for DX.
yikes. well, it is not included
and if I add the RoslynAnalyzer label, it makes it automatically lowercase
looks like this, at the bottom
On a side note I don't think you should select any platform at all, since SG is only run during build time.
I think the wording in Unity manual is wrong/confusing on that part.
it works!
yeah, I was just following directions as closely as possible because it wasn't working lol
By build time, do you mean when unity reloads the assemblies after you save a file?
That was going to be my next question, as to when the SG actually runs.
Whenever compiler runs.
it finally goes. now time to learn to make it do what it needs to do. ty
Compiler runs not only in Unity, but also in your IDE. That's why SG gives you the amazing DX that whenever you changes anything, the source generated code are immediately updated and you get autocomplete/compile errors/etc.
alright
I noticed VS doesn't let me find the file for the auto-generated source code. does it not have a file?
Generated code are in memory only (and that gives the nice side benefit that it doesn't pollute your version control) but you can view it in VS project explorer IIRC.
ty
You should be able to use typical IDE features like go to definition/find references/etc just fine (though someone else said it wasn't workng for them)
is it possibly to get a roslyn analyzer for VS on mac?
on windows, it's very easy to get .NET CompilerPlatform SDK
I have been reading into FSMs, behavior trees, GOAP --- do yall have any tips for making player-like bot roaming?
Like just looking around for other players to hunt down
hey guys, I am trying to add skew support for the UI, and I made a script to apply the same skewing matrix to all the children of a UI element, but it doesn't look right, should I be calculating a matrix for each UI element separatelly?
not too sure how the maths for that would be
Changing my terrain rendering to unity dots
https://docs.unity3d.com/Manual/roslyn-analyzers.html
What do they mean in the second part by "Unity doesn’t support the installation of Roslyn Analyzers or source generators through NuGet directly".
We're compiling the source generator into a DLL outside of unity, so why would I need to install anything inside unity?
I'm so confused.
but your dll will not contain the dll's that it references, so when you put your dll into a unity project it will need access to those referenced dll's as well
I managed to do it!! 😄
No need for anything complicated for wandering NPCs. Instead of idleing, it can wander between predefined points.
I'm trying to have the bots in my game be as close to indistinguishable from players as possible
Just worse haha
Like how fortnite supplements lower level lobbies with bots so new players still have a decent chance of winning
My game is a top down large scale 2d multiplayer game. The movement and killing scheme is similar to among us
Im currently leaning towards trying to trying to train my bots with unity ml agents but I don't have a good sense of if i'm in over my head.
I know ML agents is fairly unsupervised but I see they also have imitation learning -- looking into that rn
So my source generator is spitting out files in the temp folder on my hard drive. Is there any way to get them to generate inside of the project?
Why though? Them not generating actual physical files is one of the nice benefits since they won’t pollute your source control.
That's true. I guess I just want to be able to read the output to verify everything. It's not that big of a deal.
I am however getting a warning when accessing the generated class. It's "conflicting with the imported type"
Other than that, it seems to be working
^
What’s the warning?
public static T CopyComponent<T>(GameObject source, GameObject destination, bool force = false) where T : Component
{
if (force)
{
Component comp = destination.GetComponent<T>();
if (comp != null)
GameObject.DestroyImmediate(comp);
}
T sourceComponent = source.GetComponent<T>();
if (sourceComponent == null)
return null;
T destinationComponent = destination.AddComponent<T>();
System.Reflection.FieldInfo[] fields = typeof(T).GetFields();
foreach (System.Reflection.FieldInfo field in fields)
{
field.SetValue(destinationComponent, field.GetValue(sourceComponent));
}
return destinationComponent;
}
Does anyone have any idea why typeof(T).GetFields() is empty? I can't seem to find anything.
Do you have multiple assemblies?
Probably your SG unconditionally generates an example class for both assemblies.
Is there a better way to cache sprites?
I will have anywhere from 20-1000 sprites I need to pull from my resource folder, and in the future from a game updates API https Request that will store "image" to their device; and keep in memory because of this and the uncertainty of keeping 1,000 sprites in a collection I wanted to know if there's a better way than storing the Sprite in a dictionary that I'm currently doing. (Hoping there's something that already exists that I missed), Addressable won't work as I have my own modding system that handles custom data added into the game.
Each sprite is 128x128.
Dictionary<string, Sprite> spriteMap = new();
public async Task<Sprite> LoadSpriteAsync(string spriteFile)
{
if (spriteMap.ContainsKey(spriteFile))
{
return spriteMap[spriteFile];
}
var spritePath = Path.Combine("sprites", spriteFile);
var resourceRequest = Resources.LoadAsync<Sprite>(spritePath);
while (!resourceRequest.isDone)
{
await Task.Yield();
}
if (resourceRequest.asset != null && resourceRequest.asset is Sprite loadedSprite)
{
spriteMap.Add(spriteFile, loadedSprite);
return loadedSprite;
}
else
{
//Do error
return null;
}
}```
Seems fine to me. What are you concerned about?
Having 500 sprites sitting in memory.
Well, if you want to cache them, they will need to sit in memory.
Basically looking if there's any sprite handler in unity that would just hold a reference or some other pointer.
Yes, that's what caching means.
Pointers point to somewhere in memory. The sprite would need to be loaded in memory to have a pointer to it.
Correct, I'm a Senior Engineer, I fully understand this, what I'm asking is if there's a better way to do this than what I am.
Better in what way? Do you want these sprites to be cached? Then they will need to be in memory.
A solution that unity might offer for sprites in this type of use case?
Alternatively, you can not cache them and load them every time you access them.
There's no such solution. And if there was anything it wouldn't differ from your solution.🤷♂️
Thanks, do you know off the top of your head if there's any format that just contains the byte[] of an image / texture and can quickly buffer to texture or would I always have to encode using sprites or texture2D?
I may just drop the sprites and handle the raw data.
I just don't know the overhead for that without testing.
Write a webp encoder / decoder.
you took a hard turn for some weird wtfery there
?
You could definitely load just the bytes of the image, but what's the point? The Sprite class data itself is probably very small. And you'll need to create a proper sprite/Texture2D when you want to use it.
Since I'm passing raw byte data from my API I have it, so if the sprites are increasing 10% of the size it's worth it.
The issue is I can potentially have 1,000 images in the game being pooled and used at some point.
Are you actually running out of memory on your target device or is it a premature optimization?
So yes, I can just I/O the textures when I need them, but that seems like a waste.
My only real option I see is just create a collection of First in textures, then releaase any that haven't been pulled in a while.
Premature optimization doesn't neglect a proper way to do this.
Why not just load the textures that you really need and unload them when they are not needed. Instead of messing with raw bytes?
Premature optimization is when you try to solve a problem that doesn't exist yet.
Raw bytes is what constructs the textures in the first place, I have some initial images that are built with the game and hundreds of modded images and updated images from our server.
PO doesn't mean you shouldn't do things properly, this archetecture is 30% of the actual design of the system, so arguing I shouldn't do it because it doesn't exist yet doesn't help me.
By loading the files as raw bytes, you probably won't be saving any more than 1% of the memory depending on the image resolution and format.
Besides, I'm not sure you would be able to pass that data into a Texture2D properly afterwards.
When a user loades the game, it hits our update server, websockets the raw images, stores to device and loads when needed.
I don't seewhat you're trying to suggest here, the bytes are already loaded and handled. Regardless if it's a sprite or not it's there.
Dealing with them is trivial.
it makes absolutely no sense to do anything at all with raw bytes. You don't load those into memory, you leave them on disk where they take 0 memory space until you use them. Then when it's needed, you load into memory in a usable format
How many times have I said so far that we download these images 😄
if you're downloading them into memory and not saving them then that is where your actual problem lies
If you only need to download them, then for sure, just download the raw bytes and save them to disk.😅
WE can store them, that's not the point here.
otherwise you're talking a worst case scenario of 1000 128x128 RGBA uncompressed textures taking a whopping ... 60ish mb of vram
You guys are so far off the actual original question trying to discuss something that has nothing to do with what I orignially asked.
Do addressable-like refcount and if you don’t reference it drop from memory?
Basically, unload them if they're not needed. That was suggested several times already.
Do addressables handle external data (If a users adds a modded image to our server), or do they need to be built?
And I literally said that myself. Thanks for joining the convo:
Eh I think you can somewhat extend it, but you can just take their concept.
I'll check it out.
You should investigate the access pattern of those sprites
Without knowing your access pattern, any optimization is moot.
I agree to a point, but it's still a simple hour or two implementation of a system. It's worth it in my opinion.
Any PO that takes a day or two then you should rethink, not something that takes a hour or two.
Throwing things at the wall and seeing what sticks doesn't really do well 😅
But creating a system that works as intented if it only takes you an hour is what to you? 😄
A waste of time?
if it solves a non existent problem, yep that would be my definition of a time waster
I'd rather do it once than have to refactor later.
You're trying to argue with me on Discord, is your time that valuble? 😄
If you investigate your access pattern first, you may gain insights such as "95% of the sprites are no longer used/only used again after 5 minutes of gameplay" then you can properly turn that into an optimization strategy of "purging cached sprites if it hasn't been used for more than 5 minutes"
That's way more useful than whatever 10% you can save by storing the raw bytes.
Sure but implementing that compared to just doing it in a proper way would actually take longer. I'd have to have an anylitics server and parse the data.
Way more of an investment than just doing it the way I think is the proper way.
then just do it your way if you consider that proper..
I hear what you're saying, and agree mostly, but implementing a sprite cach / unloader is worth it.
You don't need to deploy a server and collect analytics from all your players, what you should be doing is simply not worrying about it and keep developing your game.
Once it's near a realistic playable version, then you can do a test play on your dev machine, following a typical play pattern of your players, and just debug log whatever to gain insights.
Then afterwards, you do the optimizations.
Basically I was hoping that there was some archaic functionality one of you would have known about that handles this solution as it's one that I'm sure a lot of people have dealt with.
Mate, it took me 5 min to write the sprite cach, it's taken me longer to explain to you that I can do it properly than me doing a proper system
You telling me how to develop like I don't know what I'm doing doesn't do anything.
Sure, I've offered my suggestion of profile first before optimizing, I have no more to say.
I hear what you're saying, but in this case I disagree, as doing this properly I've already decided needs to be done.
And profiling users takes time.
I'm not saying you shouldn't optimize or that this is premature optimization, I'm saying your optimization strategy should be obtained by empirical data and specifically how those sprites are accessed in a realistic gameplay of a player.
Right, then on to developing your system, because there's no preexisting solution.
In almost every case I agree with you, but you're not understanding for me to implement this will take an hour or two at absolutle most.
So you're trying to suggest and fix a problem that isn't a problem. Youre trying to suggest that I don't know how to handle my time as a developer.
Okay, so you've spent 1-2 hours implementing the "storing raw bytes in memory rather than decompressed texture" and now you saved 10% memory consumption, great.
But you still could've saved way more than 10%, if you knew "95% of the sprites won't be accessed again after 5 minutes of inactivity" and use a strategy of purging sprites that are stale by more than 5 minutes.
Some day when your memory consumption is once again going over the board and you have to do profiling to gain that insight to really fix your problem, that 10% memory consumption optimization you spent 1-2 hour making is just wasted time.
What's the actual question?
Because it kinda just sounds like a poorly explained problem and then a whole bunch of arguing about other people's opinions about the poorly explained problem
This is akin to "optimizing locations of your data centers when your database queries have a N+1 problem"
A bunch of juniors trying to argue what Premature Optimizing is, done with what I assumed was my only option was here anyways. Was hoping there would have been a unity function for this that I missed.
private Stack<string> spriteStack = new Stack<string>();
public async Task<Sprite> LoadSpriteAsync(string spriteFile)
{
if (spriteMap.ContainsKey(spriteFile))
{
return spriteMap[spriteFile];
}
var spritePath = Path.Combine("sprites", "cards", spriteFile);
var resourceRequest = Resources.LoadAsync<Sprite>(spritePath);
while (!resourceRequest.isDone)
{
await Task.Yield();
}
if (resourceRequest.asset != null && resourceRequest.asset is Sprite loadedSprite)
{
if (spriteMap.Count >= 300)
{
string leastUsedKey = spriteStack.Pop();
spriteMap.Remove(leastUsedKey);
}
spriteMap.Add(spriteFile, loadedSprite);
spriteStack.Push(spriteFile);
return loadedSprite;
}
else
{
var errorMessage = "Could not load sprite: " + spritePath;
var notifiationData = new NotificationData("Error", errorMessage, NotificationType.Critical);
notificationController.Set(notifiationData);
return null;
}
}
These people are not juniors
Sure.
What's your problem dude? Chill out
You've come in here with some preconcieved notion about what the solution to your problem is, poorly explained what you wanted to achieve, and got angry when people are trying to tease out the real problem and what your actual question is
I'm working on a loot table and just learned about Parallel processing. Would implementing Parallel processing for loot tables be advantageous, or would a simple loot table work if the player is collecting loot from 50 different sources at the same time.
public void Loot(string location, string tier)
{
string key = $"{tier}_{location}";
if (lootItems.ContainsKey(key))
{
int totalChances = lootItems[location].Sum(item => item.chance);
int lootRoll = Random.Range(1, totalChances+1);
foreach (var lootItem in lootItems[key])
{
if (lootRoll <= lootItem.chance)
{
itemStorage.LootItem(lootItem.itemName, 1);
break;
}
}
}
}```
don't be obnoxious, and just assume people are actually trying to help
You're pre maturely optimizing is not help mate.
poorly explained question
IMO it's not bad to use, but you won't gain that much from implementing it for 50 drops. Also know what device and platform your targeting as some don't support it.
It's poorly explained because you're asking about caching something because of memory concerns, and yet got up in arms when told caching involves having things in memory. Was your actual question how to store them on disk?
What actual function are you looking for? What is does caching mean in this scenario? What are you actually trying to do? Storing something in a dictionary or something else, it's all meaningless
We're done with this conversation, thanks though.
lmao
Thank you. I'm not use to the processing power of unity yet, I use to work with Flash AS. and a code like this would kill the game. Thank you.
Look into Tasks, while they won't specifically help much with what you're doing with drops, what you're looking into is 100% usable in many scenerios and just makes you a better dev.
Isn’t loot table just some immutable setting? I doubt you’d gain benefit from parallel processing.
Yea but I'm worried about the amount of times I'm calling the script to gain items if it would be too much. If I'm calling the loot table 50+ times per second to grab items.
That doesn't sound like much on modern hardware.
Why would you need to call it 50+ times per second?🤔
You should profile it and see if there's actually an issue.
Well I’d say optimize your logic first, stop making string every time, cache Sum, etc
Making a type of Idle game, but you have monsters collecting items for you. and they do tasks faster as they level up.
I will start learning how to profile then.
If you are coming from a Flash background (hasn't that thing died for close to two decades now) then you might be surprised at how fast compiled languages like C# are.
I see. In this case, indeed you should profile the game with the worst possible scenario. Then you'd probably see that string allocations take quite a bit of time and GC allocations.
Unless it's actually a problem to begin with, you're going to make so much work for yourself trying to multithread it. Especially if you already have slow code to begin with.
Unless the code you are writing is some deep foundational building block of your architecture, delay profiling and optimizing it to as late as possible.
So i should stress test the system before fixing a problem that isnt here?
I mean, yeah
If you don't know what you're doing, your multithreaded code will end up being slower than single threaded anyways.
I've seen countless times people having an unfinished game, so one part of the code is seemingly more important than it actually is in the finished game where optimizing it wouldn't make a real difference.
Unless I'm misunderstanding how loot tables work, 50 / second is literally nothing anyways
even on mobile hardware
Ok. I guess I'm worrying over nothing. I'll just write it as i have it and stress test it and see if it is a problem. Thank you. This helps a lot.
Small last tip: Make sure you're using structs where appropriate instead of classes for things like data containers. Random access is a huge killer
that's one thing I didn't understand early on, and it killed the performance of my applications
Ok I will learn what a struct is and Profiling.
Imo structs are not a fixer, and misusing them can cause way more problems than just using a class ever would
Structs also have their own performance pitfalls such as passing by value (and thus copying large structs is expensive) and defensive copies regarding readonly structs and in.
Boxing...
Unity Rust support pls 😄
Yeah boxing too, especially if you start implementing interfaces and boxing can sneak in without you noticing.
If ive learned one thing to day is that I know nothing about coding. the hell is Boxing.
you dont have to answer that Ill ask Chat GPT
Structs need to be wrapped up in an object in certain cases and put on the heap, and that allocates. You can easily do it mistakenly by passing structs through methods that aren't using generics but are using interfaces.
Please god just research using documentation instead of asking a text generator
yeah chatgpt is god awful for programming related things
it was banned from stackoverflow for just making shit up
._. I'm using it to teach me how to code for like the last 4 months
It can be fine if you know what you're doing/how to work with it.
It's just that this community is a bit biased against it, so better not mention it here. 😛
I'll keep that in mind. Sorry.
Already completely wrong in the first sentence
But that's the issue. You have to know when it's lying. Learning from it means you can be led down a completely wrong path for a while
I didn't want to start problems sorry. I do use it and If it can't help me than I come here to learn. But I dont wanna have to stop and ask real people for help everytime a run into an issue. cause thats atleast 3 times a day.
Google works
the thing is you dont know when it cant help you. It will always act glad to help you and say "yea just do this", then tells u to use Class.FunctionThatDoesntExist
Yeah I asked it for clarification and it still got it wrong
Perhaps gpt-3.5 is less reliable in this case. I rarely use it for coding question. GPT-4 would be right most of the time.
🇽 to doubt
The last thing I'll say on this topic is that ChatGPT scrapes from google. It doesn't think like a human. When you start working, most companies also don't want you uploading chunks of expensive private code to a public neural net and saying "whats wrong with this"
and then when you break something and you tell your boss "chatgpt did it". He's going to fire you
I mean I'm using it at my work to solve all kinds of problems in different languages and frameworks and it boosts my productivity by quite a lot. There are instances when it is not helpful of course, but these are cases where I myself have to google for a good 30 min to figure it out.
But I guess there's not much point in convincing anyone here.🤷♂️
That being said, I would definitely suggest double checking the information that it provides you, especially if you don't have some background knowledge on the topic.
The generative power of it is pretty good, especially for things like writing tests or mundane. If you already know what you are doing and just too lazy to do it, letting it generate and you review it is pretty nice.
I'm mostly against it for beginners trying to learn.
It's quite convenient to plagarise the works of others through a large statistical model 😛
It's not a reliable source of information, and the last thing you want while learning is not knowing if you are even learning the right thing.
But isn't that what we as humans do as well? Most of our knowledge is gained from other people examples. 😛
No, if I'm copying code from somewhere, especially from somewhere with a license, I will include that license in the code, or at least have a comment pointing to where I found it
I think Bing AI does it
What if you just looked at some code on github and thought "that's a great idea. I'll use something similar in my code"?
If I'm making new code from knowledge gained from learning, then I have learnt something myself and applied it
I also am aware of where it came from, and recommend those sources to people when I talk about it
Well, the model also learned from the training data to generalize to different problems. You don't usually include licenses on everything you've seen with your eyes.
As long as the learning/training material is gained legally, I don't see a problem.
This reminds me of the classic: A: "I stole your code", B: "Its not my code"
"I made this"
Well, that's almost certainly not the case, we just can't do anything about it
Whether the training material is legally gained or not is a different issue though.
As for the model learning, I think it's pretty much what it does.
If it was learning it would have knowledge instead of just the ability to generate convincing looking text
There is nothing following on from this where the AI has sentience
It does though. And generating convincing looking text is not as easy as it might seem.
And you don't need sentience to learn something. It's simply a mechanism of approximating a function that gives a good solution.
@untold moth, If AI is empowering you and you have no moral issue in using it, feel free to use. However, AI is most of the time factually incorrect and induce a LOT of people in error thus making it poorly suitable for answering question.
Even Unity's Muse being definitely sourced using their own documentation is a moral problem, as I doubt the technical writers who wrote it actually agreed to it. Which is another scenario of "it's probably not right, but we can't do anything about it", workers having their work transformed infinitely out of the original context they wrote it for, without seeing any profit from that transformation.
You need to specifically ask in the prompt for it to credit, it only outputs what is asked of it.
Which is a major reason why there's a massive writers strike going on
Which is sometimes going to hallucinate.
Agreed, but humans are not 100% accurate either.
Even source needs to be double verified.
You will never invent a source...
That would be pure malice.
I'm sure people do it all the time. 😄
Do what you want, I will continue to view it as morally reprehensible though 🤷
So, you agree that the AI act with pure malice... ?
And still relying on it.
No I'm saying mistakes can be made by good intentioned humans as well.
Philosophical conversations in the advanced programming section are always great
I personally think AI is a great tool, but you need to understand the source material to use it properly.
Copy pasting AI outputs is like copy pasting Stack overflow.
Why would it act with malice?😅
You will not invent a source. Not by if you have good intention.
Mistakes are not intintional, I'm saying people can make mistakes as well.
It doesn't act with any thought, knowledge, idea, etc. It has no malice, but it certainly exists and performs maliciously
These are not mistakes, these are pure fabrications for no reason but the statistics that made the model perform its function in the first place
Mistakes is something, totally fabricating truth is an other thing.
an action or judgment that is misguided or wrong. In terms of AI you can apply a mistake, this is the entire argument of "What is good".
AI can In my opnion (and yes I understand your guys point) make mistakes, from what they are intented to do.
AI doesn't fabricate as it's just outputs what it wants.
What if you give a person incomplete learning material. Let him read it and make certain conclusions.
Then when you ask them a certain question on the topic of the learning materials, they get it confidently wrong. They simply made wrong conclusions, but they are confident in their answer because they think they learned it from the training data. Wouldn't that be the same as the model giving a wrong answer?
It's your role as a user to understsand this and apply it while using AI
If a dog doesn't do what you want it's not imorral. You are the master.
No. The model doesn't have knowledge on a topic, you can get it to generate confident responses about anything. It's literally just generating text, and the text it generates is just an amorphous representation of the data set. It has no understanding of topics or correctness.
^ It's literally What data comes next
I'd disagree with that.
There's an interesting research paper called "TinyStories: How Small Can Language Models Be and Still Speak Coherent English?"
Reading that kinda changed my perspective on the LLMs.
To put it simply, it's not possible to generate a coherent text without certain understanding of it. Not just syntactically or grammatically, but semantically. The model does have a certain understanding. Words and other building blocks of language are basically concepts that can be represented in numbers(in the case of LLMs - multidimensional vectors) and there are relationships between different concepts. The model learns these relationships and knows what words to output next based on the whole context. It is next token prediction, but next token prediction requires so much more than just some statistical model.
Things are semantically connected in the model, but these connections and relationships are not understood by the model. You can for example make an approximate semantic comparison between different sentences by compressing the inputs as pairs and comparing the resulting lengths. A relationship exists between A and B when the compression distance is small, these two things are likely related. It doesn't say shit about knowledge or understanding though, the model can just group things somewhat successfully. In the case of LLMs the grouping of related constructs in a sentence is very well understood, it can generate human-looking language. In the case of things outside of language, it falls apart and these relationships are just endlessly pushed around by each new model, having confidence boosted in some areas, and totally lost in others. You lose knowledge because the model's "understanding" of related things is not based on knowledge, it's not based on "learning". Learning as a term in these AIs just means progressing closer to the desired outcome over time, it doesn't actually mean anything meaningful was considered along the way to get there
But all of that is irrelevant imo, none of that compares to the immorality of scraping the work of others for the sake of a text generator that can gain you revenue off the backs of workers. That just speaks to why the model's will never be able to be relied on for correct answers.
@untold moth @austere jewel, the nature of the AI means little anyway. It could be the most "intelligent" being ever, if it gives factually wrong answer or hallucinate things its value is greatly diminished to the point where it is barely usable.
I also don't understand how people don't realise how insulting it is to have people you spend time explaining something to, writing resources for, only to have them go "thanks! I will go ask this text generator now"
Anything can give a wrong answers, if you don't understand this and prepare for it you lack both common sense and the ability to use a tool properly.
It is a question of proportion obviously.
Google can give a wrong answer, doesn't mean it's flawed or it's unusable.
If documentation gives you a wrong answer you report a problem or make a PR and it gets fixed
by people
You can report many public AI responses. (Midjourney, GPT, Bing)
Personally, I've just never had any positive experience with it, including gpt4
I have to double check its work and often come up with a completely different solution. It's generally way faster to just look at the docs, even if they just show the method names and properties, it's still often more helpful to me
Shockingly I don't expect reporting a problem and having them eventually push the ML pile around by putting in a bias to actually fix the problem
Part of the solution to AI is understanding what it does well, this saved me 10 min, rather than doing it myself:
I can agree, but it's still there and potentially can be used in the future to do good.
I see how it can be disappointing. Might be arrogant coming from me, who never wrote or published something for the sake of other people, but I think if it was my creation that was used as a training data, I wouldn't consider it offensive. If that would help transfer my knowledge to someone else, even indirectly, that's fine with me. After all "my" knowledge, wasn't "mine" in the first place. I didn't invent any of it. And even if I did, it was just putting together some concepts that existed before.
Yeah, totally fair. For something like that it makes sense. I was gonna say just boilerplate has been helpful
Licenses exist for a reason, and Open Source has many problems with real people not getting paid properly for work they contribute. It's a complex topic involving actual workers and people all over the world in different scenarios with different types of contributions. Not one for a model to slurp up and regurgitate later with every piece of context stripped
Whether or not you would be find with it really doesn't matter
Well, you mentioned that you don't understand how someone would be fine with it. And I gave you an explanaition of why someone might be fine with it. You make it sound like a systematic problem, but I really think it's a matter of opinion.
We can disagree 🤷
I also feel like it is a matter of opinion HOWEVER it has systematic issue for sure that cannot be dismiss.
I agree with this, there's many cases of Google and other systems / companies "slurping" data and serving it without giving credit, and they hide behind their terms of service. (and no one argues against it, because it's just what happend before regulations)
Almost every large company uses spiders for data, it's not any different than what AI uses.
I've never wanted to GTP to write code for me, seems totally unnecessary and not something I'd really trust workflow wise. As an extension tool to Unity's docs though, it's amazing. Often I need a bit of information that I know is in the docs, but maybe I'm blanking on exact terms or references. GPT's ability to interpret my question in correct detail and give me the exact snippet (that I can then look into further in the docs) is awesome.
The difference is that when you Google something you go straight to the source; if the source is wrong, you know who the site owner is and can contact them to correct the information, or alternatively next time you search something else you don't click from that site anymore since you know that's a dodgy source.
When you get an answer from AI...
I am a big believer that cool/convenient doesn't mean something needs to exist; but that also seems controversial against the face of today
Who is getting paid for serving this data?
I didn't click a link to get that.
That's coming from extensive Unity experience though, I feel differently about it (and use it differnetly) for other languages - for example I don't really want to become an expert at Google Sheets formulas. It's kinda fun, but just not what I'm ever gonna spend my time on. Having GTP's ability to turn a broad intention into a correct formula I can just copypasta into a cell has been brilliant as well.
Or this data?
I'm not sure how it works exactly, but I would those features are hardcoded.
this is a really good point, hadn't considered that aspect.
I don't think it's just "cool/convenient". I really think that's the gateway to the AI that we see in fiction. And it's only gonna get bigger from now. You can deny it or embrace it, but it's gonna be a bigger part of our lifes gradually.
I will just move into the woods
But they had to get that info from somewhere, someone had to host and pay for those servers. They don't get anything now.
"They" will find you eventually.👀
My only point is the same practices that AI is doing companies have been doing for the last 15 years and no one complained.
No-one complained?? Where have you been!
Okay, but complained complained 😄
I am attempting to make a multiplayer lobby system with Photon's PUN 2 and what ever I do when I get the player count it throws me the error: NullReferenceException: Object reference not set to an instance of an object
LobbyManager.Update () The code is here: https://pastebin.com/GBG2Xnh6 Video here: https://youtu.be/-kl-b7NRMRw Ping me
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.
The people that made these reviews are not getting credited. Same system as AI spitting out info.
When you're trying to reference your player count it's null.
Nobody can help you if you don't provide the stack trace. But an NRE... that sounds like a #💻┃code-beginner issue, where there is a resource for NREs pinned.
This is not just a matter of "AI doesn't cite its sources" but also a point of credibility and taking responsibility. When I answer questions here I'm putting myself out here and if I keep spewing wrong answers or misleading people, there are consequences whether it's in the form of people stop taking me seriously or even worse moderation actions. And what comes along with it is that I can personally improve every time I'm wrong and don't make the same mistakes again.
When AI is wrong...
Should probably move this AI discussion to a thread in #497872469911404564, or if you're like me we can go our separate ways (I'm gonna go finish the Witcher 3)
I don't know what that means so your probably right sorry.
AI only does what you ask it to do:
That message isn't about citing sources.
Custom instructions
If the quality of your response has been substantially reduced due to my custom instructions, please explain the issue.
Do not be playful or tell me how to speak to you, you are a machine, only respond to me like a machine.```
It's about AI can't possibly take responsibility.
Whenever I want to change my source generator, do I really need to delete the old DLL, and upload the new DLL? So damn slow and such a pain
Yep it's unfortunate
In regular C# projects you can just project reference the source generator project, and you don't need to build anything at all; changes to SG is immediately available in the consumer project.
But in Unity, you have to rebuild the SG dll and move it to Unity project's assets.
It's helpful that you use dotnet CLI to build the SG project so you can chain a terminal command to copy the dll over, and you just rerun the last command in your terminal.
Sorry, to bother you but I don't know what a "stack trace" or "NRE" is?
Silver lining is that SGs don't tend to change a lot once you are done developing them, so it will only be a bit of temporary pain at the start.
#💻┃code-beginner message See ❗ NullReferenceException
Thanks
Is there a way to make a source generator only run when I press a button or something, and not every time I press a key?
I imagine that would depend on the source generator and whatever is generating it
Can someone explain how this works?
Wondering what exactly is being done in calculateGlobalRotation and how the rotation is calculated.
To give some context - I have 3d joint positions of joints for RightUpLeg, RightLegKnee, RightLegAnkle. The below code is calculating the rotation required at RightUpLeg trasnform.
var rotLeftForward = Quaternion.LookRotation(Vector3.left, Vector3.forward);
//Rotations[1] = calculateGlobalRotation(Positions[1] - Positions[2], Positions[0] - Positions[1], rotLeftForward);
Rotations[RightUpLeg] = calculateGlobalRotation(Positions[RightLegKnee] - Positions[RightUpLeg], Positions[RightLegAnkle] - Positions[RightLegKnee], rotLeftForward);
Quaternion calculateGlobalRotation(Vector3 boneDirection, Vector3 left, Quaternion init)
{
var d = boneDirection;
var up = Vector3.Cross(d, left);
d.Normalize();
up.Normalize();
var target = Quaternion.LookRotation(d, up);
var rot = target * Quaternion.Inverse(init);
return rot;
}
That kind of defeats the purpose of SG though, SG always being in sync with your source code is a huge benefit.
What is the issue you are trying to solve by preventing SG from running?
What you want to know ?
I just do not need it running every time I press a button
all I need is something more like InputActions, where I just need to tell it "Yeah, please generate now"
Are you having performance issue or?
Because my project has 80k LoC in one giant assembly, it has two SGs scanning for attributes and generating code, and I’m getting zero lag in IDE while typing, on a 10 year old laptop that has less RAM than phones nowadays. You’d be surprised how performant SG is, unless you are doing something unconventional.
//Convert Local Direction to World Rotation (If I am correct, this is from local space to world space)
Quaternion calculateGlobalRotation(Vector3 boneDirection, Vector3 left, Quaternion init)
{
//Current Direction
var d = boneDirection;
//Find the up
var up = Vector3.Cross(d, left);
//Normalize direction. (Might be unnecessary, I believe that Quaternion.LookRotation already do that)
d.Normalize();
up.Normalize();
//Find the targeted orientation in quaternion.
var target = Quaternion.LookRotation(d, up);
//Apply the rotation from the original oritentation. (Convert from local space to world space)
var rot = target * Quaternion.Inverse(init);
return rot;
}
And btw, Unity analyzer (SG is a form of analyzer) that gives warning about empty Unity methods and incorrect null usages, runs on every key stroke.
@dusty wigeon
Actually I wanted to know why/how left value is passed to calculateGlobalRotation. Can't exactly find out why Bone 2 (1-0 joints) is picked as left and passed to calculateGlobalRotation.
And also, consider when Bone 2 (1-0 joints) is bent at some angle (let's say knee bent at right angle ) , the cross product will be something like vector.right which don't give any kind of clue 😐
What are you trying to do ?
I have 3d positions of joints. I need to target a humanoid where it matches those joint positions.
So, you are manually doing IK ?
I have positions for all 13 joints so I don't want to do it via IK.
What do you mean ?
You are doing a fullbody IK ?
Yes.
I think so. It will end up full body IK.
Any pointers on how to solve it. I heard full body IK will be too costly. so wondering if there is any other way.
Then, I'm sorry, but I can't help you there. This is a pretty ambitious challenge. You should just use an asset such as Final IK.
Yes, do not use full body IK or use an Asset. You are making a game arent you ? Not a game engine or an asset.
Oh ok. Any directions/theory on how I can move forward?
Start with simplier challenge.
Such as 2 bone IK.
Then ramp up.
Ok. Actually I wanted to understand how it works...so experimenting...
Also, you want to read books and white paper.
You are going to be on this for a while.
Ok, will keep trying! thanks for giving a note on my focus :), yea finally I want to finish my current game 😄
So, I will try for some time and later start with something as simple as 2 bone ik in free time.
Anyone have a minute to help a bad programmer out?
A fail to understand for the life of me why this array, when I clearly can log its length, it's not null... but then in the next line it returns a null reference exception.
How can that be when it has a default value specified in the Contents class
contents[0] returned null
shouldn't it automatically set that value when its created?
When you initialize an array with a specific length, it fills all the slots with the default value of the type the array contains.
If that type is a class, then it's filled with nulls
oh I see... so in this case my values are null after the newWave is instantiated? the assingments I specified are basically ignored?
You don't add anything into your array right now
you did not do any assignments to the contents array
From what I can see
At some point, you need to do
.contents[0] = new Contents()
To fill the first slot
you created an empty array each element of which may contain a Content or a null
but when I do 'newWave.contents[i].count = X' it also gives me a null reference, as if the array element index0 didn't exist (but length returns 1 so it must?)
oh I see
The array has a length, but it doesn't mean what's inside has valid values
the array is an array of references. Those references can be null (not pointing to any actual object). In fact by default they will all be null
new Contents[3];
// -> [ null, null, null ]
oh thanks so much guys!
big brained programmer chads hanging out here helping noobies out, really appreciate it
this did the job
One thing Unity does to confuse people about this is that if you did:
public MyClass[] = new MyClass[5];``` it will actually create those objects for you if MyClass is serializable. This is a quirk of Unity's serialization mechanism not how C# actually works under normal circumstances
perfect
that is good to be aware of!
Does anyone know if there are benefits to using SceneManager.UnloadSceneAsync on a scene with several root game objects, vs calling GameObject.Destroy for each root and then unloading the empty scene?
In my testing, the latter seems better because UnloadSceneAsync destroys all roots in a single frame, whereas with the manual method you can place the Destroy operations in separate frames to avoid single frame FPS spikes.
It seems to me UnloadSceneAsync is just a convenience method to make us have to implement less code, however I want to be sure that there aren't other benefits to using it over GameObject.Destroy.
If any of you are willing to help me with an inventory system dealing with scriptable objects please DM me. I really need some help on this.
Seem to have an error with my mesh but can't figure out why. I am copying a prefab's mesh to a new mesh so im directly copying the triangles across like this:
Debug.Log("Total submeshes: " + _prefab.subMeshCount);
for (int i = 0; i < _prefab.subMeshCount; i++)
{
Debug.Log("Submesh index: " + i);
_mesh.SetTriangles(_prefab.GetTriangles(i), i);
}
And i get this error:
Failed getting triangles. Submesh index is out of bounds.
What might be the issue here?
how can i be out of bounds if i have 2 submeshes yet index 1 triggers the error
you're doing _mesh.SetTriangles but reading submeshcount from _prefab
two different meshes no?
Any reason not to do _mesh = Instantiate(_prefab);?
well its an editor tool so i didnt want to generate new objects as i want to save the data to a scriptable object
how is that any different from manually creating a Mesh with new
either way you're going to save the new mesh in the asset right?
instantiate creates a gameobject in the scene no ?
oh
if you Instantiate a Mesh it only creates a Mesh
so instantiate is like a deep copy?
yes
interesting
ill try it
would i have to add destroy here to avoid memory leaks:
_prefab = EditorGUILayout.ObjectField(_prefab, typeof(Mesh), false) as Mesh;
Destroy(_mesh);
_mesh = Instantiate(_prefab);
encase i change the prefab
yes, but that was the case when you do new Mesh also
well wouldn't you be able to delete all of this code now?>
Instantiate should do all of the submesh copying etc automatically
oh true but see im back to my previous issue of memory leak warnings
since im not using shared mesh
oh i see the issue
OnInspectorGUI is every frame so im just destroying and instantiating every frame 🤔
need to rethink that
oh nice
I use SceneManager.LoadSceneAsync on an empty scene then load the next with the same method. Never had any issue about lag spike for unloading.
Thanks, but my testing shows different. How big is the scene you are unloading (i.e., how many game objects does it contain)?
It is production game 100'000-200'000 gameobject and 2 years worth of asset 5-10 artist.
I worked on game that have 1'000'000+ gameobject that was constructed with tools.
Anyone here good at netcode for gameobjects? I just started and I cant seem to figure out a way to make vehicles like a ship work well. Running into problems where the players movement isnt properly synced as a child of the vehicle. Not really sure how to approach this
Ah ty
It's a production game with 100,000-200,000 game objects in a single scene?
wow
Yes
Our scene range from 100'000 to 200'000 in one project
An other has over 1'000'000 gameobject
But it was made with tooling an a lot of empty gameobject.
Also, knows that Complience Testing Team are strict on loading that stuck because it is a TRC for multiple platform.
So, I'm pretty confident that it does not lag out of proportion.
In that case maybe LoadSceneAsync does modulate how many game objects are destroyed in a single frame once the frame surpasses a certain ms threshold
and my test doesn't catch that because the unload was literally the only thing happening in the frame
Or maybe that you have a lot going on in OnDestroy ?
not unless there's something about LODGroups that has a heavy OnDestroy penalty
the game objects only have colliders and mesh renderers (and the LOD Group component on the parents)
Did you try profiling or are just guessing ?
I profiled, but going to try a deep profile.
Profiled in a build too. I'll try some more test with more game objects in the scene.
It sounds like your game used non additive loading (where the old scene is unloaded automatically). Is that right? Maybe the performance is different than using UnloadSceneAsync, since the latter would theoretically have more work to do in terms of combing the scene for dependencies?
I do not use additive scene, correct
I guess I'll test that too. Thanks!
Do anyone here uses poisson disk sampling? any idea how to use multi sized objects?
like this
having a weird issue generating meshes my mesh generates all the verts in the correct place, yet it only renders a 10th of my mesh then its all invisible, ive checked reversed normals its not that either
got no idea how to debug the problem
Reduce the amount of vertices till you find the actual one that are problematic. Then reduce it to a single triangle. At that point, the issue should be pretty obvious.
i think i know the problem but not sure of the solution
Then you could explain your problem, someone might be able to help you.
im copying and lofting a mesh along a bezier spline
but im not sure how to update the tri index array correctly
public class Test
{
public Test()
{
Debug.Log("Hello, World");
}
~Test()
{
Debug.Log("Goodbye, World");
}
}```
just curious but does anyone know why both the constructor and destructor are called twice in edit mode
Maybe you have 2 instances? I don't think it should be called twice in any situation.
i think it got called twice because i used the new keyword
I can't think of a way to create an instance of it without using the new keyword.🤔
likely two MonoBehaviour scripts
Activator.CreateInstance
Pass game object to Test method and use it in Debug.Log context parameter, you'll find your copy clicking on the console message
ty
Is there a wise reason as to why not make a console like that, instead using inheritance?
also I could skip the struct part theoretically
using System;
using System.Collections.Generic;
using System.Linq;
public class Console
{
Dictionary<string, Func<string[], bool>> commands;
public void ProcessCommand(string input)
{
string[] splitIntoCommands = input.Split(';');
foreach (string command in splitIntoCommands)
{
string[] splitIntoArguments = command.Split(' ');
commands[splitIntoArguments[0]].Invoke(splitIntoArguments.Skip(1).ToArray());
}
}
public void RegisterCommand(string keyword, Func<string[], bool> function)
{
commands[keyword] = function;
}
}
So it would be like that. Any reason thats not how its done in all the online materials on the topic I could find?
if it works for you then why not 🤷♂️
For some basic debug funcionality in a build, cheats, dev commands etc... its perfectly fine imho 👍
Just be aware of the exceptions this might throw, for example when you enter an invalid command, this will throw an exception on the line where you index commands with the split string
commands[splitIntoArguments[0]].Invoke(splitIntoArguments.Skip(1).ToArray());
this is horrible
not how its done in all the online materials on the topic
I'm more curious about this and the comment about they do it "using inheritance"
They probably do it the more OOP way, where each command derives from a base one, allowing more features to be added like argument validation
Oh for the commands, I thought they meant inheritance for the console.
why
aside from the fact it throws exception on invalid command
- LinQ, which I hate
- Unnecessary, ArraySegment should do the job
- Lots of GC
true, linq is unnecessary there
write a simple parser and build a trie of command can prevent invalid input and even show suggestions
but node of trie quite "big" in memory (4*number of char supported+4 or more byte) suppose you trie is "array implementation" (pooled in array)
do you mean tree?
https://en.wikipedia.org/wiki/Trie
prefix tree
In computer science, a trie (, ), also called digital tree or prefix tree, is a type of k-ary search tree, a tree data structure used for locating specific keys from within a set. These keys are most often strings, with links between nodes defined not by the entire key, but by individual characters. In order to access a key (to recover its value...
man, someone needs to learn to spell
Do you mean why command console uses inheritance? Because you can add more functionality and characterlistics to command than using single delegate, while consolidating bolierplate like arg verification or suggestion.
how ive seen it made is they use IConsoleCommand interface, then from that a generic ConsoleCommand inherits, and from that inherit all the regular commands and they are loaded into the Console class as objects
Sounds correct to me, you could add virtual info like “what type/how many args this command takes” or “what this command should suggest”
yeah but that seems to me like an awful lot of classes for what is essentially keyword-function pair
Well nothing really wrong with having many classes
You can probably easily make generic SimpleCommand that takes your delegate
Then change it to regular class when you need it
I don’t see “minimal” as opposite as “modular” though
i will just having some
struct command{
char*prefix;
char (*process)(char*args);
}
```simple.....
yeah, thats what I had before
except I figured for now I can skip the struct step, until my functionality is required to be more complex
Hey, so I am working on a editor that automatically places platforms for a platformer along a spline. I am trying to figure out though how to determine if a given placement for a platform is 'valid' (reachable) by the player. Any suggestions about how to go about this?
You'd have to explain to us what "reachable" means first
Honestly, it's probably easier to eye ball and test it. 🫥
Within jumping distance (standard first person game jump, no double jump or other platformer type movement)
There is going to be 100s of the platforms :/
Yeah, not sure. There are too many questions to answer with making something super procedurally driven like that. I would personally probably start by manually answering the "how far can two platforms be", and use that distance as a way to check two points along a spline.
There are just too many other things that go into a platformer that making a whole platform placing tool is going to eat up so much time. Unless the game is only about moving platforms. 🙃
Yeah makes sense.
you could use the kinematic equations to figure it out
You could do some trajectory math to check if a point to other point is reachable
Ahh, that might work. Though I will have to check if the character controller is actually using any form of physics, or if it is all manual. Good idea either way though.
it should work even if it doesn’t use physics
as long as the player has a speed and jumps in a parabolic shape then the equations will work
Cool. Do you happen to have any suggestions for where I could find such functions? This is the type of math I am very bad at. (If not that's fine. I can search for them my self)
there are only like 5 of them so ya i have to send you to google
I'm reviving a project from 2017 and upgrading to 2022 lts. I'm in the process of switching to the newer netcode implementation because it seems like it'd simplfy implementations.
I'm working through moving my messaging to using the rpc mechanism and running into an error where I get my clientrpc "does not exist in the current context". I have both client and server functions in NetworkBehavior inheriting classes, and both specify the attributes and correct naming convention. I'm clearly missing something that is probably obvious in the examples and tutorials online but I'm not sure what that is...
If netcode related then you should probably ask in #archived-networking but the CS0103 "The name 'identifier' does not exist in the current context" error isn't netcode related, it's a syntax error. And you might need to send your code.
Ah thanks I didn't see that channel
Not sure which channel is the most appropriate. working on a unity game with mapbox and trying to build to iOS. I had an issue with the line #import <MapboxMobileEvents/MapboxMobileEvents.h> which couldnt be found. I moved the contents of MapboxMobileEvents/Include/MapboxMobileEvents to MapboxMobileEvents and then changed the <> to quotation marks. I am now getting an error Library not found for -lUnityARKitFaceTracking and Linker command failed with exit code 1 (use -v to see invocation)
I dont have a ton of experience building to iOS and im wondering if anyone has a solution for this. I also dont need to include face tracking in my application, since I have no need for it. Does anybody have any ideas for how to fix this?
Hello, I have a problem. I want to call UnityWebRequest during build time in console mode but now I didn't get a response. If I do it just in editor then it works well. Could you tell me if is that possible?
which response code did you get?
I received nothing. It looks like the editor skip coroutines but only during build time.
time to build in some Debugs
for coroutines I used EditorCoroutineRunner
but to answer your original question, if the console is attached to the internet then yes it is possible
you cannot have Editor code in a Build
you mean you are calling WebRequest as part of your build process?
During an actual build?
Now I want to start building and send some data at end of build process
Why does it need to be a coroutine if it's during an actual build?
the point of coroutines is to maintain interactability during some process
you don't need to be able to continue to interact with the editor during a build
to call UnityWebRequest
you don't need a corotuine to call UnityWebRequest
and what do you mean by 'console mode'?
I think they mean headless mode
confused me I thought they had built to a games console
sorry, I forgot a name of this mode
If you just want to make a synchronous HTTP request during the build maybe just do something like this:
https://stackoverflow.com/a/66655958
UnityWebRequest is designed for asynchronous use during playmode.
still you must be getting a response code from the WebRequest
I know, but do you know a solution for how to call that during the build process?
in my case, when I use EditorCoroutineRunner and UnityWebRequest in Editor to connect everything is fine. But the same code didn't work during build process.
but what is failing. you started by saying it was the webrequest, now you are saying it's the coroutine itself?
when I put Debug.logs then Unity didn't call a function with UnityWebRequest
so why is webrequest relevant. it's the call of the method that has failed
You cannot run EditorCoroutineRunner in a build ?
right and I've suggested to you a workaround
instead of using EditorCoroutineRunner (which you don't need), just make your web request synchronously
of course not, you cannot have any Editor code in a build
this is the build process not a unity player build
but I still don't think that EditorCoroutines work in headless aka batch mode
never even thought of doing it
yes, the whole webrequest thing is a red herring
I think there's trying to use editor coroutines BECAUSE they see UWR as the only way to make an http request and they need a coroutine to properly wait for such a request to finish
Hence my suggestion here of using a different approach to making the http request #archived-code-advanced message
Didnt see the distinction between the build and the build process.
using Process and passing it a URL? that should work but you wont get a response into your process
Thank you for your help, I will try different coroutines or maybe a different approach. I write if I will need more help.
How?
The build is your game
The build process is the Unity editor BUILDING the game
Oh sorry
I think you are misunderstanding what i'm saying.
just realised why it does not work, EditorCoroutines are multi threaded, the headless build process is single threaded
Can you just not do a while(...) then ?
You could but I hate the idea of a busy loop...
Also IDK if UWR actually updates its state on a different thread or not
@potent roost you might get away with using HttpClient
How would I go about making seamless metroidvania-like scene swaps? Like, when you exit a level, it pans the camera to the next level. I'm thinking of loading scenes additively and unloading scenes that are more than 1 exit away. (I'm using one scene per level for organization) Though, I'm not sure how I should place the loaded scenes so that the exits line up perfectly? Also how I can easily select scene objects?
you do not place scenes.
if scene1 has an object at -1,0,0 and is x=1 wide and scene2 has an object at 0,0,0 when you load scene2 additively the 2 objects will be side by side
yeah I knew that. I was asking if there was any way to automatically set the content to be lined up
no
or if i'm obliged to construct the scenes so that they all line up by myself
you have to do it
alright
do you think it's going to be resource intensive if I just construct the entire map in one scene? I plan to have a pretty big map so idk what to do honestly
if I do multiple scenes it might be really hard to know exactly where to place the tiles
to make one map is going to take a while to load the scene. it's really not that difficult to place the objects as you can have multiple scenes loaded in the editor at the same time
how am I supposed to know where the tiles of the previous level are when making a level (without having to look back)? since it needs to be lined up
sorry, did you not read what I said, you can have multiple scenes loaded in the editor at the same time
oh yeah sorry I don't know why I didn't understand that
if you want to make it easy then add a gameobject in scene1 (Exit) and a GameObject in scene2 (Entrance) make all gameobjects in scene2 children of Entrance then when you load scene2 set Entrance.position to Exit.position. Perfect alignment
hey, in my space strategy game i want to set waypoints for the units with the mouse by clicking at the point in the scene where they should go, but it's a space game so there is no ground, and i want to also have the y axis so not all units at the same height. the player can change the y position with key input, but where do i get x and z from? any ideas? (sorry if it's a stupid question :D)
the x and y are not a problem, you can get those from mouse position then screen to world point. The z is more difficult if you are not clicking on an object
yeah there is only empty space so i click at nothing
then you are going to need to interpolate z using the start position and the eventual destination position
Can someone help me with an Inventory system. If you are experienced with that stuff please DM me. I really need the help.
This server is for asking questions, not for posting requests for 1:1 help. Show your attempts, and get your help.
Also, #💻┃code-beginner (I feel like you've been directed to that channel multiple times already?)
Nah I haven’t
And an inventory system isn’t beginner with all due respect
Yeah 3 months ago
It's not advanced. These channels are for people who can already code and need to have a conversation about what they're doing.
Beginner is for people who have no idea what they're doing. Ask your question there with details and your attempts.
Okay
how does mesh combine work if you have meshes with submeshes
i cant seem to get it to merge them correctly
if i make it combine submeshes then each mesh is alternating between submesh materials
if i dont then it dont really combine properly
you'll have to combine all the submeshes for each material
how though
im duplicating a mesh prefab alone a spline
but want to combine all these meshes into one mesh
i cant figure out how to correctly combine each submesh seperately
the CombineInstance lets you specify the submeshIndex
so you'll have to go through each mesh's submeshes, check their materials and organise them into separate lists of CombineInstances
🤔
then combine each list into a mesh and assign the associated material
that sounds confusing as heck
why cant they just have it understand if its the same mesh object that im combining that it should just merge it into one mesh with the same submesh formatting
probably the one thing that people would use it for they dont even support the feature
im not using gameobjects just mesh classes
😦
my plan B is to generate two seperate meshes entirely rather than one with two submeshes
then combine them - that might be simpler
alrighty.... over the whole week, i pretty much exhausted almost all of my ideas, so i am presenting myself here with a frozen editor.
the story:
so, my game has a lot of sprites that i've been turning to 2d colliders, but because of how long it takes to get them all done, i've been working on setting up a way to automate creating polygon colliders to the sprites. i've came across this nice free asset on the asset store that handles the bulk https://assetstore.unity.com/packages/tools/physics/advanced-polygon-collider-52265
this works actually super good... gave me polygon colliders right on the very pixel edges of the sprite, which was exactly what i wanted
the problem:
until you use it on specific sprites that seem to have a non-random reason for causing the unity editor to crash upon add component.
the intention
so when i attach the component to the gameobject, the intended result should have been:
- checks if a 2d polycon collider exists and makes one if it isnt,
- then updates the points to fit cleanly around the sprite
the request for help
i have attached one of the few sprites in question that caused my editor to crash. i've tried in unity 2018.4 and 2021.3. at least 2021 realizes it's freezing.
if anyone whose good at figuring out these sort of bugs could enlighten me and maybe point me in the right direction to solve this, that would be wonderful.
Have you contacted the asset dev?
ah, i haven't actually. i'll go ahead and dothat
Is it possible for a sprite mask to affect only one specific object without using layers, with configuration controlled via a script?
Is using texture array a thing for a skinned mesh merger?
Is it viable? instead of atlas
Can someone help me understand this?
The render thread says to be 1.5 ms on the game stats windows
however on the profiler, most of the time is spend on waiting for signal
Render thread and GPU processing time are 2 separate things.
Since most of my gpu processing is done through command buffers, I thought that meant that it was counted as the render thread
What is render thread then?
Also, every so often there's a huge spike by unity editor, is this normal?
I'm not 100% sure, but I think it builds the command buffer.
Then the command buffer is executed on the main thread(?)🤔
im not sure either, it seems that if I click on GPU Usage, the values seem to be more precise, things change
Executing the command buffer means that the CPU is issuing commands to the GPU and waiting for it to complete them. That's the "wait for present" that you're seeing.
But in theory, the command buffer will just schedule the calls for once the rendering pass happens its executed in order
I don't think that's normal, select the frame with the spike and see what's taking up all the time.
As said, it's EditorLoop
Doesn't give more info
You can inspect the editor loop too.🤷♂️
Change the profiler to editor mode.
Ah got it
You can't stop it, because that would freeze the editor.
Profile a build, not the editor.
That too. But sometimes fixing the editor issues worth it to make the development smoother.
Also, High Render Thread times usually means a lot of object that needs to be processed. Reduce the amount of object by manually culling things that are not visible. Like interior of a house, a cavern or a far aways Point of Interest.
This is what Im getting on the editor
That is more than fine for the editor
Close the frame debugger and try again.
Yeah, It's mainly because Im doing draw mesh instanced, and im already applying occlusion and frustrum culling, but I guess I will need to find more techniques to reduce size and frame time
Okay
I will try to profile a build and see
Anyways, it's waiting for the GPU to finish rendering.
Probably because it does not have a Network component.
@trim aspen Don't crosspost. #💻┃code-beginner
(where someone answered your question)
Hey, where do I find the scripting reference for UGUI?
I can only find the old one, and the manual for the new one (1.0.0, package version). It's pretty broken.
Like, this is the generated doc and the ACTUAL doc is worse than thiis.
😦
compositionString is not a numerical value, of course.
(extremely sloppy documentation)
Text Mesh Pro is open source. You can check whatever you need directly inside the package.
It's not documented in the package, either.
I'm not going to reverse-engineer their code.
But this is a basic event/property, this ought to be documented somewhere.
Just look where it is called.
Unity says Unity Objects shouldn't use Null propagation ?
Why though ? anyone know?
Because it works fine, also thats Null Conditional.. I thought it was Null Coalescing that didn't work on components ?
Also, you could say what you are looking for.
I guess what I'm asking is , what are any potentials for something to go wrong? why is the exact reason we shouldn't use it if its working?
Unity override the equal operator for null.
The object could be considered null, but it is not really null.
It will not detect destroyed objects like == null will
I'm looking for the documentation for property TMP_InputField.stringPosition
TextMeshPro docs are here: https://docs.unity3d.com/ScriptReference/index.html
Ah I see, so basically is part of the engine and wont be "fixed"
unfortunately yes
tragic
Instead of overriding null all those years ago they should have just written public static bool IsDestroyed(UnityEngine.Object obj)
and we wouldn't be in this mess
That page has no working search. Reported this for years now.
idk why I sent the wrong link
and the search indeed works
👎
And as you can see, these are ALL undocumented.
Works for me
But yeah ok, so nothing changed since Unity 2018
they're documented - they just have no useful info lol
They have 0 documentation that is beyond type inference.
The decompiled source code has more than that.
YOu want to see undocumented try the implicit conversion-to-bool operator for RaycastHit2D 🙏
Yeah only on that page, but thanks.
Very funny. I just want to know how the selection rect in a InputField works (want to set it / move the cursor to the end).
I'm pretty appalled at the quality of this, I didn't realize UGUI was in such an unfinished state.
The docs for UIToolkit are almost better. (if the tech wasn't garbage)
Thanks though, I will have to keep trying to solve this. 🙂
This one helps. 😛 That's the doc for the old UGUI, the one before TextMeshPro.
There's <inheritdoc/> for a reason... sigh.
Still can't solve it. It unreliably selects the wrong characters (swallowing the one that I communicate in from input system after activating it)
Just randomly trying fields, I'm glad this isn't C 😛
To be honest, if has no particular functionality, I expect the TMP inputfield to work correctly given correct input.
Maybe you should try to isolate one and reduce as much as you can your code.
yeah what are you doing that involves messing with anything special here?
Basically - what are you trying to achieve here?
Do you use the EventSystem ?
Input field is hidden.
If user starts typing alphanumeric characters, SHOW input field, and put first typed character into the field, then carry on with normal field function.
Hide field if string cleared or escape pressed.
Yes, but now I'm using ActivateInputField, this fixed the first issue that the focus wasn't reliably returning on 2nd or 3rd use of the filter.
But the first char is always selected and thus lost.
Even with hax like this. (of course I WANT the selectall feature then the field is focused by mouse at a later time)
arrgh. 🙂
Got it. Must be called in EXACTLY this order:
public void Open(char start_value)
{
input.text = start_value.ToString();
gameObject.SetActive(true);
input.stringPosition = 1;
input.ActivateInputField();
}
Oh goodie. It works for all keys, except for W, A, and S. (but it works for D)
(I'm serious, tested the entire keyboard, whoa. w, a, and s retain their focus)
I have a theory, EventSystem may interpret these "move" events as cursor navigation. Doesn't explain a, but might explain w and s.
Yes, that was it.
So the REAL problem is in my event handler that treats move letter key the same as a input key, but... my event handler is just Keyboard.current.onTextInput
. That doesn't even have a concept of "Move" or "UI/Navigate".
Also, if I do this with the cursor keys, it doesn't cause the focus to stick, but it does move the cursor.
W, A and S event may be consumed by something else ?
Visual Studio his intelisense becomes slow when we added a package (the package yarn)
when we delete the YarnUnity.DLL visual studio becomes faster? (we use visual studio instead of code)
does anyone has a idea how to solve this because we need this package and this DLL?
How do I debug XCode Simulator instance or app running in iPhone? I have a case where I click and do some raycast check. And this works for me in Unity, but not in XCode Simulator or iPhone. The XCode build is totally unreadable to me.
Read the section called "Debug Android and iOS devices with Visual Studio":
https://docs.unity3d.com/Manual/ManagedCodeDebugging.html
Thanks
by the way what exactly is the difference to this and combining meshes ?
It does what you want, except it sadly does it with GameObjects as inputs.
i did a quick experiment with it, it seems to not remove the original GameObjects and merge it into one ? maybe i am misunderstanding how it works
does it still do it but keep the original gameobjects visible in the heirarchy
I haven't used it for like... a decade, I remember it as being manual and returning a combined object but the docs read like the combined object is internal and the original objects stay there unused
Can you just not merge the array (triangles, vertices, normals) into one to combine a mesh ?
Is "Debug" enough to have the simulator appear there? Do I also need "Development build" and "Script debugging"?
You would have to offset the indices arrays so they pointed to the appended data
How do I do this in unity?
Finally it worked, but the debug build starts so slow...
I wonder if it's because of my code, but on the other hand the Release build starts almost instantly
no, debuggers are quite slow, especially remote debuggers
On the third hand, I haven't tried running Debug build on iPhone, maybe it's Rosetta that is slow?
yeah add in emulation and 😵💫
Hey guys doesn't Unity suport Thread Afinity for PC platform? I only see Android on documentation. Is that correct? Thanks