#archived-dots

1 messages Β· Page 177 of 1

fluid kiln
#
        {
            entityManager.AddComponent<NetworkStreamInGame>(entity);

            var req = entityManager.CreateEntity(); //THIS ONE IS DELETED AUTOMATICCALY
            entityManager.AddComponentData(req, rpc);
            entityManager.AddComponentData(req, new SendRpcCommandRequestComponent { TargetConnection = connection });

            entityManager.DestroyEntity(entity); //I HAD TO ADD THIS
        }).WithoutBurst().Run();```
#

Well now I do see it doesn't make sense that I add NetworkStreamInGame if I delete the entity on the same frame

viral sonnet
#

i see, yes you need to delete this one

fluid kiln
#

What's the point of NetworkStreamInGame, I think this one is just used for the GoInGameRequest, but not necessary on other RPCs

viral sonnet
#

it inits the ghost streaming

#

basically nothing works without it

fluid kiln
#

But it's a singleton right?

#

We add it to the Network Connection entity

viral sonnet
#

no it's on the connection entity

fluid kiln
#

exactly

viral sonnet
#

do you use a GoInGameRequest like in the sample?

fluid kiln
#

Yes

viral sonnet
#

then you don't need NetworkStreamInGame - remove the WithNone and the add

fluid kiln
#

But NetworkStreamInGame needs to exist on the connection, it's an initializer, I don't need to create one for every RPC I make

#

Yup, got it

viral sonnet
#

and add .WithNone<SendRpcCommandRequestComponent>()

fluid kiln
#

Ha yes

#

Otherwise it'll loop

viral sonnet
#

exactly

fluid kiln
#

good catch

viral sonnet
#

what's weird about this system is that it creates the same comp. at which point are you creating ChangeTargetRequest?

fluid kiln
#

I have an input system, where upon a left click, it raycasts, if it finds a targettable ghost, it creates the ChangeTargetRequest, but I suppose now that you mention it I could directly create the SendRpcCommandRequestComponent entity

#

I kind of just abstract these few lines of code

viral sonnet
#

yeah, do that

fluid kiln
#

But instead of creating a new entity

#

I can just AddComponent<SendRpcCommandRequestComponent>

#

Makes sense

viral sonnet
#

this is my create code in a monobehaviour

fluid kiln
#
    {
        EntityManager entityManager = EntityManager;
        Entity connection = GetSingletonEntity<NetworkIdComponent>();

        Entities.WithStructuralChanges().WithNone<SendRpcCommandRequestComponent>().ForEach((Entity entity, ref ChangeTargetRequest rpc) =>
        {
            entityManager.AddComponentData(entity, new SendRpcCommandRequestComponent { TargetConnection = connection });
        }).WithoutBurst().Run();
    }```
viral sonnet
#

var localNetworkEntity = group.GetSingletonEntity<NetworkIdComponent>();

#

and group is ClientSimulationSystemGroup

#

you don't need a system to add the TargetConnection

#

it should work though

fluid kiln
#

Yeah makes sense. But that means everytime I want to send this RPC, I should write

CreateEntity
AddComponent ChangeTargetRequest with ghost hash
AddComponent SendRpcCommandRequestComponent -> targetconnection = GetSingleton<NetworkIdComponent>
viral sonnet
#

yeah

fluid kiln
#

I could create an extension method for that

#

Alright cool, thanks that kinda clarifies the whole RPC thing a lot

#

I do need a system to receive it tho?

#

on the server

viral sonnet
#

sure, you already have it

fluid kiln
#

Yeah yeah

native marsh
#

i will send dot

#

.

blissful gorge
#

Just wanted to celebrate a little bit. I'm trying to build a Burst-compatible Linq library. Was struggling with making a deferred, stack allocated, Enumerable , but I finally figured it out with some generic-foo.

tight blade
#

whaaat, are you for real?

#

@blissful gorge whats the strategy there? is it like stack based?

amber flicker
#

@blissful gorge sounds like you're exploring some interesting places! Just in case - cuz it caught me out - make sure you test it in a build as the editor can con you into thinking generics are working when they don't in practice.

coarse turtle
#

https://github.com/VictorNicollet/NoAlloq I remember seeing this for Span<T> support sometime ago for linq, not sure if it'll work with burst, but maybe instead of Span<T> , a ptr to the collection might work πŸ€”

tight blade
#

anyone know if theres a way to pass native arrays into Entities.ForEach jobs as writeable?

#

or do I have to use the lower level apis for that?

#

I have this native array thats like a buffer of past positions that is the coordination point between 2 systems. one system reads from it offset backwards, and the other one writes to it

deft stump
#

I am confused on how to raycast

north bay
#

What's wrong?

coarse turtle
#

anyone know if theres a way to pass native arrays into Entities.ForEach jobs as writeable?
@tight blade

var native_array = new NativeArray<T>(n, Allocator.TempJob);
Entities.ForEach((Entity e, in SomeType c0) => {
  native_array[c0.Value] = some_data; // where c0.Value is probably some ID
}).WithDeallocateOnJobCompletion(native_array).Run/Schedule();

// You might need WithDisableParallelForRestriction if you need to do some kind 
// of looping to write on multiple threads but you may overwrite your data if 
// you're not careful
tight blade
#

ah, thats interesting. So, this probably isnt correct, but I'm actually intentionally using the native array persistently

#

its a static member of a class that both systems have access to

coarse turtle
#

Hmm not sure if you need SharedStatic<T> for burst related things, but I think you can do:

var localCopy = StaticClass.SomeNativeArray;
Entities.ForEach((...) => {
  localCopy[n] = some_value; // Do something here
}).Run/Schedule();
viral sonnet
#

how can a system foreach pick up entities that have a prefab component? they are auto filtered and I don't know how to change that

deft stump
#

uhm...

#

WithAll<Prefab>()

viral sonnet
#

thanks, I tried WithAny

#

it works WithAll

amber flicker
rough crown
#

Is there a physics Job safe API to use without converting game object to entities? I'm trying to make a SphereCast.
Edit: nevermind, I found SphereCastCommand that serves this function

deft stump
#

so I have a question on the ECS sample on raycast

zinc plinth
#

?

deft stump
#

I'm confused on the IgnoreTransparentClosestHitCollector

#

like, what does it do specifically aside from its namesake

zinc plinth
#

huh I have no idea, never used this

deft stump
#

hrmmm

#

okay what does filter do?

stone osprey
#

its me again πŸ™‚ Lets say our progress bar ingame is represented by a entity inside the ecs, it simply has a progress and location component... so it can get spawned by its own. But the player/mob/structure should define the exact location of the progress bar... A player has its progress bar besides him, a structure at the top and a mob at the bottom... any idea how we may realize this ?

fluid kiln
#

I feel like you could work this out with prefabs

#

If the progress bar is a child of the object with the good location, you can choose to hide or display it instead of spawn it

stiff skiff
#

Why is it its own entity?

fluid kiln
#

Or you have a child who's transform is the bars spawn point and you use that to spawn it on its location

stiff skiff
#

Instead of a component defining an entity has a progress bar

deft stump
#

so I'm casting a ray

#

but how do I filter out entities that I dont want it to detect?

fluid kiln
#

Use the filter

#

Your physics shape have a "Belongs To" field that represents what category they're in

#

When you raycast, in the CollisionFilter you can specify categories to hit or ignore

stone osprey
#

That could work some sort of script on a gameobject that defines the progressbar canvas, where it belongs to... @stiff skiff Because i want to have full controll over it and thats only possible if its a own entity

deft stump
#

@fluid kiln what if I just want to check if certain entities has certain tags?

fluid kiln
#

Probably shouldn't work with tags in ECS, not even sure if they're transfered over when they are converted to entities

deft stump
#

not that kind of tags, I mean, certain components (empty components are called tags)

fluid kiln
#

Ha good to know

deft stump
#

but yeah, is there way to do it? filter out entities being hit by the ray that have, say, ExampleComponent attached to it?

fluid kiln
#

I would have a system that adjusts the Belongs To field of all PhysicsShape in your world

#

Cause afaik you can only filter raycast using the categories

#

Are your tags static or do they change during runtime?

deft stump
#

static

fluid kiln
#

In that case can't you just manually set the Belong To field in the inspector?

deft stump
#

I can but... it feels like a pain in the ass to set up all these tags and then NOT use them in physics other than batch updating.

fluid kiln
#

What's your use case?

#

That could work some sort of script on a gameobject that defines the progressbar canvas, where it belongs to... @stiff skiff Because i want to have full controll over it and thats only possible if its a own entity
@stone osprey Let's say your structures/characters etc have a ProgressBarLocationComponent with a position, you can have a system that places the progress bars and updates their "progress" every frame

deft stump
#

uh... it's simple.
I have 3 entities.
the first has a PlayerControlledTag on it.
the second has SupportTag
the third has AIControlledTag on it.

assume that the PlayerControlled entity casts a ray and it's meant to hit the AI controlled one. But the Support entity is in the way.

#

@stone osprey you want to make a canvas some sort of a child to the entity?

fluid kiln
#

I would definitely go the Physics Category way

#

That's basically what they're made for

#

There's no problem with the tags being only use in your batch updates

deft stump
#

well what if my tags are not static?
I keep switching up my PlayerControlled entity with my Support entity. and vice versa
I have to update my Belongs To filter each time I switch?

fluid kiln
#

Yeah you'd have a system that updates your physics shape accordingly

deft stump
#

uuuugh... so freakin tedious...

fluid kiln
#

It'd be cool if we could raycast with the same filters as like an entity foreach

stiff skiff
#

I feel thats over thinking it a bit. Progressbars arnt a "thing", just something you render. A component with progess and color field should be enough? You already have components for the position used to render the actual entity, all you might need extra is a lookup from entity type to offset to render the bar at relatively.

fluid kiln
#

@deft stump you could use CastRay() with the all hits override

#

Then you have an ordered collection of hit entities

#

THat you can filter with tags πŸ™‚

#

It might just be more costly

deft stump
#

god why is this not documented

#

and it's buried between layers of examples that's not commented right

fluid kiln
#

πŸ€·β€β™‚οΈ

deft stump
#

give me a freakin' explanation Unity!

fluid kiln
#

It's preview packages πŸ˜‰

scenic oracle
#

In DOTS physics, is there something special to do to make position changes play nice with the physic engine ? (Like using Rigidbody.MovePosition/MoveRotation in legacy physic)
I have a system that animate an Entity's Translation&Rotation, but each time it move it result in massive jitter on the joints that are tied to it.

fluid kiln
#

You'll want to set the velocity of the physics velocity component as long as you have a physics body attached @scenic oracle

#
        {
            //Add velocity but keeping vertical (gravity)
            float3 speedVector = movement.speed * direction.direction;
            velocity.Linear = new float3(speedVector.x, velocity.Linear.y, speedVector.z);

            //Prevent angular movement from physics
            mass.InverseInertia = float3.zero;
        }).Run();```
#

Don't mind my naming

scenic oracle
#

Does this work even if said entity is set as kinematic ?

safe lintel
#

yeah you can move an entity thats kinematic with its physicsvelocity component

scenic oracle
#

Sadly, I just tried and acting on the velocity instead of the translation doesn't remove the jittering.
Maybe Havok's joints are just as unstable as the previous physics engine's.

safe lintel
#

theres a demo that showcases this as the preferred way in the physicssamples

#

i dont think its anything special though. if its simple enough to showcase maybe make a post on the dots physics subforums to get the devs attention? no idea if these things are bugs, by design or just not properly implemented yet

tawdry lotus
#

is there a way to not explode if a singleton entity wasn't set yet? (for example, I'm in another scene), I am checking for query count to avoid get singleton to explode

#

but don't like the solution, had to add the check in multiple places, I can add an extension method I suppose, that checks for that before getting the singleton

#

like a TryGetSingleton(out ...) : bool or something...

coarse turtle
#

You can do in OnCreate

OnCreate() {
  RequireSingletonForUpdate<T>();
}
safe lintel
#

or ```cs
if(HasSingleton<T>())
//stuff

