#archived-code-advanced

1 messages · Page 63 of 1

sage radish
#

You would replace the constructor with GetTemporary, it's a static method that returns a RenderTexture. After you're finished with it, which is after the CopyTexture, you call RenderTexture.ReleaseTemporary(buffer)

modest solstice
#

not strictly tied to post processing, just as an example

vapid pawn
#
    public GameObject Car_itself;
    RenderTexture buffer;
    Texture2D texture;
    public void Create_Texture() //  Creates Texture from one Material then Send it to Other Material
    {
        Material This_Object_mat = this.GetComponent<MeshRenderer>().sharedMaterial;
        This_Object_mat.SetColor("_Color", Random.ColorHSV(0, 1, 0, 0.6f, 0.5f, 1, 1, 1));  // This Object's Material
        
        buffer = RenderTexture.GetTemporary(            /// <--------------------------<-----------------<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<-<---------------<--------------
                         1024,
                         1024,
                         0,                           
                         RenderTextureFormat.ARGBFloat,  
                         RenderTextureReadWrite.sRGB 
                     );

        texture = new Texture2D(1024, 1024, TextureFormat.RGBAFloat, false); /// <-------<--  AND MOVE THIS TO START/AWAKE VOID  <<<<<<<    AND MOVE THIS TO START/AWAKE VOID<<<<<<<-<----
        Material material = GetComponent<MeshRenderer>().sharedMaterial;
        
        Graphics.Blit(null, buffer, material);
        RenderTexture.active = buffer;
        Graphics.CopyTexture(buffer, texture);

        RenderTexture.ReleaseTemporary(buffer); /// <--------------------------<-----------------<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<-<---------------<--------------

        Material Target_Material = Car_itself.GetComponent<MeshRenderer>().sharedMaterial;  // Target Object's Material
        Target_Material.SetTexture("_MainTex", texture);
    }
    private void OnDisable()
    {
        Destroy(buffer);                     /// <--------------------------<--  AND REMOVE THIS  <<<<<<<    AND REMOVE THIS  <<<<<<<<<<-<---------------<--------------
        Destroy(texture);
    }
fickle inlet
#

Hey guys, what are good things to do in an Update that wouldn't be possible anywhere else like fixed update or start/awake? I found these input handling, timers and raycasting. But I need more examples and nothing comes to my mind. Whatever I come up with could be done inside an IEnumerator or in a single frame

hushed fable
#

I don't think there is much you can't do in a coroutine that you could do in Update. This is a bit odd exercise.

fickle inlet
#

What about smooth animations? Those could work better in an Update loop vs coroutine?

devout hare
#

There's absolutely no difference between them in that regard.

upbeat path
#

Not looked into it but what about script execution order?
Say we have ScriptA and ScriptB with the execution order B, A
So Update in B runs before Update in A
Will Coroutines in A and B also run in B,A sequence regardless of starting sequence?

ancient solstice
#

Coroutines are processed in Update as far as I know, and bound to a UnityObject instance like MonoBehaviour. So, probably

stuck onyx
#

'm launching these expecting to create an unhandled exception but they are being treated as common errors (Debug.logError)

#

is it because im in debug mode with script debugging enabled?

#

Usually what should happen here is the type would be exception and continue with the method but its not happening

#

weird, if i do it in editor behaves as expected

devout coyote
#

Uncaught exceptions will stop execution of a script

#

Your problem definition is too vague for me to know what's going on

stuck onyx
#

@devout coyote then what is this setting for?

#

Oh i guess thats just for exceptions happening outside of the unity SDK? native crashes?

devout coyote
#

No I think that's also for scripts

stuck onyx
#

rider says is handled

#

how can be handled if theres nothing there to handle it??

#

is unity handling it by default ?

#

Even the CrashReporterHandler....

#

why i cant create an unhandled exception 🤣

stiff hornet
#

the runtime would terminate the program if it wasnt handled

stuck onyx
# stiff hornet why would you want to?

i want to create an unhandled exception so i can test how Sentry differs before sending a report when is handled or unhandled so i can add logs or not in the report

#

i think the problem is the place im calling it

compact ingot
stuck onyx
#

now worked, accessed a scene missing reference and it was treated like an unhandled one

#

i was calling the other exceptions from a console plugin, maybe it has a wrapper somewhere that was catching the exception who knows

keen glade
#

Should you use pointers? UnityChanThink

upbeat path
keen glade
#

Ah okay. UnityChanThumbsUp

tiny pewter
#

if i have to modify properties in struct inside a unmanaged array, since is it not allowed directly modify the properties in nativearray (i.e nativearray[i].a=A;) so if i directly declare a T* and malloc it, will it faster than the "usual" way to modify the properties? i.e. T t=nativearray[i];t.a=A;nativearray[i]=t vs arrayofT[i].a=A;

sage radish
#

If you're using NativeArray outside of Burst, then it may be faster to use it as a Span. But Burst knows how to optimize NativeArray.

tiny pewter
#

i havent heard of span but i find NativeArrayUnsafeUtility namespace, thank

ashen hill
#

Anyone familiar with GPGS? I'm trying to implement a save/retrieve using GPGS, but I'm going a bit wrong... First, here's what I want

1. on startup, check if there are any games stored on the Google Play Games server.
2. if there is, load the game.
3. if not, do 3-1. 
3-1. Parse the new class into JSON and save it.
4. repeat step 3-1 for each button press.

But... I've got a problem, I'm saving the new class if there's no game saved, but I keep getting NullReferenceExtension, if you know of any code that accomplishes what I'm trying to do, may I ask how you did it?

raven elk
#

how do i ancer things

upbeat path
#

or possibly answer questions

native lintel
#

im trying to load a texture2d image and put it on my maintexture and it isnt actually applying the texture i want but rather its making a new one, now everytime i look this up its always the same thing so im wondering if someone could help me with this issue.

craggy sierra
#

Context?

dusty wigeon
# fickle inlet Hey guys, what are good things to do in an Update that wouldn't be possible anyw...

I know a substantial amount of people do delayed action in a coroutine. When the object is pretty simple, it works perfectly fine, but whenever it starts to be complicated such as CharacterController, it can become really hard to properly manage all those delayed action. The worst is when you have multiple delayed action that could happens at the same time.

A concrete example that I came across recently is a camera fade. (Multiple call to the fade method, Simultaneous call to fade in and fade out, etc.) All of that made the coroutine a real pain in the ass.

native lintel
# sly grove You need to share more details

So i import the texture from my local path but this isnt the texture i wanted but it just took the data and made a new texture2d, how would i actually import the texture rather than making a new texture2d in script?

public void LoadTextureFromFile(string path)
    {
        byte[] fileData;

        if (File.Exists(path))
        {
            fileData = File.ReadAllBytes(path);
            playerTexture = new Texture2D(2, 2);
            playerTexture.LoadImage(fileData); // Load the image data into the texture
        }
        else
        {
            Debug.LogError("File not found at path: " + path);
        }

    }
native lintel
upbeat path
native lintel
#

nope

upbeat path
#

open a local .html file in a browser and look at the url it uses

native lintel
#

o

native lintel
upbeat path
#

yes, the one you read from disk.
Are you talknig about loading a Texture that is already in your project?

native lintel
#

yeah

upbeat path
#

then your Texture needs to be in a folder called Resources and you can use Resources.Load

native lintel
#

o

#

alr i'll try that

#

Bruh, i've been stuck on this all day. But it works, thank you!

agile spoke
#

How would you get the height of an object on a terrain?

For example I can get the coordinates of an object and then get the height of the terrain at that position, but the object has a different height in that position and I want to change the position of the heightmap at those coordinates to the position of the object.

terrain.SampleHeight(position); // More or less the same thing but it takes in a vector ```

These are the two functions being used currently Is there another way to do this without raycasting and getting the distance between object and terrain?
dusty wigeon
agile spoke
#

@dusty wigeon It gives the the height from the heightmap where the object is at, but it is referencing the height of the terrain and not the height of the object. For example terrain is 10meters at that location, the object is at 15 meters height, it gives me 10 meters and not the height of the object which is 15.

dusty wigeon
agile spoke
#

let me check...

#

also by the way, the height map is in normalized form so a double/float value between 0.000000001 to .99999999999.

I mention that because I would need to do a conversion there too.

dusty wigeon
agile spoke
#

I created a similar function for something else a while back and was hoping I didnt have to do that. You might be right though as the only course of action

dusty wigeon
#

I am not sure what you do not understand or expecting. This is pretty elementary. Maybe you should to ask in #archived-code-general

agile spoke
#

it doesnt seem that simple to me... as all other solutions that I've found refer to using a raycast downwards from the object to the terrain to get the distance and offset that way - this is simple. An advanced form of code would be the one we are discussing...

dusty wigeon
#

You want to use raycast if you dealing with more than a terrain

#

If you do not care about the actual height, but the height relative to the terrain, this is as simple as getting the height relative to ANY object/point.

agile spoke
#

I think I see what you are talking about the simplistic side of scaling/converting etc. I should have mentioned that I have a complex system that creates meshes and terrains and I was looking for a simple solution similar to the Transform.InverseTransformVector/InverseTransformPoint. I figured it would have been something unity would have integrated specifically within terrain functionality ***edit *** that gives your height relative to heightmaps

dusty wigeon
agile spoke
#

huh?

dusty wigeon
#

(transform.position.y - terrain.transform.position.y)

#

If you want the non normalize height, it is (probably) as simple as Terrain.SampleHeight(position).y * TerrainData.heightmapScale.y (if this is really normalized)

agile spoke
fickle zodiac
#

hey I just did an internal release and two of my testers got this:

regal olive
#

How would one get the PhysicsShape2D of a tile

sweet niche
#

wait mb idk why i come into this chat for the firs ttime and thats right ast the top

ashen hill
surreal juniper
#

In [UnityTest] it is said that "yield return null" skips one frame. However this is not what I'm seeing (in 2023.1 beta). I have a simple test:

        {
            int yieldCount = 0;
            var renderedFrameCount = Time.renderedFrameCount;
            var currentFrameCount = Time.frameCount;
            while (currentFrameCount == Time.frameCount)
            {
                yieldCount++;
                yield return null;
            }

            Debug.Log($"Wait 1 frameCount required {yieldCount} yields " +
                      $"over {Time.renderedFrameCount - renderedFrameCount} frames");
        }```
And it logs this:
```Wait 1 frameCount required 360 yields over 1 frames```
#

Is this expected or a bug or an issue on my part?

#

I read this as: it takes 360 yields to advance both Time.frameCount AND Time.renderedFrameCount by one.

#

The number of yields varies, and they are extremely high if I do the same in a IEditModeTestYieldInstruction class in the Perform() method.

#

I have a hunch that this is only true in PlayMode whereas in EditMode tests the frame updates are slowed down a lot. Although I did set the editor to "No Throttling".

bleak citrus
#

wrong venue. !collab

thorn flintBOT
manic shoal
bleak citrus
#

I do not care. This server is not the appropriate venue -- especially not this channel, which is for asking about advanced programming in Unity.

visual spruce
#

Please, someone help me with this. I couldn't find the solution anywhere:
Trying to remove Hours (TMPro.TextMeshProUGUI) from rebuild list while we are already inside a rebuild loop. This is not supported.
Here's the piece of code it points to:

    {
        daysActive[child_index] = !daysActive[child_index];
        GameObject child = allDaysContainer.transform.GetChild(child_index).gameObject;
        GameObject child_text = child.transform.Find("Text (TMP)").gameObject;
        child_text.GetComponent<TextMeshProUGUI>().color = daysActive[child_index] ? new Color(0.87059f, 0.31765f, 0.39216f) : Color.white;

        GameObject child_time = child.transform.Find("Time").gameObject;
        child_time.SetActive(daysActive[child_index]);
    }```
patent bear
#

Hi! Is there a way to built in/simple way to remove unused serialized fields from a material?

#

The single thread I found states that these are stripped before the dependency walk but I haven't dug in to confirm that one way or the other, yet.

pale coral
#

Hello, maybe it's not the exact place to ask, but I'm looking for a system to be able to destroy a map.

In short, my goal is to reproduce a game you need to kill your opponent, imagine a Worms 3D like.

