#archived-code-advanced

1 messages · Page 59 of 1

stuck onyx
#

lol let me check 🤣

#

i have the memory profiler package installed and I ran this:

#

Im guessing this is the package's one

untold moth
#

Yeah, that's the package one. What if you check the one in the regular profiler?

stuck onyx
#

the regular profiler doesnt show barely info about the memory

untold moth
#

It does. You need to capture the frame memory.

#

But you'll need to compare several captures manually.

stuck onyx
#

uhmmm, ill note that down and add it to my attempt list 😄

#

thanks dlitch

#

ill let you know the result if you wish

stuck onyx
#

already found i have a set of textures that i create in runtime and im not releasing from memory when im done

#

REALLY helpful

untold moth
#

So it was resources that you load/create and don't release after all.

scenic forge
#

For any runtime generated resources that must be manually destroyed, I wrap them in a Allocated<T>, then I follow the rule of: if a T is passed to you, then you don't need to worry about destroying it, it's the caller's responsibility; if an Allocated<T> is passed to you, you must manage the lifetime and destruction of it yourself (or pass that to someone else).

#

It's not a perfect system but I've found it to be very effective at eliminating most of the issues.

stuck onyx
scenic forge
#

It's poor man's Rust ownership model, except without any of the compiler help 😄

#

If you want to go a step further you can write an analyzer for it, specifically to ensure methods that accept Allocated<T> to always handle destruction in some way.

stuck onyx
#

or tell me the name of how this practice is called technically for me to search

scenic forge
#

For the analyzer?

stuck onyx
#

yes, what do you mean by writing an analyzer?

scenic forge
#

A C# Roslyn analyzer.

#

Unity supports them (well a pretty dated version), so you can write an analyzer that does something like, "if a method accepts Allocated<T>, it must fulfill one of the following conditions: 1) calls Allocated<T>.Dispose() in the method body, 2) passes Allocated<T> to another method, or 3) saves it to a class field, and the class implements IDisposable"

#

And it will produce a compile error/warning if the criteria isn't met.

#

But honestly in my project the pattern is already good enough to catch most of the issues that I don't find writing an extra analyzer for it is worth the time investment.

fluid totem
#

I would like to ask how a diablo-like game handle different stats for spells with different tags. For example, a item can increase fire damage that can benefit fire spell only. There are usually many tags for the spell and at least 30-40 variable for increase different stats. Do they just add 30-40 variable in the game, and use them as reference? I think its kind of "stupid". Right now I am using scriptable object (each for each stats) to link the spell, every time I create a new spell, I need to "pull" the related scriptable object/stats (eg. fire damage, fire cast speed) into it and I feel I will eventually miss pulling. Is there more efficient way to do so?

bleak citrus
#

that sounds very similar to what I'm doing right now!

#

it's fine as long as you have a nice, neat, orderly set of stats

#

sure, you could forget to assign the right scaling stats

#

but you could just...forget to do whatever alternative scheme you come up with, too

#

one thing that could help is to describe the spell entirely based on the stats assigned to it, rather than hardcoding the description, so that it's immediately obvious if you forgot something

#

i'm working on weapon scaling and special effects for my soulslike game right now, and I'm going to do that as much as possible

fluid totem
#

I wonder if there is some kind of way to set the related stats automatically when setting its tag or set one time only for different tags. So, if I have fire/cold /lightning, I need to create 3 variable for fire damage/cold damage/lightning damage? << thats what I am doing now, and I feel there is way too many variables.

sly grove
#

Maybe something like this:

enum Tag {
  Fire,
  Poison,
  Paralysis
}

enum StatType {
  Damage,
  DamageMultiplier,
  Healing,
  AddStatusEffect
}

public class Stat {
  public StatType StatType;
  public float Quantity;
  public Tag Tag;
}```
#

So then 10 fire damage can be expressed in the inspector as:

  • StatType: Damage
  • Quantity: 10
  • Tag: Fire
#

and a spell that increases fire damage by 40% can be:

  • StatType: DamageMultiplier
  • Quantity: 1.4
  • Tag: Fire
fluid totem
#

yea, thank you. I was thinking to create one scriptable objects containing all stats for one tag . So, I only need to pull one and no need pull every related one when I create new spell.

#

Every time I get a new item, I can directly increase the stats in the scriptable objects and all related spells can benefit from it

bleak citrus
regal lava
#

then consider doing like a lookup table to combine with those operations if you're going to have this large system of tags

tired fog
#

I need some help related to Command Buffers. I'm trying to generate temporal render textures, but when retrivign im getting nothing

#
public void GenerateDepthTexture()
    {       
        DepthTexture = new RenderTexture((int)RTSize.x, (int)RTSize.y, 0, RenderTextureFormat.RHalf, MipLevels){
            name = "Temp DepthTexture",
            useMipMap = true,
            filterMode = FilterMode.Point,
            autoGenerateMips = false,
            enableRandomWrite = true
        };
        DepthTexture.Create();
        cmdBuffer = new CommandBuffer();
        cmdBuffer.name = "Copying Depth Buffer";
        cmdBuffer.Blit(BuiltinRenderTextureType.Depth, DepthTexture);
        int width = (int)RTSize.x;
        int height = (int)RTSize.y;
        for(int i = 1; i < MipLevels; i++)
        {
            width /= 2;
            height /= 2; 
            width = Mathf.Max(width, 1);
            height = Mathf.Max(height, 1);
            int tempName = Shader.PropertyToID("_tempRT"+i);
            cmdBuffer.GetTemporaryRT(tempName, width, height, 0, 
                DepthTexture.filterMode, 
                DepthTexture.format, 
                RenderTextureReadWrite.Default, 
                DepthTexture.antiAliasing, 
                true,
                DepthTexture.memorylessMode,
                DepthTexture.useDynamicScale);
            cmdBuffer.SetComputeVectorParam(downscalerShader, "RTSize", new Vector4(width, height, i, .0f));
            cmdBuffer.SetComputeTextureParam(downscalerShader, 0, inputRT, DepthTexture, i-1);
            cmdBuffer.SetComputeTextureParam(downscalerShader, 0, outputRT, Shader.GetGlobalTexture(tempName));
            int groupsizeX = width / 8;
            int groupsizeY = height / 8;

            cmdBuffer.DispatchCompute(downscalerShader,0, groupsizeX, groupsizeY, 1);
            cmdBuffer.CopyTexture(Shader.GetGlobalTexture(tempName),0,0, DepthTexture, 0,i);
            cmdBuffer.ReleaseTemporaryRT(tempName);
        } 
        TargetCamera.AddCommandBuffer(CameraEvent.AfterDepthTexture, cmdBuffer);       
    }
#

For some reason, the texture set on outputRT is null/ on the frame debug it's say native internal, but I don't understand why. if i manually execute this again, or if i execute it twice after the first time, it works just fine

#

Does anyone have any idea on why that might be???

regal lava
sage radish
tired fog
#

I hope it's not that, been trying too many days for it to be so simple

#

lets see

#

I hate my life

#

Thank you @sage radish

#

Does anyone know what this amount of GPU ms comes from?

sage radish
tired fog
#

Gpu

#

GPU Usage

sage radish
# tired fog GPU Usage

Oh, didn't know that shows timings. Skybox can be expensive since it usually covers a significant portion of the screen, but that would depend on the resolution and the complexity of the shader.

tired fog
#

I'm using the default skybox

bleak citrus
#

that seems funky

tired fog
#

:/

#

My guess is that Im using compute buffers, and they are wrongly tagged as skybox rendering

sage radish
#

I could see that being the case.

#

RenderDoc also has time profiling and captures all GPU events, including compute.

tired fog
#

Render Doc?

sage radish
#

With Unity integration

sand acorn
# tired fog GPU Usage

Hmmm, are you using DeepProfile to check if it is really the skybox rendering the problem? maybe the problem is way deeper

tired fog
#

Im getting this now, but it still doesn't add up

tired fog
sage radish
#

The timing data is a bit hidden. You have to click the little clock icon at the top of the Event Browser

tired fog
#

Im not sure how to use this tool

sand acorn
vivid fjord
#

googling for "unity tree shaking" isnt giving me anything useful... is the unity build system at all intelligent about what it includes and what it doesnt? just thinking - im adding all these asset packages of models textures etc... are the entire packages going to be included in my build, or just what i use? can anyone point me at a guide or resource or what terms should i be googling for 🙂

bleak citrus
#

it does, indeed, try to figure out dependencies

#

this is why you sometimes, say, need to explicitly say "include this shader!"

tired fog
sage radish
tired fog
#

I see, can I sort by duration?

sand acorn
sage radish
tired fog
#

Mmm okay

bleak citrus
#

you might need to do a binary search

tired fog
bleak citrus
#

turn off half of it and see if the work goes away

vivid fjord
bleak citrus
#

I believe that anything in a Resources folder is always included

#

since you can use Resources.Load<T> to fetch those assets

vivid fjord
bleak citrus
#

since Unity has no way to know what you're gonna load, it just includes it all

#

but for assets that you're referencing, it can clearly see what is and isn't used

vivid fjord
#

BUT I AM AN ADVANCED CODER, SO I ASK HERE 🤪

#

cool tyty

bleak citrus
#

iirc you can view a report after completing a build

#

i forget where it goes

sand acorn
#

Maybe there is a way to store the data in an array and read the data from there instead of calculating at runtime?

tired fog
#

That's what I'm doing, but it seems to be some other issue

#

And i think I've found a trail

#

Im running some compute shaders for occlusion culling, and it seems im dispatching them with crazy big size

#

need to make sure about those values now

sand acorn
#

ah yes, handling large arrays / data at runtime can be problematic

#

I have a question, so 2 days ago I tried to make procedural mesh generation using a Parallel Job, I splitted my jobs in 3 parts: Vertices generation, triangles generation and UVs generation (originally it was an Ijob with all 3 process attached to it)

#

My code just didnt work, it looked like it was not processing the vertices and faces count as they were supposed to

#

for example the working sample was returning 1700 verts, then 5000 verts, and then 9000, and so on

#

while the parallel code was returning way lower values, like it was missing some data

#

does parallel writing to list fail like that?

#

I made sure to rewrite the exact same stuff

#

but still my mesh was degenerated

#

it looked like this Lmao

#

some parts where correct as you can see in the picture, it generated blocks

#

but the rest was just degenerated with less vertices than it should have

tired fog
sand acorn
#

the meshes should look like this

sand acorn
#

an extra loop?

tired fog
# sand acorn what was going on?

To select the thread dimension I was using the total amount of grass blades, instead of the amount of grass blades per chunk, aka, every chunk was doing everything

sand acorn
#

glad you fixed it

tired fog
#

Thanks :)!

#

Can you send your code? Maybe I can help you out!

sand acorn
#

So that's how the multithreaded code was looking, I wrote it following the GenerateMeshJob structure (which is the code that currently works but it is non parallel)

tired fog
#

Oh damm, that's a lot of code

sand acorn
tired fog
#

Do you have any ideas on where the issue might be? It's a lot of ode to understand quiclky

sand acorn
#

No need to worry too much about that code, my project is already insanely fast using a Ijob, I just wanted to push it even further so its not like a mandatory to get that working

midnight marlin
#

how can i add ads

rancid widget
#

I am moving my player with AddForce in FixedUpdate, but am seeing jitter when a platform is moving and when the player is on that platform, and the platform's movement is also FixedUpdate. I have found that the player moves smoothly as it is unless on the platform, and the platform itself would move smoothly in LateUpdate, but this causes the player's AddForce to work incorrectly when they are a child of the platform. The objects mentioned have their RB2D set to continuous, Never Sleep, and Interpolate. What I am trying to do is get the platform to move smoothly while also allowing the player to move on it, so while LateUpdate for the platform makes it smooth, it makes moving on the platform unfeasible in it's current state. Here is the movement snippet for the player and the script for the platform: https://hatebin.com/lpqiorfeof

sly grove
rancid widget
rancid widget
sly grove
#

Right because now the platform is actually physically moving

#

rather than teleporting

#

so friction is taking effect

rancid widget
#

so before, the player stuck to the platform unless they were making themselves move, is there a way to get to that point now? Essentially, the original script setup worked as I wanted to, but the platform and player were jittering.

sand acorn
bleak citrus
#

haha, yeah, the video looks very funky

rancid widget
#

I tried to compress it for discord

bleak citrus
#

you should just use an mp4

#

it won't auto-play, i guess

#

but gif is a horrendous video format

sand acorn
rancid widget
#

well right now i have a gif tool available, im trying to demonstrate the three methods I have right now

#

you can see the jitter here

sand acorn
#

or how are you moving your plattform

rancid widget
#

Its all in my writeup above

#

This third gif is in late update, this is what i want it to look like, but the player can barely move on the platform due to the late update of its parent

sand acorn
#

I just took a look at your code, I dont think thats the best way of moving an object from side to side; I would use vector3.lerp instead and on the last parameter of it I would use a Mathf.Sine(some value) so your platforms moves from point a to point b and backwards

#

also this would make your code shorter

rancid widget
#

Ok, would you be able to provide an example? I get the idea but i'm still a bit new to this...

sand acorn
#

this is not lerp but works

merry hill
#

so im finally having a proper look at quaternions and am trying to use them to rotate points around an origin point:

    public Vector4 RotateAroundOrigin(Quaternion rot, Vector3 input, Vector3 origin)
    {
        input -= origin;
        // Rotate using quaternions.
        Vector3 result = rot * input;

        return result;
    }```