tawdry lotus
#

thanks! that was what I needed, didn't know there were singleton methods in the component system!! was using queries

#

thanks a lot

coarse turtle
#

Hmm what assembly definition has NativeArrayUnsafeUtility?

worldly pulsar
#

Editor\2020.1.2f1\Editor\Data\Managed\UnityEngine\UnityEngine.CoreModule.dll
According to Visual Studio

coarse turtle
#

ah thanks πŸ™‚

worldly pulsar
#

I have an array of prefabs at conversion time. The only way to convert them is to store the primary entities in a dynamic buffer, right? i.e. no way to put the entity prefabs in Blobs?

low tangle
#

if the reference doesn't go stale the entity is just a struct you can store in a blob

#

ie leave the auto filted out prefab component on it and dont destroy it

worldly pulsar
#

yea, there seems to be some Entity rewriting magic for component and buffer element fields

#

at post-conversion

low tangle
#

ah, chain a system to consume the dynamic buffer then?

worldly pulsar
#

what I want to do is put an array of entity prefabs in a blob, specifically avoiding dynamic buffers

low tangle
#

yeah I get that, but if you need to get around the rewriting logic for entity indices you might have to use the dynamic buffer as a inbetween

worldly pulsar
#

ah, you mean at the start of runtime read the buffer and reconstruct the blob?

low tangle
#

yeah, read the dynamic buffer of entities, destroy that buffer entitiy

#

use a unique key for lookup, since that will ride along conversion just fine

#

then you can use that key to lookup your blob

worldly pulsar
#

Probably will end up with something like this, was hoping for a less messy solution. Thanks

low tangle
#

conversion workflow is pretty brittle so you have to make due

deft stump
#

I am confused in Raycast example in unity...

#

why is this not called?

deft stump
#

okay so now I have this raycast script.

var raycastHits = new NativeList<Unity.Physics.RaycastHit>(Allocator.Temp);
Entities
    .WithAll<PlayerCurrentControllableTag>()
    .WithoutBurst()
    .ForEach((in Translation translation) =>
    {
        //HACK: use math.forward 
        var start = translation.Value;
        var end = start + new float3(5f, 0, 0);

        var raycastInput = new RaycastInput
        {
            Start = start,
            End = end,
            Filter = CollisionFilter.Default,
        };

        collisionWorld.CastRay(raycastInput, ref raycastHits);
        for (var i = 0; i < raycastHits.Length; i++)
        {
            var entity = raycastHits[i].Entity;
            if (HasComponent<EnemyTag>(entity))
            {
                Log(entity);
            }
        }
    }).Run();
raycastHits.Dispose();
#

now this is okay. if I only have 1 Enemy entity.
but what if I have 2 Enemy entities lined up. and I just want to hit the closest one?

#

hrmm I could just early out uuuugh.

deft stump
#

okay after a while of fixing unrelated bugs, I've returned to my original problem:
so I got the entity i want from casting the ray. so what's the most efficient way of manipulating ComponentData of the entity being hit by the ray without doing ecb?

opaque ledge
#

well its either you have to run Entity Manger directly, which means your system has to run on main thread and without burst or you have to use ecb

north bay
#

What's wrong with ComponentDataFromEntity?

deft stump
#

ComponentDataFromEntity can only be used in jobs right?
coz you'll have to pass GetComponentDataFromEntity

#

not sure, I only used that type once

#

well its either you have to run Entity Manger directly, which means your system has to run on main thread and without burst or you have to use ecb
@opaque ledge no other way like using a job?

#

I did get the entity i want

#

I just need to process that entity's stuff.

opaque ledge
#

well you could store that entity to native array and use it on a job after that physic job

#

you can use ComponentDataFromEntity inside ForEach lambdas as well since ForEach generates IJobChunk on background

#

you can also use GetComponent<T>, SetComponent<T> as well if you are inheriting from SystemBase

#

they are essentially "less code" version of ComponentDataFromEntity

deft stump
#

wait, I thought you can't use SetComponent without ECB

#

aaaaaargh

opaque ledge
#

ECB is only for structral changes, such as adding/removing components and create/destroy entities

#

changing component values is not a structral change

deft stump
#
collisionWorld.CastRay(raycastInput, ref rayCastHits);
for (var i = 0; i < rayCastHits.Length; i++)
{
    var entity = rayCastHits[i].Entity;
    if (HasComponent<EnemyTag>(entity))
    {
        //Log(entity.ToString());
        var health = GetComponent<HealthData>(entity);
        SetComponent(entity, new HealthData
        {
            value = health.value - 1
        });
        break;
     }
}
#

so I can do something like this?

#

argh it works T_T

fluid kiln
#

Are we just not supposed to use GetComponent with burst?

proven minnow
#

Can't see why we would't

fluid kiln
#

The ECB doesn't have that method

opaque ledge
#

if you need random access to a component yeah, you use GetComponent (or ComponentDataFromEntity if you cant/wont use ForEach lambda)

pliant pike
#

I swear I spend more time trying to debug problems with Unity than I do with my actual project

#

all the Unity packages namespaces have suddenly stopped being recognised by Visual Studio, things like entities, transforms, mathematics etc

coarse turtle
#

try regenerating the csproj files

#

should be in the project settings or preferences (I forget which exactly)

pliant pike
#

I think its to late, I updated the Entities package and now I'm getting a ton of errors cannot resolve packages are broke etc

hollow sorrel
#

yeap updating packages is hell

#

if one package has a dependency on another one that has an error then it'll error too

#

it's especially bad when you update unity and it automatically updates all your packages at the same time no matter if you want to or not

pliant pike
#

yeah I'm trying to figure out which one requires which version

hollow sorrel
#

might have to uninstall all dots packages and reinstall in order lol

pliant pike
#

yeah maybe

craggy orbit
#

any ideas as to why only entities at a certain child index of a subscene would break rendering? if i rearrange the order of gameobjects-to-be-entities in the subscene, only entities at child indices 31, 46, and 50 break like this. it might happen at other higher indices but i dont have enough entities in the subscene to test that. currently using HR v2 0.8.0 with URP 10.0 on Unity 2020.2b1 on a mac

deft stump
#

there's URP 10?

#

to the package manager!

craggy orbit
#

it's still in preview but it's much more stable than URP 9

deft stump
#

so urp 10 is for 2020.2

#

meh

craggy orbit
#

fixed the issue. something to do with me trying to use half precision material overrides. my solution is a little hacky but now im using float precision properties in a half precision graph

amber flicker
#
Unity Technologies Blog

The Unity Burst Compiler transforms your C# code into highly optimized machine code. Since the first stable release of Burst Compiler a year ago, we have been working to improve the quality, experience, and robustness of the compiler. As we’ve released a major new version, Bur...

stiff skiff
#

Anyone here have some experience with the DOTS mathematics random struct?

pliant pike
#

I had a brief attempt at it and then quickly gave up leahS

stiff skiff
#

I'm using random.NextFloat2Direction() * Distance which is magically returning the EXACT same value every time when I use them inside a Entities.Foreach

pliant pike
#

are you sure your able to use them inside a job

deft stump
#

I have a solution for that

stiff skiff
#

I'm using .Run and .WithoutBurst to be safe

#

When I use it multiple times within the ForEach it gives a different value every time

#

but the sequence every loop is the same

deft stump
#

you need to give it a seed

stiff skiff
#

It has a seed

deft stump
#

does the seed change?

pliant pike
#

like time or something

stiff skiff
#

the issue seems to lie with the capture in the Entities.ForEach

deft stump
#

like.... time.deltatime

#

aaah

stiff skiff
#

Seems the issue doesn't lie with the capture, but the copy by value

#
randomGenerator.InitState();

var random = randomGenerator;
Debug.Log($"2 {random.NextFloat2Direction()}");

var random2 = randomGenerator;
Debug.Log($"3 {random2.NextFloat2Direction()}");

var random3 = randomGenerator;
Debug.Log($"1 {random3.NextFloat2Direction()}");
viral sonnet
#

very likely that's the reason why schedule is so slow sometimes. Any usage of GetComponent without this attribute leads to hard syncs

stiff skiff
#

I forgot about the copy.

#

The issue is that the state gets changed only on the copy, the original stays the same

#

so next frame, the copy is made from the unchanged original, meaning the output will again stay the same

#

I could create the instance of Random inside the job, using something like time.ElapsedTime as the seed

#

But that would break things when scheduling in parrallel

pliant pike
#

there isn't really any time in the job though is there πŸ€”

stiff skiff
#

You can pass in the Time struct that the system has

#

Just capture it via a local variable var time = Time;

pliant pike
#

but that would be the current time before the job is started and it would stay the same throughout the job surely

stiff skiff
#

Thats fine

#

you just need a "unique" value for the seed

amber flicker
#

yea it only becomes more tricky when you go wide.. there was a useful syntax/web page I found for that.. will try and copy here in case it's useful

little moon
#

I use random like that:
"""
var random = new Random((uint) UnityEngine.Random.Range(1, int.MaxValue));
"""

stiff skiff
#

The timing master @amber flicker himself brings us knowledge

little moon
#

And then you can reference it inside ForEach

amber flicker
stiff skiff
#

@little moon Thats broken

little moon
#

Why?

stiff skiff
#

Random is a struct, which mean it will copy on capture

#

so any .Next you do inside the jobs, will update the state of the copy

#

The next frame, you'll be using the initial state again, copy it, etc

#

This is why, in the article above, you see the write back to the native array, which is required

viral sonnet
#

@little moon i do the same

little moon
#

But it will receive new random seed each frame

pliant pike
#

that tutorial looks great I might have to try using it in jobs, thanks Timboc

stiff skiff
#

@little moon If you do any ScheduleParrallel

little moon
#

Ah, that makes sense. I only ever used it with Schedule()

keen sorrel
#

Hello guys,
I wanted to ask you a question: I have an array with about 60,000 coordinates (x, y, z), these points if joined together give a 3d geometric shape, at the moment I was able to join them using only the LineRenderer. Can you think of any other approach I could try to generate a mesh?

zinc plinth
#

Just throw your vertex data in a new mesh, generate your triangles and boom

#

Generating your triangles will completely depend on how you generate your vertex data

#

So can't help you much o' that, idk the shape you wa't out of these

#

With that *

coarse turtle
#

Probably delauney triangulating if you want those coordinates to become a surface - if you're going down the mesh route (or even just using a vertex and index buffer with the appropriate shader)

stone osprey
#

How do we normally track collision events ? As far as i know unity mono behaviours have three different states : OnEnter, OnStay, OnExit... Lets say we want to check for those inside the ecs... Therefore we have 2 important components, collisions and collisionHistory... collisions stores the collisions this frame and the history those from the last frame. How do we detect those events now ? Do we simply iterate over all entities that are able to collide in order to compare "collisions" with "collisionHistory" ?

#

Or is there a smarter way ?

amber flicker
#

Rather than a collision history I'd maybe store an 'isColliding' bool per entity?

stone osprey
#

Ah alright... and once that flag changes we notify all involved entities about the state ? Enter/Stay/Exit ? But we still need to iterate over all those entities each frame, right ? Thats propably not that performant for a large amount of entities ^^

amber flicker
#