I want to have the freedom of making all the map/elements from blender or anything, low poly accepted.

For now I tested solution like voxel/marching cube one, it works for generation but not for using existing map without converting it.
So I found a "better" solution using and modifying an open source lib to cut mesh, I made a quick proto with it and the result is cool for testing the system but in the current stats, it's cutting a lot of objects an creating a lot of vertx/tri so from a simple test the fps will drops, a full game using this is not possible.

Probably cause of all objects getting rendered... so I'm trying to find a good solution to create a simple map and be able to destroy it on explosion in an efficient way to be sure we don't duplicate objects or vertices/tri.

I would like to know if there's other technique to do thats? Actually I'm trying the mesh deformation which is a way to simulate a mesh damage but still hard to handle the moment you remove the vertices or re-pos the triangles with a ton of edges cases.

Any help would be appreciate!

dapper cave
#

Trying to iron out this hiccup, wondering if there is a better way to wait for Async GPU readback:

sage radish
dapper cave
floral sphinx
#

how would i check if the opponent is able to capture my king in a chess game without causing a stack overflow

#

ive tried so many times and every time theres a stack overflow

#

i think its because im checking the opponents legal moves in the same function that im using to check my own legal moves so its like overlapping or something

#

but idk

dire viper
dusty wigeon
#

Are you using recursion ?

floral sphinx
#

i think so

#

but i cant figure out how to do it without

dusty wigeon
#

You do not need recursion for 1 move.

dire viper
#

Well the easiest way but kinda dirty would be to take your king position and check in direction if there is some enemies

#

For example if you have a rook on the line/column

dusty wigeon
#

And trying to find all the possible combination of all action is impossible to hold in memory.

floral sphinx
dire viper
#

Pawn in diagonal

#

It's not really clean because it's code related only for the king so like an exception in your code

#

But in this way you are sure you are handling the win/lose condition in another function

#

That you could test/debug easily

floral sphinx
#

i dont have a win lose condition yet

#

i think that comes after making checks and stuff

sage radish
floral sphinx
#

i might just handle checks in a completely separate script and see how that does

dire viper
#

It's just an idea but with a 8x8 chess it's not really heavy to calculate the possible cases

dire viper
#

Just to be careful to not look for cases hidden by your piece

#

or you will loose at the first turn 😄

dapper cave
dire viper
#

Btw do you know why this issue is occuring ? The linerenderer is glitching when I am changing direction. Is it a known issue ?

sage radish
timber flame
#

I have combined same voxels (faces) using greedy mesh algorithm to generate optimized meshes for chunks in my voxel game. Now, I want to be able to control the height of each voxel. In some situations, The height of a voxel (voxels have height 1 generally) can decrease until height = 0, then it should be removed.
My problem is that because I have used greedy mesh to combine faces, it is possible some voxels have been combined and so there is just one face (2 triangles + 4 vertices for each face), I cannot change the height of a specific voxel.
The only way is to regenerate that chunk again.
I think I should forget the greedy mesh combination algorithm and use a simple combination (Just remove hidden faces). What is your suggestion?

sand wraith
#