Now this seems to work for simple quaternions (cartesian-axis rotations etc.) but for more difficult things it seems to react weirdly
for example, if i try using this program to get the local position of a point relative to the camera (and its rotation) with the following parameters:
camera.position = -3,3,-3
camera.rotation = 0.35355,0.35355,-0.14645,0.85355
Vertex.position = -1,-1,-1
result = 0.41,-4.24,-2.41
as can be seen from the z value of the result, my program thinks it's behind the camera, which it is not
any idea what might cause this?
sand acorn
#

Lerp would be Vector3 mov = new Vector3.Lerp (StartPosition, EndPosition, Mathf.Sin(Speed * Time.time));

rancid widget
#

This script snippet still has the player having trouble moving, they move very slowly as compared to being on the ground, regardless of direction in relation to the platform

#

I think I might just live with the platform jitter for now, other solutions are introducing new problems. The ideal I suppose would be to use late update and to give the player a force boost when they are on the platform to even things out

crystal oar
#

Anyone have tips for the best method to move the spine in the direction the player is looking in a FPS game? Should i rotate the spine bones directly from mouse input? Or should i have them face towards an empty gameObject attached to the camera? First time creating this and im not sure the best method

rancid widget
#

oh boy, I might have just needed one line of code, let me try something chatgpt suggested

shell jasper
#

Hey, I'm looking for a way to get an AsyncGPUReadbackRequest from CommandBuffer.RequestAsyncReadback. The callback from the second argument is only fired when the request is completed, while I need to explicitly wait for it in case it's not done by the time data is needed.

Using AsyncGPUReadback.WaitAllRequests works, but I'd rather just wait for this one request.

sly grove
merry hill
#

because im using this as a way to learn quaternions, dont want to do it all using built-in functions

rancid widget
#

So the solution to my issue for right now is to use other.transform.gameObject.GetComponent<Rigidbody2D>().interpolation = RigidbodyInterpolation2D.None; when the player lands on one of these late update platforms, the player can move on it normally and there is no jitter, then just set back to interpolate when they leave the platform.

merry hill
brittle horizon
#

Quick question: I'm interested in dependency injection frameworks for Unity. Is Zenject/Extenject the standard or should I look into something else?

compact ingot
bleak citrus
#

i also really need to give DI a try

#

if only so that i can then go back to thinking I don't like it :>

dusty wigeon
#

You can do everything without dependency injection.

brittle horizon
compact ingot
#

for me it’s more about whether it suits the project and org structure on working in, it doesn’t always work well

bleak citrus
#

hm, so i'm reading through the Zenject readme

#

I see that a lot of the "construction methods" are various flavors of component lookups

brittle horizon
bleak citrus
#

i guess the point of that is so that you don't have to perform the lookup yourself

compact ingot
bleak citrus
#

partially from the size of my scrollbar

compact ingot
#

But you’ll struggle way more with it because it really doesn’t like you to take shortcuts

bleak citrus
#

one major roadblock for me is that

#

this feels like someone just glued a bunch of sequins to singletons

#

it's very shiny and complicated

#

also there is now a Factory, because of course there is a factory

compact ingot
#

Most people use di conrainers as glorified singletons

#

Missing the entire point

#

And to insulate themselves from being viewed as unprofessional

#

i think if you really try to understand IoC and what containers can do for you to implement it, they can be very helpful, but they do not make anything easier and you need to be really good at architecture to get something out of it

bleak citrus
compact ingot
#

i mean, IoC is a brilliant thing to do even if you are not using a container

#

but its tedious

bleak citrus
#

i'm gonna be honest

#

i've had a much easier time understanding Haskell than this stuff, lol

#
type Monad :: (* -> *) -> Constraint
class Applicative m => Monad m where
  (>>=) :: m a -> (a -> m b) -> m b

i can grok this, but i just bounce off the wikipedia page for IoC

plucky vine
#

Does anyone know of a way to speed up converting float3 to Vector3? When the implicit operation occurs a lot, it seems to bog down my performance.

#
    public void GenerateMesh(VoxelData data)
    {
        int size = data.size;

        vertices.Clear();
        triangles.Clear();

        if (!trianglesQueue.IsCreated) trianglesQueue = new NativeQueue<GenerateCubeJob.Triangle>(Allocator.Persistent);
        if (!values.IsCreated) values = new NativeArray<float>(data.data.Length, Allocator.Persistent);

        trianglesQueue.Clear();
        values.CopyFrom(data.data);

        GenerateCubeJob job = new GenerateCubeJob();
        job.scale = scale;
        job.size = size;
        job.values = values;
        job.triangles = trianglesQueue.AsParallelWriter();

        handle = job.Schedule(values.Length, 8);

        handle.Complete();

        int i = 0;
        while (trianglesQueue.TryDequeue(out GenerateCubeJob.Triangle v))
        {
            vertices.Add(v.a);
            vertices.Add(v.b);
            vertices.Add(v.c);

            triangles.Add(i++);
            triangles.Add(i++);
            triangles.Add(i++);
        }

        triangles.Reverse();

        mesh.Clear();
        mesh.SetVertices(vertices);
        mesh.SetTriangles(triangles, 0);
        mesh.RecalculateNormals();
    }
#

This is the code I'm looking to optimize

#

GenerateCubeJob.Triangle is this struct:

        public struct Triangle
        {
            public float3 a;
            public float3 b;
            public float3 c;
        }

bleak citrus
#

NativeArray has a Reinterpret method, which may be relevant here

#

it directly reinterprets the data as another type

plucky vine
#

and triangles is a List<Vector3>

dusty wigeon
#

Do you really need to convert to Triangle ?

plucky vine
plucky vine
dusty wigeon
#

I mean, from.

plucky vine
#

Becuase GenerateCubeJob is a parallel job

#

Should I just try to convert the queue into a NativeArray?

dusty wigeon
#

Do you know the amount of data at the start of the generation ?

#

If so, could you not places them in a predefined array ?

plucky vine
#

I will not know the size of trianglesQueue at the start, that's why I'm using a queue

#

This is my attempt at marching cubes with dots

dusty wigeon
#

The issue is not the conversion, but the memory allocation I would guess.

#

This comes from the design of your algorithm.

#

You need to come up with a way that prevents that.

#

What is the usual size of your trianglesQueue ?

plucky vine
#

Yeah, I've been diddling around with this trying to optimize it all. The deep profile says that the implicit operation causes a decent bit of the performance hit

dusty wigeon
#

Are we talking millions ? Thousands ?

plucky vine
#

or wait, divide that by 3

dusty wigeon
#

And the cost from the implicit conversion ?

#

Interesting.

bleak citrus
#

deep profiling may not be entirely useful here

plucky vine
bleak citrus
#

doesn't it add a constant cost to every function call

plucky vine
#

Maybe if tracking the implicit operation is a problem

#

It's possible

#

Then I'd guess I'd have to look elswhere for optimization

#

But anyway, another issue is a big lag spike every 7 seconds or so