I'm unfamiliar with the unity physics sorry - ah here comes psuong πŸ™‚ (but it's basically stateless right? so I'd expect to get a collision from the physics world every frame that something collides?)

coarse turtle
#

lol - I'm not familiar with Unity's physics system also - but what I did was store their states as a bitflag in a hashmap for my own 2d physics lol

stone osprey
#

Im actually not using unity physics... im mostly asking that question for my server side implementation πŸ˜„

amber flicker
#

whether bool or tag is better will depend on your use-case - if it were me I'd maybe use a tag with a .Enabled bool in the hope that one day soon we get the .enabled backed components

#

or yea, you could use a hashmap - useful if you're doing any other processing over them potentially

keen sorrel
#

@zinc plinth is there a system to generate triangles automatically?

#

@coarse turtle delauney triangulating is used purely for 2d..

coarse turtle
#

Ah I didn't read the 3d geometric shape part - sorry

amber flicker
#

@keen sorrel not really dots but you'll probably need to do this yourself. Treating your points as unique verticies and creating an array of indicies for them - creating a triangle strip. Obviously unless you're points come from a mesh in a particular order there's no guarantee this will produce a nice mesh with lines going between the verticies you want. If you use a wireframe shader I guess you'll mostly be alright.

keen sorrel
#

@amber flicker thank you, I'm going to see the wireframe shader

rough crown
#

Hi, is there any way to make a spherecast using jobs without entities (normal gameobjects) and return multiple colliders? I've tried SpherecastCommand but it only returns one collider, I don't know if I could use physics scene inside a job and what would be the performance impact of doing so.

amber flicker
#

Does anyone know what the IJobChunk equivalent of CDFE is for managed types? It used to be something like GetComponentObjectsForEntity and I'm struggling to remember what it has changed to

#

dynamic something?

fluid kiln
#

How can I instantiate a prefab => entity during runtime?

amber flicker
#

It’s not really advised at runtime but it’s a matter of using eg GameObjectConversionUtility the EntityManager.Instantiate with the resulting entity

zinc plinth
#

this damn method should have a omega fat WARNING THIS METHOD IS SLOW AS FUCK

fluid kiln
#

Yeah not interested in using it 😦

zinc plinth
#

(talking about GOCY.CGOH)

fluid kiln
#

Should I just create an entity for each prefab on startup then?

zinc plinth
#

would be the best ye

fluid kiln
#

But there's an entity limit yeah?

zinc plinth
#

? no

fluid kiln
#

Also my entity debugger gonna be cluttered asf

#

nvm I was thinking of something else

zinc plinth
#

I have 260k entities in my scene without doing anything appart from my grid

fluid kiln
#

Okay cool, for some reason I had put in my head that a lot of "prefab" entities = bad

zinc plinth
#

maybe you thought of that because of the chunk count, but it's really fine even for like 100/200 diferent meshes

fluid kiln
#

Great πŸ˜„

#

How do I tell unity to create entities for every prefab in say a folder on startup?

zinc plinth
#

I know that if you put a go as field in a mb inside a go that's going through conversion the go in the field will turn into a prefab

#

but I don't remember exactly how that's setup

#

and I may tell bs on that, I didn't use this design pattern at all

fluid kiln
#

Yeah so I'd have to create a prefab manager with a list of prefabs mono, then have it converted

deft stump
#

is there a way to get the number of entities from a query instead of doing something like this

HexQuery = GetEntityQuery(typeof(HexTag));
var hexQ = hexQuery.ToEntityArray(Allocator.TempJob);
var size = hexQ.Length;
hexQ.Dispose();
dusky wind
#

What's the suggested way of creating prefab Entities that aren't actually in any active worlds?

opaque ledge
#

i think EntityQuery has a method called "CalculateEntityCount" @deft stump

#

@dusky wind what do you mean by not active in any worlds exactly @dusky wind ?

#

entities lives in a world so they must always belong to a world i guess

#

but i generally stash my entity prefabs to Shared Statics, so i can instantiate them inside a job, i guess you can use it like that to instantiate them for different worlds

dusky wind
#

@opaque ledge not simulated, rendered, and does not show up in EntityQueries

#

Only way I can think of is via Disabled components

#

But you'd need to remove the component on instantiated ones

#

Which sounds inefficient

opaque ledge
#

prefabs arent active

#

prefabs have a component tag called "prefab", they are not processed by Entity Queries unless you explicitly tell them to include prefab entities

dusky wind
#

Oh how do you specify that when manually converting in code?

opaque ledge
#

put prefab tag on it i suppose

#

if you are using IDeclaredReferencedPrefab in your authoring component and you are converting gameobjects they will be converted to prefabs, so you dont need to add prefab component manually

low tangle
amber flicker
#

what CurlyOne said was spot on but just fyi @dusky wind if you add it manually, be sure to add it to the whole hierarchy

stiff skiff
#

Do phyics IContactsJob still require the JobComponentSystem stuff, or are there example for the SystemBase yet?

sand sentinel
#

is New NetCode system in unity have a toturial .?

fluid kiln
#

Only the getting started guide

sand sentinel
#

ohh no .

fluid kiln
#

It's only in preview

sand sentinel
#

ok plase link

sand sentinel
#

thanke you bro .very much

stiff skiff
#

I've been trying to get the physics trigger job to work, andit simply refuses to trigger

#

with no debug information on what im missing 😒

fluid kiln
#

Yeah I gave up on it, I'm using PointDistance cast instead. But sometimes you have to use triggers -_-

stiff skiff
#

Tried searching github for usages of ITriggerEventsJob

#

But it sadly came back with a mixed bag of people using very old code, old code, and checking in the Library

#

Official "documentation" also has no info on events for triggers or collision

fluid kiln
#

Theoricaly speaking, how does one go about creating multiple unique behaviors in ECS? Let's say I have items that give different complex bonuses to a player, or a large number of abilities that have complex structure? If logic is always implemented in system, do I need one system for every ability, or should I find a way to abstract them?

#

Can anyone help me see out of the box πŸ˜“

amber flicker
#

Whether it's one system per ability, one job per ability or you can generalise what you're doing to fewer systems is highly dependent on your implementation details.

#

The only thing I can generally say is that if you're not manipulating a primitive type, there's almost always scope to abstract your system further.

#

Especially if it's not in the hot path, using e.g. HasComponent to branch on what tags are present can turn 10 jobs into 1.

fluid kiln
#

But like when I try to structure it in my head it doesn't make sense.

Let's say I have an ability called Fireball that deals 10 damage to a single target after a 2 seconds cast.
Fireball is an entity that has a damage component with a value of 10, a single target component with the target entity and a cast time component with a value of 2.

Another ability might be say, Healing Aura, that heals 10 health to every friendly creature within 3m of the caster every second and lasts for 10 seconds.
Healing Aura is an entity that has a component for each of these values.

Now the player triggers the Fireball spell. I create an entity called SpellCast with a component of caster entity, target entity, and spell entity.
I have a system SpellCastingSystem that retrieves the SpellCast. What do I do here? Do I have a super long Update containing a bunch of ifs => if(Spell HasComponent<Damage>) if(Spell HasComponent<Healing>) if(Spell HasComponent<Aura>)?

amber flicker
#

having said that, you want to iterate and refine your concepts - that is very much a lot of the hard work. Is healing anything but negative damage for example? All things that mix both spatial & temporal effects will be harder to make conceptually tidy and work in any combination.

#

Possibly from the above description you only have one ModifyHealth system?

fluid kiln
#

Okay yeah I like the abstraction of Healing and Damage

#

Thank for the link i'll check it out

#

Maybe my SpellCast system has a WithNone<CastingInProgress>()

#

It's clearing up, thanks for the help, I'll work on it

amber flicker
#

Yea, best of luck. The more you can reduce the concepts you're working with, the easier you'll find it to implement but it's still not easy. There are a lot of timing and priority issues - what happens if two players cast a drain health on each other, or one drain on another casting regen etc etc.

#

Combine with AOE, falloff and time spells for a good old bag of fun πŸ™‚

fluid kiln
#

That sounds like a lot of fun πŸ˜‚

#

Musty be really satisfying once it's all working tho

amber flicker
tight blade
#

alright so I'm kind of intimidated by lerping. Ive never really understood its use very well. specifically I've never gotten a feel for the practical guidelines surrounding the 3rd parameter. Its something akin to "the amount of time it would take to go the entire way to the destination" right? So would that mean if I wanted to lerp to the destination, would I discount that argument value by the time since the last frame or something?

#

you know what Im gonna rtfm. I mostly just wanted to share my lerping anxieties.

#

or, okay, so its kind of even less straightforward. its probably more accurately stated as "the current accumulated progress towards the destination", which is particularly confusing for my use case (and the only use case for which I ever would use lerping)

#

because the destination im lerping to changes each frame, so I'm always 0 percent of the way towards my end state before I have lerped

#

you know what? this isnt even a DOTS question.

fluid kiln
#

hahaha

#

I've often found that when I use LERP, my use case doesn't really match

#

And I end up switching to another solution

tight blade
#

me too!

#

but then when I return to something that looks like a lerping problem, my instinct is "maybe I just never understood lerping to begin with"

amber flicker
#

the third argument is very simply how much do you want A vs B. so lerp(A, B, 0) -> all A, lerp(A, B, 1) -> All B, lerp(A, B, 0.5) -> (A+B)/2.
Likely your issue is that you're keeping the third argument static over time (e.g. 0.1) so every frame you're always 0.1 between A & B

fluid kiln
#

What's the component name to access an entity's children?

#

ha it's a buffer, nvm

fluid kiln
#

What's the best way to store sprites and strings in ECS to be referenced by components?

coarse turtle
#

couple of ways I can think of

  • A managed IComponentData class which stores the sprites/strings
  • Hybrid workflow to interface with MonoBehaviours (e.g SpriteRenderer or any custom MonoBehaviour)
proven minnow
#

You could store the sprite as a texture2darray referenced by a component ID, and the string in a nativestring

viral sonnet
#

anyone got something like channels working in netcode 0.3?

#

@fluid kiln You can try FixedString32/64 - it works in IComponentData

fluid kiln
#

I want to reuse sprites and strings without copying them into every component that uses them

#

I'll probably do a managed dictionary

leaden heron
#

Can someone plz explain dots to me, as in what it is?

deft stump
#

DOTS is an umbrella term to a series of preview engine features that's aimed entirely at performance.

safe lintel
#

anyone using hybridv2 and finding its guzzling inordinate amounts of video memory?

#

a very simple blockout scene is taking 8gbs? 😩

dense storm
#

Is there anyone documenting the best practices for each use case for DOTS here?

#

What are the best way to implement events? and one shot interactions such as simply opening a door when E is pressed?

#

Sorry if these are very basic, but I am having a hard time finding an updated tutorial to start with DOTS

deft stump
#

events isn't necessarily dod, afaik.
but it's not impossible to implement

untold night
#

@dense storm
There are a few ways to do "events"

  1. Have an entity that represents the event, and has the event data as 1 or more components. Clean this up after you're done processing these events.

  2. Add a component to a target entity that gets removed at end of frame after the event is process, as part of the system that handles the event.

  3. Look into using NativeStream to do parallel event writes, as you can stuff arbitrary data into the stream. This takes a bit of setup, but can be done in parallel and you can avoid structural changes (sync points) if you do it correctly.

stiff skiff
#

Has anyone here gotten Trigger events to work with the dots physics?

#

I can get collision events to work, but the triggers wont .. trigger

opaque ledge
#

are you choosing "Raise Trigger Events" in physic body script ?

stiff skiff
#

I'm not using the conversion flow

#

I've added a material to the physics body that includes the IsTrigger flag though