Hi,
I am trying to write a function which will take a vector3 lets say(20,30,40) and return a unit vector which I can use to align a gameobject such that its rotated 20degree in x , 30 in y and 40 in z. In following code, its working fine in x and y axis, but giving 0 in z

    Vector3 angle;
    public void UpdateAngle()
    {
        Vector3 newOrientation = Vector3.zero;
        newOrientation.y = -Mathf.Sin((angle.x * Mathf.PI) / 180);
        newOrientation.x = Mathf.Cos((angle.x * Mathf.PI) / 180)* Mathf.Sin((angle.y * Mathf.PI) / 180);
        newOrientation.z = Mathf.Cos((angle.x * Mathf.PI) / 180) * Mathf.Cos((angle.y * Mathf.PI) / 180);
        Debug.Log(newOrientation);
        newOrientation.Normalize();
        gameObject.transform.forward = newOrientation;
    }```
urban warren
sand wraith
severe topaz
#

@sand wraith if you look at operator for setting transform.forward in source, it's using quaternion math behind the scenes anyway
so, you may aswell just cut the redundant steps and learn how to use quaternions <_<

light falcon
#

is there a way to have different inspector icons for each copy of a scriptable object? I'd like to have my game items' images as icons on the scriptable objects

#

SetIconForObject changes the icon to the same image for every instance

silver lark
#

Does anyone know of any resources on how to use GPU instancing with SRP?

Thanks in advance guys

bold shuttle
#

Hey, what could be causing my OnTriggerEnter2D function to be called twice?

public void OnTriggerEnter2D(Collider2D other)
    {
        if (other.GetComponent<GroundMoney>() != null)
        {
            this.GetComponent<PlayerMoney>().AddMoney(other.GetComponent<GroundMoney>().MoneyAmount);
            Destroy(other.gameObject);
        }
    }

Sometimes this gets called twice on one item.
The money collider is a trigger and the other is not. What could i be doing wrong?

untold moth
#

Debug the current and other object/collider to be sure what is colliding.

bold shuttle
#

yeah i did and the collision happens 2 times within one frame

#

On one object

#

Which is extremely weird

bold shuttle
untold moth
sage radish
silver lark
#

@sage radish Okay, but let's say I use DrawMeshInstanced? That works the exact same way if you disable to srp batcher?

sage radish
silver lark
#

Why doesnt it matter? Because it just works? or what do you mean?

bold shuttle
#

Is there a way i can debug it better?

#

To see what is causing it?

untold moth
#

Share the exact code...

#

Honestly, this is not the channel where we should be teaching you how to debug...

sage radish
light falcon
regal lava
#

That actually sounds like a pretty neat idea which I'll probably look into in the future

whole quest
#

hey guys i am trying to da match 3 blast game like toon blast. I cant write the filling tiles algorithym. Does anyone know how to do it ?

regal olive
#

Are there common standards for MVP UI in the industry? In particular, related to screen transition handling? What is the expected approach when a company wants MVP knowledge? A giant state machine for all UI? A bunch of navigation controllers whose sole job is to call .Show() and .Hide() on presenters or maybe views themselves(in which case views would create required presenters)?

dusty wigeon
regal olive
#

But there are standards in the Android and iOS community aren't there 🤔

dusty wigeon
#

Yes, for application. Not for game.

#

That being said, you can still try to apply those standard to your game.

#

But, a lot of them does not make any sense.

regal olive
#

The problem is my brain melts when trying to read Android/UIKit code cause they got a shitton of concepts on top like activities, fragments and a whole bunch more 😄

dusty wigeon
#

By example, Android use MVVM principally

#

Not really an approach that is good for video game.

#

As you do not have a lot of input to make.

regal olive
#

Hmm. Alright then, if we are talking theory wise, does .Show/.Hide API belong in the view(in which case the view will create and activate the presenter when instantiated) or in the presenter(in which case the presenter would forward the calls to view's own Show/Hide API)?

#

Is this a difference that could melt my lead's brain if I were to enter an MVP project and make the choice they didn't prefer?

#

Cause I'm stuck doing mobile game contracts(where they like overengineering) and so I'm trying to figure out the desired way.

dusty wigeon
#

If you are following wikipedia, it seem the implementation differ a lot. You can probably find both implementation.

scenic forge
#

MVVM and MVP are both kind of old fashion.

regal olive
scenic forge
#

Component based, where each component is individually a perfect encapsulation of MVVM.

dusty wigeon
#

MVVM implies that you bind on individual field. That would require a considerable amount of boilerplate code or the usage of library.

Also, I do no consider MVVM a good approach in most video game as it adds a lot of overhead and is most of the time unnecessary as there is little to no input field removing the need of double way binding.

scenic forge
#

Not sure if you have experience with web frontend, each component drives its own behavior and your app is a tree of components interact with each other without a central brain, per se.

dusty wigeon
#

Also, in opposition to more classical way of doing UI where you have a far amount of UnitTest, in video game there is little to no UnitTest which makes it acceptable to have approach such as MVC.

dusty wigeon
scenic forge
#

The boilerplatey ness of MVVM is indeed very unfun, in C# MVVM frameworks there are source generators dedicated to help with that issue.

dusty wigeon
scenic forge
#

Well it’s completely dead in web frontend, no one writes MVVM there already.

dusty wigeon
#

I see.

#

Then what are you suggesting ?

scenic forge
#

Component based like how web frontend frameworks do it

regal olive
#

I've used a Unity library for reflection based MVVM binding, not knowing you didn't bind properties correctly until runtime errors start flooding the console is not fun.

scenic forge
#

This is under the assumption that you actually do need an architecture for your UI, most games have simple enough UI that you can do it quick and dirty.

plucky laurel
#

you can strike a balance

regal olive
plucky laurel
#

pick and chose concepts and use sufficiently simple and robust mix

scenic forge
#

Again, only if you need an architecture; my game’s UI complexity is basically to the level of most frontend apps, with 50+ components and 100+ screens for users to navigate around, this is the point where an architecture is absolutely needed to make sure you don’t start cooking pasta.

#

For most games that’s not the case.

regal olive
#

Or would widgets be attached to some sort of Screen concept and that Screen would be managed by something else (when it comes to transitions between screens)?

tired creek
#

do these two influence layout of Vector3 in memory?

#

I added them to my C++ dll Vector3 equivalent but that broke the program 🤔

scenic forge
regal olive
#

And the parent would bind the bars to a value?

scenic forge
#

Yeah, it would be something like new Bar().Value(player.HP).MaxValue(player.MaxHP)

#

Everything (that needs to be reactive) in the game builds upon reactive primitives, so that’s all the code needed, when player HP updates, the UI automatically updates.

#

You don’t need to remember to “hook up a player HP change event and update the UI” and you won’t have issues with “when HP bar UI is destroyed I forgot to remove that event and caused a NRE”

regal olive
#

Hmm. I found animated events hard to deal with with reactive UI in the past.

#

Cause sometimes I needed to instantly reset something and skip the animation.

scenic forge
#

For mine I just have a Tween() method, which takes in a reactive value and produces another reactive value with tweeting applied.

regal olive
#

I mean like a UI panel appearing.

plucky laurel
scenic forge
# regal olive I mean like a UI panel appearing.

You can build that with tween too, let’s say you have a button that toggles variable isHPBarVisible, to give it alpha transition the code would look something like:

var hpBarAlpha = isHPBarVisible.Computed(x => x ? 1f : 0f);
var tweenedHPBarAlpha = Tween(hpBarAlpha);

(Normally I would just write the above in one line, but split into two here to make it easier to understand)
And simply bind that to the HP bar:

new Bar().Value(player.HP).MaxValue(player.MaxHP).Alpha(tweenedHPBarAlpha)

And that’s it, a togglable player HP bar with alpha transition when you toggle it on/off.

regal olive
#

I see. Now I understand your approach better. Though it doesn't seem like something I should bring into client projects due to being overkill.

scenic forge
#

The important thing here is that the UI code is declarative (I declare that HP bar’s alpha is derived from visibility variable in this way), rather than imperative (when visibility variable changes, execute this code that plays a fading animation), it is very important for complex UI to be written declaratively for it to be scalable.

scenic forge
regal olive
#

So I guess simplifying your approach would be simply smashing presenters and views into a singular widget.

#

@scenic forge wait, does your framework do explicit navigation from screen to screen? Or do you only have isolated screens that show and hide themselves?

scenic forge
#

Yes it’s like a whole browser, different buttons lead to different screens, and there’s even a history list.

#

Root component of the game is a Router, each Route can simply call Router.Push(new SomeDifferentRoute()) to navigate away.

#

The implementation of Router.Push is very simple too: do the tweening like above for the exiting route, then do the tweening again for the entering route, and there’s your transition animation.

scenic forge
#

It’s like the content of a webpage.

#

Title screen is a route, settings screen is a route; clicking the “settings” button in title screen is just navigating to the settings screen route.

regal olive
plucky laurel
#

is it like mainmenu.settings.audio ?

#

so you can set the state by a path string if needed

scenic forge
#

When you change the URL to something else, router detects it and updates the displaying route according to it.

regal olive
#

yo can anyone help me with this - I followed a guide on URP outlines using shadergraph, I downloaded the files from online and got it all to work however when I build the game and play it (it works in the editor though) it comes back with an error "ArgumentNullException: Value cannot be null.
Parameter name: shader" so the script that creates the effect uses the path (Hidden/"nameOfTheShaders") however Im guessing in the built version of the game it cant find this directory? I have tried changing the path in the code but it just causes even more errors.

fresh salmon
regal olive
#

thx man will try that now

#

thanks a load bro it worked

light copper
#

(Please forgive me if this is the wrong channel) I'm relatively new to writing shaders and especially with a local to world matrix, but here is the issue at hand:
I have a matrix4x4 in my shader and apply it directly the unity_ObjectToWorld. But I also want to apply a small local offset stored in a float2. Does anyone know what the best way is to approach this issue?

Update: I have the following code in Unity with Mathematics

        private void OnDrawGizmos()
        {
            float4x4 ogMatrix = transform.localToWorldMatrix;
            float3   ogPivot  = math2D.float3(_pivot);

            Gizmos.color = Color.green;
            float4x4 matrix      = ogMatrix;
            float4   transformed = mul(matrix, -float4(ogPivot.x, ogPivot.y, 0, 0));
            matrix.c3 += float4(transformed.x, transformed.y, 0, matrix.c3.w);
            Gizmos.DrawSphere(matrix.c3.xyz, .1f);

            Gizmos.matrix = ogMatrix;
            Gizmos.color = Color.yellow;
            Gizmos.DrawWireSphere(-ogPivot, .2f);
            Gizmos.matrix = float4x4.zero;
        }

This pits a gizmos marker to the position of where I want it to render from, but it doesn't translate into the shader well, since mul(float4x4, float4) returns a float4 instead of float4x4 in Mathematics, does anyone know an fix for that? I have been experimenting with setting the positions manually but with no luck.

timber flame
#

Hello, Which one is faster?
Calling RecalculateNormals method or calculate normals for each voxel?

worthy lodge
#

I made a guide on how to use Jobs + Burst in Unity. Does someone have the time to quickly look over it before I publish it?

timber flame
timber flame
worthy lodge
#

For the chunk regen, maybe have an if else in the job.
If a distance to the player (or other pos) is greater then a treshhold, simply take the old vertex pos. For anything closeby recalculate.

For the normals, if you calculate the jobs in the background and get the data ij late update, the main thread might not even stall, making that a ton faster than recalculate normals

timber flame
#

Yes

#

I just regenerate visible chunks

#

But because the number of workers can be large, it can take time.
Yes, all jobs are executed in job threads without freezing the main thread

burnt egret
#

is it possible for unity to take a screenshot when running it in headless mode?

#

im trying to do that right now and it doesnt seem to be doing anything

plush hare
#

@burnt egretafaik all of the render stuff gets wiped out when you compile headless builds

#

doesn't mean it's not possible. Just probably going to be a huge pain in the ass

burnt egret
#

that makes sense

#

ty!

plush hare
#

@burnt egretDepends what you're doing, but you could always have the server pack up data about the current scene

#

then it gets sent to a client

#

and client renders it

#

whether it's mobile, web, etc it should work

burnt egret
#

im trying to do some automation, i was thinking of trying to make a github action that would automatically screenshot of the scene and then add it to a PR as a comment

twin belfry
#

Alright now I know this is a shot in the dark, but i desperately need help. I'm running a playtest for my game and the release is in a week. There is a massive issue though. When you first start up the game for the very first time ever, it freezez or maybe its just taking forever to load? Then upon restart the game works fine. I have no idea if this is maybe some poor coding ive implement or something with maybe the build settings or assets having to load but this is obviously a terrible issue but im not sure where to start... (really no idea what channel to put this in so sorry!) Please help me save my game!

plush hare
#

it will tell you what's hogging resources

untold moth
novel hull
#

No idea where to ask this but I have been researching the A* algorithm for AI pathfinding for a game I am planning to make and I am stuck on what would be the best heuristic to use for finding a path through mazes that can be any shape including but not limited to squares, circles, triangles and Hexagonal shapes? If there are any resources I can look at please let me know. This is a game for mobile.

tall ferry
#

I imagine 0 or just the distance in a straight line from point to point should suffice

#

Does your maze have many solutions? Its been awhile since Ive looked into these things but i feel A* wouldn't be the optimal choice for performance

hollow sedge
#

hi guys can someone help me with the udp connection thing im stuck with please?
I'm trying to receive a message from arduino through ethernet udp but I can't seem to receive any message in unity, when I test it with sockettest it works. this is my code in unity :
https://paste.ofcode.org/fvvhrk6r6LsrfQZAgr5mrf

novel hull
tall ferry
#

Yea I didnt suggest Manhattan because you said circle, although I dont know how your maze works. Like if the inner walls are curved, then Manhattan will overestimate.
How would euclidean distance overestimate though? It is a straight line, how would you have a path that's faster than a straight line

novel hull
#

If Euclidean distance is a straight line would it not interfere with winding paths?

tall ferry
#

I'm unsure what you mean by winding paths, but this is just for your heuristic. You can literally plug in all 0s and it will run

#

It just wont be good obviously if it's a bad estimation

novel hull
#

It is the best solution I have so far as considering maze algorithms with multiple solutions and shapes.

tall ferry
#

You mean using 0?

#

Still I dont understand what winding paths means in this case. Heuristics are supposed to be an underestimation of the cost to get there. It's not the actual path it will try to take

novel hull
# tall ferry Still I dont understand what winding paths means in this case. Heuristics are su...

Sorry, let me rephrase a straight line through a set of paths that do not follow a straight line. The purpose of the Heuristics I understand. It is using the best estimation for approximating the cost and therefor distance to the goal using the shortest path, taking into account for a variety of different shaped mazes and multiple solutions that I am trying to determine while keeping it performant for mobile as I need to run Least Cost Routing on top of the pathfinding for another system in the game as well. Important note I am still researching. All other test I have done with online simulations.

tall ferry
# novel hull Sorry, let me rephrase a straight line through a set of paths that do not follo...

Having the euclidean distance wont interfere with winding paths, itll just set a slightly better estimation than all 0s.
The only better estimations that could exist would be if you solved part of the maze or knew more about the domain possibly and how it spawned. Like if you took how it spawned and could deduce that everytime, it would be at least X cost to get from start to end

#

The straight line isnt about having your AI take that straight line as a path, it's simply just getting the distance from start to end

novel hull
tiny pewter
#

i am looking for the best data structure for "visited" in grid-based a* path finding
for each cell in grid, it need three data: distance from source and parent cell (coordinate) and estimation. The "data structure" should provide a O(1) coordinate to values access
the most simple solution (and widely used) is a 2d (or 1-d flatten array) that same size as grid but it need (12+4)*(number of node) memory (there should be 4 padding byte but i am not sure) assuming the coordinate are two short, estimation and distance from source are float
another solution is Dictionary which may have smaller memory consumption depend on search space (O(2**search space*) memory ) but the access time will slightly slower than 2-d array.....
i want to run k pathfinding parallelly and that means i need k such data structure....

compact ingot
#

a 2D array is not particularly efficient btw, if you want speed you need to use a jagged or flat array

tiny pewter
#

i have test jagged and 2d array
for random access (random i j) 2d array is faster

#

idk why maybe for jagged access row i have to load the T[] first then column j in that T[]

#

i have searched how [,] represented in memory but i find nothing

#

and i think if i implement my custom hashtable it always run slower than built in library since i think they write it on c++

vale spindle
#

i want to make ai dodge projectiles, meaning move away. an example of how i would want it to work: probably a projectile will have some kind of over time check that predicts list of potential targets, and when it finds any it gives them info. For a slow linear projectile that would be line and velocity, and then the unit would have to stay away from that line. then unit calculates all dodge options, in this case moving away in all directions, and ranks them based on how optimal they are. it either chooses the best or doesnt dodge at all based on that. I want to go even more complex but i'm already digging my grave with my ai aspirations. want to hear some thoughts on this

tiny pewter
#

it sound a deterministic algorithm rather than ai

orchid lichen
#

hey i'm tryna make a shader that gets its variables from objects instead of materials, since these values are gonna be unique for each object and i don't feel like having 1000 df materials in my repository, here's a shitty drawing to explain what i'm tryna do lol. please lmk if u know a solution i'm at a loss idk what to google even
the only solution that comes to my mind'd be writing my own renderer but there's gotta be an easier way to do it

orchid lichen
untold moth
orchid lichen
untold moth
orchid lichen
#

oh really

#

aight thanks i'll look into that

scenic forge
#

You can also pass them via vertex data.

vale spindle
tiny pewter
#

your algorithm will calculate cost for all dodge options in all direction and choose the optimal one, i think it actually backtracking

light copper
misty glade
#

Why is this suggested?

#

UNT0024 didn't google properly

#

Oh, nevermind, I see now. One integer multiply + one vector multiply versus two vector multiplies

orchid lichen
#

the approach @untold moth gave me doesn't really work for me cus i'd want them to be editable while not in play mode

#

it causes some weird leak when i run it in edit mode and all sprites get fucked up

light copper
tropic stag
#

I swear I tested this a million times, this code works as expected in one scene, but in another scene only works if it's in the beginning of the Update(), and if it's at the end of update() it's like it's stripped by the compiler or something:

            if (!( isDropping || isRotating)) {
                isSpawning = false;
            }
        }

all 3 isSomething vars are public booleans which I can see in the inspector. isDropping and isRotating are in the same update, and if the object rotates or moves to a given threshold those vars are set to false; then isspawning should get set to false once they both stop animating.

If I leave the above code at the end of update() I can see in the inspector that isSpawning is checked as True, while the other vars are false.

fresh salmon
#

Or a return; instruction was hit

tropic stag
#

I added the log with $"... {(( isDropping || isRotating))}" and it logs True as if one of the other vars were true, but at the same time I can see they changed to false and the logs I have in their respective if (isRotating and if (isDropping are not printing. It's like whatever fancy thing unity is doing with the serialized vars is going out of whack.

fresh salmon
#

So it's not getting "stripped out" by the compiler after all, it's just not entering the if statements

#

How can you see that they changed to false, by observing the Inspector? Know that it has a small but noticeable delay updating the visuals after code changed

tropic stag
# fresh salmon How can you see that they changed to false, by observing the Inspector? Know tha...

this is my full Update():


        if (isDropping) {
            transform.position = Vector3.SmoothDamp(transform.position, dropTarget, ref dropVelocity, dropTime);
            if (Math.Abs(transform.position.z - dropTarget.z) < 0.01f) {
                transform.position = dropTarget;
                isDropping = false;
                if (!isSpawning) {
                    EventBus.onPieceDropped.Invoke();
                }
            }
        }

        if (isRotating) {
            rotationBlend = Mathf.SmoothDamp(rotationBlend, 1.0f, ref blendVelocity, smoothRotationTime);
            if (rotationBlend < 0.99f) {
                transform.rotation = Quaternion.Slerp(rotationCached, rotationTarget, rotationBlend);
            } else {
                transform.rotation = rotationTarget;
                trueRotation = rotationTarget;
                isRotating = false;
                if (!isSpawning) {
                    EventBus.onMoveDone.Invoke();
                }
            }
        } else {
            if (rotationBlend > 0.99f) return;
            rotationBlend = Mathf.SmoothDamp(rotationBlend, 1.0f, ref blendVelocity, smoothRotationTime);
            if (rotationBlend < 0.99f) {
                transform.rotation = Quaternion.Slerp(rotationCached, rotationTarget, rotationBlend);
            } else {
                transform.rotation = rotationTarget;
                rotationBlend = 1f;
            }
        }

        if (isSpawning) {
            if (!( isDropping || isRotating)) {
                isSpawning = false;
                //EventBus.onNextPieceReady.Invoke(currentTemplate);
            }
        }```
#

So while the rotating and moving is happening, I can see all 3 checkboxes, after some time when the movement is done, the dropping and rotating are unchecked, and the "spawning" checkmark sits checked.

fresh salmon
#

So you need to set spawning to false when not rotating nor dropping, if I understand this correctly

tropic stag
#

yes

fresh salmon
#

Also you have a return; statement in if (isRotating). else

#