dusty wigeon
#

What happens every 7 seconds ?

plucky vine
#

Not sure

dusty wigeon
#

You have 2m of allocation

#

O.o

#

That is enormous.

plucky vine
#

Lots of garbage

bleak citrus
#

sip big sip of memory

plucky vine
#

been trying to trim it down

dusty wigeon
#

You gotta find a way to make near zero.

bleak citrus
#

oh wait

#

is that just the deep profiler

plucky vine
#

Not deep

bleak citrus
#

ah nvm

plucky vine
#

It's annoying using the deep profile because you can't zoom out to see the spike

bleak citrus
#

i was having trouble telling which line was which

dusty wigeon
#

And, shouldnt use ComputerShader for such operation ?

plucky vine
#

I was watching the sebastian video and he did the compute shader and one of his comments was that using dots for it was an idea, so that's what I'm doing

#

I'm completely new to dots too

#

and compute shaders are intimidating to me, I'll get to learning them later

dusty wigeon
#

Anyway, you gotta remove the 2mb of allocated memory.

#

This is gonna run hella smoother after.

plucky vine
#

Unsure of how to do that. I've already eliminated most of the arrays being recreated over and over

dusty wigeon
#

What is creating 2mb ?

#

Did you manage to do it in sequential ?

#

It might give you an idea of what is happening.

#

Maybe there is something with Jobs that are not working as you are expecting.

plucky vine
#

Well, in my noise generater I've got the voxel data, then the mesh generater got vertex and triangle data

dusty wigeon
#

The voxel data is recreated each frame ?

plucky vine
#

Oh it is

#

I'm blind

bleak citrus
#

splat

plucky vine
#

Well, that trimmed it down to 1MB

#

Found another source being data.data = nativeData.ToArray(); working on fixing it

#

Got rid of all of it. GC Alloc now at 0B

bleak citrus
#

😄

#

now you can add lots of garbage back in

#

getting down to zero allocations is kind of fun

sand acorn
#

PAIN

sand acorn
#

nativeData.CopyTo(data.data), it does not make garbage

sand acorn
#

until you realize your new lines of code generate more garbage than before....

bleak citrus
#

or are garbage

sand acorn
regal olive
sand acorn
#

thank @bleak citrus , he made me realize that method existed

karmic surge
#

I am trying to use a nuget package in unity.
I tried NugetForUnity package, to install automatically, it fails (split or spanned not supported)
googling this, shows it is a connection problem of some sort.
So I downloaded the the nupkg and took the runtimes and put them inside Plugins directory inside Assets
I copied .lib and .dlls as well.

I am getting references errors when I try to use the package, any ideas?

bleak citrus
#

"connection problem of some sort"?

#

"split or spanned not supported" sounds like a problem with an archive

karmic surge
#

more importantly, why would copying the dlls to Plugin folder not work? is there an extra step?

#

I was able to install other libraries with no issues.

karmic surge
#

solved the issue, by downloading the dependencies manually as well and copying everything.

urban warren
#

Is there a way to reference a NativeArray in a field in a job in a way that would allow for nesting?

public struct GroupedElements
{
  public NativeArray<Nodes> Nodes;
  public NativeArray<Edge> Edges;
}

public struct GroupProxy
{
  public int StartIndex;
  public int Count;
  
  // I want this to be a 'reference' to the struct, so I can have a NativeArray<GroupProxy>.
  public GroupedElements Elements;
}
rapid osprey
urban warren
# rapid osprey You can't have NativeArray inside another NativeArray but you can have a UnsafeL...

Yeah, I am aware of the limitation of nested NativeArrarys. So in this case, I would need to have the Nodes and Edges NativeArrarys be UnsafeLists?
Basically, I am just trying to make it easy from my GroupProxy to access the the nodes and edges it controls.

NativeArray<GroupProxy> proxies;

proxies[i].GetNode(0);

// IN GroupProxy
public Node GetNode(int index)
{
  return Elements.Nodes[StartIndex + index];
}
#

All proxies would 'reference' the same GroupElements

rapid osprey
#

Yep changes it to UnsafeList and it should works exactly the same. You need to allocate it and dispose it like a NativeArray but there is no protection for read and write access. But the root NativeArray should take care of permissions.

urban warren
rapid osprey
#

Just to clarify my point @urban warren

it should works exactly the same
There is one thing you need to keep in mind. UnsafeList are copy by values contrary to NativeArray so for example:

NativeList<int> a = new (Allocator.Temp);
NativeList<int> b = a;
b.Add(1);
a.Length == b.Length // True

UnsafeList<int> a = new (Allocator.Temp);
UnsafeList<int> b = a;
b.Add(1);
a.Length == b.Length // False

Since the length is copy every time even if the pointer point to the right buffer, the length will defer. So the TL:DR: Don't copy the UnsafeList and always access it through the NativeArray unless you know what you are doing.

Lost multiple hours with random crash because I disposed a copy and not the original UnityChanBugged

urban warren
#

Thank you very much for the info. Would have lost a lot of time trying to figure out what as going on haha

frigid cliff
#

hey guys, i have a function that takes a looong time to process. i have a texture i have to go through every pixel of, and the lag increases exponentially with resolution, freezing the game for several seconds at the 2048x2048 resolution i have it at right now. i could, maybe, find a way to reduce the lag, but i think a healthier option is to make unity do a bit of the loop every frame, to slightly reduce the FPS until it's done, rather than freezing the game entirely. are there any common ways to do this in indsutry that's good coding practice? i heard about using coroutines or async/await, but those dont seem to take lag into consideration whatsoever, only using a set interval. i assume unity must have something that makes this easier - does anyone have any ideas?

urban warren
frigid cliff
#

okay, will do

#

unfortunately this is a student project due in about two weeks so i cant do compute shaders

#

but i might be able to do Jobs - what is that?

rapid osprey
rapid osprey
#

If you are not too familliar with multithreading I advice you to read a little bit about it first

urban warren
gritty python
#

Is there a way to strip assets on dedicated server build?

#

My dedicated server build is huge and i don`t need any asset at all

dusty wigeon
gritty python
dusty wigeon
#

I do not know. There must be other solution for ECS. (or not, and you would then understand why ECS is crap)

gritty python
#

I see

rapid osprey
plucky vine
#

So, when setting mesh vertices, I am able to use a NativeArray<Vector3> as a parameter to Mesh.SetVertices(). But I'd like to be able to do the same for the triangles. Thing is that it doesn't have an option for that. Is there any way to make it work without generating garbage?

grand tiger
plucky vine
#

Is there anything wrong with doing something like this? mesh.SetIndices(triangles, 0, triangles.Length, MeshTopology.Triangles, 0);

grand tiger
dusty wigeon
#

You are talking about Moves.Add(new Moves(move.Base)); ?

dusty wigeon
#

It is pretty straightforward. You cannot directly convert a Moves into a NewMove.

#

You need to do new NewMove() instead of new Moves()

#

Or use a Moves list instead of a NewMove list.

dusty wigeon
#

This means that you need to define a constructor... This is beginner level coding. Ask in #💻┃code-beginner

#
[System.Serializable]
public class NewMove
{
    [SerializeField] Move_Data moveBase;
    [SerializeField] int level;

    public NewMove(Move_Data moveBase, int level)
    {
       this.moveBase = moveBase;
       this.level = level;
    }

    public Move_Data Base
    {
        get {return moveBase;}
    }
      public int Level
    {
        get {return level;}
    }
}
#

Your whole architecture seem flaw also.

grand tiger
dusty wigeon
#

You might want to ask your self what are Moves and NewMove.

#

What is the purpose of NewMove ?

native nebula
#

So I'm generating 3 different textures: districtNoiseMap (1), districtColorMap (2), and districtRoadMap (3). I have one texture I'm using called districtMap that's used during the noise, color, and road methods. I would like to change districtNoiseMap to the districtMap at the end of noise so it gets the texture information at the time, respectively for the other maps. Currently, it copies districtMap to each of them at the end of districtRoadMap instead of individually. Any advice here? Here's my code: https://pastebin.com/VSUHacpi

#

basically districtMap is being copied as the same thing instead of individually each time

sly grove
#

You're creating a new texture which is good.
But then on the very next line you're throwing your Brand New Texture in the garbage

#

districtColor = districtMap;
this line of code means "point the districtColor variable at the same texture object that the districtMap variable is pointing at"

#

So from that point forward, both variables are referring to the exact same texture object.

#

If you want to completely copy a texture the simplest approach is probably:
Texture2D districtColor = Instantiate(districtMap);

native nebula
sly grove
#

In fact I highly recommend never using Instantiate on a GameObject reference

native nebula
#

I think it's because of how many tutorials use instantiate for GO

sly grove
#

It's almost always inferior to calling Instantiate on a particular component

native nebula
autumn topaz
#

im using a command system and I need a command which sets a values of scripts to something else so that you can change it in the console e.g setting player jump height. is there a way to do this without ref feilds?
public class SetCommand<O,S> : ICommand{ S item; S newValue; public SetCommand(ref S item,S newValue){ this.item = item; this.newValue = newValue; } public CommandResponse Process(){ item = newValue; return new CommandResponse("modified value",true); } }

sly grove
sly grove
#

It will make your life easier

native nebula
#

How would you suggesting generating the prefabs? I have a "tileAsphaltPrefab" which is a 2D game object, sprite renderer, and has a "TileBase" component on it that gives the tile unique properties and functionality.

I was basically planning on reading the texture pixel by pixel and instantiating the prefabs according to each color

sly grove
#

It will enforce that only prefabs with the TileContainer script can be assigned and it will avoid the GetComponent you do after

native nebula
#

That's implying the game objects are already there before play though

sly grove
native nebula
#

Wouldnt' I need to assign the TileBase component?

sly grove
#

Yes

native nebula
#

to the GO

sly grove
#

Which you can do

#

With the prefab

native nebula
#

without instantiating the prefab itself?

sly grove
#

Who said not to instantiate the prefab?

native nebula
sly grove
#

I didn't say don't instantiate the prefab

native nebula
#

but you said not to instantiate game objects?

sly grove
#

I just said instead of using a GameObject reference use a reference directly to your component

native nebula
#

hmm

sly grove
#
public TileBase prefab;

void Spawn() {
  TileBase instance = Instantiate(prefab);
}```
native nebula
#

