{
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();```
#archived-dots
1 messages Β· Page 177 of 1
Well now I do see it doesn't make sense that I add NetworkStreamInGame if I delete the entity on the same frame
i see, yes you need to delete this one
What's the point of NetworkStreamInGame, I think this one is just used for the GoInGameRequest, but not necessary on other RPCs
no it's on the connection entity
exactly
do you use a GoInGameRequest like in the sample?
Yes
then you don't need NetworkStreamInGame - remove the WithNone and the add
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
and add .WithNone<SendRpcCommandRequestComponent>()
exactly
good catch
what's weird about this system is that it creates the same comp. at which point are you creating ChangeTargetRequest?
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
yeah, do that
But instead of creating a new entity
I can just AddComponent<SendRpcCommandRequestComponent>
Makes sense
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
this is my create code in a monobehaviour
{
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();
}```
var localNetworkEntity = group.GetSingletonEntity<NetworkIdComponent>();
and group is ClientSimulationSystemGroup
you don't need a system to add the TargetConnection
it should work though
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>
yeah
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
sure, you already have it
Yeah yeah
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.
whaaat, are you for real?
@blissful gorge whats the strategy there? is it like stack based?
@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.
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 π€
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
I am confused on how to raycast
What's wrong?
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
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
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();
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
A rare bit of info on subscene manipulation here: https://forum.unity.com/threads/generate-sub-scenes-programmatically.868984/#post-6280625
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
so I have a question on the ECS sample on raycast
?
I'm confused on the IgnoreTransparentClosestHitCollector
like, what does it do specifically aside from its namesake
huh I have no idea, never used this
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 ?
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
Why is it its own entity?
Or you have a child who's transform is the bars spawn point and you use that to spawn it on its location
Instead of a component defining an entity has a progress bar
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
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
@fluid kiln what if I just want to check if certain entities has certain tags?
Probably shouldn't work with tags in ECS, not even sure if they're transfered over when they are converted to entities
not that kind of tags, I mean, certain components (empty components are called tags)
Ha good to know
but yeah, is there way to do it? filter out entities being hit by the ray that have, say, ExampleComponent attached to it?
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?
static
In that case can't you just manually set the Belong To field in the inspector?
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.
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
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?
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
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?
Yeah you'd have a system that updates your physics shape accordingly
uuuugh... so freakin tedious...
It'd be cool if we could raycast with the same filters as like an entity foreach
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.
@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
god why is this not documented
and it's buried between layers of examples that's not commented right
π€·ββοΈ
give me a freakin' explanation Unity!
It's preview packages π
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.
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
Does this work even if said entity is set as kinematic ?
yeah you can move an entity thats kinematic with its physicsvelocity component
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.
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
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...
You can do in OnCreate
OnCreate() {
RequireSingletonForUpdate<T>();
}
or ```cs
if(HasSingleton<T>())
//stuff
thanks! that was what I needed, didn't know there were singleton methods in the component system!! was using queries
thanks a lot
Hmm what assembly definition has NativeArrayUnsafeUtility?
Editor\2020.1.2f1\Editor\Data\Managed\UnityEngine\UnityEngine.CoreModule.dll
According to Visual Studio
ah thanks π
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?
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
yea, there seems to be some Entity rewriting magic for component and buffer element fields
at post-conversion
ah, chain a system to consume the dynamic buffer then?
what I want to do is put an array of entity prefabs in a blob, specifically avoiding dynamic buffers
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
ah, you mean at the start of runtime read the buffer and reconstruct the blob?
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
Probably will end up with something like this, was hoping for a less messy solution. Thanks
conversion workflow is pretty brittle so you have to make due
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.
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?
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
What's wrong with ComponentDataFromEntity?
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.
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
ECB is only for structral changes, such as adding/removing components and create/destroy entities
changing component values is not a structral change
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
Are we just not supposed to use GetComponent with burst?
Can't see why we would't
The ECB doesn't have that method
if you need random access to a component yeah, you use GetComponent (or ComponentDataFromEntity if you cant/wont use ForEach lambda)
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
try regenerating the csproj files
should be in the project settings or preferences (I forget which exactly)
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
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
yeah I'm trying to figure out which one requires which version
might have to uninstall all dots packages and reinstall in order lol
yeah maybe
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
it's still in preview but it's much more stable than URP 9
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
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...
Anyone here have some experience with the DOTS mathematics random struct?
I had a brief attempt at it and then quickly gave up 
I'm using random.NextFloat2Direction() * Distance which is magically returning the EXACT same value every time when I use them inside a Entities.Foreach
are you sure your able to use them inside a job
I have a solution for that
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
you need to give it a seed
It has a seed
does the seed change?
like time or something
the issue seems to lie with the capture in the Entities.ForEach
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()}");
very likely that's the reason why schedule is so slow sometimes. Any usage of GetComponent without this attribute leads to hard syncs
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
there isn't really any time in the job though is there π€
You can pass in the Time struct that the system has
Just capture it via a local variable var time = Time;
but that would be the current time before the job is started and it would stay the same throughout the job surely
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
I use random like that:
"""
var random = new Random((uint) UnityEngine.Random.Range(1, int.MaxValue));
"""
The timing master @amber flicker himself brings us knowledge
And then you can reference it inside ForEach
Here we go - https://reeseschultz.com/random-number-generation-with-unity-dots/
N.B. This features a ComponentSystem that can easily be swapped out for SystemBase (not sure why they used it given they change it in the second part)
Reese Schultz
How to idiomatically generate random numbers in Burst-compilable jobs with Unity DOTS.
@little moon Thats broken
Why?
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
@little moon i do the same
But it will receive new random seed each frame
that tutorial looks great I might have to try using it in jobs, thanks Timboc
@little moon If you do any ScheduleParrallel
Ah, that makes sense. I only ever used it with Schedule()
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?
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 *
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)
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 ?
Rather than a collision history I'd maybe store an 'isColliding' bool per entity?
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 ^^
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?)
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
Im actually not using unity physics... im mostly asking that question for my server side implementation π
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
@zinc plinth is there a system to generate triangles automatically?
@coarse turtle delauney triangulating is used purely for 2d..
Ah I didn't read the 3d geometric shape part - sorry
@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.
@amber flicker thank you, I'm going to see the wireframe shader
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.
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?
How can I instantiate a prefab => entity during runtime?
Itβs not really advised at runtime but itβs a matter of using eg GameObjectConversionUtility the EntityManager.Instantiate with the resulting entity
this damn method should have a omega fat WARNING THIS METHOD IS SLOW AS FUCK
Yeah not interested in using it π¦
(talking about GOCY.CGOH)
Should I just create an entity for each prefab on startup then?
would be the best ye
But there's an entity limit yeah?
? no
I have 260k entities in my scene without doing anything appart from my grid
Okay cool, for some reason I had put in my head that a lot of "prefab" entities = bad
maybe you thought of that because of the chunk count, but it's really fine even for like 100/200 diferent meshes
Great π
How do I tell unity to create entities for every prefab in say a folder on startup?
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
Yeah so I'd have to create a prefab manager with a list of prefabs mono, then have it converted
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();
What's the suggested way of creating prefab Entities that aren't actually in any active worlds?
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
@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
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
Oh how do you specify that when manually converting in code?
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
neat, didn't know that there was a include prefabs option for queries https://docs.unity3d.com/Packages/com.unity.entities@0.11/api/Unity.Entities.Prefab.html
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
Do phyics IContactsJob still require the JobComponentSystem stuff, or are there example for the SystemBase yet?
is New NetCode system in unity have a toturial .?
Only the getting started guide
ohh no .
It's only in preview
ok plase link
thanke you bro .very much
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 π’
Yeah I gave up on it, I'm using PointDistance cast instead. But sometimes you have to use triggers -_-
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
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 π
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.
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>)?
you may want to check out this for people who have thought about the exact thing you're doing more (https://github.com/WAYNGROUP/MGM-Ability)
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?
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
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 π
That sounds like a lot of fun π
Musty be really satisfying once it's all working tho
You can do a lot with time and damage - if I were doing it I'd try my hardest to not jump into implementing AOE, healing etc all at once. Some other people here may have more hands-on experience and this thread (should you want to ask questions) is where the other link is from: https://forum.unity.com/threads/dots-skill-system-repo-available.894007/
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.
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
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"
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
What's the best way to store sprites and strings in ECS to be referenced by components?
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)
You could store the sprite as a texture2darray referenced by a component ID, and the string in a nativestring
anyone got something like channels working in netcode 0.3?
@fluid kiln You can try FixedString32/64 - it works in IComponentData
I want to reuse sprites and strings without copying them into every component that uses them
I'll probably do a managed dictionary
Can someone plz explain dots to me, as in what it is?
DOTS is an umbrella term to a series of preview engine features that's aimed entirely at performance.
anyone using hybridv2 and finding its guzzling inordinate amounts of video memory?
a very simple blockout scene is taking 8gbs? π©
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
events isn't necessarily dod, afaik.
but it's not impossible to implement
@dense storm
There are a few ways to do "events"
-
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.
-
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.
-
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.
Has anyone here gotten Trigger events to work with the dots physics?
I can get collision events to work, but the triggers wont .. trigger
are you choosing "Raise Trigger Events" in physic body script ?
I'm not using the conversion flow
I've added a material to the physics body that includes the IsTrigger flag though
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 ?
maybe you can make a static ecb
but why need to create a new commandbuffer system? why not just hook up to existing ones?
I'd like to know too, if the standard is to instantiate the ECB in the OnCreate method or OnUpdate?
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)
Okay that's what I do, thanks
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 ?
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
@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"
@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?
@deft stump I think so, also the fact that the CreateCommandBuffer returns an EntityCommandBuffer with "PlaybackPolicy.SinglePlayback"
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
How did you create an ecb from UI code?
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
@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
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
nope, it's not costly at all
well its relatively costly, but there is no alternative
gotcha
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
ommgggggg
I never realized there was a GetComponent method in Systembase
What the hell
oof
what does the numbers mean whenever the console outputs Burt timings?
higher the number means, that's how much performance benefit we got?
Pretty sure that's the compilation time
@fluid kiln Please don't post memes/reaction gifs on the server.
Got it, sorry
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
so you want the tree to be a child of the drop-calc entity?
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
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.
@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
hmmm are you sure you're not talking about a prefab @stone osprey ?
oh so you haven't filled it up with data huh. so it must load on runtime?
are there prefabs in dots ? Im not talking about mono prefabs ^^
there's prefabs in dots
yea - if you have an entity (or hierarchy of entities) and add the Prefab IComponentData, it becomes a dots prefab
Uh, thats new... and what makes them so special ?
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)
And those prefabs can be used to combine archetypes with data in order to "clone" them multiple times ?
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
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
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.
a prefab is really just a regular entity that doesnt get picked up by systems by default, kinda like the disabled tag.
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() )
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.
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 π
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?)
Nothing stops you from running your server single threaded
afaik dots leverages the power of multiple cores but can still run on one?
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.
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
God I wish there was a better way to reference entities in between client and server in NetCode
What's your problem with the current way to reference entities?
Well, afaik, I can't pass an entity reference to the server because they don't have the same ID.
Do you mean non ghost entities?
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
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
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
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
but then how do I reference "this ability"
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
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
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
Right right I'm liking this, thanks I'll give it a go π
you have to manually add it now
so basically hit the "+" button on top left corner of package manager and write "com.unity.entities"
... why? o.O
because... unity
Entities update, from 0.14.0 preview 18 to preview 19 lol
Yeah, I can't find a changelog for it tough. It still shows changelog for preview 18
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.
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.
diff check shows basically only jobreflectiondatapostprocessor.cs changed
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)...
i wouldn't read too much into it lol
it can be that dots development have slowed down to a crawl
it's been months of no communication and missed timelines for the couple things we were told about Β―_(γ)_/Β―
what dif tool is that @hollow sorrel looks cool
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
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.
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
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.
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
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
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
hmm does anyone have an example of using IJobParallelForBatch? Kind of curious on what ppl have used it for
β€οΈ git fork, also been using it for a long time
Any idea how i could detect destroyed entities ? I would love some kind of reactive system :/
SystemState components may help you
ISystemStateComponentData might help you
Yep and thats where i need help with ^^ : https://pastebin.com/A6nwp1wn
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
My reactive system
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
First: Burst compiling the state... does nothing?
Probably, i just place burst over nearly every component :p
The components aren't the thing you burst compile
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
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
you burst compile methods
^
As a note: No tutorial exists for DOTs. Even if it is labeled "tutorial" it likely has either changed or is wrong
Or is outdated
Tutorials will only exist in my eyes when it is no longer a preview package
https://pastebin.com/1J5DGZ9h this is what i use to determine the "destroyed" entities :/ i only query for the state... shouldnt that work ?
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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?
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
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
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 ^^
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
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... π
fyi you can use WithChangeFilter if you want to - using it comes with caveats and is not meant to contradict what Soaryn is saying
sure
that will still catch every entity that has had a component added or removed though right?
Mmmmmmmmm should, but unsure if you could get "what" changed necessarily
yea I guess you could get a bunch of existing entities in a chunk as well as the ones that were just moved there
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
Likely
I have a cocacola bottle covering a part of discord so having to read around it 
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?
On a side note @stone osprey, your system for checking what was added seemingly does nothing π You just run the invokes no matter what
@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
How exactly?
for removed entities: Always add ComponentA & ComponentB to your entity. Make ComponentA : ISystemStateComponentData then make a system that is: Entities.WithAll<ComponentA>().WithNone<ComponentB>()
@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.
I, don't like it
I uses ECS for the actual performance
Callbacks are inherently bad in this regard
You can simply use : Entities.ForEach(child, childCreated) to iterate over all newly created/attached childs components
As i said, no callbacks here -> performance
Out of curiousity
Have you tried building this to a player?
Just curious if it supports generic systems now
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
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
But wouldnt this run continous ? ^^
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"
}
});
One little other question... is it normal that the stacktrace is not visible sometimes ? :
I haven't seen that. Could be worth checking your editor log and see if it's a ui issue.
potentially but it could have also been a bursted function in the backend
Does anyone know if it's possible to call a burst function from non-bursted code?
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
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
"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."
hmm I read that and then forgot I read it... going to give it a go π
You are setting transforms?
You can do that in burst
you just have to do some silliness to get it to work
???
Sec I'll get you what I did the other day
ugh the new entities package ruined some of my icomponent datas i set in editor wth.
I spent an hour fixing some undesirable movment
Last part should help
Thank you.. processing...
I actually noticed that the Copy To GameObject was broken
Some caching likely could speed it up
The state component is the "only" component left after that entity was destroyed... right ?
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 ?
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
^except not that, as that's internally taken π
yea.. you can't use it in your systems (unity private) but it gets added to entities
oh wait
my bad
I have a CustomSystem.CleanupTag as an example
it's called CleanupEntity - the one I was talking about - my mistake
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
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
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
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? π€
I couldn't figure out where the companion system comes into play so maybe?
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
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"
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 ^^
What is wrong with WithAll/None?
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
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?
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
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
@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)
Why would you recommend against a cleanuptag? I can't read
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
hahah
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
I blame Java for commercializing OOP
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
I believe it wasn't that apparent during C++.
but yeah Universities and Enterprises really pushed OOP to the monstrosity it is now
And it can be useful, but not everywhere π
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...
For sure
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.
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...
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
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
Off of the top of my head that entire event chain is handleable in Unity ECS just fine π
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...
well we wouldn't have C# without OO (probably).
Universities should at somepoint express that there are other paradigms. That is my point
Disclaimer: former Univ professor here.
Not that they need to teach DOD necessarily
Correct...:)
but more indicate heeey OOP is not the only one
We kind of used it in Parallel computing but never generalize it enough to discuss that it is a paradigm
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
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
Good, back to technical topic...:)
did you add it manually?
It it was our ECS I knew...:)
Nope, normally they are getting add by unity itself
I'm half tempted to say it is the generic
dependencies for the system might not be met on the initial frame?
but unsure
@solar ridge Its a destruction system i wrote
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
are you querying components that exists? (I think it'll display as not run if you're query is coming up empty, not sure)
Can you get us a quick image of your system list?
just shift + win + s
unless mac/linux... then rip
there's a dropdown in entitydebugger for show inactive systems, it'd show up with that but not without if dependencies aren't met
As a related note, the Editor they have in the forum is a recommendation I'd propose
Whyyyy is it green?>
Because its running π its the only color that "works"... tried red, black, grey... they all looked awfull
the green burns my eyes
jokes aside. does this DestroyAfter component attached to an entity?
@solar ridge in your post you linked to earlier, what is _transformAccessArray?
TransformAccessArray
Not in the full player loop either :/
ah that makes sense! didn't know that was a thing
private TransformAccessArray _transformAccessArray;
_transformAccessArray = new TransformAccessArray(0);
@stone osprey show inactive systems is a seperate checkbox
That is done in on create to init it once
Than its inactive for some reason
Does anything match its query?
It does... im gonna give rider and unity a restart, hopefully this fixes that issue :/
are you saying you're destroying every frame?
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
cuz if not i'd expect it to just run once and go afk because there's nothing left with destroy tag
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 ?
Like in a ForEach? Don't see a problem in that
Alright thanks ^^
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
Yes that ^
_ecb.AddJobHandleForProducer(Dependency);
Alright, great π
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
is anyone using singleton entities that have managed data without SharedComponentData? is it possible or do we always need SCD?
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
}
hm, thanks. i have to try again with class ICompentData. last time I wrote them I had compiler errors and I stopped bothering.
https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9
Looking at function pointers! This is pretty cool. Does anyone know if this will allow burst to AOT compile function pointers now?
(if/when unity finally supports c# 9 lol)
Also the foreach now recognizes GetEnumerator extension methods -- would this solve the foreach limitation in burst as well?
π’
Also the
foreachnow recognizesGetEnumeratorextension methods -- would this solve theforeachlimitation 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
@solar ridge its an 'or' unless you use require for update on each query
Is there a way to get a component by its type ? Uhm... i mean the type from "typeof()" ^^
Not "manager.GetComponentData<...>();"
Any ideas ?
I don't think this is doable without reflection. Even with reflection I don't know if that would work at runtime.
Hmm... thats awfull, i saw the method "GetComponentTypes" and hoped that you could simply iterate over them in order to extract each one...
I might be wrong
As far as i know not without editing the package
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.
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 π
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 ^^
I once made an entity in game inspector which made use of that
Yeah thats pretty much want i want to achieve ^^ but how did you received all those components with their data ?
Let me check
I wonder if you could use something like chunk.GetDynamicComponentDataArrayReinterpret - not really sure what that's for
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
@north bay So we have the same approach ^^ thanks, and what about the component values ?
What do you mean?
Getting and setting the component values?
yep
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
Thanks a lot ! That should do the trick π
Ah cmon... its not possible to write those methods as extensions ?
no you'd have to copy the package locally - that's why I'd try going with reflection if I had to
Im not that familiar with c# reflection, furthermore i have no clue what method we need to acess :/
Have you tried finding the inspector code that currently exists? I'm unsure if it's in a package somewhere.
@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 );
As for reflection: https://stackoverflow.com/questions/232535/how-do-i-use-reflection-to-call-a-generic-method - is this for editor or runtime?
Not sure how performant this is... but should do the trick for ui
it's not that slow - you can also cache the method info
So i created a little extension for this : https://pastebin.com/euNV3wtU in case someone needs a similiar feature ^^
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
in general you do probably want to cache that methodinfo you make though π
@amber flicker You are right, this time we cache it first and reuse it later on : https://pastebin.com/uzbXdG63
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Atleast a simply cache... of course there more optimizations to follow
I was about to write that you can even cache var genericMethodInfo = GetComponentDataInfo.MakeGenericMethod(type.GetType()); for the individual types
Yep that was exactly was i was thinking π but tbh, im to lazy to implement this rn...
it gets a bit complicated with the entityManager possibly changing too.. looks like it gets you moving forward at least
Do you guys often use reflection? I normally only use it for attribute lookups and stuff
Generally I'm scared about it
Me too... thats why i only use it for serialisation, checking properties/variables or "hacking" into stuff like this entity manager
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.
Apple π
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.
Heard similar stuff about apple... they are pretty scared of everything that they cant "detect" or check during their app review
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
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
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
Your inspector looks like my character authoring prefab
That looks like a slightly painful way to do things π - though not sure what's actually going on
@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
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
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
It should loop over all the vertices and multiply them, but only a couple are affected, and very weirdly
@solid flume my guess is all your threads are using the same noise values or that kind of issue
@solid flume code?
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
@north bay Im actually relieved that im not the only one with so many components ^^
Are float variables shared across all instances of the job?
Oh that's only my character, it doesn't hold anything like moving, shooting or other functionality lmao
@stone osprey are you sure you don't wanna go oop for that? π€£
@amber flicker Its complicated π currently its a mix of oop and ecs xD
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
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
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
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.
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
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.
Yeah, my idea is to try and shy away from things that might complicate it like physics and depending on data such as animations
Someone here is using Worlds for deterministic rollback. Possibly a few. Perhaps check in next week and see if they're around.
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
Yeah I wouldn't really go for it if determinism wasn't a requirement
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
Ok, so your sim world also contains this id?
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
ok, that make sense yeah
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)
How do you copy just the specific components between the worlds?
or do you manually just loop over the necessary archetypes and do it?
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
Alright
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
Thank you, I think I know how to go about this now
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
you can use a static function
Hrmmmm i think i misunderstood your question
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
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?
there is FunctionPointers that you can use: https://docs.unity3d.com/Packages/com.unity.burst@1.3/manual/index.html#function-pointers
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?
One million vertices in less than a second. I love jobs
Although I'm probably never going to be able to make collision for this
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?
UpdateBefore/After onlly guarantess the Update order, OnCreate, similarly to Awake, doesn't have a predefined order
@rancid geode Ok. Thanks!
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?
unless it's a shared component data, I don't think there is
I'm trying to set up a build configuration, but it would seem that the option is greyed out for me. Am I missing something obvious?
@whole hornet you might need to install platforms - (https://github.com/DOTS-Discord/Unity-DOTS-Discord/wiki/Current-Packages) - I guess you're looking for e.g. com.unity.platforms.macos and com.unity.platforms
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?
Curious - I assume you have Mac Build Support installed for the editor? (You can check via Unity Hub -> Add Modules)
I have that as well. In the hub I also tried setting the target as Mac
that's me out of ideas sorry! Good luck π€
No worries, thanks for trying
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?
https://www.jacksondunstan.com/articles/4796 might be interesting
Otherwise there is CodeMonkey who makes tutorials on DOTS, I haven't really watched any of his stuff but might be worth it
Cool I appreciate it
Gonna dive in right now.
Since we're on the topic, BTW, if anyone comes across this at some point, these examples look very promising: https://github.com/stella3d/job-system-cookbook
any idea how to sync dynamicbuffers in ghost snapshots? (netcode 0.3)
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?
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 ?
which namespace is the physics shape? trying to make physics shape a required Component
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Getting that error in that line where i use the "eventCreator.createEvent"
Any ideas regarding that il issue ?
@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
@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.
Ok π - good luck
@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
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 ?
@stone osprey The issue with that is you end up processing twice... Once as addressable, then another to convert to ECS
@violet cosmos How do you mean that ?
You're trying to load in GameObjects stored on disk as Adressables to ECS, right?
right
So, it's loaded once as a GameObject, deserialized in that fashion. Then, it needs to be converted again to ECS
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
Ahh, so you've written a coupling system
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
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
If thats the case... then thats wonderfull
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?
@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
Cool - there are definitely lots of ways to approach it - good luck πͺ
@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
@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 ?
yea you can still use entitymanager for that
also need to add .withstructuralchanges to your entities.foreach
What's the best way to have a lookup in a Component? It seems I can't use NativeHashMap
DynamicBuffer
@hollow sorrel Thanks, that solved my issue :9
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?
How about UnsafeHashMap and put it in a ComponentData?
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 π
Any measures I have to take when using UnsageHashmap?
Yeah - you'll need to release the allocated memory if you destroy the entity
Got it, thanks!
Is there a way that one archetype depends on another archetype and only adds further components to it ? Something like archetype inheritance ?
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 π€
@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 ^^
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.
@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
@hollow sorrel I think that's exactly what I was looking for. Thank you!
How do I instantiate a gameobject prefab into an entity, but without the prefab tag?
why would you want do that
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.
They are supposed to
Thanks @north bay π
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.
@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 π
if you think you need inheritance, you may be missing the point of composition.
landon is right
@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
π Support the show by becoming a Patreon
https://www.patreon.com/funfunfunction
This is a weekly show where we try to become more confident and excited about programming by learning intriguing things that we didnβt know before. Today, we are are going to talk about compositio...
and composition still allows you to reduce code duplication without these problems that inheritance creates sooner or later
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
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
So i should repeat my self till im dead ? :ΓΌ
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.
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.
@stone osprey I see your point
You are talking strictly about data-composition "prototyping", to simplify archetype definitions
Not code inheritance...
Exactly finally someone that understands me π @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...