#archived-dots
1 messages · Page 109 of 1
but the line "Hybrid Components are an experimental feature, their use isn't recommended yet." says a lot
Still, seems like a potential replacement for GameObjectEntity
it's high risk if they don't recommend it
it could change dramatically, or go away
as for GameObjectEntity replacement, how I see it the current ConvertToEntity component is already it if you use convert and inject
what I do wonder is that when you use the HybridComponent, it doesn't actually add that GO to your scene, so I do wonder if it can be more efficient (or if I'm missing something here)
0lento still living and breathing dots! Took a break... Had a baby, you know how it is. Looking to resume my unity happy times. I wonder how much has changed in 6 months or so.
I'm only fiddling with this tech, just trying to keep up where it's developing
the dots are.. still being connected 😉
but there are bunch of real hardcode dots devs here, so lots of cool stuff to see here
congrats on the baby 🙂
ty ty 😄
👶
lol
she will be my 3d modeller later
@minor sapphire you've probably kept up-to-date with things that Unity has showed on last Unite tho? basically we just have those new systems now
when was last unite lol
like the entity conversion live preview in editor for dots subscenes, simpler way to write basic foreach on entities, and autogen for componentdata
it was last fall on copenhagen
right right. I saw havok physics pricing, and 256 lights on URP too
would love to see if those things perform well
urp support for hybrid is still coming up
dsp graph is still there..
I think some of the URP's hybrid fixes may have been included on 7.2 which is set to release today
there's no higher level dots audio yet
damn, taking a while ey 😄
it's coming but we don't have it
and we got that DOTS sample for their third person shooter (with dots anim, netcode etc)
the thing they showed at Unite CPH keynote
oh cool that should be handy to look at
so networking in dots is coming along then?
if you'd ask the networking guys, they'd say it's still raw 😄
I don't know enough of that side to comment even
current state of hybrid renderer is still pretty weak feature wise, but Joachim recently said they plan to make the hybrid work with fully featured HDRP soon
expect it to happen through 2020 cycle
interesting
officially focus is making HDRP work well first but they are fixing URP as well, it's just not their primary focus first
right so HDRP is getting the love
with hybrid rendering that is
yea
I guess it's easier for Unity to make flashier demos with HDRP
true
it's not like they abandoned the rest, just matter of resources
has anyone seen performance comparisons between unity and havok physics?
I think Havok guy had some figures on the havok physics talk at that same Unite, not heard of user made benchmarks
there were bunch of issues with the first havok package and the whole physics setup is still bit... raw
I dunno if it's really something you'd want to start benchmarking against atm as there are more pressing matters than the raw perf
but for example, with the first havok package, you got even huge perf regression on editor even if you didn't even use any physics from it, if you just had package installed it sank your perf figures 😄
and also if you used HDRP with it, your final build would have only rendered one color on whole screen
it was really funky
I don't even know how they managed to break totally separated system
I first thought it was some built-in protection system to prevent people from shipping games with the early havok plugin version, but after I talked with the havok guy, turned out it really wasn't like that by desing 😄
lol
they did release a new version like month ago for that plugin but it's changelog was super small
it really felt like they just released it because the initial version had timer that prevented you from using it after certain date
this happened around the same time they put the havok sub to asset store
physics still feels kinda raw considering how much they seem to be logging as bugs and improvements for future releases
like surprised havok has a paid thing considering
https://docs.unity3d.com/Packages/com.havok.physics@0.1/manual/licensing.html so is that licensing model still accurate? - I haven't actually taken a look at the pkg
ah cool 👀 thank goodness im on free haha
I wonder where they draw the line on having to pay for the sub
like, once you launch the game using it, you'd assume you don't need to keep paying unless you do some updates for it
hmm yes interesting
can you just pay for months where you did actual development...
I haven't read the fine print
"Oh, I was using unity physics to develop, I only just started using Havok physics the month before deployment..."
according to the docs, they actually prevent you from using Havok on Pro unless you pay
tbh, it's tad weird offer, I was hoping they would have just included the havok on the pro sub price when they said they bumped the sub pricing in general
pro went from 125->150
but at least they didn't make it pro only thing 😄
that would have sucked
and knowing Unity's past, they could have totally done that again
especially with Joachim telling through 2018 that ECS sources are planned to be given to pro subscribers only
or was it dots packages in general
anyway, there never came any info about it and we got full sources for most things
so all good now
(I'm on paid tier myself but only on Plus)
It was interesting to me that havok was also free on Plus
they announced the pricing model at last Unite
but it's only been for sale for one month or so now
yeah I saw that a while ago
right
are you actually working on a project 0lento?
my main fear is that if some other asset publishers follow this model now that asset store supports subs
yes
may I see?
it's unannounced atm, but should be able to show some stuff soon
yes, it's one of those eternity projects but I'd really not want to go to details on that 😄
ambition kills indie devs
lol yes
after baby, I thought I really need to think of something i can actually achieve on my own
but I would like to work with someone in reality, just, how do you find people that will work well with you and not cause more problems than it's worth lol
realistically you have to pay to get good people
yes, and to avoid disagreements
be the boss
but yeah, main thing is to keep the scale down when you work on your own
I'm not building my dream project as I simply don't have resources for it atm
did you end up getting a ryzen cpu?
you mentioned the 12 core 3900 a while back, or was it someone else heh
yeah, I got 3900x, I was waiting for 3950x for ages but got tired waiting
even 3900x stock was nonexisting but managed to find one locally
did you get some sweet sweet dots performance?
did you even manage to saturate it? lol
I just did some naive test yesterday with new burst preview and it's AVX support, tried to see where it goes with double precision floating point math
roughly I got 4x perf with 6x cores (I tried running same code with 3 workers and also with 23 workers)
main painpoint with this cpu is that unity profiler is just massive PITA on 24 hw thread computer
imagine having 23 workers on your timeline and trying to find things there
haha I was imagining the profiler yes
4x perf improvement due to this AVX thing??
and if you limit it to few workers, it still spawns them initially to random placse, so your 3 workers may be worker 1, worker 10 and worker 23
oh lol
so you actually have to scroll down to see each worker
I'm considering the 3700x
I should report this on the forums as it really is pain
3700x is awesome
like, best bang for the buck today
reason why I was going for higher is mainly because I also compile ue4 source code
right, which takes advantage of the threads?
but extra cores do help in unity too, especially when you build hdrp shaders
right
yeah, c++ and shader compilation is just brute force
it scales almost in linear fashion when it actually compiles things
linking stage is the one that's slow as it's often just going on one thread
I was going to come back to that, it's not quite that substantial increase
I really should do better test as I did have issues on getting Burst to even vectorize properly trig math
apparently there's no crossplatform sin etc
but on the initial test, I got tad better perf on AVX for doubles than with SSE4... but with floats it was almost 100% same on both
which could change if I got the vectorizing working
I then just manually forced it to use double4
is it a SIMD related thing?
yeah
but for example, my naive brute force test ran 600+ms on regular unity c# code, and with 3 workers + burst I got 37ms on SSE4, 28.5ms on AVX
and under 7ms on AVX with all 23 workers active
so even if it wouldn't scale perfectly, it's still huge perf improvement
even the SSE2 to AVX is a nice improvement, and that bit is free from burst?
sweet, burst gets even better
but SSE2 should be quite similar (edit, ah I had a typo)
did they ever implement burst for non-jobs?
Burst also supports AVX2 now which I also tested but it was only fraction faster
or being able to reference constants outside of jobs etc
right right
there are function pointers now for burst: https://docs.unity3d.com/Packages/com.unity.burst@1.2/manual/index.html#function-pointers
oh and, those tests I did, I didn't use ECS for them, only burst + jobs
wanted to keep it simple as the main focus was to test what happens with doubles
but yeah, you can run burst outside of jobs if you use those function pointers
it's not the simplest setup but it's there
and you can also schedule a job to run directly on main thread now, bypassing the job system overhead
(which can be quite substantial if you don't do much on your job itself)
Sweet
Wasn't that just something like Job.run or something. Memory is sketchy though
yeah, that thing
this is still my new favourite thing on DOTS (when it actually works): https://bintray.com/unity/unity/com.unity.dots.editor/0.3.0-preview
that gives that entity conversion live preview on editor for DOTS subscenes
works at runtime too
Interesting. I guess the editor must have some nice improvements too
Soooo.. how can i assign my systems to work on only 1 scene ? i was trying to explore some samples from one of the packages but my systems still tries to run, should i create my own world ?
You have to add [DisableAutoCreation] to yours system and handle creating and updating it yourself. For my roguelike tutorial I had to manually attach a bunch of related systems to each scene. For each scene I add a bunch of systems to a ComponentSystemGroup with AddSystemToUpdateList and manually update the ComponentSystemGroup inside the monobehaviour update.
It works well and the systems will still obey the [UpdateBefore] and [UpdateAfter] attributes as long as they're in the same ComponentSystemGroup
Only downside is the systems don't show up in the entity debugger since they're no longer a part of the "default" groups
wow thats actually huge downside 😄
i actually tried to create my own world but.. i have to add default systems myself which i was lazy to do
but i will check it out, thanks
Are there some restrictions of not being allowed to use "GameObjectConversionUtility.ConvertGameObjectHierarchy" inside a convert method of an authoring component?
I am trying to get my head around the new DOTS stuff. I have a script that suppose to render the objects at random points. But all them them appear at [0,0,0]. Is there something I am doing wrong?
{
EntityManager entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
EntityArchetype entityArchetype = entityManager.CreateArchetype(
typeof(Translation), typeof(RenderMesh), // Rendering
typeof(LocalToWorld) // Coordinate conversion
);
NativeArray<Entity> entityArray = new NativeArray<Entity>(3000, Allocator.Temp);
entityManager.CreateEntity(entityArchetype, entityArray);
for (int i = 0; i < entityArray.Length; i++)
{
Entity entity = entityArray[i];
entityManager.SetComponentData(entity, new Translation { Value = new float3(UnityEngine.Random.Range(-500f, 500f), UnityEngine.Random.Range(-100f, 100f), (UnityEngine.Random.Range(-500f, 500f))) });
entityManager.SetSharedComponentData(entity, new RenderMesh
{
mesh = mesh,
material = material,
});
}
entityArray.Dispose();
}```
ok. so it did this because it didn't like the material I selected.
entityManager.SetSharedComponentData(entity, new RenderMesh
{
mesh = mesh,
material = material,
});``` i think not a very good idea🤔
How come?
or mayby not😋
got the GameObjectEntity class removed? setting everything up to convert my projectiles to hybrid ecs and i cant find that damn class 😦
You use ConvertToEntity now
awww great -.-"
@fiery sinew but you can use cs Entity entityPrefab = entityManager.CreateEntity(entityArchetype); entityManager.Instantiate(entityPrefab, entityArray); and get rid of 2999 SetSharedComponents🤔
Found it, it gets added if you add any "Transform From GameObject" script.
@plush portal ty for feedback, i agree
Quick sanity check before I spend time implementing it... I want a NativeArray<> or NativeList<> accessible on a player entity - it's not currently implemented as a singleton entity and I'd rather not do so so that I can later extend this code to multiplayer if possible.
I'm thinking of making a dynamicbuffer instead of the NativeList<> - is it comparable in speed? Is this still the canonical and/or a sensible way to go about the problem where you'd ideally have a NativeContainer sat in an IComponentData struct?
Cheers in advance!
If I wanted to have all my entities move around.. I create a ComponentSystem and iterate through the entities that contain the component I want and the move them?
{
protected override void OnUpdate()
{
Entities.ForEach((Entity entity, ref MovementComponent movementC, ref Translation translation) => {
translation.Value += (float3)Vector3.right;
});
}
}```
like that?
they all move.. but I am not sure if that's the correct way of doing it
it is-> but get used to tag(dunno if its the right description) components you dont change with "in" and not with "ref";
Entities.ForEach((Entity entity, in MovementComponent movementC, ref Translation translation) => {}
Hi guys. Still in the process of learning how to design in ECS, I'm doing a turret which is firing "target seeking rockets". In my design right now I've got a system that spawns rockets with a given impact position local to the target. But the target is moving. How would you do that using dots? would you put the target entity inside the component and retrieve the new target position for every rocket inside the RocketMotion system?
I wouldn't use ComponentSystems either they are probably not going to be supported in the future, and Vector3 wont work bursted in Jobcompsystems
DynamicBuffers still the canonical way to have per entity arrays?
@wary anchor i think canonical way is to use dynamicbuffer and .ToNativeArray() it when iterating
if you want to store containers on icomponentdata you could also try fholm's unsafe collections
https://github.com/fholm/UnsafeCollections
would need to benchmark tho, i think fholm's stores the array outside of entity chunk as opposed to small dynamicbuffers
@pliant pike What do you use instead?
If I have a fixed size arrays that never change, basically array of prefabs, is it better to put in in a DynamicBuffer or as an blobasset?
Cheers @hollow sorrel Yeah fholm sent me that link a while back about something else, I stupidly didn't think to look through it. Thanks!
@fiery sinew in place of Vector3 you mean? you can use it outside of the Entities.foreach if you really want to, assign it to a local variable then pass that local variable into the foreach
I mean the ComponentSystems
JobComponentSystem
I tend to use JobComponentSystems and float3 as my go-to
@mystic mountain i could be wrong but i think blobs are meant as immutable data that's shared across multiple entities, like scriptableobjects
not sure what perf difference would be
Thanks! Ill look it up
creating blob is prob slower than just adding a dynamicbuffer to an entity
yeah I've used Blobs and they are a bit of a headache to set up
they kinda feel like an afterthought atm
I'm hoping they get a similar treatment to the job struct, they simplify the code bloat needed
there's some good examples of blob use here: https://github.com/periodyctom/Hydrogen.Entities/tree/master/Samples~/SimpleDatabaseExample but they still seem like a giant pain in the ass to use
As this is maybe like 30 entity prefabs for spawning (visual and collision), it would be adding this dynamicbuffer which never changes to all of the same entity. Why I thought using blobasset would be less memory etc.
i hope not, not a fan of all the codegen
it makes sense to codegen lambda's away and netcode to avoid reflection but everything else feels like extra overhead
also i wish physics didn't use blobs for colliders
changing a collider is a real pain in the ass with blobs
I know, this is my problem x)
I get invalid codes when I try iterating over children of compound colliders to change filter, so my current setup is to create a entity prefab for each physics layer I need.
i want to change them nearly every frame of animation for a 2d game
haven't tested how expensive that is with blobs yet
since would have to recreate them every frame
also @mystic mountain if those 30 entities point to the same array then blob sounds like a good use case there
unless they all need their own
I don't think the CollisionLayer is within a Blob, only the collider, so depends what you do.
yea i mean the shape of the collider
like if you are crouching your hitbox should change
What I do is I create all colliders on startup, store the reference in a component, then I swap the PhysicsCollider's reference.
hmm that might be the way to go
Or store in a system, how ever you want.
This is my code rn to create the blobassets, my problem is that I get errors that the physicsColliders blobassets are invalid https://pastebin.com/fu8fPcUn
what determines when i should create another system? in the past i've created one system for each group of *something*. like one system for characters: movement, physics, rendering, input, etc, all in one (multiple jobs, of course). so far in my DOTS projects i've had maybe 3 systems per project max. should i be splitting up systems for better performance? like a system for character movement, a system for character physics, etc (similar to how i use monobehaviours)
Mmmm looks like fholm's unsafe pointer collections may be the better bet, my data array is too big to store on the entity sensibly, so keeping it away and just pointing to it seems like the better bet. Time to get dirty with code I'm not comfortable with! 😄
@craggy orbit I'm not saying this is the best way of doing things, but this is how I have mine set up right now:
ok so I switched the job component system and the framerate tripled haha thanks guys (Y)
forgive some terrible system naming 😄
Each extra system has a small overhead but use as many systems as makes sense from a code clarity and organizational standpoint.
no worries about the names (at least, i dont personally care). but it looks like you have multiple systems for each game element
ah gotcha. so i may as well have multiple for clarity
that's nice! i didn't know if there would be huge overhead for each system. though i guess i should have know better, given the whole "performance by default" thing 😅
So I notice that if I convert my GO collisionPrefab once, it works fine without errors, but if I do it once more I get errors ...
i'll just split them like i would monobehaviours. thanks you two!
also sometimes you might have two functionalities that seem like they could be in the same system
i think a good rule of thumb for those is: does it require different components then different system, if same components could prob chain it in the same system
they said last year they want to be able to support 1000 systems in a project without causing performance issues.
i think i'll keep it under ~50 😅
😄
i'm pulling these numbers out of my ass but i imagine average finished indie game probably has around 300 systems? if you split up functionality like you do with monobehaviours
AAA 1000+ for sure
I use the rule of thumb that Scorr alluded to there: do I need to work on the same set of components? If so, one system. Do I need different components? => different systems
also keep in mind that not all systems will be running all the time
most will only do something when that component is available, like spawning smoke particles on hitting stuff will only run when you actually hit stuff
I'm currently trying different ways to get a reasonably large array associated with an entity without being stored on it as a DynamicBuffer (too much data). I'm refactoring a couple of systems as I go trying to rationalise where I can but it's a whole new approach to refactoring tbh
I can solve my problem by instantiating the object and converting the instantiated object instead of the prefab, lol ._.
yeah in that pic above you'll see loads of "not run" where I have for example```cs
RequireForUpdate(playerEntityQuery);```
@mystic mountain wow, that sounds super weird
kinda dealing with similar problem right now too roo, but for a grid tilemap
atm am just thinking to put a dynamicbuffer of 16x16 tiles in a chunk entity and then maybe a native map somewhere to get the correct entity when given a position
but a nativearray outside entities instead of dynamicbuffer to store tiles could also work 
or fholm's unsafe arrays, idk
My issue here was I was using a NativeList but getting errors about not being able to write in parallel (which it won't as there's only 1 player). Seems wrong to just disable the notification for that where I should probably restructure how I use and store the data instead
I suppose I could create a 2D array of player + NativeCollection for these data per player instead
I guess NativeMultiHashMap
i think at that point then entitybuffer/unsafecollection on player entity would be better
i mean dynamicbuffer not entitybuffer
the data are too big for a dynamic buffer apparently
even if it's too big it just gets allocated outside the chunk
Then I did something else boobooish
ArgumentException: Entity archetype component data is too large after adding PlayerNearbyPickupArrayBufferElement [B]. Previous archetype size per instance 1024 bytes. Attempting to add component size 16448 bytes. Maximum chunk size 16064.
{
public float3 direction;
public void Execute(ref Translation translation)
{
translation.Value += direction;
}
}```
Is there anyway to make that only happen if the entity has a specific component?
oh huh you actually get an exception for that
[RequireComponentTag(typeof(PlayerTag))]
@fiery sinew
use an empty IComponentData struct as a tag
haven't tried but i thought it should automatically resize and move it outside the chunk when it becomes too big
@wary anchor I went with using a dynamic buffer and 3D indexing to access it, which was useful in the begining because i could use the Entity Debugger inspector to see what was going on inside it at any point in time. But i didn't end up actually accessing it directly from any jobs. Just been passing it in to jobs so it was kinda pointless to be a dynamic buffer, it could have just stayed external to entities.
I'm also wondering about speed on this, but my project is massively GPU limited so I have a huge amount of headroom right now
you used NativeList because it needs to grow?
It turned out to be simpler to use on my 1st iteration I'm not wedded to the List. I'd prefer array as it's going to the GPU directly.
I'm going through a large array of all the pickups in the scene and trimming it down to those within X radius of player this frame
(not that large an array actually, it's going to be limited most likely to well under 1000)
So big array of all stuffs as input to some job, checking conditions and outputting a subset as list?
yeah in essence, an array would have been better but I don't know up front how many will be in the array. Probably a much better way to do this...
seems similar to something im doing, except i have all the pickups positions already assigned to a grid. So i can take the player position, use that to direct index into the array, and step in a cube/spiral the indices for grid locations around the player and grab any pickups found.
so it doesnt matter if its 100k pickups, its still going to be super fast becuase its not iterating the full set.
my first iteration used a naive grid to accelerate it (which I use elsewhere) but I had some other issues on this part specifically and it made some sense to switch out from that. I'm also using these data for raymarching downstream as my pickups are also point lights but that's another story. In this system I'm checking for nearby lights which I will send to the GPU to render, and at the same time checking for collisions of any of these lights with the player (for picking up code)
sorry, using "light" and "pickup" interchangeably here
got the dynamic buffer working so might stick with it if the perf is okay 😄
Mmm although getting weird NativeCollection Not Disposed error that I don't quite understand because I think I am disposing of it... sigh! Time to check more carefully where I made this mistake 😄
im just procrastinating figuring out whats wrong with my code 😄
99% of dev time ^^
Ahh I was assigning a new NativeArray<> but hadn't explicitly disposed of last frame's one (only in OnDestroy).
@mystic mountain You can serialize your colliders and load them from disk instead of creating from code.🤔 Saw that code on forums https://pastebin.com/m9bAqMyS
What do I reference in a IJob if I wanted to change the color of an object? It doesn't allower RenderMesh
You can change the material on the RenderMesh to change the color.
Kind of a tricky question. If you want to change the color of a single object you basically need a new material or you need to use "hybrid instancing", which is only supported in HDRP right now
oh that's a shame
Either that or a custom rendering solution
Is there any benefit of using math.abs instead of Mathf.Abs?
burst😏
yes! its burst compilable, and it creates simd instructions, so you should use it if you want to use burst and ecs in general
As far as I know they are both burst compatible, and I wouldn't be surprised if they get compiled to the exact same code. The only real reason is for consistency and readability
@warped trail interesting, but since it's compound and setup through GO I still kind of need to do the thing I'm doing.
I guess the "math.abs" version is decorated with "InlineAggressive" so it will probably perform better if you're not using Burst but....a bit of a stretch
My player entity is not showing anything in the inspector when I select it in the entity debugger. I'm also getting some very weird behaviour where a square distance check doesn't appear to be triggering an if statement which it should (and before this inspector problem I could verify that the values in the float3s should have passed that check!). Need a bit of help debugging this, I tried restarting unity but that didn't help
hmm I can select it when I go to All entities but not when I select the same entity from within any of the systems where it's found by the query
Whenever I've had problems like that where it seemed like the entity debugger just wasn't updating it was because I was constantly writing to the entity every frame. It doesn't like that.
The current debugger is basically just a stopgap until they write the "real" version I guess so we have to kind of work with what we've got atm
yeah that'll be the case here for sure 😄 It's got a dynamic buffer on it. At least now I can access the entity this way I can see that the number it's calculating is wrong. Now to work out why it's wrong!
it's almost certainly roo being a dumbo that's for sure 😄
yup, found it. Sigh.
how dumb was it on a scale of 1-10
I'd say probably a 7
refactoring 2 distance checks which were independently running on all pickups beforehand into a single pass, but forgetting that they have explicitly different ranges, so basically overwriting "nearest" with "latest added to the big range"
hence it would occasionally work when I happened to step on the latest added
anyone noticed weird behavior with unity physics gravity, my objects are falling in slow motion :S pretty confused because i'm not manually influencing their position, theyre just dynamic and its not friction on an object since theyre in air not touching anything.
@mint iron Did you change the Gravity Factor of the Physics Body?
its the default of 1
pretty sure thats because of the dynamic tick rate
they are meant to be updated in a fixed timescale but are currently updating in regular update
try turning off vsync and see if that speeds them up
I was about to say that
hmm, that seemed to have helped a little, its almost passable but still looks wrong.
how the unity physics atm is that they run simulation group on each unity frame update, but actual unity physics simulation code assumes each simulation group update is a fixed timestep.. so if your game runs lover than 50 fps (which physics are set to with the default fixed timestep of 0.02ms), things slow down and if you run faster physics speed up
this has been how unity physics has been setup from the start and Unity has never fixed it for anything else but the netcode package
it seems to be like super low priority thing they want to tackle only after they get rest of the systems in place
if it were up to me, I would have had some temp workaround built-in from day one :p
So physics doesn't behave uniformly based upon framerate?
it's literally skyrim physics, faster you run the game, faster your physics move 😄
it's not by design, they just haven't implemented the simulation group stepping properly yet
Yeah people have been asking for deterministic updates for over a decade. I guess getting it consistent across platforms can't be easy or surely they would have done it by now
yeah, I sure hope they wont put it back on unity's own fixedupdates
that's closed source side again
I'd always want to have full access to this code specifically
(I have bunch of extra solutions for the traditional failsafes you have there which I've implemented on other engines)
that structure is bit messy but it appears to work
you can make SetFixedTimeStep(float step) public in ComponentSystemGroup, and make whole SimulationSystemGroup update in fixed steps😏
What are the real world implications of this problem?
you basically have to solve it yourself
Not having determinstic behaviour creates a ton of issues in physics and networking in particular
or use someone elses solution
So you have to do a lot of annoying hacks to do it yourself, yeah
that post I linked will put simulation group to fixedupdates + implement physics body interpolation
Is there a really simple example you could use to illustrate the problem?
I feel like physics should be framerate independent
there was a super simple workaround in past for just the fixedupdate hack but last time I used it, it crashed the engine 😄
well it's designed to be
it's just current implementation lacks one key part
@stable fog It's ancient at this point but https://gafferongames.com/post/fix_your_timestep/ illustrates the problem when you don't have a fixed timestep
what I try to say, they never designed the unity physics to work like this
oh, but not everything you do IS framerate independent, including things which can affect physics, therefor it can lead ti issues
well, it's not even lack of fixedtimestep, you can run physics at variable timesteps too and have somewhat nice results, ue4 actually does this out of the box.. it's just not as deterministic for physics sim and lower you go on framerate, more glitches you'll get
Unity's FixedUpdate works well as far as I know, but like Olento said you have no access to it's internals so working with it is incredibly annoying
but the issue with Unity Physics is that it's actualle designed to run on fixed timesteps from day one, but someone else at unity happened to change the simulation group to run at update instead of fixedupdate just before Unity Physics released
and nobody actually did anything about it :p
if you set Unity Physics to use current deltatime instead of the fixed timestep for each simulation run, it will react to different framerates properly, it's just not going to be deterministic in any way and it'll not handle super low fps gracefully
so better solution is to just force it yourself to run on fixed timesteps (either via unity's fixedupdate or your own loop)
and I do stress that Unity's FixedUpdate is super simple implementation, it's quite literally the equivalent of the code in the blog post @zenith wyvern just posted
it's like 10 lines of code max
there's nothing magic about it
so the problem is that Unity Physics isn't using a fixed time step?
That's why I don't understand how we have never been able to just write our own update, since it's such a simple thing
(Can Unity stop using really confusing naming conventions that makes it nearly impossible to have clear conversations about shit)
Unity Physics uses UnityEngine.Time.fixedDeltaTime in regular updates
@zenith wyvern we've been able to write our own fixedupdate for years
and I talk about time before ECS now
Seriously, conversations about unity's physics systems (Not to be confused with the specific Unity Physics) and conversations about Unity's UI Features (not to be confused with the specific UGUI, IMGUI, UIElements, and Unity.UI)
rages
Unity let us step the built-in physics manually around 2017
so you can just make your own fixedupdate code on regular update and step the built-in physics there
Huh, I did not know that
also since we got access to playerloop now, we can inject whatever we want there
that forum post I linked earlier did exactly that
Can't you also run multiple independent simulations?
So you can for example, simulate the trajectory of a projectile so you can plot it for a preview
But that doesn't automatically extend to any regular script that wants to use FixedUpdate. I would want a way to literally re-write fixed update and have it "just work" with any script that wants to use the built in function
@stable fog technically there's no limitations, who physics is stateless so you can reset it back or duplicate the things you want to other world and simulate there etc.. but Unity Physics also exposes individual solvers
there's an example of this on dots sample repos example projects
I believe that's how their character controller works in the dots sample, they just override the solver for the collision logic
## [Burst 1.3.0-preview.2] - 2020-02-10
### Fixed
- Fix the error `Burst failed to compile the function pointer Int32 DoGetCSRTrampoline()` that could happen when loading a project using Burst with Burst disabled```
var baseJob = new GetTargetJob
{
Aggression = Settings.Instance.Aggression,
RandomizerType = GetArchetypeChunkComponentType<Randomizer>(false),
EntityType = GetArchetypeChunkEntityType(),
};
var firstTeamJob = baseJob;
firstTeamJob.CommandBuffer = mCommandBufferSystem.CreateCommandBuffer().ToConcurrent();
firstTeamJob.Enemies = mSecondTeamQuery.ToEntityArray(Allocator.TempJob);
var firstHandle = firstTeamJob.Schedule(mFirstTeamQuery, inputDeps);
var secondTeamJob = baseJob;
secondTeamJob.CommandBuffer = mCommandBufferSystem.CreateCommandBuffer().ToConcurrent();
secondTeamJob.Enemies = mFirstTeamQuery.ToEntityArray(Allocator.TempJob);
var secondHandle = secondTeamJob.Schedule(mSecondTeamQuery, inputDeps);
return JobHandle.CombineDependencies(firstHandle, secondHandle);
Does anyone know why this completely blows up in my face, but if I add firstHandle as a dependency to secondTeamJob.Schedule and return secondHandle everything works fine? The two queries are filtered on different shared component data, and from my understanding that means that they shouldn't be able to touch each other.
i think you also need to combine inputDeps to your CombineDependencies
Still getting the same errors:
The previously scheduled job GetTargetSystem:GetTargetJob writes to the UNKNOWN_OBJECT_TYPE GetTargetJob.Data.RandomizerType. You are trying to schedule a new job GetTargetSystem:GetTargetJob, which writes to the same UNKNOWN_OBJECT_TYPE (via GetTargetJob.Data.RandomizerType). To guarantee safety, you must include GetTargetSystem:GetTargetJob as a dependency of the newly scheduled job.
The previously scheduled job GetTargetSystem:GetTargetJob writes to the UNKNOWN_OBJECT_TYPE GetTargetJob.Data.RandomizerType. You are trying to schedule a new job JitterAndDampingSystem:JitterAndDampingJob, which writes to the same UNKNOWN_OBJECT_TYPE (via JitterAndDampingJob.Data.RandomizerType). To guarantee safety, you must include GetTargetSystem:GetTargetJob as a dependency of the newly scheduled job.
maybe queries are different, but jobs are accessing same type of components🤔
But aren't archetypes also separated into different chunks based on differing values in ISharedComponentData?
you dont actually schedule "baseJob" btw
No, base job is just a job I copy from to avoid repeating myself twice.
ah okay
i think it is not about values, it is about types🤔
smart guys will answer this question😏
But, if the values are in different locations it shouldn't cause a race condition to access them.
yeah but it says you are writing to it not reading it
maybe do [ReadOnly] in your job struct
to that randomizer field
So, the first error, the one coming from GetTargetSystem:GetTargetJob is the one I don't get. Because yes, I'm writing to RandomizerType's, but those writes are on components in different chunks (due to ISharedComponentData)
so started thinking about this... I really like the DOTS Editor and it's entity conversion preview as it lets me examine the data easily at runtime as well.. but the main issue here is that the actual objects have to be in the DOTS subscene but nothing from DOTS subscene will render without hybrid renderer (which doesn't support features I need), normally I could use Convert and Inject on regular scene and deal with the GO counterpart there for rendering but then I'd lose the entity conversion preview.. this I believe leaves me two options that would still bring me the best of two worlds:
- either manually spawn / sync to traditional GO that doesn't exist on DOTS Subscene during conversion
- abuse AddHybridComponent to get GO side mesh renderer
well i never worked with chunks so i wouldnt know
I appreciate the suggestions anyway :)
i think there is some safety checks that cares about type of data, not the location🤔
something like JobA writes to ComponentA and JobB writes to componentA, therefore they must be executed one after another
yeah but still, these are ISharedComponents, meaning that every entity will have one
Yeah, but come to think of it, they are given value at runtime.
no, it is not like that
so, assuming those chunk components arent the same, they should be different ?
shared component is stored per chunk🤔
but dont you do AddComponent to add ISharedComponent to an entity ?
If I can get pointers into jobs I can surely be able to say that there's no race between two jobs.
i mean yeah i can agree that but..
well anyway, i am not smart so
perhaps @low tangle can answer it, he is kinda ECS god
isn't changing ISharedComponent is structural change? So mayby copy everything you need into NativeArrays, do your work, and than apply structural changes at some sync point?😅
I'm using a ConcurrentEntityCommandBuffer so the structural change should already be deferred.
@gentle osprey are you sure both components are different from each other ?
Here's the job:
//[BurstCompile] // Burst doesn't support CommandBuffers with shared components
public struct GetTargetJob : IJobChunk
{
[ReadOnly]
public ArchetypeChunkEntityType EntityType;
public ArchetypeChunkComponentType<Randomizer> RandomizerType;
public EntityCommandBuffer.Concurrent CommandBuffer;
[ReadOnly]
[DeallocateOnJobCompletion]
public NativeArray<Entity> Enemies;
public float Aggression;
public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
{
if (Enemies.Length == 0)
return;
var randomizers = chunk.GetNativeArray(RandomizerType).Reinterpret<Random>();
var entities = chunk.GetNativeArray(EntityType);
for (int i = 0; i < chunk.Count; i++)
{
if (randomizers[i].NextFloat(0f, 1f) >= Aggression)
continue;
var target = Enemies[randomizers[i].NextInt(0, Enemies.Length)];
CommandBuffer.AddComponent(chunkIndex, entities[i], new Target { Value = target });
CommandBuffer.AddSharedComponent(chunkIndex, entities[i], new TargetType { Value = TargetTypes.Enemy });
}
}
}
i mean maybe there is a possiblity that those components could be same at any given time, so safety check warns you about it ?
even tho they are not same at run time
Yeah, they are the same component, that's probably why the safety check warns about it.
It's probably correct for it to warn, but I still mean it's wrong, so now I'm looking for a way to overrule it.
I think I found it. At least it silences the warning system: NativeDisableContainerSafetyRestriction. Hopefully I'm using it correctly :P
I find it fun, particularly to play around with reinterpreting data to generate SIMD instructions. But, there's more boilerplate involved :P
anyone have a idea why this line
var signedAngle = Vector3.SignedAngle(position.Value, targetPos, Vector3.up);
completly destroys my Entities.ForEach()??
with a glorious error: ECS\Systems\MovementSystem.cs(55,13): error CS1593: Delegate 'EntityQueryBuilder.F_E' does not take 6 arguments
Vector3 is a class, which you cannot use with Burst
either use float3 or use .WithoutBurst
Are you able to share the surrounding code? In particular the parameters?
and for float3 maths, you can use Unity.Mathematics class
there is a math static class inside that namespace, you can use that
Vector 3 is a struct, it should work fine in bursted code
And yeah @crystal helm Show the ForEach
got a mute because i tried to post the code here :X
here is the complete system -> the first foreach is fine, but the second gets flaged in the moment i add the SignedAngle line...
oh wait it has nothing to do with Vector3 😄
"Delegate 'EntityQueryBuilder.F_E' does not take 6 arguments"
i just cant get whats wrong there <.<
You're saying you don't get that error if you comment out var signedAngle = Vector3.SignedAngle(position.Value, targetPos, Vector3.up);?
yea
Strange
thats exactly my thought xD
All I can think is that the compiler just ignores the argument if it's not being used and the Entities lambda just doesn't support 6 arguments
But I guess your arguments are being used elsewhere too...
You could try changing it to the JobComponentSystem foreach instead. ComponentSystem Foreach is a bit older and works a bit differently
oh... iam sry, wasted your time, i was stupid
you dont seem to use mass component, maybe delete that
What was the error?
OperationShipComponent wasnt a struct -.-"
it was declared as class thats why he screamed
Easy thing to overlook :P
Ahh, gotcha. To be fair I don't think that means you're stupid, that means Unity should provide a better error for that case
anyway, thanks for your help :3
Yeah, I've pulled my fair share of debugging Entities.ForEach queries :P
but what Sark said is right, you should use JobComponentSystem not ComponentSytem
ehm, why?
well they are working differently, and its going to be deprecated later on from what i heard, it also generates GC
This thread has more details https://forum.unity.com/threads/garbage-for-every-onupdate-when-using-ecs.806895/
and.. you cannot actually schedule jobs, you just run a job
uh <.< oke, strong reasons, ty
while with JobComponentSystems all the jobs in your all of your systems is organized properly
ComponentSystem is going to be deprecated? What's the alternative for code that cant be jobified?
come to think of it, ComponentSystem is.. basically mono behaviour 😄
if you dont schedule any jobs you can simply return inputDeps from your system
i belive
In a JobComponentSystem you can force a ForEach to run on the main thread, with or without burst. See https://docs.unity3d.com/Packages/com.unity.entities@0.5/manual/entities_job_foreach.html
There's an official unity video that kinda introduces the concept, though it's pretty light on details https://www.youtube.com/watch?v=a9AUXNFBWt4
In this workshop style video we walk through an example project created by Unity Evangelist Mike Geig on how to script a Pong style game using Unity's Data Oriented Tech Stack (DOTS) including the Entity Component System (ECS). This video covers the latest syntax in Unity 2019.3....
I see, cool, thanks :)
disabling the safety system like that is correct, as long as you make sure your logic is threadsafe first like you did confirm with it being shared components @gentle osprey
correct usage, typically where that gets used is in a native array that threads only access one index and cant overlap each other
@gentle osprey i was wondering, if you are experienced with chunks and isharedcomponent, i want to make a faction system, and i was wondering if i should make a isharedcomponent for that, so i could make an int field, faction 0, faction 1 etc.. and i could easily access faction's stations, fleets etc by chunks, right now i am using faction tag components but it wouldnt scale well if lets say i wanted to make 100 factions, because then i would have to make 100 systems that does same thing but for different factions.
Why doesn't this prefab have a Scale component when converted to Entity?
cause it has a uniform scale of 1
So to force the scale to appear I need to change the prefab scale and then change it later when instantiating?
or just add a scale component during conversion
oo new animation package https://bintray.com/unity/unity/com.unity.animation
Hmm, RequireForUpdate ignores ChangedVersionFilter on a query you pass to it?
Highly lame
there's like 200 lines of changelog between that and last public unity.animation package 😄
apparently there's been releases between, just not public
bintray only lists 0.3.0-preview.7, 0.2.16-preview.5 and 0.2.13-preview
yeah i came to that conclusion too. still seems pretty low level and I dont care to try to upgrade the anim samples repo to give it a go.
im really curious who is actually finding this useful, enterprise level customers?
they probably don't plan people to uprade just yet, but making the release so they can use it as dependency for next dots sample update etc
tbh, when Unity announced 3D rigging tools to arrive I was excited as I thought it would be like Puppet3D asset
that was me expecting some artist friendly tool that anyone with any rigging basics knowledge could use
it's same story for all DOTS packages atm really, hoping they can do something about this before they actually release these things fully
even the current Entities package is not an entry level thing at all, despite it's gone further in past year in usability
if you just look at Unity's actual samples, not simple spinning cubes, it's often getting quite low level fast
Yeah the rigging tools are from first glance, final ik. Imo they shouldvre hired that guy because final ik is really well thought out
I guess because its a package and not some random git
repo I keep expecting a more complete experience😆
I'm in a situation where AddHybridComponent would really be useful.
So I want to make it so UI can be edited on runtime with ecs. So I thought of making UI in ECS, but I would have to build everything from the ground up. So that's where AddHybridComponent would get really useful(Although I haven't tried to use it yet, so I don't know how it would work with UI).
Is there another way to do this that wouldn't risk getting deprecated?
Also, is there a way I can create a second entity world, so I can send all my UI there?
well you can use entities with monobehaviours with AddComponentObject
Has anyone ran into Unable to find internal function Unity.Networking.Transport.NativeBindings::network_sendmsg when building NetCode for iOS?
"Cross-Scene references are not supported, and are prevented in Edit mode. In Play mode they are allowed, because Scenes cannot be saved."
so turns out that I can't set the ref to a transform located on non-dots subscene during conversion because it'll not get saved
it does work in editor but obviously not on build because of that limitation
I guess I could just spawn a prefab at runtime on the non-DOTS scene
{
[BurstCompile]
struct DistanceJob : IJobForEach<DistanceComponent, Translation, NonUniformScale>
{
public Vector3 cameraPosition;
public DistanceJob(Vector3 cameraPosition)
{
this.cameraPosition = cameraPosition;
}
public void Execute(ref DistanceComponent distanceComponent, ref Translation translation, ref NonUniformScale nonUniformScale)
{
float distance = Vector3.Distance(cameraPosition, translation.Value);
nonUniformScale.Value = new float3(distance, distance, distance);
}
}
protected override JobHandle OnUpdate(JobHandle inputDeps)
{
Transform camera = Camera.main.transform;
DistanceJob distanceJob = new DistanceJob(camera.position);
return distanceJob.Schedule(this, inputDeps);
}
}```
Is there anything I can do to make this job perform better? I have another job that moves all my entities (30000+) and it performs fine, but the second I try to scale them based on distance the performance tanks.
I know that I shouldn't be getting the camera position like that. I will fix that.
maybe try using math.distance() 🤔
and what exactly tanks your performance, this job or maybe some job from TransformSystemGroup🤔
did you profile it ? maybe its because of rendering
I switched to converting a gameobject to an entity instead of what I was doing before (something to do with sharedcomponents?) and now it runs absolutely fine!
not sure what you did with sharedcomponents but.. shared components should be something that rarely changes, because when it changes it creates a new chunk(if necessary) and copies changed entities to there so its a slow operation
EntityArchetype entityArchetype = entityManager.CreateArchetype(
typeof(Translation), typeof(RenderMesh), // Rendering
typeof(LocalToWorld), // Coordinate conversion
typeof(NonUniformScale),
typeof (MovementComponent),
typeof (DistanceComponent)
);
NativeArray<Entity> entityArray = new NativeArray<Entity>(20000, Allocator.Temp);
entityManager.CreateEntity(entityArchetype, entityArray);
for (int i = 0; i < entityArray.Length; i++)
{
Entity entity = entityArray[i];
entityManager.SetComponentData(entity, new Translation { Value = new float3(UnityEngine.Random.Range(-500f, 500f), UnityEngine.Random.Range(-500f, 500f), (UnityEngine.Random.Range(-500f, 500f))) });
float scale = UnityEngine.Random.Range(1F, 20F);
entityManager.SetComponentData(entity, new NonUniformScale { Value = new float3(scale,scale,scale) });
Translation translation = entityManager.GetComponentData<Translation>(entity);
entityManager.SetComponentData(entity, new MovementComponent { startPos = translation.Value, offset = UnityEngine.Random.Range(5,20)});
material.color = Color.red;
entityManager.SetSharedComponentData(entity, new RenderMesh
{
mesh = mesh,
material = material,
});
}
entityArray.Dispose();
}```
So this was I was creating all my entities before.
but now I am just converting a prefab I have made now with
{
dstManager.AddComponentData(entity, new MovementComponent());
dstManager.AddComponentData(entity, new DistanceComponent());
dstManager.AddComponentData(entity, new NonUniformScale());
dstManager.SetComponentData(entity, new MovementComponent { startPos = transform.position, offset = UnityEngine.Random.Range(5, 20) });
}```
and it performs better xD I apologise if I am coming across as an idiot haha but im slowly learning
nah dont apoligise, i am much worse, glad you solve your problem 👍
I guess my next question is there a way to access the entities in an array? Do they exist somewhere for me to grab or do I need to put them in a list myself?
for example, I might want my entities to communicate to each other.
put it to your data component, so lets say you want your player to follow an entity so you could make
public Entity target;
then in your system you can use GetComponenentDataFromEntity<T> and GetBufferFromEntity<T> to access it, for example:
var positions = GetComponentDataFromEntity<Translation>(true);
Entities.WithAll<PlayerTag>.ForEach((ref Translation, in TargetData)=>{
var targetPos = positions[TargetData.target];
Translation.Value = targetPos.Value;
});
You can also make entity queries to get specific entities that has specific components, so in your system you could do this:
var entities = GetEntityQuery(typeof(Translation), typeof(TargetData)).ToEntityArray();
Wonderful! thanks, let me try some of this out.
i just checked my system that uses ToEntityArray, you should do something like this:
ToEntityArray(Allocator.TempJob, out JobHandle entityArrayJob);
which your jobs depend on that out JobHandle if you are going to use that array inside that job
dont forget to dispose the array after jobs are finished
So i just was wondering why pressing play was taking too long to get into playmode and i found this:
http://prntscr.com/r0oakg
is there a way to reduce this ? and i dont have any box collider or sphere collider in my scene and yet those systems are running
subscenes?
live Conversion in edit mode ?
no
Enter Play Mode without Reload Domain?
Well, taking things out of subscene and put them back again seems to work
i will try if live conversion can help
seems pretty much the same
subscene should load almost instantly without conversing anything🤔
unless you are pressing play with opened subscene, as far as my understanding of subscene goes 😄
well when i put them into subscene they had box collider, i removed them and put physic body but i guess since live conversation was not on, it kept converting them on every play on old colliders
idk 😄
also i just disabled reload domain, it almost insta went into playmode wth 😄
was taking 12 seconds, now its 650 ms
isn't subscene convert thing only once?🤔
good morning everyone :D
iam converting my spawnsystem to ECS entities and i need a tip or direction to go for my underlying spawning;
what i do with gameobjects is Instantiate a specific (from scriptableobject reference) Prefab, which starts a monobehaivior that scans the Object for "weaponslots" and Instantiate (again from scriptableobject reference) the weapons for this weaponslots
ive looked for many tutorials but i didnt find a direction how to convert this; the only possible way seems to me to write "IConvertGameObjectToEntity" Monobehaiviors on my weaponslots.
Anyone has a tip or link how i can do this the best way? i handle many things over "spawnchains" like this :/
when you press close it converts everything and bakes it to binary file and on play it just loads already converted entities, am i wrong?🤔
well.. i never actually closed it 😄
and if you are not closing it, then it constantly converting everything and you can live edit some variables😅
but something weird going on idk, i was using UIElements Runtime and it's awake function was taking 15 seconds when i went into playmode, so i restarted unity and it was gone so
yeah i guess i know how subscenes works now 😄
@crystal helm have you watched this? https://www.youtube.com/watch?v=TdlhTrq1oYk&t=1801s
Uncover the process of converting GameObjects to Entities and how this can be extended and customized.
Find the code samples on GitHub: https://github.com/Unity-Technologies/unite2019-scenedatatodots
Speakers:
Simon Mogensen - Unity
Fabrice Léte - Unity
More about DOTS: ht...
yea i did, but i couldnt apply it to my problem, its more technical than practical.. you think the answer lies there?
Not sure if it's quite the same but I've also seen subscene conversion get stuck in taking like 5s to convert for no apparent reason. i.e. No matter what I changed (live edit enabled, multiple unity restarts) it took a long time... then I removed a collider, it updated instantly, added the collider back, still updated instantly (no physics installed).
Unity really need to release some proper tutorials or documentation for subscenes
@crystal helm If I understand right it sounds like you might want to write a ConversionSystem. It let you customize what happens during the hierarchy conversion in ConvertToEntity
thanks, ill look for that, right now i think about building the gameobject completly and then convert it... but i think it will obliberate the performance gain i get from it.
on the other side, its not a performance problem, i only do that 5times per combat scene, i want to use ecs for the projectiles and physics which is the bottleneck on my project
Look in Packages/Entities/Unity.Transforms.Hybrid/TransformConversion for an example
@zenith wyvern great tip! thanks
if i were to have editor entities created and serialized on a monobehaviour, to load them into runtime world on play mode (basically own subscene)
would it still be useful to put this monobehaviour in a subscene?
am i correct in thinking this monobehaviour and its serialized data won't be included in build (only its resulting entities after conversion) and so reduce footprint? are there any other benefits?
Is there a way to be selective about what JobComponentSystem is being ran any time?
there is [AlwaysUpdateSystem] attribute
It's generally handled implicitly by what the system is querying for. By default a system will only run while what it's querying for exists.
If you need to explicitly control it you can do Enabled = false but I don't think it's something you would normally want to do
@zenith wyvern I am looking at your RLTKTutorial project. You have a thing in there called a BootStrap where you are adding systems.
{
AddSystem<PlayerInputSystem>();
AddSystem<GenerateMapSystem>();
AddSystem<GenerateMapInputSystem>();
AddSystem<ResizeMapInputSystem>();
AddSystem<FOVSystem>();
AddSystem<InitializeTilesInMemorySystem>();
AddSystem<UpdateTilesInMemorySystem>();
AddSystem<RenderSystem>();
}```
whats that for?
you can also use event entities and [requirentityforupdate] I cant remember exactly what its called
Because I need to attach systems explicitly to scene, I do it that. I've really simplified that class in the latest push by the way
So in your bootstrap thing, you are adding systems that are relevant to the scene? and then if I want to turn them off and on Ill have to use querying?
But yeah, specifically, because my project is a big tutorial where each scene specifically needs a certain set of systems, I need to add [DisableAutoCreation] to all my systems and add them to the built-in ECS loop via https://github.com/sarkahn/rltk_unity_roguelike/blob/master/Assets/Common/Bootstrap.cs
I see! that makes sense
Normally you wouldn't attach systems to scenes like that. At least it's not the intended way
Does anyone have trouble with DOTS instancing with 7.2.0 packages ?? I had everything working fine using DOTS instancing param inside HDRP shader and Hybrid Instancied for update shaders and on 7.2.0 shaders render black in play while in editor it works fine
did you restart unity
... Trying
Still broken
No error message
All systems works fine
Broken in build to
somehow i break the "blobarray" of the dots physics package and i cant figue out why.
do i need to prepare something special if i manipulate the PhysicsVelocity componentdata in a job?
Error:
IndexOutOfRangeException: Index -1 is out of range Length 24
Unity.Physics.BlobArray+Accessor`1[T].get_Item (System.Int32 index) (at Library/PackageCache/com.unity.physics@0.2.5-preview.1/Unity.Physics/Base/Containers/BlobArray.cs:35)
{
public float3 Linear; // in world space
public float3 Angular; // in inertia space, around the rigid body's center of mass
}``` How can you brake this😄
exactly 🤣
but the moment my job runs this error gets thrown, not without, i still try to locate the problem :/
I asked here before about writing my own renderer using Graphics.DrawMeshInstancedIndirect instead of RenderMesh. Apparently GPU instancing is available on OpenGL ES 3.0+ on Android, which will miss out on roughly 20%-30% of the devices, and I don't really want that.
Any suggestions?
@lusty otter there is BatchRendererGroup🤔
it just creates copy of entity
yeah, it is ok and very cheap👍
Hmm, I'm quite lost on what I should do.
I'm making a 2D game and only rendering a few hundreds of sprites, though I want it to be fast even on low end mobile devices, what would be the best approach for this?
@lusty otter right now using graphics api with drawmeshinstanced is prob the fastest way to render
there's some ppl making their own 2d renderer over at https://forum.unity.com/threads/200k-dynamic-animated-sprites-at-80fps.695809/ if you hadn't seen that yet
there's one that's recently updated and on github lemme check which it was
My game will allow the player to build rather large hand built based and I am curious how dots would plugin to this and what kind of performance improvement I might expect vs the traditional base building found in unity games.
@lusty otter this one i think https://github.com/GilbertoGojira/DOTS-Stackray
dunno if that's useful for you, you'd be dependent on one guy on the internet updating their renderer
writing your own would be better but costs time
or if you're a gambler wait for hybrid renderer to become good for 2d but i wouldn't recommend that
Yeah but if I'm reading it right, GPU instancing is only available for OpenGL ES3+, which will lose out on roughly 20% of the Android market.
isn't it possible to detect that and fallback to a non instanced path
Non instanced as in, just DrawMeth one by one?
Wouldn't that be very slow, or still faster than other approaches?
i mean
if you can't use the fastest way you'd be forced to use a slower one
you can't get faster than unity's Graphics. api's tho
at least within unity
does it not support DrawMeshInstanced (non indirect) either?
I'm not exactly sure, I'm super noob to Unity, but it's what I'm reading here https://docs.unity3d.com/Manual/GPUInstancing.html
GPU Instancing is available on the following platforms and APIs:
...
- OpenGL Core 4.1+/ES3.0+ on Windows, macOS, Linux, iOS
and Android
But if Graphics APIs are the fastest then I guess that settles it.
When using BatchRendererGroup.AddBatch where do i set the transform matrices? Via customProps?
_batchIndex = _batchRendererGroup.AddBatch(...);
NativeArray<Matrix4x4> matices = _batchRendererGroup.GetBatchMatrices(_batchIndex)``` maybe like this?🤔
@lusty otter A good middle ground between performance and compatibility when rendering a lot objects is Unity's mesh api https://docs.unity3d.com/ScriptReference/Mesh.html
You combine all your objects into one or a few meshes and you can massively reduce your draw calls. You can also use the job system and burst to make building your mesh data super fast. That's what I'm doing for rendering in my roguelike and it works well.
And since you end up with a plain old mesh it's guaranteed to run on just about anything
There is no SetBatchMatrices in BatchRendererGroup? I should have a look in the hybrid render code, should be used somewhere...
hm, that works? have to try that...
@zenith wyvern Thank you, that sounds promising. Is there any examples?
Thanks!
i'd like to spawn a bunch of entities from one authoring component in a subscene. in the default script that's created for an authoring component, there's this line
If you want to create more than one entity from the data in this class, use the 'conversionSystem' to do it, instead of adding entities through 'dstManager' directly.
which is great! more than one entity is exactly what i want. i'd tried using the entity manager in the conversion system to instantiate copies
https://hastebin.com/uhimecofol.cpp
but i get an error at line 34
ArgumentException: All entities passed to EntityManager must exist. One of the entities has already been destroyed or was never created.
and im not sure where im going wrong. any ideas?
Yeah it's a bit confusing, you're not supposed to use the Entity Manager in the conversion system, you're supposed to call conversionSystem.CreateAdditionalEntity and pass in your converting gameObject to that function
ah so something like this?
conversionSystem.CreateAdditionalEntity(myPrefab);
i'd have create a separate script for that bit/do something with first-spawn, since i don't want it to spawn an exponential amount of entities, which isn't a big deal
not sure why i repeated the code you already put there 😅
You can literally just pass in the gameObject member variable and it works fine - it won't re-convert the gameobject or anything, as far as I can tell it's just the correct way to create an additional empty entity
oh nice! i'll give that a try. thanks!
90% sure that worked, since i've got a bunch of entities in the debugger and the editor didn't crash. they're all likely overlapping, but that's fixable. thank you again!
anyone know if you can exclude a component with the new codegen lambda?
Entities.WithNone
thanks
anyone know why DOTS would be generating this error incessantly and in the process largely breaking the editor? All I did was create a Subscene from an empty gameobject, and the second I clicked on it this started, and selecting other gameobejcts now has a weird compressed broken inspector
I'm in 2019.30f6
@zenith wyvern I just realized that each of my sprites will have different vertices so Graphics.DrawMeshInstancedIndirect wouldn't have worked anyways. Your mesh solution seems to be a way better fit for my problem, thanks!
did something change with maths package integration?
first of its not visible by default in package manager , even though its installed as part of burst/jobs dependency i think
secondy my IDE cant find unity.mathematics namespace
using 2019.3.f6
did you put the using unity.mathematics for it?
you can just look at your project files in the editor, it lists all installed packages below your regular assets
@naive parrot
What's the difference between NativeString and FixedString? I just want a format I can use to carry a string with a max length that won't ever change in a IComponentData. I probably won't need to get the string itself often but I may need to, so using a hash is probably out of the question
FixedString is the replacement for NativeString (they are data and functionally identical, with FixedString having a few new bells and whistles)
basically, they're in the process of renaming NativeString to FixedString, they're just letting them live side-by-side until the transition is complete
the naming schema as I can determine:
- Native* - uses native-level allocator labels. has safety checks
- Fixed* - uses fixed size structs to remove the need for safety checks, as nothing is allocated on the heap for operations. Doesn't use the native-level allocators since they can live on the stack or inside another type.
- Unsafe* - uses native-level allocator labels, has no safety checks, use only when you know exactly what you are doing and/or the memory isn't shared between jobs
Alright, seems like FixedString is the way to go for me. Thanks!
I just found this awesome post by 5argon
https://gametorrahod.com/game-object-conversion-and-subscene/
It's about different ways to convert game objects, and 5argon even mentions that super hidden feature called AddHybridComponent.
Oh, I just realized @left oak already covered the topic
I don't really understand why you would want to use that over AddComponentObject
It seems like they pretty much do the same thing
Or I guess I should say - I don't understand the difference between them
Oh interesting, if I'm reading right the HybridComponent method will automatically sync your transforms
hey guys! I'm streaming the process of learning Unity ECS right now - https://youtu.be/JyuFNwV_WGE
And it seems to have more consistent behaviour with instantiate
The "hidden gameobject" part feels very strange to me though
in a subscene, i have one gameobject (maybe it's an entity at that point? im not 100% sure) with an authoring component. i'm trying to create 31 duplicates of that object with conversionSystem.CreateAdditionalEntity(gameObject); in a loop. after i add the components i want to the resulting entity, as suggested by someone above, but none of the components on the original object are copied to the duplicates. i've tried adding the components after creating the extra entities, but then the physics components added to the original object aren't added, and i'd rather not go down the road of creating physics components by hand again. what am i doing wrong?
https://hastebin.com/xeyugatude.cpp
kinda keeps the hierarchy clean, and when the entity is destroyed so is the hidden gameobject
alguem falar portugues?
english please 🙂
btw, new package dropped, "com.unity.tiny.all" 😄
it's a kinda weird one
because all it does it just includes all tiny packages as dependencies so you don't have to enter them separately
"name": "com.unity.tiny.all",
"displayName": "Project Tiny Full",
"version": "0.21.0-preview",
"unity": "2019.3",
"description": "This package includes all Project tiny packages and their dependencies",
"dependencies": {
"com.unity.dots.runtime": "0.2.0-preview.3",
"com.unity.entities": "0.5.1-preview.11",
"com.unity.tiny": "0.21.0-preview.3",
"com.unity.tiny.rendering": "0.21.0-preview.4",
"com.unity.tiny.web": "0.21.0-preview.3",
"com.unity.tiny.desktop": "0.21.0-preview.3",
"com.unity.physics": "0.2.5-preview.1",
"com.unity.platforms": "0.1.8-preview.1",
"com.unity.platforms.android": "0.1.8-preview.3",
"com.unity.platforms.desktop": "0.1.8-preview",
"com.unity.platforms.ios": "0.1.8-preview.3",
"com.unity.platforms.linux": "0.1.8-preview",
"com.unity.platforms.macos": "0.1.8-preview",
"com.unity.platforms.web": "0.1.8-preview.1",
"com.unity.platforms.windows": "0.1.8-preview"
}```
@zenith wyvern I think ComponentObject injects a MonoBehaviour, and HybridComponent puts the MonoBehaviour on a GameObject that acts as an extension of the entity.
Gotcha, seems like a better way to do hybrid than the normal inject way. Thanks!
But like @dull copper said, the fact that it's still an experimental feature is something to be weary of.
has anyone tested that AddHybrid outside of DOTS subscene?
I just wonder if it's still hidden
but I suppose it will be
add hybrid component?
Just tested it(also my first time testing the whole feature even if I keep bringing it up) and it is hidden unless the conversion is unsuccessful, or something like that(I set it on another gameobject's component, it gave me an error and the companion appeared in the editor as a disabled game object)
is there any way to get a JobComponentSystem to update on FixedUpdate?
did you put the using unity.mathematics for it?
@dull copper i meant , my IDE cant find the mathematics namespace when declaring the 'using' itself. its as if the package is not there. even though it appears under packages in project.
well, did you check if it shows up in the editor under your assets folder?
just trying to figure out if you truly have the package loaded or not
i think i found the issue : https://issuetracker.unity3d.com/issues/pacman-ecs-mathematics-does-not-exist-in-the-namespace-unity-when-referenced-in-code-using-assembly-definitions
Reproduction steps: 1. Open "MinimalRepro.zip" project 2. In Folder "Code" -> "A" create an Assembly Definition 3. See Console Ou...
"As such, the user must do one of two things to reference Unity.Mathematics in their new assembly:
a) Manually edit the asmdef file in a text editor and add "Unity.Mathematics" to the list of "references"
b) Explicitly import the mathematics package via Package Manager (after enabling preview packages to find it) and then assign it as a reference to their new assembly definition via the Inspector"
b applies for me
you have asmdefs on your own code?
If you are using assembly definitions you need to add them via the assembly definition interface
you only need to add it to ref if you use them
not really. havent added any asmdef of my own. its fairly fresh project , mostly vanilla
if you do that, this applies to about all packages
well, it should work out of the box then
everything works except for mathematics library
burst/jobs/collections all can be references from my scripts except for mathematics
and it doesnt show up in my package manager either under "In Project"
Is it just your IDE that fails?
So you haven't added the package?
And nothing references it
its installed as part of jobs dependency
so it is in the project then
It should work totally fine then. Is it just your IDE that doesn't understand or is it actually not compiling in Unity?
alright , so i think only IDE ( vscode ) cant read it. its not throwing compile errors if added it directly in my scripts.
but that means i wont get auto autofill for entire lib now?
I don't know anything about vscode oddities myself
without "show preview" filter
btw it doesnt show here when filter is set to "In Project" only
it used to pop here whenever i installed mathematics in 2018.4
Yeah it doesn't show dependencies like that as far as I understand
If you install it manually it will
i see
but there should be no difference
2020.1 shows them on that list again
btw is there a new "auto convert mathf to math" button somewhere now?
oh i have done new maths stuff by hand before. one of the unity evangelist visited our office yesterday and he was talking about this new "Auto convert" thing..
probably not out yet
I've not heard about it and frankly I wonder how they even could do it when the new math lib still misses many things that old lib had
I'm curious what that's about tho
was wondering the same myself. probably will drop by GDC..
you sure it was about the math lib specifically?
I mean, you can already use vector3's as float3's etc if that's what was discussed, they have matching structs for the actual data
yeah i know about that.he was mentioning about a "convert button" similar to how u would convert standard materials to srps and such
but for mathf to math.
I really wonder how they can do that in practise... like would they split your inline math to new lines and implement everything again when you can't inline things the same way anymore
and there are bunch of things that simply don't exist natively on new math lib
so would they codegen them still
honestly no clue on this. but i was as surprised when it was brought up. probably something we would see in 2020
hmmmm
I mean, I could see if they just swapped things on burst compilation stage for things they know they can just swap to direct equivalents
but if it does actual codegen on your own code and you get the converted files back... it's gonna be quite funky as it would be totally destructive operation
I wouldn't mind if it did that as it would make it faster to convert stuff
i do lots of vector maths usually that i would like if it could be converted like that to new math lib , for my existing codebase
@tame monolith you should read/watch some basics about ECS first
In this workshop style video we walk through an example project created by Unity Evangelist Mike Geig on how to script a Pong style game using Unity's Data Oriented Tech Stack (DOTS) including the Entity Component System (ECS). This video covers the latest syntax in Unity 2019...
📌 Download the project files and assets from this video: https://tmg.dev/DOTS_Roll-A-Ball 📌
🎮 Let me know what other topics you want to learn about 🎮
👇 See below for time stamps 👇
- 0:00 - Introduction and Project Demonstration
- 1:47 - ECS Overview
- 3:10 - Setting up the Un...
are good starts imo
You cannot put reference types(classes for example) into IComponentData, you should store float3 in your component data and update it in a system
if you explain what you are trying to do maybe people can help you better
But imo you should watch all the ECS tutorials in Unity Youtube channel first, there are also some older videos as well
You could make PlayerPositionData, PlayerTag, FlyerTag component and make:
System 1: Get PlayerEntity(thru PlayerTag) and write Translation to PlayerPositionData
System 2: Get PlayerPositionData(thru singleton access), Flyer Entities(thru FlyerTag) and make Flyers' Translation go to player position
There are many ways to go but i just came up with this
I feel like there's something fundamental that I'm missing here in regards to ECS and cache misses.
Entities.ForEach syntax will execute on every entity that matches the query, right? When you do this, will only the queried components be iterated upon?
So for example if you have a ref ComponentA and in ComponentB, under the hood Unity is taking that query, getting the entities that match that query, and then setting up the components in a single continuous piece of memory with CompA and CompB packed together I assume? (alternating, with each pair known by the associated entity ID) Please correct me if I'm wrong.
My question ultimately is how ECS Systems that act on a large set of components prevent cache misses, and the above is the only conclusion I could come to that seemed to make sense, as assigning packing each component together into contiguous memory by type alone would be much slower, no? Provided systems iterate by entity ID, it'd have to constantly be going back to L2 to hit the different component types, potentially even having cache misses if the pool of combined component data is large enough, right? What am I missing, or am I just completely underestimating cache sizes?
Of course, the Copenhagen talk I just listened to on burst/SIMD/Intrisics seems to point to contiguous independent component types in memory, such that they can be vectorized. But if iterating a job by entity ID, how would it be vectorizing the component for 4 entities at once? I feel like there are so many things I'm missing
cache misses aren't prevented entirely but everything that can fit inside a chunk has linear access - so the more components you have, the fewer quantity of entities with that archetype can fit in a chunk.. there was a good post on the forum about the memory layout - will see if I can dig it up
actually, maybe you already saw but the docs are pretty good these days - https://docs.unity3d.com/Packages/com.unity.entities@0.5/manual/ecs_core.html
Thanks! I'll give that a look and see if it answers my questions, then I'll report back =)
Hi guys,
I'm currently trying to implement a polygon clipper based on the Weiler Atherton clipping algorithm (http://www.geeksforgeeks.org/weiler-atherton-polygon-clipping-algorithm) using the Job system but i've encountered a problem.
Every clipping algorithm I know is based on the linked list (or double linked list) data structure.
Currently we don't have a Native Collection version of the linked list so i've tried to implement it myself using NativeLists.
Does anyone knows a way to solve this problem?
Is a job the correct place to perform this kind of operation?
@amber flicker I think that led down a path that answered most of my questions, thank you!
Still have just a few more things I'd like to clarify:
So if you have EntityA with CompA, CompB, and CompC, and EntityB with CompB, CompC, and CompD, a CreateArchetype with CompA, CompB, CompC, and CompD would do nothing/create no chunks, right? As no entities have all of those components?
Unity implicitly would create archetypes for Entity A and Entity B.
Adding an EntityC with CompB and CompC would then generate an archetype with chunks that only hold component data for EntityC, EntityB, and EntityA, rather than just EntityC, right?
So then you have copies of CompB and CompC for EntityA and EntityB in two different chunks, which have to be synced up any time a system acts on an archetype that writes to CompB or CompC for EntityA or EntityB?
And if you then want EntityC to be isolated, you essentially need to give it a unique tag component so an archetype is generated just for EntityC?
Honestly finding that very hard to follow.. but I think you've basically understood. "a CreateArchetype with CompA, CompB, CompC, and CompD would do nothing.." - it would create an archetype with those 4 components. It wouldn't yet create an entity with those components though. But you could then create an entity using that archetype and then the entity would exist with those components.
And yes, if you wanted EntityC to be isolated you could give it a unique tag. There's always a balance here between reducing the number of entities your systems iterate on and fragmenting your chunks further.
@granite oasis Adding an EntityC with CompB and CompC would then generate an archetype with chunks that only hold component data for EntityC, EntityB, and EntityA, rather than just EntityC, right? No EntityA, EntityB and EntityC will all be in different chunks
Yeah sorry I'm working on trying to communicate questions more clearly, though it can be tough at times, especially if I refractor parts of my questions and forget to reread. Basically trying to understand chunks specifically, so I had meant the archetype would be created, but it's essentially doing nothing until there's a corresponding entity to add to a chunk of that archetype @amber flicker
No worries - we're all familiar with the pain of getting our heads round the terminology and what it means
@warped trail Sorry, I kind of misspoke there. What I meant to ask was whether only EntityC's component data would be in chunks for that new archetype of CompB and CompC, or would CompC and CompB of EntityA and EntityB also be copied to those chunks because they are entities that contain those 2 components and thus match the archetype, as archetypes only care about components
Trying to move away from the OOP thinking but it sure it tough to really internalize
only EntityC's component data will be in chunk
Basically Entity is just index to some array(chunk)
Interesting. So then I presume systems that query on CompB and CompC would then query all archetypes for those Components and then iterate on every matching chunk?
So in that case, isn't cache space then wasted? As it's pulling chunks that contain extra unnecessary data from EntityA and EntityB?
chunks literally live in the Archetypes, its just the storage mechanism for an archetype. So if it matches an archetype (has the same components) then it has to get copied there. If no archetype exists already for a particular combination of components then one is created.
@granite oasis basically, yes. This is why ideally you wouldn't want to add a unique tag to each of 100k entities that all had a Translation component for example as that would cause the Transform system to slow down. That said, it's still incredibly fast - after all it's just a memory address - not copying data around.
i suppose it is your job to not waste this precious cache space😏
Of course @warped trail. Just gotta understand how it all works first ;)
Alright, thanks for the answers everyone! Good stuff to know =)
Hi guys,
I'm currently trying to implement a polygon clipper based on the Weiler Atherton clipping algorithm (http://www.geeksforgeeks.org/weiler-atherton-polygon-clipping-algorithm) using the Job system but i've encountered a problem.
Every clipping algorithm I know is based on the linked list (or double linked list) data structure.
Currently we don't have a Native Collection version of the linked list so i've tried to implement it myself using NativeLists.
Does anyone knows a way to solve this problem?
Is a job the correct place to perform this kind of operation?
@vast veldt Anyone can help me? 😅
Is it possible to write loging to component system groups ?
i am using Game state tags to stop/continue my systems(like if player is in ui every system stops etc...) but i dont want to put it to every single system and i want to write to that system group so it wont update whatever systems inside that group.
@opaque ledge not sure what kind of logging you're referring to, but if you want to put systems in a group and then control if the entire group runs that seems possible.
how 😄
i am using RequireSingletonForUpdate<> in every system right now to pause or continue
ComponentSystemGroup is ComponentSystem. Mayby you can do this cs var sys = World.GetExistingSystem<SimulationSystemGroup>(); sys.RequireSingletonForUpdate<YourSinglton>;🧐
maybe override the group's OnUpdate
[UpdateInGroup(typeof(LateSimulationSystemGroup))]
public sealed class LateSyncGroup : ComponentSystemGroup
{
protected override void OnUpdate()
{
if(something)
{
base.OnUpdate();
}
}
}
yeah i will try that
protected override void OnUpdate()
{
RequireSingletonForUpdate<GameState_GameplayContinue>();
base.OnUpdate();
}
seems to be working
its converted to a physics shape I think, you have to use it differently docs are here
I've found myself using some very dubious looking tactics in an attempt to do something based on the logic of what's happened in Jobs, and I'm sure I'm missing a trick - perhaps that trick is command buffers but honestly the documentation on those made me cry like a baby for days.
https://hatebin.com/walytkliiy
In there I have comments on lines 48 where I describe the sort of thing I have been doing. How do other people handle this sort of thing where you want to do some processing that doesn't really sit in a job, eg main thread game logic
TBH that example doesn't sit in a job because there's only 1 player, so a good way to do that to the components within OnUpdate() would help!
^^^ this looks like a possible main thread only version but I don't know if this is on the right track or not!
https://hatebin.com/rlwzrohvum
Which problem are you trying to solve? Do you want to respond to logic that happens in a job or do you want to force your job to run on the main thread?
I don't care if it's main thread only or job, but I want to delete a query when a condition is met - in this case where two values within components of an entity are close
I guess the question boils down to what's the best way to access component data and act on it
I think the generally accepted way to do that is to add an ExcludeComponent to your job query and add the excluded component once the condition is met
Or just do it on the main thread and bail out immediately once the conditions is met
Also you might consider transitioning to the new ForEach https://docs.unity3d.com/Packages/com.unity.entities@0.5/manual/entities_job_foreach.html
Saves you a lot of typing while you're prototyping
What are you trying to do exactly tho ? job seems working fine, no ?
I think in order for exclude to work you need to change the archetype in your example. I only took a quick look but I think it's the bit before - knowing when to change the archetype? One option I think, if I'm understanding right, is to use e.g. a NativeArray<bool> of length 1. Pass a concurrent version into the job, early out if true, set true if finished lerping? Not sure.
Yeah, it literally results in the same code
Just saves you some typing and makes it more readable imo
k that's fine I'll move over when I have some room to breathe
oh bools blittable now?
yea, for months now, but you could use anything
k that's an alternative thanks
otherwise, yes, you can also use an ECB and write that in a job - e.g. if (x == 1) ecb.AddComponentData(new DoneTag()) or whatever - which will run once the job has completed
depends on if you'd like to try and avoid the work being done in the for loop for some reason
It'll be nice once we have something like FixedBool. The NativeArray<bool> is a good idea, just not very nice to read
This will almost certainly stay as a single player entity in the project but I'm trying to get a handle on how to do this sort of thing more robustly for the generic case too! Cheers all
im thinking that you could have them as two seperate jobs for clarity, one is responsible for updating the collision radius based on time/rate etc (which is the job you have already shown). Then forget about it, make another system or job that is goes through the players a second time, checks the radius, and does whatever with it. The good thing is that theyre not tangled together. Its going to be slower because you're looping through it all twice, scheduling twice etc, but significantly slower? you'd have to test.
then I'm still back to my original question in a different form: once you've detected in the second job that some condition is met, how do you then use that information for logic outside of the job cleanly? It seems a bit crappy to be writing to a NativeArray<bool> or whatever for this sort of thing.
Ahh okay, i see.
What i've been doing is writing out events. So whenever the condition is met, an event component gets shoved into a NativeQueue.
The events system later on in the frame deals with how those queues turn into entities with the components attached.
Then next frame a system can have a job that goes through all the event components for processing.
ahh okay I see, thanks!!
i think one of the cleanest way would be creating another component, some sort of ChangePlayerSize and system which queries for that component, changes player size and removes that component from player when it is done.🧐
yeah so that's what I'm currently doing, and it's working now on the main thread which is fine for this task. The question was more based around the practicalities of detecting when that has occurred within a job then responding to that outside of the job. xzjv Sark and Timboc have come up with a variety of ways around this 🙂
if you've converted a RigidBody there must be a Translation
There's no transform, it's LocalToWorld. Anything you convert should have that
also inside a job you will need to use a entity command buffer @wary anchor
your using a direct call to EntityManager
its not too hard dont worry
I'm sure it's easier than the docs make out 😄
but that's a big old scope right there
you can construct one if its a done right there job, if it isn't then you just grab one
I can write you two examples before I start today
oooh that would be brilliant... thank you!
thats the code you want converted right?
^
sometimes it helps to see it on your own code / how you were thinking
give me five minutes
The big gotcha is to remember to call AddJobHandleForProducer with your inputDeps after the job
oh man no that example is grand right there
yeah save your time now @low tangle but thank you! I will have a crack at this
yeah thats the way to do it with a long running job and a ecb from a end job
alright go for it
so anything that can be done any time this frame can go in there I assume: removing the query for example doesn't need to be done now just before the next time the system runs
yes thats the right way to think of it
Cheers, I had that but removed the version of unity it was on and it broke when I accidentally upgraded it 😄
its going to happen eventually
I'd much rather not introduce a sync point by completing something just so I can get the code in this part of a file, this looks much cleaner
yeah you dont need to complete
unless its a main thread thing in which case you should be using the new Run
* BeginInitializationEntityCommandBufferSystem
- YOUR SORTABLE SYSTEMS -
- YOUR SORTABLE SYSTEMS -
- YOUR SORTABLE SYSTEMS -
* EndInitializationEntityCommandBufferSystem
* SimulationSystemGroup
* BeginSimulationEntityCommandBufferSystem
- YOUR SORTABLE SYSTEMS -
- YOUR SORTABLE SYSTEMS -
- YOUR SORTABLE SYSTEMS -
* LateSimulationSystemGroup
* EndSimulationEntityCommandBufferSystem
* PresentationSystemGroup
* BeginPresentationEntityCommandBufferSystem
- YOUR SORTABLE SYSTEMS -
- YOUR SORTABLE SYSTEMS -
- YOUR SORTABLE SYSTEMS -
``` this is default sync point, choose one you like the most🧐
Entities
.WithoutBurst()
.WithAll<LocalOnly>()
.ForEach((Entity ent, Animator ani, ref CopyGestureToBuffer ctb) =>
{
if (ani != null)
{
ani.SetInteger("leftgesture", ctb.LeftGesture);
ani.SetInteger("rightgesture", ctb.RightGesture);
}
}).Run();
the new entity lambdas follow this pattern
the order is roughly Monobehaviours, in (readonly) components, ref components
is there any reason to still use the old jobstruct?
the types in the foreach have to follow that pattern
yes
when you need to sanely chain arrays and what not though them
but most of the time you wont need em
There's still a lot the foreach can't do. Like chunk jobs, or ScheduleSingle
But more api improvements are coming for sure
also for chunk iteration - i.e. do x or y based on if a component is present in the current chunk
yeah pretty much anything you didnt do in a IJobForEach
ok cool, I'm going to try and avoid using them at least
not sure how I feel about that structure but hey ho gotta bite the bullet. Don't have the bandwidth to deal with that just yet tho!
will do!
you can add and remove that Disabled component to the entity
oh wait, you wanted event when it's enabled, nevermind me then 😄
There is a special component data called system component, its great if you want to do something when an entity is created or destroyed, or even if you want to do something if a component is added or removed.
i use it to 'attach' a monobehaviour to an entity, and destroy it once that entity is destroyed
You really only need that if your system is managing some external resource that's tied to an entity. You can use the same principle though with a normal componentdata. Add a "ProcessOnSpawn" component or something to an entity, have your system query for that and remove it when it's done
Yeah thats true, i guess system component comes more handy if you want to do something when entity is destroyed, since system component wont be removed when the entity its attached to is destroyed.
I guess you could still use component data for that as well, something like "EntityIsAboutToBeDestroyed" component tag
@opaque ledge Have you seen HybridComponent? https://github.com/Unity-Technologies/EntityComponentSystemSamples/tree/master/ECSSamples/Assets/StressTests/HybridComponent
It seems like it automatically does what you're doing, it ties a hidden gameobject to your entity
I only found out about it recently
ooh 👀
When you destroy your entity the gameobject is automatically destroyed with it, and it works with prefabs
And it syncs up the transforms automatically
It does seem like it's experimental though so it might change or be removed in the future. Seems like a great idea to me though
well, i dont think i will rework my code but i am glad it exists, maybe we will see them more in 0.6
there is no ETA on preview packages right ?
hope it releases soon 😄
2019.3.1 came out, wonder if any new ecs improvements👀
Anyone know an easy way to do the EntityManager.SetName equivalent inside a job? I want to properly label my entities for the debugger but they are created from a commandBuffer.
i dont think there is one yet
i want to say that i think they want to make sure command buffers can do it in the future but I dont remember where I saw that on the forums and its also possible I dreamt it
Now that FixedString is a thing it should be possible. Guess I'll have to hack something together for now
I cant really understand the need of strings in data components, unless you are doing string manipulation on jobs it sounds unnecessary, i mean generally people use strings for showing stuff in UI right ? so i am just 'mapping' my items to a dictionary and get strings from there to my UI, plus given that strings wont change all the time and only change on specific points it seems wastefull if you keep querying it right ?
Or perhaps i am seeing this as this because i dont have any use of strings in my components 🤔
sometimes ya just want to give an entity a friendly name for the debugger 🙂
yeah - that's usually most cases lol - gotta make it less of a headache
yeah perhaps so, so far i only instantiate prefab entities so they have their names 😄
SetName doesn't even work in build, it's editor only thing
so, pure convenience while working on the code
I really dig it tho as it's pain to use entity debugger without proper names
i never converted a game object to an entity like that but i think somewhere in that code people used blobstore
try it on only 1 game object ?
maybe try it on awake method ?
can you do new BlobAssetStore instead of null ?
like settings = blabla.FromWorld(World.Defaul, new BlobAssetStore());
📌 Download the project files and assets from this video: https://tmg.dev/DOTS_Roll-A-Ball 📌
🎮 Let me know what other topics you want to learn about 🎮
👇 See below for time stamps 👇
- 0:00 - Introduction and Project Demonstration
- 1:47 - ECS Overview
- 3:10 - Setting up the Un...
in here he does that
the pong example you saw was made in 0.3, this was in 0.5, so maybe there is a change
no idea then, maybe try to convert 1 prefab to entity then dispose the blob asset store ?
native collection leak doesnt mean it 'stuck' it means you simply forgot to dispose it. i am thinking that, that error will go away if you dispose blob asset store.
i am updating some packages right now otherwise i would confirm it myself
updating some packages right now
= rebuilding everything from scratch 😄 😄
yeah, don't say that aloud on the forums tho unless you want to get into debate 😄
I made that mistake, I didn't even use that strong wording
@opaque ledge Using instantiate instead is a good idea! EntityCommandBuffer does have instantiate so I should be able to just pass a prefab entity into my job and if I instantiate that it should have the proper name. Thanks!
"Unity Physics" isn't appearing in my package manager list. I enabled "Advanced -> Show Preview Packages", and I found "Entities" and "Hybrid Renderer", but "Unity Physics" isn't there. What step have I missed?
I thikn they renamed it to DOTS physics? nope, its still called Unity Physics in package manager for me. Have you selected "All Packages" not just "In Project" ? Its also possible that packages wont show up for certain Editor versions.
@mint iron Yes, all packages. I'll verify that I have the latest Editor, back in a bit.
Yep, that's the video I have open right now 😄 He mentions three packages at the beginning: Entities, Hybrid Renderer, and Unity Physics. I found the first two ,but not the third.
Help -> About Unity, what's your version?
oh dear, mine is somehow very far behind. I don't know how, because I just installed 2 weeks ago. I have some digging to do. Thank you both.
yeah, I somehow ended up with 2018.4.blah. Installing 2019.3.1f1 now.
How can I create entities from a prefab? I'm trying to EntityManager.Instantiate(GameObject), but it creates a completely blank entity.
@plush portal https://www.youtube.com/watch?v=TdlhTrq1oYk&t=1802s
@azure saffron I think it's because it was the lastest LTS release, so it defaulted to that.
@plush portal ```csharp
[GenerateAuthoringComponent]
public struct DotPrefabinator : IComponentData
{
public Entity Dootprefab;
public Entity MovePrefab;
}
you could just use that on an object in the scene then use that entity to instantiate the prefab
ah @plush portal that makes sense. I now have the latest version, and my package manager has WAY more options.
any others here using 2020.1 alphas with DOTS?
if so, anyone can actually build IL2CPP version with the new build tools? 😄
I've kinda ignored this for a while, but it's still broken for me (but only on 2020.1, 2019.3 works fine)
should file a bug report I suppose
i can build everything just fine in 2021.0a22
I'm testing on new blank scene now and while building was super slow, just having entities there did build
it only utilizes 100% CPU only at the initial stage of IL2CPP build, normally it's stuck to 5-25% load, so I guess it's not really good at running this at parallel
oh did they fix the build packages in 2020? i'm stuck using 0.1.7 (iirc) because the anything after that has a bunch (like 2 or 3) of errors :/
ah whoops. wrong packages. i meant the platform packages
ah, I haven't tried those
i thought they were required to build a project with DOTS?
only if you need pure dots runtime (so no monobehaviours on build)
at least, I've never had those on hybrid setup
oh! so i don't actually need them for this project. even better. thanks for the clarification. the package description isn't worded well
ah yeah i saw that and tried the solution. reimport all didn't work. looks like they'll fix it in Entities 0.6?
hmmm, they really run c++ compilation on single thread?
like, wtf 😄
this build has now lasted 15 minutes so far, and it's not done
it's empty scene with entities + unity physics package
this has to be broken
this same computer would have build the whole ue4 from source in the same time
Tiny builds are just mere seconds 😏
IL2CPP builds has never taken me more than few minutes in past
so this is not normal at all
now it finished, 20 minutes total 😄
I'll try same test on 2019.3 again
2019.3 finished in 1m38s, where IL2CPP stage took 1m10s and next iterative build was 1m total
so yeah, definitely broken on 2020.1 for me
it literally breaks on the other project, but the empty scene with one physics plane shouldn't build 18 minutes extra either 😄
Is it sensible to consider doing a hybrid approach? So if I was making a roguelike, a RPG or something, I'll let ECS handle the AI but everything else I do as normal?
As long as you structure your data in a way that's ECS friendly, why not. In AI the most expensive part is sensory.
So idk, would need to have an entity version of every gameobject that the AI needs to "sense" then.
I am an absolute novice at this stuff. So I can handle the basics of the entity/job system. But I have been looking at more complete projects and everything seems way over my head.
I think that if I stick with the basics and leverage that for more heavy lifting stuff, then it could be useful for me.
I think its a good idea. Approach it with as much as you can remaining familiar, not a bad idea at all.
Not even super important to make things optimized for ECS at that point.
yeah, and I recognise that ECS is super new atm and constantly changing
I think the core of ECS is fairly well established now
but physics, animation, networking, etc is still very much WIP.
but the core processing part of ECS, and its integration with jobs, work really well
still a good overhead of boilerplate to write compared to your OOP variant, but it just comes with the territory I think.
I see. Then I think I will stick with the core stuff for the time being.
Things that I am confused by is how to visually change entities based on behaviour. There seems to be no solid way to even change the colour of the objects individually?
this is why I am seeing it as more of a background internal thing that you use for complicated stuff like AI. At least that's that I thinking atm
Yeah, the hybrid renderer, which could have been called DOTS Renderer tbh, does support it now, but its not as straight forward as with GOs
either way I agree that its probably not a bad idea to just stick with ECS for processing as you're getting into it.
As you start to get familiar, perhaps you feel tempted to try out more of it
i wish they prioritized more on URP instead of HDRP😭
it technically "works", just not to its full potential
I am finding Unity too fragmented these days. It's a minefield to figure out what works on what.
especially when you start going down AR/VR route
why not use system for that purpose?🤔
I've gone through a few DOTS tutorials, and in every single one, they have some GameManager singleton, inheriting from MonoBehaviour, for coordinating things like player score and HUD. Is that just the way of things, even using DOTS? Or is this a hybrid approach that's just easier to teach?
I think its partly the lack of any good assets/solutions to solve that particular problem nicely.
I would say the latter 🤔
Actually probably not, @mint iron 's answer is way better
I have high hopes for the new UI system they're building, as of around Unite Copenhagen they had the runtime part being demo'd and hopefully it will more naturally integrate with dots.
O that's nice - I'd be surprised if they showed something at gdc
this was a good talk on it https://youtu.be/t4tfgI1XvGs?t=887
A single, unified, UI editing tool in Unity – that's our goal for UIElements. In this session, we cover what's available now, share what we're working on, and give a glimpse of what's coming in the future. Learn about UIElements for runtime, new UI authoring workflows, and how...
uielements runtime is up as well, but its at 0.0.4 😄
UIElements isn't just the best Unity UI system ever, Its possibly the best UI system I've used in general (I say this as a windows desktop developer for the past 14 years)
yeah its pretty exciting 🙂 i have a background in web stuff, and XAML/WPF so this direction is perfect for me.
I have a big background in XAML/WPF, but I do a bit of web stuff here and there, and its easily the best of both worlds
Ah Im much more used to a QT version haha