yeah

sly grove
#

See how we skip the pointless middleman GameObject reference?

#

No need for GetComponent

#

And we know for sure the prefab has the component on it

#

Because we aren't allowed to assign it if it doesn't

native nebula
#

So I'm still confused on how it will instantiate the TileBase game object prefab. You're saying I can just do the TileBase itself, then since the TileBase is in the GO prefab TileBasePreab it'll also instantiate that prefab? With the SpriteRenderer, etc?

sly grove
native nebula
#

Gotcha

#

Okay

#

Yeah that simplifies the code by a lot then

sly grove
#

You just get to make your code simpler

native nebula
#

ey

#

yes

sly grove
#

And you never accidentally assign something that doesn't have the component on it

native nebula
#

Your previous suggestion worked 🙂

#

Thank you. Would this impact performance in a positive manner too? I assume so since GetComponent scans all components on the GO

sly grove
#

I believe the performance will be slightly better yes

#

Not a guarantee. I think it's worth it even if not though

#

I gtg now good luck

native nebula
#

Thanks for your advice 🫡

bleak citrus
#

now add predatory microtransactions

native nebula
bleak citrus
#

not with that attitude!

native nebula
wispy plume
#

I am procedurally generating a town, building up houses from many small objects and then combining meshes. Same with streets, sidewalks etc... Is anyone familiar with " Resource ID out of range in SetResource: 1129047 (max is 1048575) " ? The first number could be any number, it is more about the SetResource range, or what might cause it

granite viper
lethal frigate
#

One message removed from a suspended account.

wispy plume
#

Seems I have to many assets in my project

granite viper
#

Hm

#

They shouldn't need to be loaded all at once

#

It seems more likely your mesh combining script is leaking resources somehow

sly grove
livid kraken
untold moth
#

*flashbacks from shader debugging.😦

idle mantle
#

Hey,

I want to create a script that analyses an audio file and outputs a list of the BPM and Time Signature changes

Any ideas?

#

I know, this is an advanced issue, but if you have any advice, I'm willing to take it

untold moth
#

I'd look at libraries that already implement something like that

idle mantle
wispy plume
runic tendon
#

Horde games like Vampire Survivors have a lot of bullets and enemies. Is DOTS necessary for that or is simple pooling enough?

dusty wigeon
upbeat path
scenic forge
#

There are software made specifically for this purpose, and even their results are pretty hit or miss, usually requiring to double/half the result BPM.

sage radish
#

I want to calculate the axis aligned bounding box around a rotated box. Is there a better way to do it besides calculating each corner position and finding the min and max of those?

plucky laurel
sage radish
plucky laurel
#

is that using unity components?

#

renderer.bounds will give you that

sage radish
#

No, it's purely in code. You can think of it like this:

public struct Box
{
    public Vector3 Position;
    public Rotation Rotation;
    public Vector3 Size;
}
plucky laurel
#

im not sure you can skip min/max then

#

you can bounds.Encapsulate() each corner 😄

sage radish
#

Oh well, I was hoping I wouldn't have to brute force it. Sphere and capsule were so easy in comparison :(

karmic surge
sage radish
#

Also brute force, I guess, just fewer variables.

karmic surge
sage radish
obsidian glade
regal olive
#

Hi i am not sure if this is advanced but is this an efficient way to do this? My game is a typing game where words fall and you have to type it until word does not disappear. I am creating a list of objects that are visible on the screen by making a box and making its size approximately fit te screen. Then I check whether anything that player typed matches first letter of any word on the screen.

desert panther
#

Let me share a ghost story written in C# 👻

sage radish
obsidian glade
sage radish
#

I think this should be right.

private static readonly float3[] _boxCorners =
{
    new(-1, -1, -1),
    new(-1, -1, 1),
    new(-1, 1, -1),
    new(-1, 1, 1),
    new(1, -1, -1),
    new(1, -1, 1),
    new(1, 1, -1),
    new(1, 1, 1)
};

private static AABB GetBoxBounds(float3 position, float3 size, quaternion rotation)
{
    var bounds = new AABB(position, position);

    for (var i = 0; i < 8; i++)
    {
        var corner = _boxCorners[i];

        var worldPosition = position + math.rotate(rotation, corner * size);

        bounds.min = math.min(bounds.min, worldPosition);
        bounds.max = math.max(bounds.max, worldPosition);
    }

    return bounds;
}
sleek marsh
#

looping through 8 vertices sounds a lot faster than any trigonometry based alternative if im being honest

sand acorn
#

Hello there, is there any fancy way to dispose native arrays? "using" seemed clean but I realized using it on all stuff was causing leaks, I was not using some arrays there so I decided to dispose manually

scenic forge
#

Wdym by using is causing leaks?

#

using is just syntactic sugar to insert .Dispose() calls for you.

#

It prevents you from forgetting to dispose and causing leaks.

rapid osprey
bleak citrus
#

I hadn't thought of that!

#

I guess you'd need to move the move monotonous work out from components and into a job

#

like moving everyone towards the player?

#

you'd lose out on the data locality, but I guess that'd still be a speedup

rapid osprey
silver lark
#

Hey guys,
I have a quick question regarding Unity and shared memory with the web.

I am able to make a shared array between Unity and the web by creating an array and initializing an array at that location in Javascript.
However, i am not able to do it the other way arround, so have an array in javascript and share that with the Unity side. I tried passing the pointer to the array and initializing a NativeArray in Unity but no luck so far.

Any thoughts on this issue? or known ?
Thanks in advance guys!

sly grove
silver lark
#

@sly grove Thanks for your answer, sadly that wont work since the data is needed on both sides.

sly grove
#

Let's say you have an array on the C# side:

  • You access it as normal in C#
  • For the JS side you expose GetElementAt / SetElementAt / GetSize functions and call them.
silver lark
#

The data is needed in webAssembly just to do calculations on, the data is owned there and changed there.
Then we need the 'entire' buffer to be able to visualise that data

sly grove
#

Which side needs it "closer to the metal" and which side can deal with a little awkwardness?

#

When and where is the visualization happening?

silver lark
#

the rendering is instanced rendering in unity class

flint geyser
#

I heard in new versions of Unity you could specify that the field you are [SerializeField]ing has to get an Asset. Is it true? How to do it?

bleak citrus
#

i have not heard of that

hexed meteor
#

Anyone know off the cuff why this code doesn't seem to work?

#

Particle system code always confuses the eff out of me

sly grove
#

em.SetBurst(0, emc);

hexed meteor
#

you're a legend

#

Got another somewhat advanced programming question... I have this method which returns a random point within a given mesh. I'm using it to spawn debris rigidbodies when a destructible object is destroyed, so I just pass in the meshfilters mesh and it works.
The only problem is that neither scale nor rotation seem to be respected. Is this an easy fix or should I rather redesign my whole approach to the problem?

hexed meteor
#

I had the feeling it was related to that... but I don't know how to implement that operation in this method, do I multiply the xyz values with the objects transform xyz that I inject the mesh from?

austere jewel
#

You have to pass in the transform

#

the mesh alone is not enough information to get a position relating to an object

hexed meteor
#

any chance I could get you to show me what that would look like ?🥲

austere jewel
#

GetPosInMesh(Mesh mesh, Transform transform)
...
return transform.TransformPoint(etc);

hexed meteor
#

Something like this?

austere jewel
#

yes

hexed meteor
#

🎉 thanks so much man

#

oh boy something is very wrong though

#

perhaps its transform direction ?

#

yeah that was it

#

awesome!!

austere jewel
frigid cliff
#

okay, this is doozy, but i know my favourite and most helpful discord server can handle it!
I'm designing a UV-painting mechanic where player actions fill in pixels on an "overlay" UV map, imagine like powerwash simulator (except bad!)

there are a couple things that require looping through every pixel in the textures, one of which being "if the pixel on the BASE uv map is clear (alpha 0), then it won't be used on the dirty UV, because it would be unfair to make a dirty pixel that won't appear on the actual mesh.

this used to work just fine, however, in adjusting the code to use RawPixelData, a glitch occurs that I fail to diagnose:

#

this is the clean, and the dirty UV, when it works perfectly - but it's laggy

#

so, to be clear, it's going through every pixel of the colourful UV, and if the alpha is 0, the dirt won't be applied there. the resulting image is what you get when you try and make EVERY pixel on the image dirty - only the non-clear pixels shine through

#

with my new system, however, this is the result:

#

some pixels are still clear, but not in the right order at all. i assume this has to be something to do with the formatting of either my texture or the rendertexture i use, but I can't imagine how.

#

relevant bits of code:

NativeArray<Color32> finalDirtPixelData = finalDirt.GetPixelData<Color32>(0);```
cleanUV is the colorful image, taken as a texture directly via unity's material system given an image in the asset folder. this is the import settings i use for that:
#

finalDirt is a texture created using this code:

Texture2D finalDirt = new Texture2D(resolution, resolution);

RenderTexture.active = renderDirtTexture;
finalDirt.ReadPixels(new Rect(0, 0, resolution, resolution), 0, 0, false);```
#

so if there any obligatory format settings that make it match the "properdicemap"'s, i'll have missed them, as texture creation settings are left as default in code.

#

finally, in case it's useful, this is the settings i use for the renderTexture for the dirt (i render the dirt using a render texture, as it was simpler than moving decals pixel by pixel)

#

i know that's ... a lot. almost spam-worthy, but if anyone has any ideas i'd MASSIVELY appreciate the help - i've been at this for hours, it's 2am, and i'm gonna have to prioritise my own health soon

#

this can of course wait until the morning, so if anyone has any experience, there's no rush to help out. thank you so much in advance

sage radish
frigid cliff
#

uh, same thing i would assume, im pretty sure i showed all the data for texture2d so i dont know where else i would have changed iot

frigid cliff
steep rose
#

Hiya!

I've made a Job and i'm attempting to use NavMeshQuery. NavMeshQuery, however, requires a NavMeshWorld. I cannot pass a NavMeshWorld to the job because Jobs cannot take in references.

How am I supposed to use NavMeshQuery within jobs?

viral flame
#