Yeah something's up with that return statement, seeing that right after this there's another if/else that checks for rotationBlend, it's very likely the else isn't getting executed here

tropic stag
#

😦 I am an idiot. @fresh salmon thankyou. I have no idea why the same code works "correctly" (doesn't hit that return somehow)

fresh salmon
#

You got lucky, the value was probably exactly equal to 0.99

#

Skipping the fist if statement (the return), failing the second if statement and landing in the else block

timber flame
#

Have you implemented or used runtime occlusion culling?
I want to use it in my voxel game.
My concern is about time order

misty glade
#

I'm trying to make my title screen have some drones that fly around gracefully.. I'm having some trouble coming up with a path that isn't so ... anxiety inducing. I'm currently trying a catmull spline with 2 waypoints with a start and finish on a bounding box that's offscreen. The video above has the rect mask disabled but .. as you can see it's a little wild.

Any suggestions?

Maybe a start and endpoint that are guaranteed on opposite sides of the box, and a single waypoint..?

tropic stag
misty glade
#

I shoulda been more clear - I'm only using DOTween DOPath() to animate it

#

I didn't wanna make it too complicated to use a bezier spline and figure out control points for each waypoint that were "gentle"

#

Bounding box with opposite sides and a single waypoint in the middle worked pretty well

tropic stag
misty glade
#

thanks 🙂 it's a little bit of vector gymnastics but it seems like fewer waypoints works better

scenic forge
ashen hill
#

I want to open a project built from Unity to PC with 2 arguments using cmd. Is there a way to do it?

abstract hill
#

Hi everyone, I sent this yesterday in the code-general chat but I think it got a bit lost in chat. Since no one replied I was wondering if I sent it in the wrong place so I'm resending it here, hope this is fine.
I'm working on a simple app that uses an Azure back end of which is connected to via the SQLConnection from System.Data.SqlClient. I've been working so far on PC and have everything more or less working, now I'm looking to build it for Android and IOS (though, specifically Android for now). That said I'm getting errors when trying to play it. From what I've read online already their could either be an issue with dll's or its impossible, two very different answers. That said, I did try the dll fix however Unity didn't seem to like this: https://answers.unity.com/questions/492821/sql-connection-doesnt-work-in-standalonebuild.html this is the link I'm referring to here.

I realised when following this link that the path is slightly different for me since this was uploaded in 2013, and I am now using 2022.2.19. Does anyone know of a more recent example of how to fix this that works for Unity 2022?
(If anyone could help with this, please reply or @ me so I can see the notification as the chat will most likely get busy)

gleaming rock
#

Is it possible to force animation's position changes immediately, within the same frame of when it was called instead of waiting 1 frame in between?

I have tried animator.Play(), crossFadeInFixedTime

and animator.Update() but none seem to give me the results I want

gleaming rock
#

Ahh Play and Update do the job actually. I was debugging and testing it wrong

unborn relic
#

Hello,

I am trying to add grass to my procedurally generated mesh at runtime.
My map is segmented into chunks, and when a new chunk is generated because a player is getting close, I want the grass to be generated via gpu instancing (about 1 mil prefabs). For the gpu instancing I am using this: https://assetstore.unity.com/packages/tools/utilities/gpu-instancer-117566. Unfortunately, passing 1 mil instances to the gpu in one go freezez my game for minutes, so I want to do it on a sepparate thread, in chunks of 1000 ish.

  1. I was trying to use the jobs system for this, but as far as I can tell the Job system is mostly for math computation, since I can't pass non blittable data, nor can I instance stuff from there. Am I right?
  2. Assuming 1 is true, I am stuck with C# multithreading, correct?
  3. Is there a better way to go about this all?

Thanks!

tiny pewter
#

i know nothing about generate mesh nor gpu instancing
but if you need to access both reference type object (if it is not Transform, there is IJobParallelForTransform but i never used it) and call unity api, then there should be no ways to multithreading

devout coyote
#

I'm sure that there's better ways to do grass than that

unborn relic
devout coyote
#

Haven't watched it but other people saying it's good

#

I wouldn't know if gpu instancing would really help here

#

But you could be trying to hammer a nail with a screwdriver right now

#

Okay so the GPU instancing page says that you don't want to do a lot of low vertex meshes (which is what you are doing right now really) but rather do 1 big combined mesh

devout coyote
#

You can also instance stuff from jobs, take a look at the boids sample

dusty wigeon
dusty wigeon
novel plinth
#

note for the latter, you will need to handle culling yourself

abstract hill
#

Could you elaborate further? Right now I am just using the namespace System.Data.SqlClient from what I believe is just in .Net 4x though I may be wrong. I did try dropping the files mentioned in the link into my project however that started throwing errors and then wouldn't let me build. Just repeated it now and got the error:

#

This is by moving the libraries into the Plugins folder of the project

#

Hmm, actually maybe not. I'm going to try a build restarting Unity with the dll already in the project doesn't give the error, I'll check this out

#

Actually no, still doesn't let me build

#

Sorry those errors where building still using Mono as the scripting back end, swapped it over to IL2CPP and still failing but with different errors this time.

#

Only one error and this was its contents

dusty wigeon
#

Trying to disable stripping seem to be a potential solution

abstract hill
#

Ah I'll have a look, thanks

dusty wigeon
#

Maybe changing the .Net profile could also be something to look into.

abstract hill
#

Still doesn't seem to work, though I'm not getting as many option on my editor as the people in the post are, so my guess is that something has changed in unity with the version I'm using. The two API levels I have are .Net Framework and .Net Standard 2.1, 2.1 doesnt seem to recognise the classes for SqlConnector or SqlClient so I'm guessing I have to use .Net Framework.

As for stripping, I have a toggle for stripping engine code and a drop down for stipping level, both are set to minimal / off. Build still seems to fail, That said it does sound like the stripping could be the cause, so I'm going to look into that for a bit, they mention in the post about doing custom XML files to force things to be built too so ill look into that also.

dusty wigeon
# abstract hill Still doesn't seem to work, though I'm not getting as many option on my editor a...
#

For mobile, it is also recommanded to use .Net Standard 2.1 over .Net Framework because of the resulting size.

#

It is also stated that some part of the .Net Framework may not be available on all platform while Unity has committed to support everything in .Net Standard 2.1.

abstract hill
#

Ah thanks, I did see people where suggesting a PHP kind of middle man approach but since I've never done PHP befoer I was looking into fi there where other options. If not then I guess I'll do that. Thank you for your help, I'll also look into using .Net Stadnard 2.1 instead too ^-^

unborn relic
novel plinth
#

then go nuts, and plant your virtual treeesss! 🫡

unborn relic
novel plinth
dusty wigeon
novel plinth
#

as for LODs, they're a bit different in instancedIndirect api

dusty wigeon
novel plinth
#

unlike conventional lods

unborn relic
#

okay thanks guys!

sage radish
novel plinth
#

He shouldn't concern with drawcalls, DrawMeshInstancedIndirect will always be 1 drawcall

compact ingot
# unborn relic Hello, I am trying to add grass to my procedurally generated mesh at runtime. ...

The central limitation to grass that is procedurally instanced on the gpu is creation of the dynamic meshes and sampling/calculations for stuff like surface alignment. You can jobify that or do parts of it via compute shader, the data upload can be time sliced if necessary and you can fit a lot into 10ms. The most effective thing you can do is reducing the number of world sample points you need to query/calculate on the cpu and consequently the instancing calculations

#

Once stuff is calculated you can easily render 1mil instances (with say 20 mil triangles) on a midrange gpu

novel plinth
#

rather than 20mil, which is a heck lot, just normal blend it with the ground and spread them not too close from each other, the normal blending would make your grass field filled with lots of grass tho it's not

#

GI and Zelda did this

#

it will give you an illussion that there are lots of grass.. but... it's not

compact ingot
#

usually you’d need way less than that indeed

#

Depends on how tall the grass can be though

#

for reference, zelda style grass with NR

novel plinth
#

so you won't see the ground texture

compact ingot
#

this is the prefab that gets instanced, and the shader adds some more skew based on the view normal

unborn relic
#

@compact ingot @novel plinth
The examples you guys provided look amazing, I hope to build exactly something like that, but before I get to shaders and alingment, I want to gradually build up to it by building something more and more performant. So at the moment I'm just instantiating 50k cubes with and without gpu isntancing, and for the life of me I don't see any difference in fps.

without gpu instancing: 500k verts, 30k batches, 70fps
with gpu instancing + occlusion culling + furstrum culling: 500k verts, 50 batches, 70 fps

both have saved by batching: 0

untold moth
#

As for the "saved by batching" stat, I think it's pretty buggy, especially with GPU instancing and/or on SRPs.

compact ingot
#

didn't they recommend looking at # of SetPass calls instead as a better indicator? Also looking at a static scene doesn't reveal much, performance often only drops when the camera/environment move relative to each other and culling/instancing have to be recalculated

#

in the screenshot posted above with the 900k instances peformance immediately drops to slide-show levels when the camera moves outside the loaded chunks and takes 1-5 sec to recover depending on the streaming budget, 90% of that the time is spent calculating the instance matrices.

hazy epoch
#

How does one go about "clearing" the display between scenes. The issue I'm having is that in our game's main menu scene the Camera's viewport is set to fill the screen. However, when we go into our actual game scene, the viewport is set to only be a certain portion of the screen. That leaves the last image from the last scene filling all other areas of the screen. How can I clear it, so those areas are just black?

severe topaz
#

While billboard grass is a performant, easy option for visualizing grass, modern games like Breath Of The Wild are able to utilize real geometry to get more interesting and appealing foliage. How can games nowadays afford to do so?

Support me on Patreon!
https://www.patreon.com/acerola_t

Twitter: https://twitter.com/Acerola_t
Twitch: https://w...

▶ Play video

In this video I go over the optimizations I made to the grass in the previous video to cover any size area while still being highly performant.

Support me on Patreon!
https://www.patreon.com/acerola_t

Twitter: https://twitter.com/Acerola_t
Twitch: https://www.twitch.tv/acerola_t
Discord: https://discord.gg/FxGQvbfm6Y
Code: https://github.com/G...

▶ Play video
severe topaz
unborn relic
unborn relic
#

when disabling that, 100k prefabs are barely noticable fps wise

severe topaz
#

empty grass fields look empty though

#

you may not really need it that big

unborn relic
#

i know, but im using it as a learning exercise

severe topaz
#

the best looking grass i've seen was always something on really small scale or really stylized and blending with ground

novel plinth
#

yes, blending the grass with the ground will make it look nice and you don't need bunch of grass to make it look dense

tiny pewter
#

i have a question on job system with unsafelist
when i assign the the unsafelist struct outside the struct (in the class) to the struct (job) ,will it copy all the properties?
if true, then when i resize the unsafelist then the Ptr will be realloc()ed and free()ed that means the address of Ptr inside the struct and address of Ptr outside the struct (in the data copy of that UnsafeList in the class, called classPtr) will be different and the address pointed by classPtr is not valid anymore.

struct MyJob:IJob{
    UnsafeList<int> x;
    void Execute(){
        x.Add(10);
        x.Add(10);//here the x got extended, will x.Ptr different from XX.Ptr?
    }
}
void Do(){
    UnsafeList<int> XX=new UnsafeList<int>(1,XXXXXXX);
    MyJob job=new MyJob(){x=XX,};
    job.Schedule();
    XX.Dispose();
}
untold moth
tiny pewter
#

the add() will automatically resize it
and i am curious if the list got resize in struct how about the address of XX.Ptr

untold moth
#

It will probably be fcked up.

long ivy
#

yes of course it will change

#

it's wrapping some internal stuff, so if you're asking how to get the pointer back out: don't cache it, it might change, access XX.Ptr after the job is finished. Your Do method looks very dangerous and crashy

dusty wigeon
unborn relic
unborn relic
dusty wigeon
unborn relic
#

although, grass is quite amazing

compact ingot
regal olive
#

Hey, would somebody mind helping me how to implement a small thing to my code?
I'm developing a voxel engine. Before going into any complicated meshing algorithms and database stories, I have a script that globally manages chunks. These are essentially cubic regions of the world that are loaded and unloaded with everything in them based on their distance to the player and other loaders.

Now, at a radius of 10 chunks, Unity needs to run a rather small amount of code for 1000 elements. Part of the code is a ComputeShader dispatch and retrieval of its information, which could explain why at 1000 elements it does lag down to ~20 FPS, although my rig is composed of an Intel i9 13900k and an RTX 4090.

For now, I don't wish to focus on optimising per-chunk code, but to keep this algorithm from slowing down the main thread and the FPS of the player. It is no issue at all if a chunk needs 100ms to complete, just that it doesn't slow down the main thread. So, I'm looking for a way to offload this algorithm to execute on another thread/CPU core so that it doesn't slow down the main Update() cycle and FPS of the game. How could I accomplish this?

velvet rock
#

So question. Is it worth performance wise to use Calculus over Algibra in programing?

sly grove
#

Incredibly vague question

dusty wigeon
velvet rock
#

Well for physics for example? Using derivatives/integrals to calculate forces?

sly grove
#

in what sense would you use derivatives or integrals to calculate forces?

dusty wigeon
sly grove
#

Unity uses a discrete timestep physics simulation.
If you're talking about writing your own "continuous" physics simulation using calculus, it will almost certainly be slow as hell

#

All of the computational methods to compute integrals for a general polynomial curve involve many iterations of adding smaller and smaller numbers.

#

to approximate the actual area under a curve

#

using Riemann's method for example

#

that's very computationally intensive

#

the discrete physics used by Unity is much simpler and dumber than that

tiny pewter
#

i guess directive of finding slope at x=x0 can be done in O(1) time by lim (h->0) f(x0+h)-f(x0)/h

velvet rock
#

Yeah that was what I was thinking. I was also thinking of using calculus on a server API to check players movement. And give predictive data. Though that gets a bit out of context for Unity.

#

Off load the work, though wouldn't be a every tik type of thing

dusty wigeon
velvet rock
#

Dysnc fixing, player ai predictive movement, cheat detection. stuff like that

dusty wigeon
dusty wigeon
sly grove
#

PhysX is pretty stupid. This is how it calculates object motion:

Vector3 currentPosition = rb.position;
Vector3 nextPosition = currentPosition + rb.velocity * Time.fixedDeltaTime;```
velvet rock
#

mmhhh, so step one is make a super computer that can run perfect physics. Step two make a game engine that can run perfect physics.

sly grove
#

(for a single physics frame)

dusty wigeon
unborn relic
#

Hello again,

I'm instancing about 1 mil prefabs using gpu isntancing in my scene.
If my camera is static everything is fine, I get about 300 fps. The problem is the following: In play mode, if I move, the game stutters a bit, every 2 seconds-ish. If I build my game the stutter is completely gone. I've profiled the playmode to see what was going on, and the hiccups are caused by "EditorLoop".

  1. How can I prevent this?
  2. Is it normal for games to be almost untestable / unrunnable in playmode? (I imagine that being the case for big games)
  3. Should I strive for my game to be runnable in game mode, or is it normal to accept that from a certain point you can't really test it well?

Thanks!

robust drift
#

I don't know the answer to your question, I'm just curious how you're using GPU instancing to instantiate prefabs, that sounds neat! 😮

#

I thought it only worked with meshes and simple primitive values

unborn relic
robust drift
#

Cool, thanks!

dusty wigeon
robust drift
#

Yeah, I saw that!

#

Just forgot to follow up on it

tall ferry
tall ferry
#

Yes, that's what causes my major lag spikes too when I had almost nothing in my game

#

Your editor is constantly allocating stuff for some reason, especially quickly when you have the stats tab open. With incremental on, the gc is used on smaller amounts but more times rather than once to deal with all the memory

#

Tabs other than stats will affect it but that's just the one I remember having a major affect

unborn relic
#

Thanks a lot, that was a very good tip. Don't know why I didn't turn it on sooner. In the meantime, after the post I made above, I turned on the profiler in the editor, and saw that my hiccups were caused by the netcode package.

#💻┃unity-talk message

#

which I am unsure how to fix

tall ferry
#

Im also not too sure, someone told me about incremental gc so that's pretty much all I know.
You can expand that hierarchy in the image though to try and see what exactly is causing the issue

#

For me when I expanded it, it would always lead to like GUI.repaint and at the end gc.something I forgot the name

unborn relic
#

it's that node, the children don't take up anything almost

unborn relic
#

how do I solve the folllowing problem:

  1. I'm using netcode for gameobjects, which subscribes to EditorApplication.hierarchyChanged, and in the method it uses Resources.FindObjectsOfTypeAll, which is super slow.
  2. in my scene, I have MANY objects (500k+; grass), making Resources.FindObjectsOfTypeAll calls super slow
  3. in my game, movement triggers sounds (steps, jumps, ambient etc), which changes the hierarchy, thus triggering the subscribed function above.
  4. since I have many many GO's, my play mode is unusable.

how do I fix this? thanks
potential solutions:
a. don't create sounds in play mode, thus not triggering hierarchy changes
b. remove the stupid method from netcode from gameobjects; don't know how to do it

PS: the problem is in: GameObjects/Editor/NetworkManagerHelper

novel plinth
#

they finally did it

#

About time we embrace coreClr 🥳

#

(from alpha 16 changelog)

craggy spear
#

So ~6 months away from release and ~12 months away from being in an LTS 😬

hushed fable
#

At least some part of the build system? 😛
I wouldn't immediately assume this applies to the player.

torpid birch
#

help me please

upbeat path
#

jfc, 23 alpha and they add .net 6 which is already depreciated

fresh salmon
#

Nah .NET6 is LTS, support ends somewhere in November 2024
But that only applies to a small part of Unity, porting the whole thing isn't done yet

#

Maybe .NET 8 or 9 will be out by the time it's fully ported

humble leaf
plucky laurel
upbeat path
fair plank
#

Hello, I'm trying to make a puzzle game of "Tents and Trees". What I want is to generate unique levels and store them as json files. I know how to store them as json but what I don't have knowledge on is generating the levels.
For people that don't know the game, the rules of Tents and Trees are: the play area is a grid and every row and column has a number assigned to it, which is the number of tents that you need to place. Every tent has to be adjacent to a tree and every tent cannot be next to another tent, both orthogonally and diagonally.

What I would like help with is how to write the ruleset in code and generate the unique levels. Thank you in advance for the help~!

dusty wigeon
#

At least, this is where I would start.

tiny pewter
#

I think this problem can speed up by dp

tiny pewter
#

If you want to use wfc to generate
The rules are:
The adjacent tile of Tree tile can be none or tent
One adjacent tile of tent must be tree and no other tents in 8 directions

#

And you will get tent number of each row (or column) after generation
But likely you cannot define it if you use wfc

fair plank
fair plank
tiny pewter
#

You can random place tree first and define tents to be placed in each row and column then use backtrack to check whether solution exists

#

Dynamic programming
And i review your question dp cannot be applied

fair plank
dusty wigeon
dusty wigeon
tiny pewter
#

yes ,you said each tent needed to be next to tree and no other tents in orthogonally and diagonally i,e (x+1,y) (x+1,y+1),(x+1,y-1)....

fair plank
#

Thank you both for your help, I'll look more into backtracking and try my way.

exotic sorrel
#

I think that WFC will give you solved puzzle and then just remove tents. I'm not familiar with this game so just guessing after seeing few images

dusty wigeon
hazy epoch
unborn relic
#

hello, with gpu instancing, if i want to generate batches of grass at runtime, do I need to resubmit the whole buffer every time a new batch needs to be added, or can I just submit the new batches?

novel plinth
#

your question a bit vague, there are couple of instancing in Unity

#

I assume what you want is the procedural one(instanced indirect)? if so, then you can generate as necessary

#

you don't need a to clear the previous ones if they're of off a different batches

#

pretty sure the asset you mentioned the other day already handle this under the hood, if not, ask your money back 😄

ionic pier
#

Hey
I want to use Version Defines and Define Constraints with actual dlls, not Assembly Definitions. dlls do have Constraints but I can't see Version Defines

hazy epoch
#

Uhm, rendering is not a beginner problem. I don't think you have a clue about anything based on these two replies, and seeing some of the other stuff you've said to other people. 🙄

dusty wigeon
# ionic pier Hey I want to use Version Defines and Define Constraints with actual dlls, not A...

Dll does not have the notion of Version (In Unity) ? At least, not from what I know. You could try to combine assembly definition with DLL ? Alternatively, you could also make a package with your DLL. I have never setup assembly definition myself, take what I say carefully.

Maybe this can help:
https://docs.unity3d.com/Manual/PluginInspector.html#:~:text=General - Auto Reference
https://docs.unity3d.com/Manual/class-AssemblyDefinitionImporter.html#general:~:text=compiles the assembly.-,Auto Referenced,-Specify whether the
https://learn.unity.com/tutorial/working-with-assembly-definitions#

upbeat path
ionic pier
dusty wigeon
torpid birch
#

hello i need help in coding

obtuse remnant
remote drift
#

I want to use UniTask to create async method, but I want to run it similiar to coroutine, but attached not to game object, but manual iteration instead.
IEnumerator doesn't have much.
So... to mimic coroutine behaviour, do I just MoveNext until it's false?

#

wait

#

bruh, looks like it's not actually running task this way, but instead just checks whether it's ready. Sad

flint sage
#

Just call move next?

remote drift
#

which is triggered via try{} finally{compelted=true;}

#

so that's fake coroutine really

obsidian glade
#

what behaviour are you looking for?

remote drift
#

task creating via await/async syntax but run directly by calling MoveNext

#

instead of UniTask/.Net loop

scenic forge
#

That sounds like your are describing an enumerator.

#

What are you awaiting inside of it?

remote drift
#

netcode stuff

scenic forge
#

Well UniTask has UniTaskCompletionSource, you can create a task out of it which you can await, and MoveNext would be just setting that source to completion.

#

Odd design though, sounds like a potential XY problem.

remote drift
# scenic forge Odd design though, sounds like a potential XY problem.

This is netcode for entities and I want to make some proper handling for disconnections and other problems during game loading without a need to dispose server world (which at the same time will disconnect all connections). And without disposing world it'll be just a very painful management of every state component, which I kind of want to avoid atm

scenic forge
#

In that case I don't know enough to comment, but yeah UTCS should get you what you want.

remote drift
scenic forge
#

Create a UTCS:

var utcs = new UniTaskCompletionSource();
var waitForNext = utcs.Task;

Then you simply pass waitForNext in some way to your async code:

await NetcodeStuffs();

Debug.Log("Execution will hang at this point until next signal is given");
await waitForNext;

await DoMoreWork();

To signal:

utcs.TrySetResult();
remote drift
#

nah, that's not what I want.
I want to run task myself, so no automatic loop is run. So it's tied specifically to ECS system's state (it's update function)
But figures it's not something that is trivially available

scenic forge
#

That waitForNext is the equivalent of MoveNext

remote drift
#

but it's still run on loop

scenic forge
#

On loop?

remote drift
#

UniTask loop

scenic forge
#

I have no idea what you want then, if you want to execute a state machine step by step with full control, that's just an enumerator.

remote drift
#

what I'd want is:

var task = LoadAsync();
on init and then:
OnUpdate()
task.MoveNext();

scenic forge
#

Which is just an enumerator.

remote drift
#

yes

#

and I simply want async/await syntax with it

scenic forge
#

But why? What's the difference between:

IEnumerator Foo()
{
    DoSomeWork();
    yield return null;
    DoMoreWork();
    yield return null;
}

vs:

async void Foo()
{
    DoSomeWork();
    await waitForNext;
    DoMoreWork();
    await waitForNext;
}
remote drift
#

🤔

#

maybe you're right

#

I didn't realize I don't really need await for some reason

#

so what I really need i just

#

call Foo() and then MoveNext while it's true?

#

by while I mean non-blocking callback

#

once per frame

scenic forge
#

Sure, whenever you want to move next is entirely up to you.

remote drift
#

huh, didn't realize that implementation is that simple

#

I hope it's alloc free?

scenic forge
#

Enumerators are what powers foreach in C# and coroutines in Unity.

remote drift
#

wait a second

#

is there a way to implement it without interface?

#

so execution cycle is fully unmanaged

#

so it can be burst compatible

#

🤔

scenic forge
#

Not sure why interface has anything to do with it, you can foreach native arrays just fine.

remote drift
#

no, I mean

#

I want to implement such state machine

#

while keeping it burst compatible/unmanaged

#

so it's not called via interface

#

but via direct struct type

scenic forge
#

Interface has nothing to do with whether something is Burst compatible or not.

#

Native arrays implement plenty of interfaces and they are Burst compatible.

remote drift
#

that's not what I meant

#

they are burst compatible because you use them via NativeArray<myType> instead of IEnumerable<myType>, where latter is boxed and managed (not-burst compatible)

#

I'm not really familiar with how enumerators are implemented (especially such complex ones)

scenic forge
#

The problem isn't the interface, but the fact that it desugars to a class, not a struct.

remote drift
#

because what I need is for compiler to generate everything unmanaged

#

so declaration of enumerator is struct and all fields are unmanaged

#

is that even doable?

scenic forge
#

I mean nothing says you must use the syntax sugar, you can implement your own IEnumerator<T> as an unmanaged struct.

remote drift
#

yes, but I want sugar 😅

scenic forge
#

Too bad, they are bad for your teeth.

#

You can try implementing your own async/await like how UniTask does it, but not sure how Burst compatible that is.

remote drift
#

🤔

#

so I guess IEnumerator won't be burst compatible

#

I mean

#

unless I manually implement struct with this interface

#

and do async stuff manually without sugar

#

in MoveNExt

#

yeah, I should look into own async/await implementation at some point

#

if it is possible to make compiler generate unmanaged code it would be extremely valuable

unborn relic
sage radish
remote drift
#

oof. I'm not mentally ready for il post processing

umbral trail
#

Do you just want a custom synchronization context that updates in your system?

brittle frigate
#

I need some help.

I want to save an item class as json. So the class is the configuration. This should be read later from the json.

But JsonUtility always saves me only

{
    "Items": [
        {
            "instanceID": 0
        }
    ]
}

My Item Class

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class Item : MonoBehaviour
{
    public string name;

    public string description;

    public bool grabable;

    public Transform Attachpoint;
}

And here is my editor class.

https://pastebin.com/MFiNnUnH

#

According to the debugger, the item array is also filled up until line 279.

umbral trail
#

what is JsonHelper?

brittle frigate
#
using System;
using UnityEditor;
using UnityEngine;

public static class JsonHelper
{
    public static T[] FromJson<T>(string json)
    {
        Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json);
        return wrapper.Items;
    }

    public static string ToJson<T>(T[] array)
    {
        Wrapper<T> wrapper = new Wrapper<T>();
        wrapper.Items = array;
        return JsonUtility.ToJson(wrapper);
    }

    public static string ToJson<T>(T[] array, bool prettyPrint)
    {
        Wrapper<T> wrapper = new Wrapper<T>();
        wrapper.Items = array;
        return JsonUtility.ToJson(wrapper, prettyPrint);
    }

    [Serializable]
    private class Wrapper<T>
    {
        public T[] Items;
    }
}

Because JsonUtility doesn't seem to handle arrays.
Was an attempt.

With the normal JsonUtility comes the same error

thin mesa
#

you're trying to serialize a MonoBehaviour

#

also you won't be able to serialize the Transform field to json either, you'd probably want to make that just a Vector3 if the purpose is to just represent the point where it attaches or whatever

viral sequoia
#

lmao yoy save serialize MonoBehaviour

brittle frigate
thin mesa
#

even if that does somehow work, the next line provides at least one reason why your current setup won't

brittle frigate
#

OK.
Then I have to rebuild the system.

umbral trail
#

is this for runtime or just editing?

brittle frigate
#

writing just in Editor Mode.
Read in Editor and Runtime

thin mesa
#

why not just use scriptableobjects?

umbral trail
#

yeah, you could save actual ScriptableObjects instead of writing to json

#

though I guess you could still load or create them from json too

brittle frigate
#

What is better with scriptable objects?

umbral trail
#

they will be saved as assets in your project and can be edited with the inspector directly

thin mesa
#

they will also be able to properly reference UnityEngine.Objects unlike json which would just serialize the instance ID

brittle frigate
#

Ok. I have no experience with that.
Then I have to see how to create SO from scripts and add this to Gameobjects.

tropic vigil
brittle frigate
#

Now I have the SO on the gameobject via a manager class. That is super so.

Can I also display the variables of the SO when I have selected the Gameobject?

tropic vigil
umbral trail
novel plinth
upbeat garden
#

Hi folks. Could use some help with this if anyone knows: Question: It looks like Unity automatically changes references to parent Objects in the MonoBehaviors of children when instantiating - to reference the new parent. That makes sense in most cases, but I have a case where I’d like Unity to keep the reference to the original parent object. Is there any way (like an attribute) to prevent this from happening for a specific object reference?

umbral trail
#

that would modify the prefab?

#

or are you trying to duplicate something in the scene?

upbeat garden
#

Trying to duplicate something in the scene.

#

Or copy and paste

#

I would also want the reference to stay the same when instantiating a prefab. I basically want to turn off the auto-updating behavior for one specific reference field

umbral trail
#

oh, you don't mean you want to keep the prefab as it's parent, it's some other field?

upbeat garden
#

I have a reference in a component to itself (don’t ask - I swear there is a good reason for this). When I copy and paste the object, this field is updated to the newly pasted copy of the original component. I want the field in the new pasted version to still reference the original component - no matter what.

tropic vigil
upbeat garden
#

Unity updates this field automatically, since it expects that I want to reference the newly pasted component. But in this case I don’t. Is there a way to turn this behavior off?

umbral trail
#

I feel like I have actually had this issue before, but the solution is probably to probably to change the structure. Afaik there's no way to change the behaviour (though you could just add a function to set it back after you instantiate)

upbeat garden
#

That’s a bummer, but thanks for the advice!

umbral trail
#

you could try something like making a prefab variant and setting that field to the base prefab, and see what it does

#

just don't edit the variant

tiny pewter
#

is unsafelist (or nativelist) suggested to use if i dont use the job system? will it perform worst than List<T> ?

dusty wigeon
#

(I do not know) You can still check yourself, it should not be long.

#

But, I would use the List in most case, just because it is probably better integrated.

spare tartan
#

does anyone know how to get the Avatar from the source asset without dragging in the reference manually? im trying to use GetAllAssetPaths but it appears AnimationClips and Avatars dont fall under a specific asset, they are nested but you cant get them using conventional getcomponentsinchildren

dusty wigeon
#

Performance, is not the only criteria when you develop.

spare tartan
#

@dusty wigeon perfect, thank you!

oak sleet
#

How do I reset mobile input touches to 0? I have a mobile snake game where a snake block is created according to the angle of the swipe the player makes. The game has a press to play/replay. The problem is that the touches from the press to start and press to restart interfere with the swipe motion of the snake. Is there any way to reset the input touches to 0?

https://paste.ofcode.org/XqUtawWZzmYUjwvvGk6TU8

fallow meadow
#

any ideas ?

thin mesa
#

are you missing an assembly reference?

fallow meadow
#

I added the using ucs; at the top

thin mesa
#

that's a using directive. are you missing an assembly reference

#

and have you actually installed whatever asset/package that namespace/assembly is contained in?

#

also another useful question: are the files you are editing your own files, or are they from some asset you've downloaded?

fallow meadow
#

oh true its assets i purchased from booth, i usually just drag n drop n not have problems with them

thin mesa
#

yeah in that case it's probably using assembly definitions, which means you'd have to add the assembly reference to its asmdef file

fallow meadow
#

Oh okay I appreciate you helping me im gonna go learn about adding assemblys im a scrub

regal olive
glossy lynx
#

For all advanced programmers

#

How did u learn unity ? WHERW

#

Where

#

I spent the last 2 month trying to find a way

#

Ping me

upbeat path
glossy lynx
upbeat path
#

!learn

thorn flintBOT
#

🧑‍🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

quartz copper
#

I am wanting to make a more complicated character controller, one which offers combat in air or the ground, basically you can do combat in other states, getting to the point I have made character controllers in the past using state machines, but I was wondering if there is a better structure to use for this idea, considering with a state machine, as far as I know, there is 2 options, one i build combat into each state, or 2 i layer another whole state machine onto the character to blend combat in. I have used the layer method before, but it gets messy having to go over every state 2 times +. If you have an idea @ me

placid ocean
#

Maybe this is a better place to post rather than general.

Haven't worked on a Unity engine specific project peofessionaly. But what do larger games usually end up using for managing/referencing important objects/services. Does it usually end up being something like a service locator pattern or DI pattern?

long ivy
#

my experience is spaghetti singleton mess so far

#

I pull the codebase a step towards service locator very time I get a chance to refactor some stuff, but mostly the company is concerned with making stuff fast and not good code practices

placid ocean
#

That sounds about right then 😅

long ivy
#

service locator is kind of an antipattern in my mind too, but it's better than singletons everywhere with if statements checking the game's bundle id and then doing game-specific logic for code shared among multiple games. It was really ugly when I got here, and extremely easy to break stuff. Now it's just pretty easy to break stuff

compact ingot
# placid ocean Maybe this is a better place to post rather than general. Haven't worked on a U...

it depends what kind of code it is, for tools you hand off to another team/co a service locator can make a lot of things go smoother integrating your module, but inside your module you'd generally use manual dependency injection by default and aim to implement neat IoC. You would break away from that when needed, particularly when code gets concerned with performance and adopts a very data oriented nature. Whenever you use a service locator you have to do way too much checking for consistency to make it a convenient pattern in unity.

placid ocean
#

Ye I wouldnt want singleton mess, had it before. Gets very easy to break order of stuff or create weird dependencies that break order of innitialization or whatever it breaks (not to mention testing would suck as hell if we had some).

Service locator to me seems pretty easy to maintain if done right. Testibility not too bad either.

I can understand manually injection, but seems like effort vs speed but compromise on cleanliness.

compact ingot
#

what does ServiceLocator done right look like?

placid ocean
#

Well maybe wrong wording 😅 but use interfaces ofcourse for services. Generics. Auto or manual registering with mono or non mono objects.

compact ingot
#

architecture is not about speed of code execution it is 99% about speed of implementing unexpected changes 1 year down the road

placid ocean
#

That is what i meant, not speed of code but implementation of new code ^

placid ocean
#

Ye it is, different word for same thing

compact ingot
#

no

placid ocean
#

Container is same as service locator

#

(kinda)?

compact ingot
#

you could argue that they overlap in what they provide

#

but they are fundamentally different ideas

#

an IoC container is the root of a system and "gives" references to components, a service locator is a thing a component can ask for a reference

placid ocean
#

Ah ye, I thought word container can be used interchangeably because they are both IoC patterns unless I dont know something about Service Locators.

compact ingot
#

i think the label IoC container is very wrong

placid ocean
#

Fair enough.

compact ingot
#

i'd prefer DI container

#

because you can terribly abuse a DI container in a way that has nothing to do with IoC

#

and nothing in a typical DI container particularly encourages IoC

#

just using interfaces with a DI container is interface segregation/dependency inversion but not inversion of control

placid ocean
#

You mean youd prefer DI Container rather than IoC container for describing the above Service Locator?

compact ingot
#

if its supposed to stay manageable i'd aim for a DI container before a service locator

#

a service locator makes sense if your modules truly do not have a shared entry point, come and go in an async and unreliable context etc.

#

DI containers only work (nicely) in a system you can construct deterministically/synchronously

placid ocean
#

Its for a game, mostly for services initialized in bootstrap stage and can ideally could be changed for debug, test vs production environments.

compact ingot
#

thats probably why most people abandon these frameworks eventually, just too incompatible with the nature of how games are constructed

placid ocean
#

I dont know enough about the DI libraries ive seen floating around, so not 100% tempted to guinmea pig myself unless people suggest it strongly.

compact ingot
#

some believe that a non-preformance-oriented ECS is the best way to architect a game if you want IoC at all cost

placid ocean
#

But most of games production ive seen anyway, it all gets messy in the end however much some guy tries to keep it clean.

compact ingot
#

whether someone likes or dislikes DI containers depends on how they experienced their first large scale use of them

#

its very easy to do stupid things with extenject for example that are voiding all the reasons for using it in the first place

#

on the other hand a DI container paired with a good review process can do a lot to give everyon a common understanding of a projects architecture and provide orientation and rails for onboarding new team members

#

the worst thing for onboarding you can do is invent all new patterns and archiecture for a large project that you have to explain to even senior people

placid ocean
#

Hmm ye, leaning towards singleton based approach for now. UE does something similar in its architecture.

compact ingot
#

what do you understand the singleton approach to be?

#

why would you make up such a thing?

placid ocean
#

make up what?

compact ingot
#

singleton approach

placid ocean
#

Service locator approach then, it would be a singleton.

compact ingot
#

thats like saying i'm deliberately shooting myself in the foot to see if its as bad as everyone says

placid ocean
#

I know singletons are not bad.

#

If managed.

compact ingot
#

depends on what that word means to you

#

there is practically zero reason to use singletons for "easy global access" in virtually any project.

placid ocean
#

What do you think a service locator is?

compact ingot
#

in unity the fundamental service locator is .GetComponent etc.

placid ocean
#

Ye mine would be ServiceLocator.GetService<Type>()

#

Services auto register to global ServiceLocator.

#

(or manually)

compact ingot
#

does your service locator create services when they do not exist?

placid ocean
#

Thats a possiblity, I dont think ill allow it though.

compact ingot
#

and what is the benefit of having a system deal with all the resource acquisition itself?

placid ocean
#

Well its not set in stone yet. I need to decide fully how I want to register services based on my current work that I've done with bootstrapping. I can see auto registering being beneficial in Unity incase you want to load services as a prefab and they auto register (different prefabs for different environemnts), but thats just a thought. On the other hand its also just easier.
But I may go manual registering due to how I set up my bootstrap flow.

compact ingot
#

you may want to consider how you are going to use that service locator from the perspective of a service requesting class, and how to make the dependencies it requests explicit and how to decouple the locator API from the system's API/implementation

#

its quite easy for a service locator to end up as a glorified global-access-singleton with all the same downsides (same thing happens in a DI container)

placid ocean
#

Ye good thought, I dont think I will bother trying to decouple that far for now, atleast for the game I am making currently. But will definitely re-evaluate if I see problems come up.
Just hard to gauge what will work as I havent seen properly what a large Unity project looks like. I've seen UE and some C++ ones but cant compare.

#

And also a very bad static/singleton mess of a project in C# 😅 😅

compact ingot
#

as you said, everything gets messy eventually, clean code is a myth and you can make most things work with enough effort and willingness/opportunity to fix broken systems and correct wrong turns

placid ocean
#

Ofcourse, one can dream 😂

#

Im sure it will all work out in the end haha

compact ingot
#

i've tried pretty much every approach to a unity project architecture there is, none of them was a deciding factor in the success of the project

placid ocean
#

haha im not expecting it to be based on code arch. 😅 its a personal project with a few others, so just exploring ways of doing things in Unity while I work on it.

compact ingot
#

but if cooperating with others, #1 priority should be on using stuff the team can understand and get behind, it does not matter how stupid that thing is, only that people can handle it

#

clever designs are often the ones that don't get used

placid ocean
#

100% agree

compact ingot
#

also consider that your team can learn to live with the quirks and shortcomings of an imperfect architecture

#

thats basically how it is in gamedev

#

we arent building microservices here 😄

dusty wigeon
# glossy lynx For all advanced programmers

School,

For Reference I did:
3 years (Technique en Informatique Programmation Jeux Vidéo), 2 years (Bachelor in Computer Science), 2 years (Master in Computer Science)

Most people I work with only did a certification which is 1 year and a half.

dusty wigeon
vestal lotus
#

does anyone know how to convert transform.right to a local Transform

long ivy
#

you mean in local space?

vestal lotus
#

nvm i just had to swap AddRelativeForce With AddForce

untold moth
vestal lotus
#

realized i needed that after my bullet spread rng bugged out at 45degrees

keen glade
normal lagoon
#

what do y'all think of ECS? hear a lot of good about it
if i use it, which is better? pure ECS, or Hybrid?

tiny pewter
#

i am doing some optimization of my grid based path finding by change the data structure and control flow to see if there is different
for checking if the neighbour nodes of frontier are obstacle, i can either check a cost property of a struct node in Node[,] or value in float[,]
at first i suppose checking (accessing) the float[,] is faster than checking Node[,] since i think accessing the cost property of node should be some statements as:
*(base address+((i*ColumnLength+j)*Struct Size)+element offset)
(or *(*(*(base address+i*8)+j*Struct Size)+offset) but this is more like jagged array's way)
the result of checking Node[,] is faster than checking float[,] by 10ms, idk why, maybe my code is wrong or C# mulitdimensional array is not work in this way

upbeat garden
#

Does anyone know a way to add a menu item to the context menu of a scene object on the hierarchy window?

#

Either it’s not supported, or there’s maybe an undocumented string you can use to add to it. Never can tell.

sly grove
upbeat garden
#

Thanks, but I don’t think that answers the question.

#

I’m looking for a way to add a context menu item to scenes listed in the hierarchy window, not game objects.

#

Sorry - I said “scene object” in my OP, which wasn’t clear.

#

I meant “the scene, when it’s shown in the hierarchy window”.

#

Scenes do have their own context menus, but I haven’t figured out the magic path string needed to add a custom item to it.

plush hare
#

I would probably go head first into full ECS if I didn't have 10 projects already in OOP unity.

dusty wigeon
#

But again, it depends on the game.

plush hare
#

You're simply wasting performance opportunity by not using ECS.

#

Any game I buy has trouble running at 144hz on my very modern hardware. If you own a 144hz monitor, you know the struggle

#

The world needs to move towards ECS for video game applications.

#

CPUs are at their limit in terms of random access OOP.

#

Rust and Tarkov, the major unity titles are extremely CPU bound.

severe topaz
#

half of their problems aren't related to OOP though

plush hare
#

I mean, you're probably right

dusty wigeon
#

ECS is great when you work with a lot of a given type which is not something you see in most game. If you are doing a Vampire Survive type of game, maybe you will gain and it will be worth the headache of making everything else work, but in more standard game it is not.

severe topaz
#

you can still apply DoD without touching ECS

dusty wigeon
#

Hence why I say you should go Hybrid.

#

For things that make sense.

plush hare
#

When I say ECS, I'm more so just talking DoD in general

#

just linear access patterns that can be vectorized easily

severe topaz
#

yeah ECS itself is overkill for most projects

dusty wigeon
#

UI in ECS most be a nightmare.

severe topaz
#

does UITK work with it?

dusty wigeon
#

Good question

mint valve
#

hi! when I try to navigate through the contents of a TMP Dropdown with keyboard or a gamepad, the selected item doesn't automatically scroll into view. manually assigning to scrollRect.verticalNormalizedPosition has no effect, it always stays zero unless you scroll with the mouse scrollwheel or by dragging the scrollbar. has anybody had to deal with that?

keen glade
autumn falcon
#

I want to clone existing game object mostly as is, but some nested objects that have specific component should be removed and re-created manually. Is there any sane way to do that?

#

before cloning, I temporary remove parent from these objects and it kinda works, but now I cannot find a good way to match new and old parents. It looks hacky and wrong, but I'm not sure if there is any better way to do that.

rapid mantle
#

How can I create software gore with UI?

brisk pasture
#

talking like glitches and stuff, would figure out which direction you want to go in for it

#

and apply it as a shader in post processing

sly grove
autumn falcon
# sly grove Can you share specifics? It's a little unclear what you want.

sure. Let's say that at runtime there is component tree like so

A
  - B
  - - C
  - D
  - E

I want to create copy of this component tree (using Object.Instantiate()). But I don't want to copy some of A's (grand-)childs. Let's say that C and E have some DontCopyMe component attached to them. I want to copy A, B and D, but not C and E. And then I'll create them manually from prefabs and place them in the right place in the tree. So the result would be

A(Clone)
  - B(Clone)
  - - C [created from prefab]
  - D(Clone)
  - E [created from prefab]

The way how I can currently do that is:

  • remove parents from components C and E
  • copy the tree
  • add parents back to components C and E
  • create C and E from prefabs
  • set their parents to cloned ones

And the only way I was able to match parents without adding temporary components is to search for them by name. E.g. "B(Clone)" and "E(Clone)". But this is not very reliable and quite ugly. Is there a better way to do that?

sly grove
autumn falcon
#

These things are basically game environment - room or level if you will. Idea is that you can create copy of it, perform some actions in copy and then "import" them back into original environment. I don't want to clone some component as is, because there is quite a bit of logic to initialize those and I don't really want to be required to ensure that those components state isn't leaked to new copy.

#

C and E aren't part of the prefab. They will be spawned at runtime.

severe topaz
#

why not just use prefab variants, or is it too procedural for that?

autumn falcon
#

because these entities can be spawned at runtime and aren't pre-determined at build-time. E.g. enemy units and stuff like that.

scenic forge
#

What about just not having C and E in your prefab to begin with?

sly grove
#

already mentioned haha

scenic forge
#

Oops.

sly grove
#

the problem I think is he wants to clone the modified copy of the object that's in the scene

#

not the original prefab

autumn falcon
#

sorry, if I wasn't clear enough. In my example C and E aren't part of the prefab, they are added to existing prefab at runtime by game logic.

#

or not to prefab, but rather to resulting gameobject

scenic forge
#

So couldn’t you just clone the original prefab rather than the resulting GO then?

autumn falcon
scenic forge
#

Well, ABD+CE.

autumn falcon
scenic forge
#

Well you already have code that attaches CE to ABD, you couldn't reuse that?

severe topaz
#

wait, are you trying to swap the room itself without touching contents?

scenic forge
#

Perhaps I'm missing some critical insight to your problem, but on the surface this feels like it could be solved by simply reusing existing code/prefab.

autumn falcon
severe topaz
#

yeah there's a trend where to help someone you first have to guess the issue. rubber duck would help a lot here.

autumn falcon
scenic forge
#

That makes sense.

#

Well in that case and if you are stuck with your current architecture, I don't see other way than doing the obvious "clone, delete what you want to swap away, add back what you want to swap to"

severe topaz
#

keep a list of the objects that are replaceable
check all objects, and if they're not in a list, check their parent.
check what slot the parent belongs to
remove parent, attach to new parent with matching slot

autumn falcon
scenic forge
#

Without knowing enough context, a potential different approach could be to serialize (not in the Unity sense, but in a general sense) your hierarchy state that can be easily manipulated and recreated.
An example could be your room GO perhaps only have one state (whether the door is opened or closed), thus it can be serialized to a POCO with one field isDoorOpen. With that POCO you can freely manipulate that field, and recreate the room without needing to reference the original GO, because all necessary state is already there.

autumn falcon
#

I already do that. All dynamic objects are serialized into POCO which I'm using to re-create them.

scenic forge
#

Then your original question could be solved with: serialize the current hierarchy, swap out CE's serialized representations, then create the hierarchy again.

rancid oxide
#

Basically I integrated Amazon Polly to my unity project, so I can send request to generate mp3 of speech voice from text at runtime.

With the current system everytime I send a new request I have to store the file locally and execute an 'AssetDataBase.Refresh()',
the problem is that other than making the program freeze for a couple of frames I can't use this method on WEBGL build since I can't save stuff locally.
Is there a way to generate and Audioclip on the go after receiving the mp3 data so I can dispose it after being played?

This is the current code structure I was preparing:

#

This was the old script, which as I said worked but have the issues I listed previously

scenic forge
#

Are you synthesizing audios at runtime or at editor time?

rancid oxide
#

Its all runtime

scenic forge
#

I don't think AssetDatabase is even available at runtime, WebGL or not.

rancid oxide
#

its probably not

#

Thats why I want to change how its handled, I think it can be done better than 'Save it locally and then retrieve it locally'

scenic forge
#

On the topic of loading compressed audio like mp3 as an audio clip at runtime, the last time I looked at it the only way is to use UnityWebRequestMultimedia.

rancid oxide
#

a webrequest to handle a local file? is it me or the name is misleading?

scenic forge
#

UWR is not for local file, it's for making network requests, which can also handle local files with file:// protocol.

rancid oxide
#

I'm having issues understanding the documentation about it tho, any idea on how I could integrate it?

scenic forge
#

Three potential ways:

  • Ideally if AWS SDK allows you to somehow configure it to use UWR, then you just use that for the request instead so you get the audio clip back directly. Highly doubt it though.
  • Alternatively after you get the mp3, write it to file system and then request it with UWR again to get the audio clip. Probably won't work for WebGL.
  • If all else fails, you can always send your own request based on Amazon's docs rather than using their SDK, that way you can use UWR for it directly and get the audio clip back.
#

Ah and a fourth way, if Amazon Polly allows returning the audio in wav, you can do your own parsing (WAV is trivial to parse) and write to audio clip directly.

rancid oxide
#

So 2 of them rely on AWS and the middle one on writing the file (which will not work on WEBGL)

#

Is parsing not possible with mp3?

#

Cause aws only sends mp3

scenic forge
#

It is, you can do your own decoding (if you don't value your sanity) or bring in a library that does it.

rancid oxide
#

Yeh for sure I'll search for a library

scenic forge
#

I mean the 3rd way is just rewriting the AWS SDK.

#

Well, only rewriting the part that does the synth request.

rancid oxide
#

I wanted to keep the system flexible cause now I'm using amazon but next time I'll maybe use another service

#

The core is the same: getting an Mp3 from an external source and use it as Audioclip on runtime in WEBGL

scenic forge
#

If the external source is network, then that's exactly what UWR does.

#

But yeah, I remember looking into this awhile ago and got very frustrated that there's no way to let Unity decode an audio clip at runtime except using UWR

#

So unless things have changed, you either use UWR, or you do your own decoding to PCM so you can load them to audio clip directly.

rancid oxide
#

Ok, thanks, Ill try to take another look at UWR

#

UWR needs some adress to get the file locally, so its assuming the file will be saved locally, and that is not possible on webgl
So I guess my last option is to actually decode the data I receive from AWS directly when I receive it and convert that to an audioclip

scenic forge
#

I mean, the address could be the request address to AWS to get that synth file.

#

You do the requesting directly with UWR rather than AWS SDK client.

rancid oxide
#

Mh.. its to messy to change that system now, as I said it could be another thing that is not AWS in the future

#

Is the option to decode that difficult/unoptimal?

scenic forge
#

Don't know, I only briefly looked into it and the few first clicks were libraries that are either unmaintained, untested, or just doesn't support Unity.

#

I'm not sure what you mean by the former though, if you are going to move away from AWS in the future, you are going to have to rip away the code that requests Amazon Polly and replaces with whatever new service anyways, I don't see how that's different from changing which address UWR sends to.

rancid oxide
#

@scenic forge Is this the integration of WW you suggested? (sorry for ping)

#

Again this works locally since it has PersistentDataPath but fails once runs on web

scenic forge
#

Yes

#

But instead of using AWS client to send that request to get the audio, you construct and send the request yourself with UWR.

upbeat path
rancid oxide
upbeat path
#

paste site

orchid marsh
#

How to post !code

thorn flintBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

rancid oxide
upbeat path
#

@rancid oxide btw I hate this use of var because it is impossible to know what objects are just by looking at the code

scenic forge
#

var is fine in my book.

upbeat path
#

in your own code, yes, but on a paste site it is meaningless

scenic forge
#

If you can't tell roughly what a variable's type is just by its name, then that's a naming problem than a var problem.

rancid oxide
#

Its think var is fine, you just have to know the context of the whole code.

Basically I need a way turn filestream I get from Polly request into Audioclip without having to store it locally since I cannot use that feature on webgl

upbeat path
#

you cannot do async on WebGL anyway, you need to use coroutines

keen glade
#

Hi peps.

rancid oxide
upbeat path
#

I presume you are hosting this on AWS as well

rancid oxide
#

It will eventually, for now I'm just running locally a chrome

scenic forge
#

CORS or not, it just wouldn't work if WebGL doesn't allow you to write to a file system

#

Unless Unity implements a virtual file system for you.

upbeat path
#

webGL writing to persistentData is no problem at all. it goes into index.db

scenic forge
#

Oh, that's good to know.

upbeat path
#

you can even persist it across browser sessions if you wish

scenic forge
#

Then writing to that and then using UWR to grab it back as audio clip would work

#

The rest is just a bit of code.

upbeat path
#

yep, sure

#

this

var responseTask = client.SynthesizeSpeechAsync(request);

is what concerns me

rancid oxide
#

Is a problem about the browser blocking some code due to restrictions?

upbeat path
#

yes, I think so

rancid oxide
#

even if I'm trying it to run locally?

upbeat path
#

because you are running it locally. that is what CORS is all about

rancid oxide
#

mhhh... so if its hosted on a website it will potentially work?

#

(sorry dont know nothing about cors)

scenic forge
#

Open your browser dev tool, if there's a CORS error you will see it either in console, or in network requests tab.

upbeat path
#

yes, if the site is configured to accept CORS

rancid oxide
#

ok, ill try. give me a seec

scenic forge
#

(Surely Amazon's API would already have CORS configured to accept everything?)

upbeat path
#

do you know what CORS is?

rancid oxide
#

me?

upbeat path
#

yes you

rancid oxide
#

I can imagine is some sort of issue due to files coming from different sources

upbeat path
#

it is a security feature to stop Cross Site Scripting, in your case you have a local site and you are accessing AWS sites, that is Cross Site

#

you need to look at HTTP Request Headers to see how to mitigate this

rancid oxide
#

so potentially even if I upload the game on itch and I request a voice from polly it couldnt work

upbeat path
#

i can tell you it will not work

#

in it's current form

rancid oxide
#

ok

#

damn I hate webgl

upbeat path
#

yep, it's a pita unless you know exactly what you are doing. no easy shortcuts

rancid oxide
#

its way more restricted than I expected

upbeat path
#

it is extremely restricted. things that are 'easy' on pc or even mobile can be very difficult to achieve with WebGL

rancid oxide
#

Look at this:
https://hatebin.com/bhynwszliy

The execution is very simple (it just plays a random mp3 hosted somewhere) and yet still doesnt work on webgl

upbeat path
#

again CORS

rancid oxide
#

ye

#

So just one thing about cors in general, this is an issue about the browser in general or just unity? And can it eventually be disable by the hoster of the site or its locked for security reasons?

scenic forge
#

You should make sure the issue you are having is actually CORS first, by checking browser dev tools.

upbeat path
#

browser in general. you need to set up your web servers to mitigate this restriction by having the correct request headers

scenic forge
#

I doubt the Amazon Polly endpoints don't have CORS configured to accept any origin.

upbeat path
#

it's not about AWS it's about the requesting site

rancid oxide
#

how can I check if this setting is enbaled or not from the inspector?

upbeat path
#

inspector?

#

but by default CORS is enabled which means Cross Site access is disabled

rancid oxide
upbeat path
#

still no wiser, what page inspector?

rancid oxide
#

the one of the broswer

dusty wigeon
upbeat path
#

you mean the web developer console?

rancid oxide
upbeat path
#

or the network traffic console

rancid oxide
#

the web dev is probably what I meant

upbeat path
#

that will just show you action and results, it wont tell you if CORS is the problem but you can extrapolate from the messages if that is the case

rancid oxide
#

ok

bleak citrus
#

we recently got some more fantastic acronyms, like CORP and CORB

#

i am not looking forward to updating my mental model of all of this

bleak citrus
#

🫠

#

Isn’t this all fallout from those processor bugs

upbeat path
#

imo, it's a shitty response to the naive design of HTTP

compact ingot
bleak citrus
#

This CORP/CORB/god knows what business is there to prevent malicious sites from making your processor run code that depends on sensitive data, and thus learning the data through those cache timing attacks

#

i guess that’s not really The Cloud for once

compact ingot
#

it only matters (so much) because of the could, i.e. because everything is constantly connected

proven pulsar
#

I want to add pathfinding for my game enemy's AI however using the A-star pathfinding package in unity I am facing some struggles, firstly my map is generated randomly which means I cant use the grid graph and scan through the component as I have to wait for the map to generate first, I have some unwalkable tiles such as water and other tiles in the future such as (trees and rocks) which will also be unwalkable in the future I am kind of new to the unity so I might be doing something stupid . How could I implement the path finding for my enemy?

this is my mapGenScript = https://pastebin.com/u2jHg09C
I have the seeker component on my enemy prefab, a rigid body 2d and a 2d box collider. How do i make it so that the grid map is scanned according to the randomly Generated map and the grid map also updates in the future when an unwalkable tile is placed like a wooden wall?

i guidline and direction would be quite great!, thanks in advance

flint sage
#

Is your easy solution

#

However, it might be better to do your own solution and generate the graph while you're generating your map but that is probably a further advanced step you can take later

proven pulsar
tiny pewter
#

the path finding algorithm itself should should only consider the V,E but not the grid (or graph) is run time generate or not...

#

oh you use package, you may consider implement your own path finding

proven pulsar
thorny mortar
#

Is there a way to read downloaded mp3/png files from persistent data path in WebGL ?

#

When I try to read it says access is not allowed (ping me pls)

dapper cave
#

cinemachine brain switching between vcams, what's the easiest way to have the brain loosely coupled like a dampened rubberband?

bleak citrus
untold moth
thorny mortar
tropic stag
#

Hi, I'm new to c# and settled into a pattern of relying on c# events to decouple my code. Everything works out great except I'm stuck thinking about them as "events" and "handlers", where in reality all of that code is called "inplace". So when I call X.Invoke(), and in some onX() handler I want some code to run after all other onX() handlers already run, I often find myself calling unity's Invoke("OtherCode", 0); where the 0 time offset is only there to allow the other handlers to finish. I've already ran into problems because of type-ohs in Invoke(). Is there some other way to run code after the current Invoke() is done with all its listeners?

untold moth
untold moth
scenic forge
#

TIL MonoBehaviour.Invoke is a thing, with string name too, yikes.

tall ferry
#

you can make it slightly better by using nameof().... but yea

thorny mortar
scenic forge
#

Audio clip only accepts PCM, so you need to decode your compressed audio into PCM.

tropic stag
# untold moth You can just run your code after invoking the event. It would run after all the ...

So for example If I have a "Piece" and a "Board", and they both handle an onRestart event. Inside Piece.OnRestart() {... } if I wanted to run code after the Board's on restart has ran I have the choices of:

  • Invoke("MoreCode", 0)
  • introducing a new event afterRestart and invoke it inside Board's OnRestart (I do this sometimes if the event involves animation, so obviously it takes time to finish.
  • introduce the new event, and invoke it immediatelly after first so onRestart.Invoke(); afterRestart.Invoke()

Out of all that the Invoke(..., 0) seems the simplest but at the same time I feel like it's not what it's for (And only works on monobehaviours, so if I wanted to handle Restart in some misc data serialized object I wouldn't be able to)

scenic forge
untold moth
thorny mortar
scenic forge
#

Not sure tbh, I'm not familiar with web builds.

untold moth
#
YourEvent?.Invoke();
OtherVodeAfterEvent();
thorny mortar
#

I tried to give the unityWebRequest that idbfs (indexedDatabase FileSystem) file path it returns Error 403 is there prefix should be added for the path?

scenic forge
#

(Honestly Unity really should expose APIs to decode audio than UWR)

#

How does your game get your original mp3 file (before saving to idbfs)?

thorny mortar
#

Thanks for your help, but yeah or at least give the Unity WebRequest the ability to read from the idbfs.. thats crazy

scenic forge
#

In the case of @rancid oxide, they obtain their MP3 from a network request to AWS voice synth, so they could just rewrite that part of the code to use UWR and solve their problem, instead of having to go through a middleman.

thorny mortar
#

I think I will try the NAudio lib to decod the byte[] to pcm

thorny mortar
scenic forge
#

RIP.

thorny mortar
#

I know the AWS streaming option is valid but I am trying to avoid it because it's gonna cost me every time the user needs to hear the audio

scenic forge
#

Oh nah

#

I meant that if you obtain your audio from a network call, you can just send that call with UWR directly and get back the audio clip, and then save the audio clip's PCM to idbfs

#

Next time you can just grab the PCM straight out of idbfs and not needing to make another call.