stone osprey
#

How do we use command buffer systems correctly ? Do we need to create a command buffer system every frame we wanna use it ? Or can we create it once and save it somwhere for being reused ?

deft stump
#

maybe you can make a static ecb

#

but why need to create a new commandbuffer system? why not just hook up to existing ones?

fluid kiln
#

I'd like to know too, if the standard is to instantiate the ECB in the OnCreate method or OnUpdate?

rancid geode
#

the standard boilerplate for ECB is

private EntityCommandBufferSystem _entityCommandBufferSystem;

protected override void OnCreate()
{
    _entityCommandBufferSystem = World.GetExistingSystem<OneOfTheExistingECBSystemOrACustomOne>();
}

protected override void OnUpdate()
{
    EntityCommandBuffer entityCommandBuffer = _entityCommandBufferSystem.CreateCommandBuffer();

    // use entityCommandBuffer inside Entities.ForEach/IJobChunk

    _entityCommandBufferSystem.AddJobHandleForProducer(Dependency);
}
#

you can set the _entityCommandBufferSystem on OnCreate (updated the sample above)

fluid kiln
#

Okay that's what I do, thanks

stone osprey
#

Alright thanks ! That already helps a lot πŸ™‚ So basically... each time we use that buffer we need to call CreateCommandBuffer in order to make it work ?

fluid kiln
#

Every update of every system

#

One ECB = one system frame if I understand correctly

#

You put it in a local variable, and use that variable during your OnUpdate

rancid geode
#

@fluid kiln got it right, you don't need to call CreateCommandBuffer before each Entities.ForEach in your update, you can re-use the same one, but it is "one per frame"

deft stump
#

@rancid geode you think the reason why you need to create an ecb each frame is because they're just native containers under the hood? and gets dumped each frame?

rancid geode
#

@deft stump I think so, also the fact that the CreateCommandBuffer returns an EntityCommandBuffer with "PlaybackPolicy.SinglePlayback"

stone osprey
#

Thanks ! Well that explains why i couldnt acess it on the main thread... tried to create a event entity using the ecb once a button click occured to inform entities about it, now when i create a new ecb instead it works fine

fluid kiln
#

How did you create an ecb from UI code?

deft stump
#

ah yep it is a native container under the hood

#

ecb's constructor needs an allocator

rancid geode
#

I am close to sure that you can create an persistent ECB with PlaybackPolicy.MultiPlayback, but it would mean multiple sync points being introduced (as to playback the ECB you need an EntityManager)

#

so usually not a good idea

stone osprey
#

@fluid kiln I just do something similar to : world.GetOrCreateSystem<MyBufferSystem>.CreateCommandBuffer(); and there we go πŸ™‚ everything from dots can get used from the main thread

fluid kiln
#

Is GetComponentDataFromEntity costly? If so, how do I access an entity's components without using the entity manager?

#

I have a lot of use cases where a component holds a reference to an entity, and I need to get components from that entity

deft stump
#

nope, it's not costly at all

fluid kiln
#

cool thanks

#

the docs mention "overhead" and to use EntityManager is possible

opaque ledge
#

well its relatively costly, but there is no alternative

fluid kiln
#

gotcha

opaque ledge
#

EntityManager means its main thread, thats not good

#

if you are doing something on worker thread you have to use GetComponentDataFromEntity

#

or Get/SetComponent() method if you are using System Base

fluid kiln
#

ommgggggg

#

I never realized there was a GetComponent method in Systembase

#

What the hell

deft stump
#

me too hahaha

#

XD

#

I thought get/set component only existed in ecb or em

#

XD

fluid kiln
#

oof

deft stump
#

what does the numbers mean whenever the console outputs Burt timings?

#

higher the number means, that's how much performance benefit we got?

north bay
#

Pretty sure that's the compilation time

glacial bolt
#

@fluid kiln Please don't post memes/reaction gifs on the server.

fluid kiln
#

Got it, sorry

stone osprey
#

Another little question... lets say we have a tree entity and a "drop-calculation" entity... The tree simply acts as a tree and the drop calculation entity will calculate dynamic drops based on attached components during runtime. The tree should have a reference to the entity that is used to determine the drops... That is used for spawning in the drop entity. How could we realize this ? Basically a entity component that stores a already defined and existing other entity that we can clone

deft stump
#

so you want the tree to be a child of the drop-calc entity?

stone osprey
#

Not really... Two seperate entities, currently only the tree entity exists ingame. But once that tree gets chopped down, the tree itself should define what "drop" entity will be spawned once gathered.

#

Thats honestly a pretty hard issue... have no clue how i could solve this :p

deft stump
#

so like... once the tree gets chopped. you remove the chopped tree, and you spawn some logs instead.

#

hrmmm most likely you want to store a list of entities that would get spawned.
make a DynamicBuffer and attach it to tree, have it store a list of entities that you can add or remove in systems.

stone osprey
#

@deft stump Thanks ! But how do we actually store them ? Archetype isnt that a good idea because a archetype only contains the components, not the data that are getting filled in the components... so the only way i could imagine is to define some sort of callback like : chopComponent.onChop += () => { // create and fill entities with data }

#

But that feels... so "dirty" :/, not sure if this is a common technique

amber flicker
#

hmmm are you sure you're not talking about a prefab @stone osprey ?

deft stump
#

oh so you haven't filled it up with data huh. so it must load on runtime?

stone osprey
#

are there prefabs in dots ? Im not talking about mono prefabs ^^

deft stump
#

there's prefabs in dots

amber flicker
#

yea - if you have an entity (or hierarchy of entities) and add the Prefab IComponentData, it becomes a dots prefab

stone osprey
#

Uh, thats new... and what makes them so special ?

amber flicker
#

you can then just call EntityManager.Instantiate(myPrefabEntity) and it will create an instance along with the hierarchy

#

the prefab tag means it's ignored for all systems (unless you deliberately create one that requires Prefab)

stone osprey
#

And those prefabs can be used to combine archetypes with data in order to "clone" them multiple times ?

amber flicker
#

not sure I would word it exactly that way, but yes

#

if you have entities, with components that have data set, calling EntityManager.Instantiate(saidEntity); will create a clone of it - regardless of if it has the Prefab tag or not

#

the prefab tag is there just so you can have a base entity representation that is ignored by systems

stone osprey
#

That sounds nice, like it would solve my problems. This way stuff like "Drops" could simply reference a list of those prefabs which are getting instantiated later on

#

Any examples ? When i google for prefabs in dots i only find stuff that involves mono prefabs

amber flicker
#

I don't think there's really much to say in terms of examples unless there's conversion workflow involved. Take your entity that's set up, call EntityManager.Instantiate() and you'll have another one. There's also an overload that will clone a collection of entities and if you have a LinkedEntityGroup on the entity, it will also clone all of those too.

safe lintel
#

a prefab is really just a regular entity that doesnt get picked up by systems by default, kinda like the disabled tag.

stone osprey
#

Alright thanks πŸ™‚ I wonder how that entity is replicated in detail... if its a shallow clone, deep clone and how it acts if theres a real class object attached to the entity ( which is possible aswell .AddObjectComponent() )

amber flicker
#

it's a deep clone essentially*. I believe it also preserves component objects.
*Except, if your entity references another entity, it won't automatically go and clone that linked entity for obvious reasons

#

One additional cool thing is that if your entity has a blobassetreference, it will clone that too - which will just be a pointer to the same blob data. So if you have a bunch of immutable data in a blob and have 1000 instances of that entity, that blob data will only exist once but be referenced by them all.

finite breach
#

Is it normal that while debugging an Entities.Foreach in VS, the debugger just skipping whole lines of code when using GetComponent?

#

Like every time the debugger gets to GetComponent, it just skips the rest of the code but the code is still run 😐

woeful quiver
#

Hey guys, I have a question regarding DOTS (Networking), how well does it perform in single threaded scenarios: i.e. where you have a client-server (dedicated) architecture where the server should be single-threaded as you might have multiple of them per machine/per core and multithreading would actually cause a lot of overhead, or better said does/will it support single-threaded dedicated servers at all? (or perhaps I should ask this in the Networking channel?)

fluid kiln
#

Nothing stops you from running your server single threaded

#

afaik dots leverages the power of multiple cores but can still run on one?

woeful quiver
#

Yes, i'm trying to find out what would be the actual benefit or if there is a huge downside using it in single-threaded scenarios.

safe lintel
#

their goal with the fps sample was designed like this iirc, run the server in in single threaded mode so it can have multiple servers per machine

fluid kiln
#

God I wish there was a better way to reference entities in between client and server in NetCode

north bay
#

What's your problem with the current way to reference entities?

fluid kiln
#

Well, afaik, I can't pass an entity reference to the server because they don't have the same ID.

north bay
#

Do you mean non ghost entities?

fluid kiln
#

Yeah, like for example I have spell prefabs with data, when a player casts a spell, I send a RPC with the spell entity to the server, but it is read as null by the server

#

So I need to do some sort of lookup

#

The spells aren't ghosts

north bay
#

Do you really need to send a rpc with the spell entity? Can't you include the data you need inside the user command?

#

Otherwise if you really need a rpc have a static lookup for abilities and just send the ability id

fluid kiln
#

Well because I need to check if the player has access to the spell, calculate the damage for example etc

#

A bunch of server authoritative stuff

#

Maybe I'm not seeing this on the right angle tho

north bay
#

Well do not state 'i have selected the ability' inside the user command but 'i want to select this ability'

#

And than client/server can predict if he can change/use the ability inside the GhostPredictionGroup

fluid kiln
#

but then how do I reference "this ability"

north bay
#

Have a lookup, as an example I store all item information in a blob array which I than can just access by the array index

#

So i only have to sync that index

#

As long as the creation/setup of the blob is the same on client and server that will work just fine

fluid kiln
#

That's the problem I've been having with ECS/NetCode so far. I have a database of spells that are static at runtime. Spells are made of a list of components/tags that defines their behavior. Currently I store them in prefabs with the authoring components. The client should know of the spells and the server should know of the spells too and be able to reference them statically without necessarily instantiating them.

#

I suppose a blob would fix this, but I'm not sure how to set it up since we can't instantiate prefabs at runtime

north bay
#

So one way to do this is to have a MonoBehaviour with IConvertGameObjectToEntity and IDeclareReferencedPrefabs which references all prefab abilities.

In DeclareReferencedPrefabs you just add the list of abilities, those will be converted to prefab entities.

Because entities are bound to the world you want to add a world based reference like a DynamicBuffer with each element referencing one of those prefab entities.

You can get the entity from a prefab/gameobject by using conversionSystem.GetPrimaryEntity

#

space
In my case the Item data is not bound to entities and therefor i just use a static blob reference

fluid kiln
#

Right right I'm liking this, thanks I'll give it a go πŸ™‚

trail burrow
#

Where did the entities package go?

#

In 2020

opaque ledge
#

you have to manually add it now

#

so basically hit the "+" button on top left corner of package manager and write "com.unity.entities"

trail burrow
#

... why? o.O

deft stump
#

because... unity

opaque ledge
#

Entities update, from 0.14.0 preview 18 to preview 19 lol

little moon
#

Yeah, I can't find a changelog for it tough. It still shows changelog for preview 18

opaque ledge
#

yeah

#

this is what we get after a month 😫

amber flicker
#

So if you add an ISystemStateComponentData to an entity, when you go to destroy the entity that entity isn't destroyed yet, all other components are removed and CleanupEntity is added. Annoyingly you can't query for those entities as CleanupEntity isn't accessible in user code πŸ˜’ so instead you have to add a second tag you expect to be always be present otherwise I guess.

north bay
#

There should definitely be a easier way to query for cleaned up entities. But I don't want to imagine what would happen when CleanupEntity would be exposed and you remove it from an entity.

hollow sorrel
amber flicker
#

This could mean a) there are lots of breaking changes in the wings (so this was all they could safely push) or b) all active development on dots is being paused. b) seems totally overly dramatic... yet the complete embargo on communication about it doesn't suggest a)...