I'm trying to do something where I have "sensors" that take in the list of objects from a sphereoverlap or etc, but I want to know which ones WERE in the list and which ones will be.
Is there a non GC way to do that, or do I just have to deal with linq.except or something?

The reason I want to have those is so I can trigger events when something is added/removed from the list.

i.e.

private List<T> items;

void doUpdate() {
var newItems = [....];
var itemsToKeep = list.Union(newItems);
var itemsToAdd = newItems.except(list);
var itemsToRemove = list.except(newItems);

// do loops to add/remove.
}
untold moth
#

Everything Linq does, you can do manually without GC allocations(most of the time)

viral flame
#

Yeah, I thought about that, i.e. have a some fixed length array thing that can handle it, may work, I'll mess with it at some point.

I'll probably need to implement it via 2 hashsets or etc to prevent looping over the whole things as well... but yeah, been banging my head for a min so lol.

#

Yeah, it's just trying to balance number of loops and dealing with addressing things and etc vs the small GC that I may not even need to worry about.

#

Anyway, thanks for thinking / looking.
I'll go internet diving again soon.

karmic surge
#

I removed the inheritance for my class from MonoBehavior,
hit play button in the editor,
then got an error about my class using Texture2D.
so I derived from MonoBehavior
and now everytime I hit playbutton it crashes.

Those are the logs

#

I tried restarting, but did not work.

untold moth
#

Machine learning?

karmic surge
# untold moth Machine learning?

yes I am doing machine learning, but I don't understand, why would it start crashing all of sudden I have been using this code for 2 days with no issue, have not done any updates, of any sort. So it puzzles me.

untold moth
#

Kinda hard to tell without knowing what that library is doing, but here's the stack trace:

Managed Stacktrace:
=================================================================
      at <unknown> <0xffffffff>
      at System.Object:wrapper_native_00007FFC42B72E10 <0x00126>
      at Microsoft.ML.OnnxRuntime.InferenceSession:Dispose <0x003fe>
      at Microsoft.ML.OnnxRuntime.InferenceSession:Finalize <0x000a0>
      at System.Object:runtime_invoke_virtual_void__this__ <0x0018b>
#

It seems like the InferenceSession:Finalize method is called from the C# side, so maybe look into that method and where you invoke it.

#

Just a guess, but the error looks like a segfault🤔

#

InferenceSession pointer is probably not initialized.

karmic surge
#

I kinda suspect unity is at fault here, I am to remove the code, create a new object and attach it back, I really suspect Unity did something wrong during compilation.

karmic surge
untold moth
#

From the call stack function names it sounds, like it tries to dispose of a previous session, but it doesn't exist. Why it's doing it is a different question 🤷‍♂️

#

Finalize is called when an instance is cleaned up.

#

It could be disposed from the C# side when you create a new instance and the old instance is destroyed.

karmic surge
#

Well, I am not sure what was the issue, but I followed my sense, created a new script(which is the exact same old code with different class name), deleted the old object and the old code
attached this new one to it, and it works.

#

I really hate it when I don't understand why things happen in code..

tall ferry
#

It gets weird when you remove monobehaviour from a class that had it. I believe there are a few other issues that appear as well sometimes

karmic surge
#

noted,
Thanks everyone

untold moth
karmic surge
untold moth
#

Basically C# and C++ side went out of sync and that caused the issue.

untold moth
karmic surge
#

Make sense,
Yeah I did not mean you have to look inside it for me, I just meant the library documentation should be online for each method.
+
The problem is solved, so that is good ig.

karmic surge
untold moth
#

I think it's really just a case of disposing your C++ instance between assembly reloads.

#

Since, if you don't, you'll gonna lose a reference to it => potential memory leak.

karmic surge
#

Thanks

idle mantle
scenic forge
#

I was trying to hint that it's very unlikely anyone can give you a simple answer, or an answer at all.

#

It's one of those things you need to research a lot, and the result is probably worthy of an academic paper.

idle mantle
#

Oh, ok

#

Yeah, I think I know how to do it, but it will require a lot of time and effort

#

^^ I was just looking for directions or something
Thanks for your help

karmic surge
#

So I just noticed:
in my crash logs, I found some warnings
about a possible performance issue:

2023-04-25 10:20:52.8186999 [W:onnxruntime:, session_state.cc:1136 onnxruntime::VerifyEachNodeIsAssignedToAnEp] Some nodes were not assigned to the preferred execution providers which may or may not have an negative impact on performance. e.g. ORT explicitly assigns shape related ops to CPU to improve perf.

how do I get unity to log this when it is running?
I want to make sure, that this warning was not caused due to the error in the crash.

untold moth
#

I don't think that's related to your previous crash though.
And didn't you say it's fixed?

analog nexus
#

I have properties on various objects where the getters and setters read/write to PlayerPrefs keys using a const string for the key value

#

I am wondering if I can abstract that into a reusable class or something because the code looks the same everywhere

#

even better would be if I could use the name of the field/property as the key itself through some reflection magic

#

maybe through some implicit conversion trickery

#

in c++ I could make it a template with a const char* template parameter for the key name and operator= overloaded I think

upbeat path
#

part of the solution

analog nexus
#

yeah, something with nameof and maybe caller context or what its called

untold moth
#

You'll still need to define the properties.

analog nexus
#

I had chatgpt generate something using implicit conversion which doesn't work of course. when you convert T to KeyValueProperty<T> you lose the originals string KeyValueProperty<T>._key

#

maybe something with a overloaded indexer could be used to collect multiple settings

#

🤔

karmic surge
untold moth
#

As for the log settings, give me a sec.

#

Ok, so it was a bit different from what I remembered. The best you can do is expand the stack trace logging I guess.

karmic surge
#

Thanks ^^

untold moth
karmic surge
untold moth
#

You look in the log file I guess.🤷‍♂️
That being said, it's very rare for something to appear there and not appear in the console. Unless it's some unity diagnostic info.

rose hearth
#

In an rts game where players have access to a map editor, how would one go around to generating the minimap texture? what method can i use to make it take a screenshot of the map and display it in an ingame map browser without instantiating the map itself?

sly grove
untold moth
#

Or render it at runtime with an additional camera and replacement shaders.

mellow plinth
#

Question, in ECS. Are the ECS-components serializables? I mean, I noticed there is no "Add component" button in the inspector to add them, but if I add them by code, will they be serialized in the prefab/scene? Or must I always have an Authoring MonoBehaviour that is serialized instead?

bleak citrus
#

you definitely can't add them in the inspector because that's a game object, not an entity

mellow plinth
#

But if I open the Entities Hierarchy and use the entities inspector, there is not add component either @bleak citrus

untold moth
mellow plinth
#

So, my only option to store data in a prefab or scene is by using MonoBehaviours?

untold moth
#

Scriptable objects too. But you're not limited to storing data in prefabs and scenes.

#

Depends on what kind of data you want to store and for what purpose

mellow plinth
#

But you're not limited to storing data in prefabs and scenes.
What you mean?
I know about Scriptable Objects, but they aren't exactly bound to a prefab or so

#

I just wanted to avoid having to create authoring and baking classes to put data in prefabs

untold moth
untold moth
karmic surge
untold moth
karmic surge
#
2023-04-25 10:20:52.8186999 [W:onnxruntime:, session_state.cc:1136 onnxruntime::VerifyEachNodeIsAssignedToAnEp] Some nodes were not assigned to the preferred execution providers which may or may not have an negative impact on performance. e.g. ORT explicitly assigns shape related ops to CPU to improve perf.
2023-04-25 10:20:52.8204394 [W:onnxruntime:, session_state.cc:1138 onnxruntime::VerifyEachNodeIsAssignedToAnEp] Rerunning with verbose output on a non-minimal build will show node assignments.
NullReferenceException: Object reference not set to an instance of an object
  at Yolov7net.Yolov7.Inference (UnityEngine.Texture2D tex) [0x00085] in C:\Users\karee\Unity\EVA\Assets\Scripts\MLDetectionLib\yolov7.cs:154 
  at Yolov7net.Yolov7.Predict (UnityEngine.Texture2D tex) [0x00007] in C:\Users\karee\Unity\EVA\Assets\Scripts\MLDetectionLib\yolov7.cs:66 
  at App.GetPredictions (UnityEngine.Texture2D tex) [0x00001] in C:\Users\karee\Unity\EVA\Assets\Scripts\App.cs:66 
  at webcam_manager.Update () [0x00014] in C:\Users\karee\Unity\EVA\Assets\Scripts\WebCamScript\webcam_manager.cs:53 

(Filename: Assets/Scripts/WebCamScript/webcam_manager.cs Line: 53)

@untold moth

#

2023-04-25 10:20:52.8186999 [W:onnxruntime:, session_state.cc:1136 onnxruntime::VerifyEachNodeIsAssignedToAnEp] Some nodes were not assigned to the preferred execution providers which may or may not have an negative impact on performance. e.g. ORT explicitly assigns shape related ops to CPU to improve perf.
this was what got me curious and it was right above the crash

#

which is why I wanted to know if this was because the crash or because of something else (but such thing seems to be more of a constructor related issue, rather than crash issue)

untold moth
karmic surge
#

Btw, all what I am asking here, is whether I can increase the logging level so I do get such warnings (I assuming it is a warning, because of the W before it)

I am not asking how to resolve it, because that is definitely specific to the library I am using.

untold moth
#

In this log, the crash is probably caused by Plastic judging from the stack trace

karmic surge
#

I never heard of this,
but googling seems to suggest it is related to the Version control, which supports the theory it was because of inheriting and removing the inheritance

untold moth
#

Are you even using Plastic?

#

To me it sounds like a random ui bug.

karmic surge
#

I don't even know what it is, and even the first few hits on google search did not find it, I had to put "plasticSM" in the search

untold moth
#

Then Uninstall the package.

untold moth
karmic surge
untold moth
#

It's named Version control, since it's the default unity solution for version control now

karmic surge
untold moth
#

The null reference exception is suspicious too, but I'm not sure if it's related to the crash.

NullReferenceException: Object reference not set to an instance of an object
  at Yolov7net.Yolov7.Inference (UnityEngine.Texture2D tex) [0x00085] in C:\Users\karee\Unity\EVA\Assets\Scripts\MLDetectionLib\yolov7.cs:154 
  at Yolov7net.Yolov7.Predict (UnityEngine.Texture2D tex) [0x00007] in C:\Users\karee\Unity\EVA\Assets\Scripts\MLDetectionLib\yolov7.cs:66 
  at App.GetPredictions (UnityEngine.Texture2D tex) [0x00001] in C:\Users\karee\Unity\EVA\Assets\Scripts\App.cs:66 
  at webcam_manager.Update () [0x00014] in C:\Users\karee\Unity\EVA\Assets\Scripts\WebCamScript\webcam_manager.cs:53 
#

It's probably more related than the warning that you're obsessed with though. 😄

karmic surge
#

Thanks, will look into it.

untold moth
#

The reason that warning does not appear, is probably due to the way they output it. Probably outside the unity logger.

mellow plinth
#

In ECS, how people organices scripts into folders? Have you a folder for all components, other for all bakers, other for all authoring, other for all systems, or you have a folder per type, and in that folder you store the component, baker, authoring and system related to it? Or you put all that in a single file (not sure if Unity would like that thought)?

potent cove
#

I have an intersting problem i'm running into:
I have a ui-only project. My first scene is a "control panel" that manipulates visual information. I additively load a second ui-only scene, the information being manipulated, over the top of this (circled in red). My problem is I would like to constrain this additively loaded scene to a rectangle (green in my screenshot). How could I accomplish this? Previously, I was capturing the second scene into a render texture and simply loading it over top of the green rectangle, however I would like to drag the individual elements around to reposition them and I couldn't discover a solution doing this within render textures.

Other important side note: the additively loaded scene is also outputted as a capturable NDI source for stream graphics overlays, hence why I would like to be able to reposition the elements

nocturne mica
#

Hi everyone,
I am trying to make something like "Townscaper" but on a simpler square grid.
Anyone out there to guide a little bit?
I have seen videos by the creator of townscaper but he didn't explained that much, it was just overview.

flint sage
#

Look up wave function collapse it's the underlying technology

arctic flame
#

My player has forces to affect its movement horizontal (right-left in a 2d game) and velocity with its jumping

#

I get a bug where when i jump normally it jumps just fine but when i am walking and then jump it makes enormous jump

#

How to fix?

#

Is using both not only one ok?

plush hare
#

@arctic flameHow do you expect anyone to help you without posting your code?

#

This also isn't an advanced question.

lavish sail
dapper cave
#

has anyone gotten coroutine that stop on the first yield return null? timescale is 1 and component is active

#

looking for a solution

bleak citrus
#

why do you think the coroutine has stopped?

#

have you put log statements in it?

dapper cave
#

yes, and also a breakpoint after yield

sly grove
dapper cave
#

controlling game state with UnityEvents is turning out to be a terrible idea because rider can't trace those.

#

that's what it was. one of these silly things was being called at the end of the frame

austere jewel
mellow plinth
#

Ok

tropic vigil
brisk stone
#

I have a list of Vector3, that represents something like waypoints. I have an enemy that has to follow this path. Can I make my enemy go more smooth? For example, this is a path I have. My Enemy goes on the black path. Can I make it go something like the red path? All my waypoints are in the center of each tile in a tilemap.

novel wing
upbeat apex
upbeat apex
somber swift
brisk stone
#

Thanks, i will try all of the above

zinc night
#

Hey. How would I authenticate a player to an external rest api? I am using Steamworks in my game. Can I send the steam auth ticket to the rest api and somehow validate it?

hushed sparrow
#

Hello, I have made an abstract variable class called WorldObject, and I have a class that inherits from it called Character. I have a WorldObject variable in another script that I want to reference as a Character, but simply doing (Character)TargetObject is not working. How can I go about this?

sly grove
hushed sparrow
#

yes but this variable is a WorldObject and I am trying to reference it as a Character

sly grove
#

but if you want to access the specific fields from Character in a context where you're using WorldObject then you've made a misstep somewhere in your data design

#

not saying it's not possible

#

just that - it's usually better if you don't do it.

#

Can you explain the specific thing you're trying to do?

#

Like what data or function are you trying to access and why

hushed sparrow
#

Character Variables have a List of Limbs, and I am trying to access the List of Limbs in my Basic Attack Function. However, the way it Targets the Opponent is by referencing the Tile it is stored in, which is stored as a WorldObject variable and thus, the Basic Attack Function identifies the Opponent as a WorldObject

sly grove
#

so this code is inside Character?

hushed sparrow
#

yes

sly grove
#

Ok so I guess that's not terrible - i'd do something like this

hushed sparrow
#

well not the Attack function no thats a seperate script

#

TakeDamage is a function inherent to the WorldObject variable but limbs also have their own specific TakeDamage function

sly grove
#
void Attack(WorldObject target) {
  if (!(target is Character targetChar)) {
    print("Target wasn't a character!");
    return;
  }

  var limbs = targetChar.limbs; // or whatever
  // etc..
}```
sly grove
hushed sparrow
#

it is handled by the class it inherits from, not the character class specifically yes

#

but the limb damage specifically is done within the limb data

sly grove
#
public override void TakeDamage(float amount) {
   base.TakeDamage(amount);

   myLimbs.TakeDamage(amount);
}``` or something like this?
hushed sparrow
#

basically like that yes

sly grove
#

right so

#

do it that way 😉

#

then you have no need to do any casting or anything

hushed sparrow
#

but it wont let me reference the WorldObject as a Character for dealing damage to the Limbs stored in the Character Variable

#

that is what im trying to do here lmao

#

I have attempted to reference it as (Character)TargetObject but apparently unity wont let me :p

sly grove
#

that can work as well but it will cause an error if it's NOT a character

#

the is keyword lets us handle both cases gracefully

hushed sparrow
#

I could do this but idk if it will reference the same worldobject

sly grove
#

you have no need to access the limbs externally

#

the Character class does it all internally

#

this would be code in Character

#

overriding the base TakeDamage function

hushed sparrow
#

yes but the takedamage function isnt abstract, and i dont want it to always deal limbdamage

sly grove
#

hence the base.TakeDamage bit

hushed sparrow
#

yes but how would I be able to make a check for if it should deal limbdamage or not if its just a virtual function that inherits from the normal TakeDamage Function?

hushed sparrow
sly grove
#

There are many possible approaches here

hushed sparrow
#

this only applies however if the weapontype is an axe, should probably point that out

sly grove
# hushed sparrow this only applies however if the weapontype is an axe, should probably point tha...

Here's a few options for how you can do it without doing any casting:

abstract class WorldObject {

    public virtual void TakeDamage(float amount, float limbDamageChance = 0) {
       // normal take damage functionality here
       // Character can override this to do the limb damage logic taking into account the chance of getting limb damage
    }
}

abstract class WorldObject {    
    public virtual void TakeDamage(float amount, bool limbDamage) {
        // normal behavior here but can be overridden in character to actually account for the limb damage
    }
}

abstract class WorldObject {    
    public abstract bool HasLimbs { get; } // each subclass will have to implement this and tell us if it has limbs

    public virtual void TakeLimbDamage(float amount) {
        // does nothing by default but can be overridden in Character
    }