hollow sorrel
#

i wouldn't read too much into it lol

deft stump
#

it can be that dots development have slowed down to a crawl

amber flicker
#

it's been months of no communication and missed timelines for the couple things we were told about Β―_(ツ)_/Β―

mint iron
#

what dif tool is that @hollow sorrel looks cool

hollow sorrel
#

it's https://git-fork.com/ which is a git client
i just created a local git repo in a new folder, put preview 18 in there, commit, put 19 in there, check what files got changed
there's prob a better way of checking diffs but this is easy enough

mint iron
#

nice! didn't know about fork, is it good for git stuff too? i currently use GitKraken for personal stuff, and ive used SourceTree too but find it a bit basic.

hollow sorrel
#

yeah it's great, i tried gitkraken and sourcetree before this but didn't like gitkraken, it was really slow for some reason, and i liked sourcetree for a while but i think fork is just better

#

and is really fast, i remember having to wait for UI sometimes with gitkraken and sourcetree

mint iron
#

awesome, thanks, yeah git-kraken has had a few issues, like how it handles ignores with unity ive had situations where it just wont show the right files no matter what you do.

hollow sorrel
#

also it says free evaluation but it's like winrar, everything included in free version it just asks you to buy it every once in a while

mint iron
#

i was recently forced to use command line for a few weeks due to software approval processes and it was an absolute nightmare haha, try doing complicated merges and rebasing and conflict resolution from command line... i almost died.

#

i gave up on command line when windows 95 came out

hollow sorrel
#

oof

#

yea i don't like touching command line either
every once in a while still gotta use it to do some weird thing but fork has some nice console integration i think
it's one click away and opens in right folder and updates your changes right away in the client too

#

but ya fork is one of the few things i'd recommend to everybody

#

like rewired for unity

coarse turtle
#

hmm does anyone have an example of using IJobParallelForBatch? Kind of curious on what ppl have used it for

safe lintel
#

❀️ git fork, also been using it for a long time

stone osprey
#

Any idea how i could detect destroyed entities ? I would love some kind of reactive system :/

solar ridge
#

SystemState components may help you

coarse turtle
#

ISystemStateComponentData might help you

stone osprey
#

My reactive system

stone osprey
#

it works fine for Added entities/components... but not for removing those

#

And i have no clue where my mistake is... its also extremely hard to debug

solar ridge
#

First: Burst compiling the state... does nothing?

stone osprey
#

Probably, i just place burst over nearly every component :p

solar ridge
#

The components aren't the thing you burst compile

stone osprey
#

Weird, i saw that dozends times in some tutorials... but tbh, the support of tutorials regarding dots is pretty bad :/ So those people probably didnt knew what to do either

solar ridge
#

When you destroy an entity with a SystemStateComponent, have you inspected the entity

#

my assumption is that it isn't matching your queries anymore as it likely only has the state and nothing else

deft stump
#

you burst compile methods

solar ridge
#

^

#

As a note: No tutorial exists for DOTs. Even if it is labeled "tutorial" it likely has either changed or is wrong

deft stump
#

Or is outdated

solar ridge
#

Tutorials will only exist in my eyes when it is no longer a preview package

stone osprey
solar ridge
#

So this is why I am recommending you look in the inspector, as the entity can not be fully destroyed until the system that added the state cleans it up

#

So if it is not there, then it is likely something else causing your issues

#

... what is your update even doing?

stone osprey
#

Im gonna try that... well the update checks for the queries every frame

#

In order to determine what changed

#

Damn i hope they support reactive systems by default in the future... i hate to code fundamentals by my own, i bet its full of mistakes

solar ridge
#

Well the concept of a "reactive" system is too vague

#

for instance, I have an event system that creates entities with blob data

#

I then add a 'handled' tag when I have read and processed them

#

Abstraction in a lot of cases for DOD is not really a fundamental design option

stone osprey
#

I just wanna get callbacks once a component was attached or removed... thats all, but it requires so much boilerplate code and so much trouble to get it working correctly ^^

solar ridge
#

Call backs, should be avoided.

#

You should move forward with data, and not stop go to a line figure it out and move back

#

Otherwise you kind of mess up some of the reasoning for the memory layout

stone osprey
#

Dude, im not using dots due to the performance advantage ^^ im using it for the ecs architecture. And therefore callbacks are great because you can easily attach new logic... πŸ˜„

amber flicker
#

fyi you can use WithChangeFilter if you want to - using it comes with caveats and is not meant to contradict what Soaryn is saying

solar ridge
#

ChangeWithFilter is per chunk

#

unfortunately ;P

amber flicker
#

sure

#

that will still catch every entity that has had a component added or removed though right?

solar ridge
#

Mmmmmmmmm should, but unsure if you could get "what" changed necessarily

amber flicker
#

yea I guess you could get a bunch of existing entities in a chunk as well as the ones that were just moved there

solar ridge
#

Oh!

#

No, you'd get every entity that matches πŸ˜‰

#

So if you moved entities from Group A to Group B, and your query initially matched Group B, you would then have all of the new entities + the old Group B entities in the Foreach

#

I tried it out the other day thinking it would simplify something for me

amber flicker
#

I think we're saying the same thing

#

maybe

solar ridge
#

Likely

#

I have a cocacola bottle covering a part of discord so having to read around it soarynLOL

amber flicker
#

chunkA = [ABC, ABC, ABC], chunkB = [AB, AB, AB]
if we add C to all entities in chunkB I guess .WithChangeFilter will now return the entirety of chunkA:
chunkA [ABC, ABC, ABC, ABC, ABC, ABC]
I think?

solar ridge
#

On a side note @stone osprey, your system for checking what was added seemingly does nothing πŸ˜› You just run the invokes no matter what

stone osprey
#

@solar ridge It does πŸ™‚ It can detect newly added components/entities already... i extend that system in order to make it work for a certain component. I just cant get the last part working, the detection of removed entities

solar ridge
#

How exactly?

amber flicker
#

for removed entities: Always add ComponentA & ComponentB to your entity. Make ComponentA : ISystemStateComponentData then make a system that is: Entities.WithAll<ComponentA>().WithNone<ComponentB>()

stone osprey
#

@solar ridge You should like it https://pastebin.com/jdGXLj8q... the base reactive system works with structural changes in order to make it work with Entities.ForEach, no callbacks involved here πŸ™‚ I also have a extension which makes it work with callbacks.

solar ridge
#

I, don't like it soarynLOL I uses ECS for the actual performance

#

Callbacks are inherently bad in this regard

stone osprey
#

You can simply use : Entities.ForEach(child, childCreated) to iterate over all newly created/attached childs components

#

As i said, no callbacks here -> performance

solar ridge
#

Out of curiousity

#

Have you tried building this to a player?

#

Just curious if it supports generic systems now

stone osprey
#

That was pretty hard... i think i now of which issue you are adressing here. As far as i know this version should work. I had a guy in the forum who tried to make it available for multithreading which didnt worked due to that generic issue

solar ridge
#
var buffer = _ecb.CreateCommandBuffer();
buffer.AddComponent<Handled>(_query);
Entities
  .WithName("Demo")
  .WithNone<Handled>()
  .ForEach(...).ScheduleParallel();
_ecb.AddJobHandleForProducer(Dependency);  
#

This works well enough for me

#

Oh goodness spacing is all over the place there

#

The foreach is the callback here in my case

#

It handles the logic of what to do with the entities that now match their filter

stone osprey
#

But wouldnt this run continous ? ^^

solar ridge
#

the system would run when there is something matching the query

#

in this case what I want + NOT handled

#

So for each entity that matches it would run once

#
_query = GetEntityQuery(new EntityQueryDesc() {
    None = new[] {
        ComponentType.ReadOnly<Handled>()
    },
    Any = new[] {
        //Whatever you want. You can use All if you want My case needed "Any"
    }
});
stone osprey
#

One little other question... is it normal that the stacktrace is not visible sometimes ? :

amber flicker
#

I haven't seen that. Could be worth checking your editor log and see if it's a ui issue.

solar ridge
#

potentially but it could have also been a bursted function in the backend

amber flicker
#

Does anyone know if it's possible to call a burst function from non-bursted code?

solar ridge
#

many bursted errors have some issues pointing to the actual cause I have found

#

MMm

#

In what manner

#

To have the code be bursted itself still?

#

Potentially using the FunctionPointer

amber flicker
#

I have some systems that have to set managed components - a bunch of Transform localPositions for example. Obviously that job can't be bursted but accessing buffers (where I store the dest values) in non bursted code seems to be killing me

#

the burst docs on FunctionPointer seem to suggest they need to be called from bursted code.. I think

solar ridge
#

"Note that you can also use these function pointers from regular C# as well, but it is highly recommended (for performance reasons) to cache the FunctionPointer<T>.Invoke property (which is the delegate instance) to a static field."

amber flicker
#

hmm I read that and then forgot I read it... going to give it a go πŸ‘

solar ridge
#

You are setting transforms?

#

You can do that in burst

#

you just have to do some silliness to get it to work

amber flicker
#

???

solar ridge
#

Sec I'll get you what I did the other day

deft stump
#

ugh the new entities package ruined some of my icomponent datas i set in editor wth.
I spent an hour fixing some undesirable movment

solar ridge
#

Last part should help

amber flicker
#

Thank you.. processing...

solar ridge
#

I actually noticed that the Copy To GameObject was broken

#

Some caching likely could speed it up

stone osprey
#

The state component is the "only" component left after that entity was destroyed... right ?

solar ridge
#

Potentially

#

Should be able to see if it is in the inspector

stone osprey
#

It is... but that means... that it does not make sense to detect removed components using its state

#

We only know that a component was removed, but the component isnt there anymore... so we have no idea what the value of that component was before it was removed... right ?

solar ridge
#

So this is why I brought up my system

#

You could, decorate something with "CleanupTag"

#

And then handle the entities with CleanupTag and do what you want with their data

amber flicker
#

^except not that, as that's internally taken πŸ™‚

solar ridge
#

oh really?

#

So if you put the CleanupTag in your system it won't bother it

amber flicker
#

yea.. you can't use it in your systems (unity private) but it gets added to entities

#

oh wait

#

my bad

solar ridge
#

I have a CustomSystem.CleanupTag as an example

amber flicker
#

it's called CleanupEntity - the one I was talking about - my mistake

solar ridge
#

Since it is in my namespace and my system it resolves differently

#

Regardless, if you "react" to entities in a forward manner things become a lot more inline with what they want you to do and designed for

stone osprey
#

I already have something similar called "Destroy"... it simply marks a entity for being destroyed at the end of the frame... but i hoped that theres a way to handle this using the reactive system instead of getting forced to mark every entity on my own

solar ridge
#

So Entities.WithAll<CleanupTagOfWonder>().Foreach((in YourReactiveData data)=>{}).Schedule;

#

You don't really change the way you are marking

#

I could change WithNone<Handled> to WithAll<CleanMe>

#

and have the result you want

#

My query would then be, All={CleanMe}

#

And destroying the entity would be buffer.Destroy(query)

#

But make sure that the buffersystem comes after the systems that need this

#

And you add the dependencies to the buffer system

#

Data oriented design suffers from the sad fact that most of us have had little practice with it, but once you start thinking in that mind set, everything becomes MUCH faster, more efficient, and overall cleaner

amber flicker
#

if you create an entity and do AddComponentObject(someGOTransform) and then give that entity e.g. a Translation ICD will the companion systems automatically run and sync things does anyone know? πŸ€”

solar ridge
#

I couldn't figure out where the companion system comes into play so maybe?

stone osprey
#

Thats true :/ in my case i dont need the overall performance... i simply want a clean way to react to structural changes.... im not that sure about the .WithAll/None way... i would love to have some sort of predefined interface/class/callback for such tasks... atleast all the other ecs i used before that such a way

solar ridge
#

Most other ECS introduce some form of boxing which defeats the purpose of Unity making this system. Remember, they are striving for 'Performance by Default'

#

personally, I'd love a simpler method, but a few lines more is not much of a sacrifice

#

As a note, they have made things A LOT simpler than before

#

so there is always hope for newer systems to be "simplified"

stone osprey
#

Yeah but that doesnt mean that they could wrap some sort of "lower performance" layer around the high performance core... Its only a extension, not a complete rework ^^

deft stump
#

What is wrong with WithAll/None?

solar ridge
#

Mmmm no

#

If they add less performant things then they have no reason to be claiming "performance by default"

#

also I defer you to gameobjects. There is your lower performant layer

deft stump
#

also, I'm not sure why you want to stick with unity's ecs just for the sake of the ecs structure.
why not just use entitas or some other?

stone osprey
#

Well performance by default does not exclude that they add utility classes, extensions, additional packages... it does not make it slower, it you simply dont use them. I mean, you could also use the high performance stuff but code badly which results in bad performance... this doesnt hurt "performance by default" either

#

@deft stump I already implemented tons of stuff using unitys ecs... i dont wana switch again :/ furthermore entitas has a awfull documentation & nearly no tutorials

solar ridge
#

Considering they have changed the system at least 5 times, I would say they are not going to be adding utility 'til later

#

Them adding utility now would just involve more work for them

#

And considering we just got, after a month, a preview package number bump

#

I'm more curious what all got added to preview19 or if it was just back end processings

hollow sorrel
#

@stone osprey Any idea how i could detect destroyed entities ? there is also EntityManager.GetCreatedAndDestroyedEntities
i haven't read all of the above but i generally would also recommend using a systemstate cleanuptag, but the entitymanager method is an alternative (dunno when you would use it instead or how well it scales though)

solar ridge
#

Why would you recommend against a cleanuptag? I can't read

hollow sorrel
#

regarding scaling, it seems to iterate every entity that ever lived to check if it was destroyed or just created, or i could be misreading the code

#

no i'm recommending for a cleanuptag

solar ridge
#

OOOH

#

Im bad at reading XD

hollow sorrel
#

hahah

solar ridge
#

As a note for those wanting the easy path to things, understand that OOP was primarily made to be an easy to understand paradigm and decreased developer time. This however comes at the cost of your users. You may often thing that this is ok, and your system won't be that expensive, but I can tell you right now, that if you EVER decide to scale up (and you likely will) that it will be 10x more work for you to change to DOD or to improve your OOP enough to not require it

deft stump
#

I blame Java for commercializing OOP

solar ridge
#

I wouldn't really

#

As this is also a problem in C and C++

#

An object is just easy to grasp

#

I'd blame really universities

#

As my university made NO mention of DOD until a group member of mine mentioned that we are going to be using it for our capstone project

deft stump
#

I believe it wasn't that apparent during C++.

#

but yeah Universities and Enterprises really pushed OOP to the monstrosity it is now

solar ridge
#

And it can be useful, but not everywhere πŸ˜›

tiny ore
#

The internet is big as it is a lot because OO allowed a lot of people to embrace programming... IMHO

#

So, it's not the best for high oerf, but has its uses...

solar ridge
#

For sure

tiny ore
#

Arguably, we have discord, and all these awesome tools to enable us to develop games remotely talking to each other partially due to it...:)

#

But sure, there are better ways to express large data based problems

#

Gameplay is also very easily expressed with OO... And for the bad and for the good, you have so many game Devs today also partially due to OO...

#

So...

#

Not everything is bad.

stone osprey
#

OOP is only good for projects which structure do not change that often... thats why its mostly teached in university, for the "normal" work and projects. DOD is not the silver bullet but extremely usefull when it comes to flexibility and performance... but to be honest, most companys/apps/programms dont make use of it because they simply dont require such advantages...

tiny ore
#

I doubt unity would be nearly as popular if it had not embraced it

#

And again, personal opinion, dod is not really flexible to express gameplay...

#

And I'm not alone in that opinion tbh (just search Google for some big shots opinions)

#

Although I like it a lot personally

stone osprey
#

It really depends... i personally experienced that DOD is not that great for event based gameplay... like : Player reached Tree, Start chopping, Once finished generate loot, Once loot generated put it into inventory, Oh and some modifications on the loot drop if the player has a special weapon in its inventory... but its great for stuff getting executed at a regular base

solar ridge
#

Off of the top of my head that entire event chain is handleable in Unity ECS just fine πŸ˜›

tiny ore
#

You are correct, I mean, I agree with the two statements IMHO

#

But anyway, just don't blame oo without acknowledging all the good things it brought...:)

#

Same for universities... You can do with or without it, but it's not all bad...

deft stump
#

well we wouldn't have C# without OO (probably).

solar ridge
#

Universities should at somepoint express that there are other paradigms. That is my point

tiny ore
#

Disclaimer: former Univ professor here.

solar ridge
#

Not that they need to teach DOD necessarily

tiny ore
#

Correct...:)

solar ridge
#

but more indicate heeey OOP is not the only one

tiny ore
#

I think dod in general is a good topic

#

Should be used more frequently

solar ridge
#

We kind of used it in Parallel computing but never generalize it enough to discuss that it is a paradigm

tiny ore
#

That's what I would mention

#

I have had contact with dod with other names, without buzzwording... Many times, in univ

#

For me it's just data parallel design... Expressed with a specific set of semantics

#

But sure, i have a bit more than just a college degree, so my experience.is not average

#

I agree most colleges stay with the popular oo topics

stone osprey
#

Little question aside... any idea why one of my systems does not show up in the ECS inspector ? What could cause this ? Its also not getting called

tiny ore
#

Good, back to technical topic...:)

hollow sorrel
#

did you add it manually?

tiny ore
#

It it was our ECS I knew...:)

stone osprey
#

Nope, normally they are getting add by unity itself

solar ridge
#

I'm half tempted to say it is the generic

coarse turtle
#

dependencies for the system might not be met on the initial frame?

solar ridge
#

but unsure

stone osprey
#

@solar ridge Its a destruction system i wrote

deft stump
#

are you querying components that exists? (I think it'll display as not run if you're query is coming up empty, not sure)

solar ridge
#

Can you get us a quick image of your system list?

#

just shift + win + s

#

unless mac/linux... then rip

hollow sorrel
#

there's a dropdown in entitydebugger for show inactive systems, it'd show up with that but not without if dependencies aren't met

stone osprey
#

All system registered by unity

#

But that destroy system is getting ignored

solar ridge
#

As a related note, the Editor they have in the forum is a recommendation I'd propose

#

Whyyyy is it green?>

stone osprey
#

Because its running πŸ˜„ its the only color that "works"... tried red, black, grey... they all looked awfull

deft stump
#

the green burns my eyes

solar ridge
#

and in the show full playter loop drop down

#

do you have the show inactive checked?

deft stump
#

jokes aside. does this DestroyAfter component attached to an entity?

amber flicker
#

@solar ridge in your post you linked to earlier, what is _transformAccessArray?

solar ridge
#

TransformAccessArray

stone osprey
#

Not in the full player loop either :/

solar ridge
#

πŸ˜‰

#

sec I'll get you my code... where did I put it

amber flicker
#

ah that makes sense! didn't know that was a thing

solar ridge
#
 private TransformAccessArray _transformAccessArray;
_transformAccessArray = new TransformAccessArray(0);
hollow sorrel
#

@stone osprey show inactive systems is a seperate checkbox

solar ridge
#

That is done in on create to init it once

stone osprey
#

Than its inactive for some reason

solar ridge
#

Does anything match its query?

stone osprey
#

It does... im gonna give rider and unity a restart, hopefully this fixes that issue :/

hollow sorrel
#

are you saying you're destroying every frame?

solar ridge
#

Just to double check a suspicion, if you make 3 queries in a SystemBase, is it an "and" operation or an "or" operation for allowing the system to run

hollow sorrel
#

cuz if not i'd expect it to just run once and go afk because there's nothing left with destroy tag

stone osprey
#

I created some example entities ^^ looks like a restart really made it work, atleast those entities are now getting deleted properly

#

Can we use a command buffer inside a entity iteration ? That shouldnt be a problem, or ?

coarse turtle
#

Like in a ForEach? Don't see a problem in that

stone osprey
#

Alright thanks ^^

solar ridge
#

So a note about that. Yes, you can BUT

#

be sure of two things:
1: If it is a parallel or multiple writers, be sure to pass it the parallel writer variation
2: Make sure you add the dependency to the buffersystem as a producer

coarse turtle
#

Yes that ^

solar ridge
#

_ecb.AddJobHandleForProducer(Dependency);

stone osprey
#

Alright, great πŸ˜„

solar ridge
#

Note, this is what I use πŸ˜›

#

But I typically use the query add component and iterate over separately

#

as the query addition is faster by a bit

#

But, I tend to use the foreach to add components if there is a conditional involved

viral sonnet
#

is anyone using singleton entities that have managed data without SharedComponentData? is it possible or do we always need SCD?

coarse turtle
#