    public void TakeDamage(float amount) {
        // normal damage logic
    }
}```

the idea with the last one would be like:
```cs
if (targetObject.HasLimbs) {
    targetObject.TakeLimbDamage(amount);
}
else {
    targetObject.TakeDamage(amount);
}```
#

In all of these cases Character itself is the one responsible for choosing which limb takes the damage internally

#

and accessing the limbs, etc.

#

This is better adherence to SOLID principles.

#

and encapsulation

hushed sparrow
#

I see, I'll see what I can do to take these into consideration and see if I can get them to work properly

#

I made a new function for taking PartDamage for objects which have Physical Parts to them, such as Limbs, Mechanisms, Etc... for handling this sorta thing.

versed coyote
#

I fetch an image via MemoryStream and use the byte[] to create a sprite from it likes this:

            private static void CreateSprite(byte[] imageFile)
            {
                var texture2D = new Texture2D(928,1232);
                texture2D.LoadImage(imageFile);
                var sprite = Sprite.Create(texture2D, new Rect(0, 0, texture2D.width, texture2D.height),new Vector2(0,0), 100f); 
                var path = "Assets/_Game/Cards/Imported/illustration.asset";
                AssetDatabase.CreateAsset(sprite, path);
            }

This all works fine and looks good until I start playmode. The illustration.asset suddenly is somewhat removed. The file exists but there is no image behind it anymore and also the preview in the editor is gone.
Any idea what is happening here? Very strange and unintuitive behaviour.

versed coyote
sly grove
#

try calling SaveAssets

versed coyote
jolly token
versed coyote
plush hare
#

After that, yes. You can validate players this way.

steel snow
#

Im trying to optimise a boid sim, wondering what is the best optimisation for checking neighbouring agents? is a dictionary<hashID,list<boid>> sufficient ? where hash id is is a spatial index or are there better techniques

sly grove
steel snow
#

right now i just check all agents and check their distance to the agent

sly grove
#

what's the context here? Is this ECS? GameObjects?

steel snow
#

if below a cohesion range then they consider their alignment / avoidance

#

oh, gameobjects

#

as you can guess checking all agents for each agent doesn't scale too well 😄

sly grove
#

Maybe using the physics engine with trigger colliders to maintain HashSets of nearby boids?

#

then you get the benefit of the spatial acceleration structures in the physics engine for maintaining your neighbor collections

steel snow
#

oh true

sly grove
#

Alternatively - Physics.OverlapSphereNonAlloc

steel snow
#

can those be used without the rigidbody component ?

sly grove
#

OnTriggerEnter can't

#

Failing the physics engine - write your own spatial acceleration structure e.g. quad/octtree

steel snow
#

my current (though not yet working attempt) is to put them into bins on a 2D grid:

        private void AddToBin(Agent agent)
        {
            int range = Mathf.FloorToInt(agent.Radius / _binSize);
            var posX = agent.Position.x / _binSize;
            var posZ = agent.Position.z / _binSize;
            for (int z = -range; z <= range; z++)
                for (int x = -range; x <= range; x++)
                {
                    int hash = (int)(posX + _binSize * x + 3 * posZ + _binSize * z);
                    if (!_boidSpatial.ContainsKey(hash))
                        _boidSpatial.Add(hash, new());
                    _boidSpatial[hash].Add(agent.Index);
                }
        }
#

though this creating a lot of lists over time as they move to new areas which makes a lot of run time allocations

fresh salmon
# steel snow my current (though not yet working attempt) is to put them into bins on a 2D gri...

You'd most likely pre-allocate the grid and the "bins" once before the game starts. I would go for a HashSet<Agent>[,] or HashSet<Agent>[][] (whatever is the most performant, I never remember which one of the two array structures- jagged or 2D), and then use your Floor+division to know which cell your object is in.
Then you can easily loop through the grid 3×3 cells at a time to compute whatever you want here

gleaming lichen
#

Hey guys, can I talk about compute shader here ?

untold moth
scenic forge
dark bolt
#

I hope this is the right channel for this. Let me know if it's not and I'd be happy to correct it. I've been encountering these messages since this morning. It seems to be appearing quite randomly. I tried closing and reopening unity, and it seems to be gone until it randomly reappears again. I am using the latest URP LTS version. Does anyone know anything about this bug?

Unity pretty much randomly starts spamming these 3 messages which seem to also temper with my scripts on runtime.

Error Type: TLS Allocator ALLOC_TEMP_TLS, underlying allocator ALLOC_TEMP_MAIN has unfreed allocations, size 2832

Warning Type: Internal: Stack allocator ALLOC_TEMP_MAIN has unfreed allocations, size 2832

Message Type: Allocation of 256 bytes at 00000217D0980A50 with different numbers.

I looked it up, there are many forums about it and some of them are quite old but no answers. The contexts also seem pretty random but a few of them were about terrain, which haven't even touched. Anyone seen this one before?

Thanks! I can follow up with any necessary information just lmk.

#

!bug

thorn flintBOT
#

🪲 To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.

📝 If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click ‘Report a problem on this page’!

💡If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.

For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting

dark bolt
#

hm I'm guessing it's already been reported but still exists.

upbeat path
dark bolt
#

There were no call to action. Only told me I could debug; To Debug, run app with -diag-temp-memory-leak-validation cmd line argument. This will output the callstacks of the leaked allocations. Someone had already done this in the forums which, as it says only outputs more text that I don't understand.

#

pretty new thread

sand acorn
dark bolt
#

Actually yes. What am I doing wrong?

sand acorn
dark bolt
sand acorn
#

if you are not disposing it or you are disposing it after their expected life time, those errors will appear for sure

sand acorn
#

if its an allocator.Persisten dispose it OnDestroy

#

if it is a temp job, dispose it right after you dont need it

dark bolt
plush hare
#

So I'm trying to figure out how to save a "snapshot" of an animator in time

#

basically I need to take an animator with a blend tree, pack the data up, send it over a network, and reconstruct an animator frame exactly how it was sent. I just can't figure out what I need

sand acorn
#

you can change the unity version if the error persist or live with it

formal lichen
#

I'm trying to use a Dictionary<Type, object> moduleDictionary;
Problem is, when I use it on an inherited type, it doesn't find the object instance. Is there a way to get the object instance by the parent type?

#
// The instance type is of ChildModuleType : ParentModuleType and it doesn't find it
// since the Dictionary key is of type ChildModuleType
var test = (ParentModuleType)moduleDict[typeof(ParentModuleType).GetType()]; ```
devout coyote
#

Casting

sage radish
devout coyote
#

Now that I read it again, I don't I quite understand your question + your code, you have a dictionary with child types as a key?

#

And in your code you try and use the parent type as a key, but thats not a child type, so I would make sense that its empty right?

formal lichen
#

I'd like to get the instance of the TestChildModule type by only referencing the TestParentModule type when indexing the dictionary. I think this is a chicken and egg situation unfortunately

sage radish
bleak citrus
#

this certainly isn't going to work with an ordinary dictionary: you are looking up a value by a specific Type value

bleak citrus
#

you could use a multi-dictionary and insert a value for every single parent type all the way up to System.Object

formal lichen
#

Oh god

bleak citrus
#

that's essentially what you're asking for

formal lichen
#

My quick workaround is just iterating through the dict

#

foreach (var item in moduleDict.Values)
{
if(item.GetType() == typeof(TestParentModule))
{
// here is my item
}
}

bleak citrus
#

isn't that going to only work for exact type matches, too

#

typeof(ChildType) != typeof(ParentType)

#

you can use System.Type.IsSubclassOf

#

note that it returns false if the types are equal

dusty wigeon
# formal lichen

It seems like you should review the whole process.

Why do you need to stock object in a dictionnary ?
Why does it needs to be by type ?

sage radish
#

TIL there are undocumented internal Unity event methods:

private void Awake() => Debug.Log("Awake");
private void OnEnable() => Debug.Log("OnEnable");
private void OnDisable() => Debug.Log("OnDisable");

private void __internalAwake() => Debug.Log("Internal Awake");
private void OnEnableINTERNAL() => Debug.Log("Internal OnEnable");
private void OnDisableINTERNAL() => Debug.Log("Internal OnDisable");

These are invoked in this order:

Internal Awake
Awake
Internal OnEnable
OnEnable
OnDisable
Internal OnDisable
#

Used by some editor code and by the Timeline package to guarantee initialization before user's code.

dapper cave
#

regarding the performance of accessing nativearray in main thread, is there a way to speed this up? I remember a chat that concluded that nativearray were much slower than arrays due to extra piping.

bleak citrus
mellow plinth
#

Hi, question:
I was reading about how fluids are simulated, and found that the most common form is Smoothed Particle Hydrodynamic algorithm, which basically split a liquid into tiny spherical drops and applies collisions into each one...
And then I thought, isn't that just the same as instantiating a bunch of sphere colliders and use them as water drops?
With GameObjects it may be expensive the overhead of each drop... but with ECS...
Would that work? Has anybody did that? Why not?

pseudo mauve
#

Anyone have any ideas how I could effectively set a timeout on a function call without multithreading? I’m building for WebGL so can’t multithread, and the function I’m calling sometimes runs forever (which is a valid use case / working as intended)

sand acorn
#

The best way of doing simulations of thousands or million of objects is by using the GPU instead, so Compute shaders

#

but it can be significantly harder to get working

mellow plinth
#

So for small numbers it may work, nice

#

But if I use a custom code (to run in GPU) instead of rigidbodies and colliders, how then will the drops of water interact with other objects?

#

Should they have the rigidbody and collider, but ignore collisions of other drops of water and instead do those collisions in the GPU? Would that actually help perfomance?

sand acorn
sand acorn
#

but if im not wrong, you can retrieve data from gpu, and you can probably use this data to make colliders on cpu (honestly this sounds horrible, there is probably a way to simulate collisions directly on the gpu, probably writting your own collision solution)

sand acorn
mellow plinth
#

Otherwise, if you want your water be able to interact with non-water objects, how would you do it?

sand acorn
sand acorn
mellow plinth
#

Ok

#

Thanks

mellow plinth
#

Unrelated question, can ECS be used for 2D? I see there is a 2D entities packages, but it hasn't been updated in more than a year, and seems to not work with entities 1.0. Is possible to use ECS for 2D without that package?

untold moth
#

From the look in the docs, it's a package for "project tiny" and mostly it just provides Unity Editor visualization for 2D content as the docs say.

#

Physics might be trickier. You either will need to use the 3d unity physics for ecs, write your own physics simulation, or do a hybrid approach mixing gameObjects with ecs.

sand acorn
#

How can I reduce my procedural mesh precision from float32 to float16?

I found a class for this but the mesh was still displaying float32

dark bolt
dark bolt
#

😭

sand acorn
dark bolt
#

yeah

#

ah right I have version controlling lemme work it out

sand acorn
dark bolt
#

i forgor 💀 ,

sand acorn
#

just go into the package manager and install the recomended versions

dark bolt
sand acorn
sand acorn
dark bolt
#

I just checked the urp verison from previous commits and manually set it in the manifest. hope that's fine

dark bolt
sand acorn
dark bolt
#

aight thanks

honest thunder
#

hey guys, working on a game for a university class and started building it so i could let some friends play test it. Building works fine, but when i get in the game and click play, some of the scripts arent working, some values arent saved and some scripts are half working... not really sure what to do.

upbeat path
orchid marsh
honest thunder
#

i think i figured it out, no worries.

regal olive
#

I'm having an issue with my terraingeneration script

when the terrain finishes generating, and the player tries to break a block, unless the player places a block himself, it's not breaking. why?

https://gdl.space/acihilopim.cs

dusty wigeon
regal olive
#

check SpawnObject

dusty wigeon
#

I mean, the only reason why it does not work is because of that from what I see.

regal olive
#

it's not even giving an error

dusty wigeon
#

But I see you are using new Vector2(x + 0.5f, y + 0.5f) as a key

regal olive
#

and when It tries to break it

#

(it as in the player)

#

wait

#

nvm lemme make this more clear

#

when the player tries to break a block

#

that is created by the terrain generation

#

and not placed by the player himself

#

it doesnt give an error when it breaks

dusty wigeon
#

I understand everything.

regal olive
#

when I try to break it again

#

it gives an error

#

even tho its there

#

it says the gameobject doesnt exist

#

when it's still there

dusty wigeon
#

That you didnt say though.

regal olive
#

yea

#

should I test it and give you the exact error?

dusty wigeon
#

It would help

#

Is it an Null or a out of bound ?

regal olive
#

gimme a min

#

lemme test the game and give u the error

dusty wigeon
regal olive
#

oh wait hold on
the error comes from something else

#

it doesnt have to do with breaking

regal olive
#

omg

#

I'm an idiot

#

I should have used

#

Vector2Int

#

or Vector3Int

#

not Vector2/Vector3

#

wait let me try that

thin nova
#

I have an invisible sphere in my scene. I want the parts of planes that are in this sphere to get a specific color. Anyone knows what the best way to do this is?

bleak citrus
#

So you need a shader that highlights where there’s an overlap

#

I have a shader graph that does that. I even understood it at one point!

thin nova
bleak citrus
#

it's for the HDRP

#

i can double check when i go get my laptop

thin nova
#

Amazing, thank you so much!

bleak citrus
#