I use managed component data (haven't really used them for singleton like data)

public class ManagedComponent : IComponentData, IEquatable {
  // Add managed component here so you can query for it in an EntityQuery
}
viral sonnet
#

hm, thanks. i have to try again with class ICompentData. last time I wrote them I had compiler errors and I stopped bothering.

blissful gorge
#

(if/when unity finally supports c# 9 lol)

deft stump
#

if unity adopts .net 5

#

I can only dream

blissful gorge
#

Also the foreach now recognizes GetEnumerator extension methods -- would this solve the foreach limitation in burst as well?

#

😒

deft stump
#

Also the foreach now recognizes GetEnumerator extension methods -- would this solve the foreach limitation in burst as well?
@blissful gorge I doubt it would? foreach still has the pain point of try-catch underneath. which burst doesn't like. though might be wrong with how I read the new update

low tangle
#

@solar ridge its an 'or' unless you use require for update on each query

stone osprey
#

Is there a way to get a component by its type ? Uhm... i mean the type from "typeof()" ^^

#

Not "manager.GetComponentData<...>();"

stone osprey
#

Any ideas ?

amber flicker
#

I don't think this is doable without reflection. Even with reflection I don't know if that would work at runtime.

stone osprey
#

Hmm... thats awfull, i saw the method "GetComponentTypes" and hoped that you could simply iterate over them in order to extract each one...

amber flicker
#

I might be wrong

north bay
#

As far as i know not without editing the package

amber flicker
#

I think there was once a forum post about requesting a feature similar to this and the answer was possibly something along the lines of no because boxing - very vague memories, could be getting this totally wrong.

north bay
#

EntityDataAccess already has methods for getting and setting components with pointers, you just have to expose through the EntityManager

#

It just misses tons of safety

#

But good luck πŸ˜‰

stone osprey
#

In my case i need it in order to make it work with the ui... I have a UI popup that shows informations about entities, i wanted to list all the attached components and serialize them for being shown in the ui :/

#

@north bay Thanks, that could probably work ^^

north bay
#

I once made an entity in game inspector which made use of that

stone osprey
#

Yeah thats pretty much want i want to achieve ^^ but how did you received all those components with their data ?

north bay
#

Let me check

amber flicker
#

I wonder if you could use something like chunk.GetDynamicComponentDataArrayReinterpret - not really sure what that's for

north bay
#

So I've used EntityManager.GetComponentTypes, filtered out the ones that I cared about, grabbed the Type Index of those and passed that with the Entity to the Inspector

stone osprey
#

@north bay So we have the same approach ^^ thanks, and what about the component values ?

north bay
#

What do you mean?
Getting and setting the component values?

stone osprey
#

yep

north bay
#

I've added this to EntityManagerAccessComponentData

       public void* GetComponentDataRW(Entity entity, int componentIdx) 
        {
            var ecs = GetCheckedEntityDataAccess();
            return ecs->GetComponentDataRawRWSafe(entity, componentIdx);
        }

and this to EntityDataAccess:

        public void* GetComponentDataRawRWSafe(Entity entity, int typeIndex)
        {
            EntityComponentStore->AssertEntityHasComponent(entity, typeIndex);
            EntityComponentStore->AssertZeroSizedComponent(typeIndex);

            if (!IsInExclusiveTransaction)
                DependencyManager->CompleteReadAndWriteDependency(typeIndex);
            
            return EntityComponentStore->GetComponentDataRawRW(entity, typeIndex);
        }
#

Don't let the name trick you it's definitely not safe lol

stone osprey
#

Thanks a lot ! That should do the trick πŸ˜„

#

Ah cmon... its not possible to write those methods as extensions ?

amber flicker
#

no you'd have to copy the package locally - that's why I'd try going with reflection if I had to

stone osprey
#

Im not that familiar with c# reflection, furthermore i have no clue what method we need to acess :/

amber flicker
#

Have you tried finding the inspector code that currently exists? I'm unsure if it's in a package somewhere.

stone osprey
#

@amber flicker probably found something...

#

MethodInfo methodInfo = typeof(EntityManager).GetMethod("GetComponentData");
MethodInfo genericMethodInfo = methodInfo.MakeGenericMethod(t);
var parmeters = new object[]{e};
object componentData = genericMethodInfo.Invoke( EntityManager, parmeters );

amber flicker
stone osprey
#

Not sure how performant this is... but should do the trick for ui

amber flicker
#

it's not that slow - you can also cache the method info

stone osprey
amber flicker
#

in general you do probably want to cache that methodinfo you make though πŸ‘

stone osprey
#

Atleast a simply cache... of course there more optimizations to follow

north bay
#

I was about to write that you can even cache var genericMethodInfo = GetComponentDataInfo.MakeGenericMethod(type.GetType()); for the individual types

stone osprey
#

Yep that was exactly was i was thinking πŸ˜„ but tbh, im to lazy to implement this rn...

amber flicker
#

it gets a bit complicated with the entityManager possibly changing too.. looks like it gets you moving forward at least

north bay
#

Do you guys often use reflection? I normally only use it for attribute lookups and stuff

#

Generally I'm scared about it

stone osprey
#

Me too... thats why i only use it for serialisation, checking properties/variables or "hacking" into stuff like this entity manager

amber flicker
#

I generally avoid it for anything runtime but occasionally use it for editor tools and such as a) timing is usually less critical and b) it's a much more reproducible environment.

#

I think, for example, you can't use reflection when publishing to ios? Could be completely wrong about that though - never thought it was a good idea to try.

north bay
#

Apple πŸ˜„

amber flicker
#

Possibly android too. I see it very much as a last resort. For example, if you want to have a textfield in the editor that enables copy/paste that you can change the caret position of via code, you have no choice but to use reflection.

stone osprey
#

Heard similar stuff about apple... they are pretty scared of everything that they cant "detect" or check during their app review

north bay
#

I mean the big thing that I always have in mind when thinking about reflection is that it allows you to change/use stuff that the author of the code didn't want you to touch

stone osprey
#

Yep, probably even remote code injection... not quite sure if c# is able to compile and bind received code, but i heard that there were some java apps that did similar stuff in the past

stone osprey
#

Currently wiring UI with entities... i hate UI, it should get filled from outside, search own values for being filled and... what im currently implementing, getting filled from entity components. Probably im overcomplicating things

north bay
#

Your inspector looks like my character authoring prefab

amber flicker
#

That looks like a slightly painful way to do things πŸ˜… - though not sure what's actually going on

mint iron
#

@stone osprey You can get a component type index by its type. TypeManager.GetTypeIndex(System.Type); then TypeManager.GetTypeInfo(typeIndex) to get more useful things about it. You can use the type index to get a component by switching out the typeIndex in any of unity's retrieval containers. ArchetypeComponentType etc

solid flume
#

Any reason why the same code won't work inside a job but functions fine outside it? All I'm doing is multiplying a bunch of vector3s by a noise value

#

The job is IParallelFor

stone osprey
#

Its awfull, isnt it ? πŸ˜„ well every component does exactly one single job... and UI is always way more complicated, chaining stuff like : Oh when that title is set, also reload this

solid flume
#

It should loop over all the vertices and multiply them, but only a couple are affected, and very weirdly

amber flicker
#

@solid flume my guess is all your threads are using the same noise values or that kind of issue

solid flume
#

The noise value is based on the vector3

#

Unity.Mathematics.noise.snoise

north bay
amber flicker
#

@solid flume code?