I think I set the material to be transparent and to only render backfaces

#

iirc it compares scene depth to the distance to the sphere's surface, and draws if the sphere is further away

thin nova
#

Ahh okay perfect, I will try and see if it works for me.

sand acorn
#

hello there, how beneficial can it be to change from float3 to half3 or from int to byte (using very small ints here)? is this worth doing for optimization purposes? I found a forum talking about it which is 10 years old, and it said it was not worth it and it could apparently be worse than sticking to standard units

#

for example here, what if I use byte instead of int?

static readonly int[] XUVOrder = new int[] { 2, 3, 1, 0 };

fresh salmon
#

For 4 values, not much

#

If you had thousands of them, it would start to make sense to go to smaller types, but here there's no need

sand acorn
#

and what about here, these arrays can get larger

sand acorn
fresh salmon
#

Arrays have a fixed size. C# arrays, I mean. Native arrays no idea

tropic vigil
# sand acorn hello there, how beneficial can it be to change from float3 to half3 or from int...

Smaller variables are beneficial if you need to cut data size in half, which might be handy for save files or sending network packages. However those values are sometimes annoying to use, e.g. when you add short to short you will end up with an int 🙈. Also, plenty of methods don't have alternatives made for smaller variables, so you would need to create your own alternatives or cast them every time.

On the other hand, halves are quite often used in shaders.

fresh salmon
#

But by their coloring I see they're structs, so even less memory inefficient because they get freed faster when execution exists the scope

#

By faster, I mean immediately

sand acorn
fresh salmon
#

Casting in itself does nothing in memory. What's slowing it is checking if the cast is valid

sand acorn
tropic vigil
sand acorn
fresh salmon
#

Nah there's three of them

#

And the compiler would be intelligent enough to get rid of the casts entirely when it sees that the calculation result falls in range of a ushort

#

For JIT'd code at least, I don't know if Mono uses one nor if it is as smart as .NET core's

fresh salmon
#

But it's insignificant, as always use the profiler to see what goes wrong if something goes wrong

#
  1. Make it work
  2. Make it look good
  3. Make it performant
sand acorn
#

I will move float2 to halfs2 and such, to check whether or not I see any major improvemnt

bleak citrus
#

i'm not sure about changing from floats to halves

#

CPUs have floating point units to do float math

#

do they also have hardware for halves?

#

i'm not familiar with that

dusty wigeon
#

Usually, you change to half for memory size.

scenic forge
#

Also keep in mind of memory alignment, when you read a byte from memory it's not just reading that one byte, but (on a 32 bit machine) all four bytes aligned to the nearly memory address of multiples of 4.

#

But these are the micro optimizations I wouldn't bother, there are plenty more impactful optimizations you can do.

#

For example, maybe instead of reallocating those lists and arrays for every run of the job, allocate once and reuse them over and over.

sand acorn
#

how do I clear a native array without disposing it?

scenic forge
#

Well before you can even think about reusing them, does the job that use these containers run sequentially (one always has to finish before next one starts) or in parallel?

sand acorn
#

the rest of the 10+ containers are used by a single job

fleet shell
#

I'm using my own physics solution for my player movement (not using rigidbody or character component). My component moves every FixedUpdate and for performance reasons FixedUpdate runs 20 times per second.
Rigidbody kind of works the same where the character moves every FixedUpdate, but then it also interpolates the character every frame to achieve smooth movements.
Does anyone know how I can recreate this interpolation? Just lerping the positions isn't enough to achieve a smooth result

scenic forge
#

Sure, and if you are currently allocating new containers for every run of the job (which seems like you are judging by Allocator.TempJob), then you should look into just allocate once and reuse them.

#

As for zeroing an array, there's a low level native container utility that does it.

sand acorn
scenic forge
#

Correct.

devout coyote
#

Do you really need to empty the array? Can't you just overwrite all the data, might save you a little bit of time

sage radish
# scenic forge For example, maybe instead of reallocating those lists and arrays for every run ...

Reallocating is usually faster, because TempJob allocated arrays are faster to read/write to than Persistent arrays.

One thing that can speed up allocation of big arrays is to specify new NativeArray<float3>(Allocator.TempJob, NativeArrayOptions.UninitializedMemory), but only if you know your job is going to overwrite the array completely. If you need it to start with zeros, then you can't leave it uninitialized.

sand acorn
sage radish
devout coyote
#

Essentially the same as what @sage radish but then for a persistent array

scenic forge
#

Maybe things have changed since I benched it a few years back.

sage radish
scenic forge
sand acorn
#

Sorry if those were kind of beginner questions, I am fairly new into the world of job system and optimizations

scenic forge
#

One other performance thing to look out for that's specifically relevant for Job and Burst, is passing large structs

#

Pass by ref if the struct is "large" (even 12 bytes is large enough for this to see some benefits)

sand acorn
scenic forge
#

Enums in memory is just their backing data type.

sand acorn
scenic forge
#

No, an int enum is just an int which is 4 byte, and pass by ref wouldn't do much.

sage radish
#

Default backing type is int, which is 32 bits, while ref is 64 bits (on 64-bit computers)

plucky laurel
#

also ref semantics

sage radish
#

But something like Matrix4x4 is 64 bytes, or 512 bytes.

sand acorn
plucky laurel
#
class Foo
{
   int a = 0;
   void Bar()
    {
       Method(ref a);
       // a == 5
    }
    void Method(ref int i) => i = 5;
}
sage radish
# sand acorn So why would using ref be better on large structs here? the higher the bits the ...

I'm not sure about Burst, but at least in Mono, there's a certain threshold where a more expensive copy operation has to be performed, I think at about 40 bytes. This shows up in the Profiler as String.memcpy. It's not related to string, the memcpy function just happens to be defined in there:
https://forum.unity.com/threads/string-memcpy-in-profiler.119166/

bleak citrus
#

it makes little sense to pass an enum by ref unless you want the called function to mutate the value

#

big structs make a lot of sense to pass by ref

scenic forge
#

Structs are value types, when calling another function it has to make a copy onto the stack, so if you are passing an int it will have to copy the value of that int (4 bytes), but if you are copying a large struct that's 512 bytes, that's a 512 byte copy.

bleak citrus
#

you can use the in keyword to pass by ref but prohibit modification

#

very handy

sand acorn
scenic forge
#

Passing by ref just copies a pointer to that variable onto stack, for a 64 bit machine it means always 8 bytes no matter how big the struct it.

bleak citrus
#

C#'s ref stuff is pretty cool

#

it ensures that you don't have stale references

#

(by severely limiting how you can use them)

mellow plinth
sand acorn
untold moth
#

Maybe not as simple as I made it sound.

sand acorn
sand acorn
#

you can always take a look at how the physics package was made and come with your implementation

mellow plinth
#

Oh, ok

sand acorn
#

Hello there, according to our conversation earlier, I am trying to reuse a single native list instead of creating one each time, but my problem right now is that I cant find how to clear a native list, I already found a method for clearing native arrays but not native lists

#

what is happening right now is that my list is growing each time with the previous data

#

I am using the same method I use with native arrays but I pass my list with. asArray()

#

Oh wait.....

#

List does have a Clear method built in lmao

scenic forge
#

Yeah and it should be very efficient, since that should just be setting the count to 0 and that's it.

sand acorn
#

now, how can I pass my arrays as ref? I cant find anything related

scenic forge
#

For a native array?

sand acorn
scenic forge
#

I'm not sure if a single native array struct is large enough to be benefited from passing with ref, since it contains just a pointer to the memory (well and container safety stuffs, but I'm not sure if those are striped in production build)

#

Someone correct me if I'm wrong about that.

#

But passing with ref in general is just slapping the keyword on both the caller and callee side.

sand acorn
sand acorn
#

this should be the right way of putting the ref into right?

[ReadOnly] public ref NativeArray<half2> Zero;

thin mesa
#

Passing by ref is done on the method not the field, you make the method parameter ref

scenic forge
#

That's a struct ref field, not the same as ref parameter.

sand acorn
scenic forge
#

I think you can use ref in ctor parameters, but you shouldn't need to.

#

Are you creating the job struct over and over every time?

sand acorn
scenic forge
#

Yeah then it doesn't matter if you are just creating the job struct once and reuse it.

sand acorn
#

Okay, let me try

thin mesa
# sand acorn Oh so this can be done in a constructor then?

for a nativearray i imagine it's pointless considering it's just a pointer and length so even passing by value doesn't copy the entire array. if you create it using Allocator.Persistent you don't need to worry about using ref to pass it around at all

sand acorn
#

By the way ,I just faced this issue where I need to define this native array size and it is going to be different each time because the lenght has to be different, so what should I do here? maybe changing the native array by a nativeList so I can resize instead of allocating a new array?

#

this is what Im doing right now, but seems very ineficient

textureLoaderInstance.UVmap = new NativeArray<float2>(textureLoaderInstance.UVDirectionsCache.Length * 4, Allocator.Persistent);

sand acorn
thin mesa
#

wdym by "clearing"?

scenic forge
#

A native array struct contains the pointer to the memory, not the memory itself; no matter how big the native array is, it's still the same size.

thin mesa
#

actually whatever you mean by that, it probably doesn't matter since if you're disposing it then it needs to be recreated no matter what and if you're just assigning the default values that doesn't matter because the actual struct is really just a pointer and the length so passing that around points to the exact same block of memory

scenic forge
#

As for your problem of needing a different size native array on each run of the job, using a native list works but eh that's kind of using the wrong tool for the job.

#

Lists are modeled to support append and thus also support resizing, and you are not utilizing append but only the resizing aspect.

#

You can wrap the resizing logic into your own struct, it's trivial (if requested size > current size, reallocate; otherwise reuse current native array)

#

Better yet, if you know the upper bound of what you job needs, you can just allocate the upper bound.

sand acorn
thin mesa
#

yeah that didn't really clarify, but like i already said it doesn't really matter anyway

sand acorn
#

So let me check if I understood, ref is only necesary if the content is resized? for example refs can be useful on native lists instead?

#

Srry, I am new to this concept of refs

scenic forge
#

It doesn't have to be C#, these concepts are universal in almost all languages, but after learning them you should be able to really understand what C# struct, ref, Unity native containers, are doing under the hood.