solid flume
#
public void Execute(int index)
    {
        // Debug.Log(index);
        float value = 0f;
        float3 position = new float3(Points[index].x, Points[index].y, Points[index].z);
        for (int i = 0; i < Octaves; i++)
        {
            
            value += noise.snoise(new float4(position*NoiseFrequency, i)) * NoiseAmplitude;
            
            NoiseFrequency *= Lacunarity;
            NoiseAmplitude *= Persistence;
        }
        Points[index] *= value + Radius;
    }```
#

Wait

stone osprey
#

@north bay Im actually relieved that im not the only one with so many components ^^

solid flume
#

Are float variables shared across all instances of the job?

north bay
#

Oh that's only my character, it doesn't hold anything like moving, shooting or other functionality lmao

solid flume
#

So if one job changes it they all change?

#

Okay got it never mind

#

I was being dumb

amber flicker
#

@stone osprey are you sure you don't wanna go oop for that? 🀣

stone osprey
#

@amber flicker Its complicated πŸ˜„ currently its a mix of oop and ecs xD

wooden falcon
#

I've seen mentioned at a few points about splitting up simulation and rendering in separate worlds, does anyone have a resource on how to go about doing this?

#

I don't quite understand how you would go about doing it as the rendering world would depend on the simulation needing to read its data

amber flicker
#

you wouldn't want the simulation to read data from the rendering though right? The simulation world would keep track of all the data. Then every X frames you copy the data needed for presentation over to the rendering world.

#

at least in theory - physics and other things makes a lot of this difficult in practice

wooden falcon
#

I mean I think I would want the behavior render Model at a interpolated location between current and previous simulation ticks

#

and yeah simulation wouldn't read any data from rendering it would be a one way dependency

#

Trying to make a deterministic update to do lockstep

amber flicker
#

If you want your faster tick world to be rendering, you're going to need all supporting systems (like lerping positions) to run at that higher rate. So if there are systems that you don't want to run e.g. at 240/120hz for example, I'd say it might be easier to put all those systems in a SystemGroup and manually Update that group every 2 frames for example. Perhaps other people can weigh in here.

wooden falcon
#

Well my hope is to have the simulation world clean from any excess components related to rendering as I would keep 2 separate worlds to do rollback

#

and potentially serialize it to a file every now and again and just do a hash check so I can auto test determinism

amber flicker
#

I'm not sure this is a great use of multiple worlds. Keep in mind entities & systems in one world know absolutely nothing about entities and systems in another world. You can copy/merge entities into another world at a hard sync point (which isn't free).

#

Determinism is a hard topic. I guess what's right for you will depend on a lot of things to do with physics, networking, what data you need to realistically keep deterministic over what platforms etc. Perhaps multiple worlds would help you but I don't see what they would do for you atm.

wooden falcon
#

Yeah, my idea is to try and shy away from things that might complicate it like physics and depending on data such as animations

amber flicker
#

Someone here is using Worlds for deterministic rollback. Possibly a few. Perhaps check in next week and see if they're around.

hollow sorrel
#

there's a few of us here doing that also, but yea there's not really good resources on it atm

#

i'm also doing deterministic rollback tho my game still in pretty early stage

#

also i'd say it's the best use of multiple worlds, you absolutely want your simulation to be isolated

#

that's where all your deterministic code lives

#

if you just want to seperate render tick from sim tick, then yea you'd prob use 1 world and different update groups and it'd prob perform better

#

but deterministic lockstep/rollback is different beast

wooden falcon
#

Yeah I wouldn't really go for it if determinism wasn't a requirement

hollow sorrel
#

also they're isolated but technically you can still reach into another world and do stuff in there
basically all the entityqueries etc, you can run them on a different world than the system you're scheduling from

#

but yea i'd also recommend copying

#

what i do is have a system that takes care of creating/destroying render entities, that are basically mirrors of their sim entities
so a sim entity could e.g. have a mesh component that just has an int id of a mesh
then that render system will look up all sim entities with that mesh component in the sim world and create a 'mirror' entity in the render world

#

and the render world takes care of looking up that mesh id and loading a real mesh in the render world etc

#

and also interpolation

wooden falcon
#

Ok, so your sim world also contains this id?

hollow sorrel
#

yeah, sim world contains all data necessary for rendering, but not the rendering data itself, so mesh id to know what mesh it is, but not the Mesh class itself

#

also animation timings etc happens in sim world as well so it's all deterministic

#

and it just copies the data that it needs for rendering into render world

wooden falcon
#

ok, that make sense yeah

hollow sorrel
#

but not all data, we just copy the render components

#

no need to know about wether player jumped etc in render world (unless you do, then copy that too)

wooden falcon
#

How do you copy just the specific components between the worlds?

#

or do you manually just loop over the necessary archetypes and do it?

hollow sorrel
#

yeah just manual loops basically, it's a bit of boilerplate and i'm sure there's a better way but haven't figured it out yet

#

basically looks like this

#
Entities.ForEach((ref LocalToWorld ltw, ref PreviousLtw prevLtw, in SimLink simLink) =>
        {
            prevLtw.Value = ltw.Value;
            ltw = simWorldEntityManager.GetComponentData<LocalToWorld>(simLink.SimEntity);
        })
            .Schedule();

        Entities.ForEach((ref PhasedSprite phasedSprite, ref FlipX flipX, in SimLink simLink) =>
        {
            var newSprite = simWorldEntityManager.GetComponentData<PhasedSprite>(simLink.SimEntity);
            if (newSprite.SpriteHash != phasedSprite.SpriteHash)
            {
                newSprite.Changed = true;
            }
            phasedSprite = newSprite;
            flipX = simWorldEntityManager.GetComponentData<FlipX>(simLink.SimEntity);
        })
            .Schedule();
#

1 system with a bunch of these, different entities.foreach for copying different components

wooden falcon
#

Alright

hollow sorrel
#

and the copying of components is random access because of the lookup into sim world, which is blegh but again, dunno about a better way

wooden falcon
#

Thank you, I think I know how to go about this now

solid flume
#

Is there any way I can pass a function inside a job

#

The function is in the job, and I just need to pass it as a parameter to another function in the job

#

I could do a switch-case to choose what function, but passing it is more elegant and less code

deft stump
#

you can use a static function

solid flume
#

I can pass static functions?

#

In jobs

#

Would the type be System.Func<...>

deft stump
#

Hrmmmm i think i misunderstood your question

solid flume
#

Ah

#

Basically I have different noise functions

#

And a couple transformations of the noise

#

And I want to be able to layer multiple noise functions

minor sluice
#

maybe that will be a pain to extend, but how about passing an integer or uint as bitmask, and the bits are checked and indicate which noise methods to execute in the job?

solid flume
#

Yeah I just used an enum

#

And a switch case

rancid geode
coarse turtle
#

hmm guess I have a question regarding debugging on a build on Android for DOTS. Does a remote debugger to "step" through the code work nicely when trying to debug something since there's code gen involved?

solid flume
#

Although I'm probably never going to be able to make collision for this

finite breach
#

Is there an known issue at the moment with UpdateInGroup and UpdateAfter/Before. I have 2 systems that are in the same group and System1 has and UpdateBefore System2. However the OnCreate on System2 fire before the OnCreate of System1 😩 Or are the OnCreate call not affected by UpdateBefore/After?

rancid geode
#

UpdateBefore/After onlly guarantess the Update order, OnCreate, similarly to Awake, doesn't have a predefined order

finite breach
#

@rancid geode Ok. Thanks!

tawdry lotus
#

can queries be used to filter specific data? like if you want all MovementComponent with speed between 5 and 10? (where movementcomponent has float speed)

#

or is there another way to do that with ecs api?

deft stump
#

unless it's a shared component data, I don't think there is

whole hornet
amber flicker
whole hornet
#

Yeah, I have those

#

I tried it in various projects last night including one of the ECS samples, but they all looked the same. I'm starting to think there may be something missing from my Mac maybe?

amber flicker
#

Curious - I assume you have Mac Build Support installed for the editor? (You can check via Unity Hub -> Add Modules)

whole hornet
#

I have that as well. In the hub I also tried setting the target as Mac

amber flicker
#

that's me out of ideas sorry! Good luck 🀞

whole hornet
#

No worries, thanks for trying

rapid agate
#

Hey guys. I don't mean to double-dip, but I think this channel might be better for a question I posed in code: Does anyone have an article/tutorial (hopefully written but video is fine) that they absolutely loved and can recommend specifically for learning Jobs?

north bay
#

Otherwise there is CodeMonkey who makes tutorials on DOTS, I haven't really watched any of his stuff but might be worth it

rapid agate
#

Cool I appreciate it

#

Gonna dive in right now.

viral sonnet
#

any idea how to sync dynamicbuffers in ghost snapshots? (netcode 0.3)

proven minnow
#

Subscene gurus- can I have a subscene with nativearrays stored in my systems, or do I need to store them in entities and rehydrate them on load?

stone osprey
#

So i have been running into a strange issue... im loading my assets using adressables, those provide a callback once finished. If i create a entity in that callback unity tells me : "Exception due to invalid IL code"... if i dont create a entity in that callback it works fine :/

#

Any ideas ?

deft stump
#

which namespace is the physics shape? trying to make physics shape a required Component

stone osprey
#

Getting that error in that line where i use the "eventCreator.createEvent"

deft stump
#

ah

#

shit

#

Unity.Physics.Authoring

stone osprey
#

Any ideas regarding that il issue ?

amber flicker
#

@proven minnow afaik you can't serialize a NativeArray like that but I believe you can have a BlobArray in a BlobAssetReference, associated with a subscene that gets populated on conversion

#

@stone osprey I'd be highly surprised if that was a supported workflow. I'm surprised it compiles at all - not that helpful to you I guess but I suspect the invalid il code is about unity not being able to generate code that makes sense in that situation. I'm not sure what the lambda is really doing for you there - might be better just to use a for loop

stone osprey
#

@amber flicker Its simply, i loop over all entities with a mesh component, search the adressable for them and initialize it. I dont see why this shouldnt be supported.

amber flicker
#

Ok πŸ‘ - good luck

hollow sorrel
#

@stone osprey yea i'd also guess it's the entities.foreach codegen like timboc said
but even if it works, callbacks with ecs are no bueno
dunno when that callback is called but if it happens from a different thread immediately when an asset is loaded, every structural change is a sync point so imagine you're loading 100 assets and they all complete at different times, you'd get 100 sync points

#

prob better to store the handle and check if its completed next frame

#

or in a different system that runs at end of frame if it can complete in between now and then

stone osprey
#

Thats something i could try... storing those tasks, looping over them later to check if they are finished... If yes, then attach those gameobjects to them... but they still finish at different times and cause different sync points or ?

violet cosmos
#

@stone osprey The issue with that is you end up processing twice... Once as addressable, then another to convert to ECS

stone osprey
#

@violet cosmos How do you mean that ?

violet cosmos
#

You're trying to load in GameObjects stored on disk as Adressables to ECS, right?

stone osprey
#

right

violet cosmos
#

So, it's loaded once as a GameObject, deserialized in that fashion. Then, it needs to be converted again to ECS

stone osprey
#

No no no

#

Im not using it that way

#

In order to prevent those issues im doing it like this : Prefab = Visual / ECS = Logic, ECS spawns in the Visual and moves it around... thats pretty much all

#

Theres no conversion going on here, atleast not that automatic ecs conversion from unity

violet cosmos
#

Ahh, so you've written a coupling system

stone osprey
#

Yep, or atleast my own mechanic to prevent this automatic conversion. I couldnt use it because it was not compatible with the rendering im using

hollow sorrel
#

but they still finish at different times and cause different sync points or ?
no since then you'd be doing addcomponent in the same loop, so just 1 sync point
the benefit there is you've got one centralized and predictable point in your gameloop where you're doing structural changes

stone osprey
#

If thats the case... then thats wonderfull

amber flicker
#

Apologies for being a bit lazy to get into this earlier. The way I think about it is the lambdas/jobs are used for scheduling - "I'm doing this main thread work now", "I'm sending this work wide starting from now". Having async within that block makes it very hard for the scheduler or user to understand imo. That's why I'd be surprised if it was supported. Sounds like you've got a way forward at least?

stone osprey
#

@amber flicker Its all fine, thanks πŸ™‚ The problem here is that adressables are only using async operations... but im gonna try the task approach now ^^ we will see if that works better

amber flicker
#

Cool - there are definitely lots of ways to approach it - good luck πŸ’ͺ

violet cosmos
#

@stone osprey I think you're approaching it from the correct angle too, to bypass Hybrid

#

I was trying something different, to load complete Prefabs, before I got annoyed and quit DOTS haha

stone osprey
#

@violet cosmos Thanks a lot πŸ™‚ I honestly dont like the hybrid approach that much, its ton of works to convert all the scripts... and i think its much cleaner to seperate the visuals and the logic... the only difficult think is to handle such things as healthbars/progressbars that normally belong to the player gameobject itself ^^( furthermore that aprroach gives more controll to my server, which is now able to "build"/construct entities by itself )

#

Is there a way to add components to a entity inside a Entities.ForEach without a command buffer ?

hollow sorrel
#

yea you can still use entitymanager for that

#

also need to add .withstructuralchanges to your entities.foreach

fluid kiln
#

What's the best way to have a lookup in a Component? It seems I can't use NativeHashMap

deft stump
#

DynamicBuffer

stone osprey
#

@hollow sorrel Thanks, that solved my issue :9

fluid kiln
#

Even if my keys are not incremental? If I have key 9 and key 128 I'll have to create a dynamic buffer with 129 spaces right?

coarse turtle
#

How about UnsafeHashMap and put it in a ComponentData?

amber flicker
#

You can use dynamicbuffer but your entries are another component with a key/value. Alternatively you could store a hashmap separate from an entity. Alternatively I think if you get comfortable with unsafe you can use unsafe containers with ICDs - like psuong just mentioned πŸ™‚

fluid kiln
#

Any measures I have to take when using UnsageHashmap?

coarse turtle
#

Yeah - you'll need to release the allocated memory if you destroy the entity

fluid kiln
#

Got it, thanks!

stone osprey
#

Is there a way that one archetype depends on another archetype and only adds further components to it ? Something like archetype inheritance ?

coarse turtle
#

hmm not that I know of, there might be some way to get the composition of an archetype and use that in your new archetype πŸ€”

stone osprey
#

@coarse turtle Thats a good idea ! I just saw we can get the stored components... so we can simply pass them to the next archetype ^^

drowsy igloo
#

I've got a somewhat complex movement system that I want to break up into functions; however doing so seems to require running on the main thread because I'm passing components to those functions. Anyone have some best practices, tips, or resource/info links on this? I was hoping to avoid breaking into separate systems due to the dependency logic needed there but will if necessary.

hollow sorrel
#

@drowsy igloo if these different functions make use of the same set of components, you can use static functions and call them from your entities.foreach

drowsy igloo
#

@hollow sorrel I think that's exactly what I was looking for. Thank you!

fluid kiln
#

How do I instantiate a gameobject prefab into an entity, but without the prefab tag?

opaque ledge
#

why would you want do that

amber flicker
#

Does anyone know if ICD's with BlobAssetReferences should get copied over when using EntityManager.Instantiate? I thought they did but from what I'm seeing right now they don't.

north bay
#

They are supposed to

amber flicker
#

Thanks @north bay πŸ‘

inland root
#

Is there a way that one archetype depends on another archetype and only adds further components to it ? Something like archetype inheritance ?
@stone osprey I may not understand your use case exactly here. But, in general: if you think you need inheritance, you may be missing the point of composition.

stone osprey
#

@inland root No... heres a little example : We have one tree archetype, but we also wanna have certain variants of it, one should be on fire, the other one should be moving around randomly and the last one should be a apple tree... in other ecs theres archetype inheritance, which means we would have the tree archetype and all the variants use the same archetype as a base for adding more components. This way we save us some code πŸ™‚

zinc plinth
#

if you think you need inheritance, you may be missing the point of composition.
landon is right

inland root
#

@stone osprey I can see the how that may seem useful on some higher levels of abstraction in a codebase... but i don't think it's really saving you that much code and like all inheritance, it can break in the future if you didn't predict the inheritance taxonomy correctly. composition avoids this guessing game entirely

#

and composition still allows you to reduce code duplication without these problems that inheritance creates sooner or later

stone osprey
#

Probably the word inheritance is wrong, because its no real inheritance... thats what i mean, its only the inheritance of the structure of a entity... i see no reason why we shouldnt inheritate the structure, otherwhise we repeat our self in such cases : https://pastebin.com/RwJkPaBm

zinc plinth
#

that's exactly what inheritance is..

#

tldr: no you can't do that

#

and you shouldn't

stone osprey
#

So i should repeat my self till im dead ? :ΓΌ

zinc plinth
#

yes

#

I mean repeat your archetype code *

inland root
#

but yeah I can see what you mean and there being a use case for it, similar to struct inheritance. Just wanted to mention that if not for you, for others reading.

stone osprey
#

I dont agree with that, i totally understand that composition is a great concept and thats why im using the ecs, especially for runtime... but structure inheritance is a whole different topic. If i really need 50 variants and all should only change a few components its much more effective to inherit the base structure. Its still composition, because those can get changed at any time.

tiny ore
#

@stone osprey I see your point

#

You are talking strictly about data-composition "prototyping", to simplify archetype definitions

#

Not code inheritance...

stone osprey
#

Exactly finally someone that understands me πŸ™‚ @tiny ore

tiny ore
#

To me it would make sense to a certain extent (I see a value in it for when prototyping entity archetypes that will be used to instantiate the entites)

#

Just one remark, however

#

Because you should INDEED embrace the purist composition approach when creating the systems/code itself, the value of this is LIMITED...

#

As you should fully use and abuse adding and removing components in runtime based in code... Not fully pre-defined archetypes that never change...