#archived-dots
1 messages · Page 224 of 1
You are building a custom ECS?
The first thing that comes to my mind would be to allocate headerSize + componentSize instead of only the component. And then you access your header which holds the entity by ComponentPtr-HeaderSize.
Not production ready, no news
@gusty comet I'd say it's production ready
Unity themselves say it is. There's almost no hand holding though
Is there a way to remove element from Dynamic Buffer by value? Or may be some advice how to remove element by key like in HashMap implementation, but this buffer/collection should be placed on entity
For example i have Entities A,B,C,D. A logical parent for B,C,D and linked by LinkedGroup. In some case B,D can change their parent. When B,C,D creating they adding to LinkedEntityGroup on A and Add() return their index in buffer. Then Parent changing for B,D and remove them from LinkedEntityGroup on A by Index stored earlier with Add() and this causes LinkedEntityGroup length changing and then some time С should change parent too im getting index out of range because buffer length 2 ([0],[1]), but C has id 2 trying to remove from 2
How large is the dynamic buffer typically? A simple approach for when the buffers all small is to just iterate all values and check if it is the one you want to remove. This is how the ParentSystem looks for and removes Child elements in the ECS source code. You could also do something like your index approach, but instead of actually removing the buffer element, you "null" it out by giving it some sentinel value. This element could then be used by a future call to Add().
@whole gyro potentially dynamic buffer size infinite. So i can't just iterate over it
Where did they say that? ECS is still a preview package and everything I've seen from unity devs on the forums claims that it is not production ready. However, parts of "DOTS" like Burst and Jobs are considered production ready.
How often are they changing their parent?
Its like user tool. User can group or ungroup objects, but child count can be huge when ungroup will call
It still might be worth trying sequential iteration. Its quite fast with burst and is often faster than other strategies that rely on random memory access. However, if you really want a hashmap, you could always store a NativeHashMap or NativeMultiHashMap on a system. Yet another option is to store the parent in a SharedComponent. Then when you want to iterate children of a particular entity, you can use a shared component filter. The main downside with this approach is that it entities to move chunks when they change their parent.
an infinite list is pretty long I can't see how you'd make searching through that efficient 
they have literally gone out of their way
to make it as hard to install as possible
because they know it's not production ready
wdym?
I installed four things and it's working fine
Aside from the Entities package everything is poorly documented though
Yes, because it's not production ready
and they reserve the right to make sweeping changes to anything and everything
before the release
there are too many things to list
that require workarounds to get functional
in a DOTS only project
Such as?
well forget working with most of the unity tooling for things like animations
You can implement your own, it's not hard
the render is still missing features
What like?
still says it's missing decal shaders lightmaps keywords
and sorted transparencies
yea things do mostly work
I'm not trying to say nothing works
but telling people it's production ready is definitely not right
Jobs/Burst are
ECS doesn't even work on the latest version of unity right now
it just crashes
and they've said they don't expect it to be functional until the end of this year
Yeah don't trust what Unity calls "Stable"
The last actually stable LTS build was 2017
But also don't trust when they say it's unstable? 😄
Don't trust at all
Hi, I've seen some usage of [MethodImpl(MethodImplOptions.AggressiveInlining)] on some helper functions in some repos I've been reading. Would someone be able to explain to me why this inlining is useful? And perhaps where I should be looking to use it?
AggressiveInlining hints the compiler to substitute a method call with the body of the method. it helps to see the runtime JIT il code/assembly, I think that's where it's most obvious in seeing what AggressiveInlining does
[MethodImpl(MethodImplOptions.AggressiveInlining)]
int add(int a, int b) {
return a + b;
}
void Main() {
int c = add(a, b); <- Instead of a method call, it can compile into int c = a + b;
}
generally speaking less IL calls mean more optimized code - and it helps w/ small functions, if the compiler can't determine the executed code can be inlined, then on runtime it will just do a method call
That's like saying "Unity is production ready - Just make your own engine"
Isn't the whole point of production ready to not have to roll your own solutions?
Thanks for the helpful reply :). Are method calls to be avoided in DOTS/ECS programming?
No, but very very small methods can be inlined just fine
You can't avoid method calls, but for frequent small operations it may be beneficial to just have them inlined. Ultimately, it's just profiling and determining where you can optimize that would provide the best yield
Got it, thanks !
You can measure the difference of inlined vs non inlined without dots/ECS involved at all. It really only matters on code that's run in a hot loop. If you aren't doing it like 100k+ times you won't notice the difference. I generally just put it on any of my methods that are only a couple lines long if they have a chance of being used in a loop for something
And by 100k times I mean in a tick
We are talking a nanosecond or less of overhead difference
Per function call
Why does Unity.Physics.BoxCollider contain the fields for BevelRadius, Orientation, Center, and Size as well as a field for BoxGeometry?
Hey, is it possible to remove an element from a dynamic buffer during a ForEach that is running parallel?
I wanted to do it with an ECB but it can only append and not remove
I doubt it, that would likely cause chaos if it was even possible 🤔
you could set elements to zero or whatever other value though
Thanks, that's what I thought
Is it possible to access an entity query's shared components for a readonly job?
I'm looking to read the mesh data of entities with a certain tag component
I've seen in some places that SRP is usually heaviest on the main processor core
I wonder if Hybrid Render proposes to correct this, since it basically distributes the rendering of entities among the CPU cores for the SRP.
Soo I'm making my own ECS for learning https://dpeter99.github.io/projects/necs/.
And I'm thinking how should I return a list of the attached components so that i can draw them in the editor:
As I would need a ref so that it is the same instance of class that i have allocated
Hmm now i'm quite confused on how this should work. And there is a huge lack of any blog posts or similar on how to write anything like this..
If anybody feels like helping that would be greatly apreciated
My basic problem is on how to expose all the data to higher level code.
Anyone who use asmdefs with dots?
yeah
I have a little problem, and i have googled it, and see that looks like people have solved it in 2018. I have very frequently solution reloads in VS with asmdefs in project.
One type renamed -> reload whole project, bruh, it is so time consimung
not sure how big your project is, but it does seem to take longer to reload
i have cached Entities package
you could separate things out to an empty project with that particular package and its dependencies to speed up things if you are doing a lot of work on just the asmdef related stuff
yes but separating is not an option every time. Since we all here develop games we have a lot of game logic which is normal to have in same project
I personally have 44 asmdefs inside my project, 32 are my own, that doesnt include things inside the library cache
i have less and reloads timings in VS are huge
i see only old threads on forum about this was fixed in 2017 or 2018
ah I dont use vs, only rider. reload times in unity can be annoying though. and if im working on a particular package a lot, the reloads can break the editor requiring me to kill & restart it+rider
what type of reload are you talking about
VS reloads your entire project if you rename a type? that doesn't sound normal
yes, reloads in VS, reloads in editor are good
do you have the visual studio editor package in your project?
If I were to create a blob reference to a NativeArray. Will nativeArray[i] retrieve a blob asset reference to that array item, or will it just give me a copy?
my guess is it would be a copy 🤔
blob assets are immutable data when you create them it creates and copys the data over into them
If I order a system before BeginSimulationEntityCommandBufferSystem, create an ecb from BeginSimulationEntityCommandBufferSystem in it, and then use that ecb to set a component, should that component be set before the systems after BeginSimulationEntityCommandBufferSystem run?
Like, will that ecb have run all of its commands before moving on to systems after BeginSimulationEntityCommandBufferSystem?
Yes, since the BeginSimulationEntityCommandBufferSystem will complete all its previous dependencies
Ah yeah thats what I figured
It doesn't seem to be working that way for me tho
I must have messed something up
Make sure you assign the Dependency field from your system
Yea that too
oh is there something else i should be doing?
I thought this.m_BeginSimulationEcbSystem.AddJobHandleForProducer(this.Dependency); was the way to do this
Dependency = new SomeJob().Schedule();
ohh
i actually am not using a job
in this system
i'm reading input data from InputSystem
and assigning the input data to Singletons for use later on in the frame
is it not possible to use an ecb outside of a job?
You can
hmm
I guess the question is why do you need to use an ECB for this?
I wasn't originally
Why not just use a ForEach or SetSingleton?
But button presses weren't getting written into the Singleton in time for them to get read
oh dunno about the new InputSystem
Im still on the old one 👀
but iirc you can implement the new input system interface onto a SystemBase
Here is how my systems are set up currently. I'd read user input from the UserInputSystem, write it into Singletons, and then use it later on in the SimulationSystemGroup (for example in CameraFollowSystem). On some frames the Singleton would get written to late, so I wouldn't be able to register button presses later in the frame.
and register the system to the InputSystem to avoid using a MonoBehavior
Oh I didn't know that
I'm not sure if the issue with InputSystem anymore tho, I think I'm just not writing to the singleton correctly. If I check the singleton at the beginning and end of the frame, it gets written to correctly. But in the middle of the frame its sometimes not updated in time.
Yeah I'm not sure either
I think the new input system gets updated in PreUpdate, so the data should be all good before Update runs, so it's probably something with copying the data
I think I may have solved the issue, posting here in case it helps anyone else (or in case I'm wrong and someone wants to correct me lol). I was trying to read the input in a system that I had assigned as part of the FixedStepSimulationSystemGroup, which I think may have a different update process due to being part of the Unity Physics package. I've instead switched to reading the input in a system outside of that system group, and everything seems a lot snappier (I was probably missing frames for stuff like mouse movement before and didn't even realize.)
I'm pretty sure it does have a different update rate its the same as FixedUpdate in Monobehaviour
yeah its definitely different, took them like 1 or 2 yrs to do get it implemented. i remember using all the workarounds prior
I think fixed step simulation groups still runs in the "Update" loop since its independent of UnityEngine's fixed time step (you also don't see it if you visualize their loop)
could be wrong though
Ah ok, that is interesting to know. Would you know of any better ways to get accurate input into the FixedStepSimulationSystemGroup using InputSystem? I suppose I could try to create the InputSystem in that System, the data would be refreshed correctly but I'm trying to avoid references like that in my systems
I just get the input in Update and cache it. Last known input is read into FixedUpdate.
@sage mulch
Whats the best way to make sure a NativeMultiHashMap parallel writer has enough capacity?
Since it cannot auto-resize while being written to in parallel
Hi, I'm creating a shooting system in my game. The thing is, there will be shooting enemies, and shooting logic is the same for all units. But there is one moment: player's projectile must aim at crosshair. Any thoughts how I can handle this?
I think I should create some kind of AimPoint component for all the units
you can use EntityQuery.CalculateEntityCount
that sounds appropriate
Yeah I thought as much, thing is the upper bound is much much higher than the average, so I think I will just not make it parallel at all and keep the auto resize
OK, thanks
wouldn't setting the size every frame based on entity count effectively make it auto-resize (new hashmap each frame)?
The required size isn't only dependant on the amount of entities, but also on how much they move
The upper bound is when they are all spawned, as it then needs to register their position
Only if they move it needs to re-register
gotcha. then maybe the simple way (non-parallel) is best. if you really wanted to know the size for the hashmap you'd need another component to track that other movement difference and filter the query on that as well
Yeah I think that's a bit overkill
or make a hashmap for each thread 🙃
It's plenty fast even without it being parallel atm
🆗
I guess the other idea is mark the entity with a tag if it moved, and then iterate over that. Not sure if the overhead from archetype changes are worth it though
(Like you mentioned)
yep, that's what i meant by another component or the query
but if you only ever use it for that bit, then yeah maybe it's overkill
It's very hard for me to judge the overhead from something like that without just testing it
I guess it really depends on how much stuff moves each frame
yep. i'm eager for better entities docs one day. i usually just put a ton of entities in when i'm testing alternate options. but yeah, not everything is gonna be a lot of entities
Definitely, the docs are very scarce atm
Even collections
I had a bug earlier because I assumed NativeMultiHashMap.GetKeyArray gives you unique keys
There is no documentation at all for that function
:(
You can usually check the Tests for help in understanding functions
I was using shader graph flipbook node to animate sprites based on sprite sheet, but my artists wants to specify frame durations and i see there is no way to do it whole inside shader graph, so now i think i will write custom system which will change sprite on SpriteRenderer over time. I worry about performance of such system, because i need to use WithoutBurst.Run() because of referenced components. Can you give me any advice how to write good system which will operate with sprite renderer frequently?
Maybe don't use SpriteRenderer if you have tons of sprites, you could probably just have a constant sized mesh and change/adjust the UVs using the low level mesh API instead
It is not really tons, but one little system with Run() forces whole jobs to complete. I think maybe fill persistent NativeQueue with entities i want to switch sprite and do it on main thread just on next frame without lambda code
Is there a reason why there is no Job.WithCode().ScheduleParallel?
Kind of annoying to have to create structs for it
Also I have a question regarding dependencies.
Assume I have SystemA and SystemB.
SystemA runs before SystemB, and they both share a NativeList.
What is the correct way to schedule their jobs so they can use the list?
Is it:
SystemADependency = JobHandle.CombineDependencies(SystemADependency, SystemBDependency)
SystemBDependency = JobHandle.CombineDependencies(SystemBDependency, SystemADependency)
?
Or should I simply call JobHandle.Complete() on the other jobs last Depencency?
I believe you want:
SystemBDependency = JobHandle.CombineDependencies(SystemBDependency, SystemADependency)
Just make sure that this system B dependency is used to schedule the jobs in system B. This will ensure that system B jobs will run after system A jobs. You should also make sure system B runs after system A using UpdateAfter or UpdateBefore.
What if SystemB has not completed before SystemA runs again?
It seems both versions error out, telling me that SystemB writes to a collection that was scheduled in SystemA
Nvm, the issue was something else
I'm getting these errors when I stop playing.
This started happening when I added this for conversion:
#region ECS Conversion
public void Convert(Entity entity, EntityManager dstManager,
GameObjectConversionSystem conversionSystem)
{
var actionsBuffer = dstManager.AddBuffer<ItemActionElement>(entity);
// using var actionsArray = actions.ToNativeArray(Allocator.Persistent);
// actionsBuffer.AddRange(actionsArray);
foreach (var action in actions)
actionsBuffer.Add(action);
}
#endregion
The commented out part was my first try, both ways give me the same result. Don't know how to debug this. What did I do wrong?
is ItemActionElement a proper IBufferElementData struct?
Does it have any managed fields?
Yes it’s a IBufferElementData. It has 2 public fields an int and FixedString32. 5 public properties byte, 3 bools, and ushort. 5 private const int. And 1 private method.
I'd try restarting the editor and seeing if that clears it. The asset toolchain looks like it might be in an invalid state.
If that doesn't work, close unity and nuke the Library and Temp folders.
If that doesn't work, submit a bug report with your project or minimum reproduction project.
Restarting editor worked thanks!
I can understand how GetCompnent is slower than using in keyword, but what about GetComponent vs ref keyword? From what I gather, just by providing ref, it will mark that data struct as dirty and write it back to memory (even if I don't update it in my loop. So wouldn't then using GetComponent and only using SetComponent if a condition is met, be more easier on the memory access and performance than just leaving it at ref? Or am I incorrect to assume so?
- GetComponent is slower compared to just using ForEach parameters because it does a bunch of lookups to find that one component for that entity, whereas ForEach just iterates all at once with much less lookups
it's similar to doing a dictionary get for each value, vs just iterating an array, iterating an array is going to be much faster refandindon't really have different performance characteristics, at least not in regular C#
the only reason it does in unity ecs is becauserefcomponents are automatically marked as write and thus other jobs have to wait for it that system's job to finish before they can read/write that component
whereasincomponents are marked as read so other jobs can also read them at the same time
Yeah I get both 1 and 2 individually. So even if I need to write to component a much longer intervals than each frame, using ref (marking write each frame) is still faster than just GetComponent (each frame) and SetComponent at write intervals?
yes for sure
SetComponent still should be marking those components as write because that's what it's doing, not sure if unity does that automatically tho
but even without that
GetComponent is like doing several lookups to find that component, and then SetComponent doing several lookups to find and set that component
just having a ref in the foreach is several times less cost
I see. Thanks for that explanation.
Scorr explained it perfectly as usual.
I'd add that it looks like you're fighting against the framework. Usually that's not where you look in order to optimise.
Where you look first* at least ^^
Noted 🙂
Is the only way to have a collider ignore an object via Collision Filter? Is there a way to have it ignore a very specific item, or a group of specific items that don't belong to the same Physics Category?
Use a custom collector when raycasting or collider casting @drowsy pagoda
No, I meant on the actual colliders themselves (those that are authored by PhysicsShapeAuthoring)
Does anyone know when using ref on an IComponentData, does it get marked for write for the remainder of the frame, or only until the next Sync Point?
Heya - any good guides for DOTS based UI in Unity?
Or shouldn't it be based on DOTS
?
There is no real support for UI in DOTS afaik. We just use MonoBehaviours which poll data from entities and display them.
So... say I want to make a Grid based board game. The grid would be based on UI elements? Monobehaviors?
Or a monobehavior holding a vfx
You could then have that vfx reference a texture and have that texture updated via jobs
Vfx in your case could be the board, pieces, or what ever really
Thanks, I'll look into it
Why would you build your grid with UI components rather than 2D tilemaps?
if you're willing to get your hands dirty, you can play with the new UI Toolkit in the 2021.X series, but I don't think it will be actually production ready until 2021.3 or 2022.1
2021.1 adds the runtime version of UI Toolkit (previously it was for making editors, most of the editor UI has been rewritten over the last 2 years to use UI Toolkit).
2021.2 is adding simple transition animations (basic tweens for alpha and position) and is less buggy
oh wait, this is DOTS channel, nevermind. You can't use DOTS with 2021.X yet. I recommend a uGUI UI that reads data from World or uses a system to cache data that the UI reads from.
Otherwise use the VFX route or even roll your own from meshes and shader effects.
basic question but is it possible to loop through a bunch of separate Nativequeues?
gdc starts today, still nothing new on the dots side of things 🥲
where can we read about gdc's content?
you mean https://gdconf.com/ ?
yeah sorry
Is UI Toolkit usable at all in DOTS on 2020.3.x?
there's an older expirimental package for it, but I eventually ran into issues trying to use it, new Input, and a few other things together.
I cannot remember offhand the exact combination of packages / Unity versions that led it to fail, it may have been fixed with newer 2020.3. I haven't touched that project in over a month, so I can't give you more info right now.
No @molten flame , been broken for a year now, and thats whats been so insulting about the thread on dots compatibility. I removed uitk from my own project, though if you use a uitk that is older (like p7 or 8?) it may work though then you may find its incompatible with the editor
(also its fixed in 2021.2, but then entities is incompatible with that after alpha 9 😒 )
damn, that's annoying - dependency management hell
Do Nullables not play well inside ForEach jobs?
I tried SetComponent(look.Target, lookTargetItemData.Value) where ItemData? lookTargetItemData (and yes, I checked if it was null before setting, I confirmed it wasn't null and HasValue was true).
But it didn't set it at runtime. When I did it as the ItemData directly, it set it.
Is this another limitation of ECS? Or am I doing it wrong?
I think there is an issue with null values in components or something, I can't remember 🤔
I don't think a null value is a valid value, because they are structs, they have to be initialised with a value
Ah I see. Setting a nullable to a struct only copies it huh? I’ll see if there is a way to attach that reference instead. If not, then my code design is really bad lol.
yeah I think it was thelebaron that told me, I can't find the code example but you have to check it against default somehow
you'll likely need to implement System.IEquatable (or do hash comparisons on the struct)
Does DOTS support accessing Unity.api library such as Texture2D.GetPixels()?
@hard wagon you cant use managed types in burst jobs, so getpixels would need to be mainthread. you could put the results in some nativearrays and burst job any calculations though
If i have several conditions, and only a few of them require SetComponent on an item. Will just calling SetComponent several times in one shot work? Meaning will ECS know to just do it once for that component, or will it actually call it as many times as I call SetComponent in one frame?
@drowsy pagoda - it'll be the whatever the last value with SetComponent was
Oh nice! So to confirm, if I call it 4 times in one frame, it will only set it once, ignoring the first three calls?
Why would it? It'd probably just call it 4 times and the last written value is the last valued stored
Not sure why it would skip the first 3 times if you're instructing to write to the address 4 times (if the conditions are all true for each preceding if statement)
Nothing new on DOTS from GDC? :/
I am a little confused about the purpose of the burst compiler. Does it work in IL2CPP builds? It seems like these two tools do similar things…
works in both il2cpp and mono @vale grotto its really confined to a small subset of code, namely dots specific things
@little moon kinda doubted anything new would pop up, unity didnt say they were having any official presence and just two talks with unity guys on very specific topics, nothing dots related. but still vexing theres been zero news and updates for so long
AFAIK
IL2CPP converts your IL code to c++ code. Burst optimize your code on instructions level
Alright, that clears that up then, thank you!
Did anyone implement the complicated character movement system with different mechanics like bunny hop, dashing, sliding, ladder climbing and etc? I just need some help with this (I'm using ECS, so I decided to ask in this channel)
can share this 🙂
https://youtu.be/ps0CuoWbLbQ
Wow, looks cool
Hello why is NativeString64 removed from unity.collections? is there an alternative?
FixedStringXX
Thank you 🙂
is anyone using SerializeWorld successfully? im getting IoExceptions when using it in a build, but not the editor, wondering if anyone had come across and found a workaround.
@safe lintel there are a few threads on forum about it. Some people use only SerializeUtility instead of SerializeUtilityHybrid and do some pre and post logic while saving/loading. I'm currently implementing such logic but i'm a little bit far to test it in build. But i have tried simple SerializeUtility in empty project without subscenes and other complicated stuff and it works in editor and in build.
thanks, yeah I guess Ill have to add something to one of those threads. everything works perfectly in editor which is frustrating
Can I change a value in an ISharedComponentData for all the entities that it belongs to?
isn't that kind of the point of shared components
how do you set it in the first place, can you not just do that again
something like entitymanager.setsharedcomponent, but tbh not sure if you then move that entity into a new chunk or the entire chunk with a new component
might actually say in the source notes
SetSharedComponent takes an EntityQuery, which lets you set a sharedcomponentfilter, so that is what should work for me
Now if only I could find out how to properly remap entities...
Anyone had to deal with Internal: deleting an allocation that is older than its permitted lifetime of 4 frames when calling CreateServerWorld in netcode?
I downloaded the sampleproject from GitHub over at https://github.com/Unity-Technologies/multiplayer
I didn't change anything, I just go into...
Is there a way, in Editor code, to determine of the gameobject is within an ECS SubScene? I only need to figure this out during editor mode, not during runtime.
Simply doing GetComponentInParent<Unity.Scenes.SubScene>() does not work.
Ok I found a way to do it. If there is an easier way, please let me know!
[UsedImplicitly]
private void ManualConversionUpdater()
{
var scene = gameObject.scene;
foreach (var subScene in Unity.Scenes.SubScene.AllSubScenes)
{
if (subScene.SceneName == scene.name)
{
manualConversion = false;
return;
}
}
manualConversion = true;
}
Yeah I saw that, but won’t that trigger true if it’s under an additive scene? Or did they add that directly for ECS sub scenes ?
dont think it should trigger for additive scenes, ive used it for checking if stuff is in subscenes though I dont use any additive scenes
Cool thanks. I suppose I’m just overthinking it lol.
what can i do to speed up compile time in ECS
is there some junk cache somewhere because my scenes are not complex but is getting slower and slower
*scene
we are talkingn 3 shader and only cubes
very basic stuff
Hi guys, I have read that exists other framework ECS different from unity ECS.. what do you think about that? are they usable?
Most of them use reference types so they can't be used in jobs and can't be Burst compiled. In this regard, Unity's ECS would still be faster than any of those.
Compile time in ECS mostly boils down to IL weaving.
In my project I had crazy compilation times after a single line change in my core assembly (I think I shared the screenshots some time ago).
Because of that I changed most of the Entities.ForEach calls into manually written IJobEntityBatch/IJobChunk, edited the ECS source to disable blob safety checks and split my code into more assemblies.
Nowadays I only have ~15 seconds compilation times which is still pretty stupid...
is there any ETA or news on ECS or the new demo
I was hoping at GDC there will be an update or at least some news/post about it
i'm now trying to manually load subscene in my world without initialize world with all default systems. And as it was with companions mostly all systems which are part of loading logic is private with no reason. Just hate it. No news, half a year no updates, only upsetting notice on forum with still no answers. Losing my hope
@granite spoke My own conjecture is at this rate they will hold back big news for the next unite conference, alternatively dots could be in trouble shaping into a bigger mess than their transition to renderpipelines 😀
Who the fuck knows
Render pipelines are in ok shape even in 2020.3 IMO. We are using both in multiple projects.
Regarding dots, they are building much new stuff, animations, terrains and ... for the multiplayer shooter probably so there is much to be done. I would like to know but understand that preview tech is unstable. However more transparency is appreciated
unity conf are normally going once per year?
yeah
and when was previous?
Hi. How do I instantiate stuff in Dots?
EntityManager.Instantiate or CommandBuffer.Instantiate
i think 2019 copenhagen @frosty siren
no conf in 2020? @safe lintel
cancelled due to pandemic, they made unite now in response but then almost zero dots stuff
seems 2020 is some kind of unhappy num
So does anyone know how to properly use EntityRemapInfo? :(
Hey guys, small question. If I have some data in an array, and many gameobjects will access this array with jobs, does it have to be NativeArray in order to work with jobs?
I have a 2D procedurally generated map and characters will modify it, assuming there are many players and NPCs on a map in a multiplayer game, is NativeArray what I need for this or did I understand something wrong? Thanks.
pretty much yeah, if you want the full potential of jobs and burst
thanks a lot, I'm getting small performance loss because my application worked with an int[,] so far and I had to replace it with a NativeArray and a method to map from 2D to 1D so I was wondering if it was worth using it. 🙂
almost everything that goes into a job is a nativearray of some sort, they have all safety checks and things by default
Good to know. Thanks 🙂
for the multiplayer shooter probably
Did I miss something ? Is a reboot of the multiplayer fps in the works or are you guessing ?
I have enabled preview packages from Project Settings, but still Package Manager doesn't show Unity Dots physics (Unity version 2020.3.12f1)
It only shows Havok Physics for unity
Try to add from URL com.unity.physics
Thanks, it worked. dots physics documentation only said "To install this package, follow the instructions in the Package Manager documentation." which wasn't very helpful.
👌
hey
i guess in this place i can find people that mess with 2021.2b04
unity crashes while doing this
am i the only one?
@solid osprey, dots practitioners are largely restricted to 2020 LTS for compatibility reasons. You might get more traction in the render-pipelines section
I have a system that needs to read a component via in keyword. And right after there is a system that needs to write to the same component via ref keyword. Because of this, I am getting the following error:
InvalidOperationException: The previously scheduled job HandsawItemSystem:OnUpdate_LambdaJob0 reads from the ComponentTypeHandle<TradeCraft.Data.Item.ItemData> OnUpdate_LambdaJob0.JobData._lambdaParameterValueProviders.forParameter_itemData._typeHandle. You are trying to schedule a new job ItemSystem:OnStartRunning_LambdaJob0, which writes to the same ComponentTypeHandle<TradeCraft.Data.Item.ItemData> (via OnStartRunning_LambdaJob0.JobData._lambdaParameterValueProviders.forParameter_itemData._typeHandle). To guarantee safety, you must include HandsawItemSystem:OnUpdate_LambdaJob0 as a dependency of the newly scheduled job.
How do I accomplish what it's suggesting? How do I include that system as a dependency to the one that needs to write?
And if this is possible, how can I combine multiple systems as a dependency as I suspect I might have an issue with this with my future systems.
You could just pass around a job handle between systems
Yeah I got that, I think I need help to see how to do that. Pattern-wise that is.
Old but still good: https://forum.unity.com/threads/scheduling-several-jobs-that-must-execute-in-order.583972/#post-3894346; specifically, "Usually for modularity reasons you have some kind of class / struct that is referenced by all 3 systems that stores the active JobHandle so you essentially use it as dependency then change the dependency to the just scheduled job. Thus creating a chain with every step that you introduce."
Thanks. I’ll look into it
Hi, I'm having difficulty changing the value of my custom MaterialProperty component. It works fine when I update it outside of a Physics system, but when I try to move the logic for changing it into a Physics system it stops updating. Is there a reason for this?
(By 'Physics system' I mean a custom System i've written that I have updating within FixedStepSimulationSystemGroup)
Did you check to make sure it’s not being updated somewhere else? I ran into this issue only later to find out that the values were being reset elsewhere because more than one system was writing to that particular component.
Yeah I did, no luck 😦 Have you had any success updating a material prop within the FixedStep system group?
No, but your avatar takes me back to my GameBoy days, Red, Blue, then Yellow.
The good old days 🙂
anyone have an idea when dots is going to officially launch?
Someday...
In a galaxy far away...
It's already late compared to expectations and is under rework at Unity. So better not bet anything
we even have no idea when will see any news
who told that dots is under rework?
My bad, not implying on the logic/framework side. More like on the delivery workflow and editor compatibility
Based on latest news
oh, ok 🙂
hey guys, its been a billion years. LocalToWorld.Position gives you the worldspace position of the entity, right?
awesome, thanks!
every my experience with quaternions goes like googling "How to"
right yeah. I don't know what the threshold is for working with quaternions where it sticks, but I've certainly never hit it
I basically need to shorten the lever arm on this physics thing relative to its rotation around the x axis. its a shame that quaternions don't use 3 axes :/
no one here happens to be a deft enough hand with quaternions to know the pattern to get rotation perpendicular to the forward vector, would they? 😅
oh sick, yeah let me take a look in that quaternion math module
hmm, nah, fwiw, there are only ways to convert from euler to quaternion. apparently its a mathematical principle that you can't go in the other direction. something called gimble lock
I could be wrong, maybe they can make certain assumptions and give you something that would work, but if so I haven't found that method
i think there should be equivalent in Unity.Mathematics for this https://docs.unity3d.com/ScriptReference/Quaternion-eulerAngles.html
the toEuler method is in the Physics package I think if you want to copy it out of there (who knows why they deem it not worthy for the math package (there's a whole thread on it))
But anyway, probably stick to quaternions anyhow. Do you mean the rotation around the forward vector axis?
yes, exactly
something like i think you might lose precision going toeuler?
I think you want roll perhaps? e.g. https://stackoverflow.com/questions/54214698/quaternion-to-yaw-pitch-roll
yes, roll is exactly what I want
the problem is, all of those stack overflows are either people for asking for help with no answer, or people saying "you cant do that directly because quaternions represent TWO euler angles, not one"
and I'm like, I get that, but surely that means I could make the equation work by just tracking that secondary quaternion information, like, its "up" quaternion or something
have you tried using the roll from one of the answers to see if it's what you need? e.g. https://stackoverflow.com/questions/12088610/conversion-between-euler-quaternion-like-in-unity3d-engine
but yes, there are fundamental issues with going between quaternion & euler unfortunately
lerping is especially tricky
the thing I'm worried about is the fact that each of those are making some kind of assumption that allows them to make that conversion, and each of those assumptions is going to cause it to have weird behavior in certain circumstances. So, unfortunately that means I either have to talk directly with someone who understands the math well enough to flesh out the assumptions I have available in my problem, or I need to keep reading these wikipedia articles until I understand the math myself lol
also to mention it, one option is to store the transformations something has had applied and apply them in inverse to give the remainder rotation
what is the problem?
basically, imagine an airplane that retracts its wings as it rolls. when the plane is flat/parallel to the ground, the wings are fully extended. when the plane is rolled completely to be perpendicular, its wings are fully retracted
other than that, this is all standard entities coordinate space. I have the localtoworld.rotation quaternion, and the world quaternion
I think a lot of those answers are for monobehavior stuff or shader stuff, and I'm worried there will end up being different assumptions about worldspace in those usages)
also, certain things assume Z is forward, like in Unity, but the wikipedia article on the quaternion -> euler conversions assumes X is forward
for instance, the link you posted has 4 different solutions, each with different results lol
I suspect the roll from above will serve you just fine. Go with the top answer from that last link I sent and convert it to math class equivalents. It's true you need to be mindful of what coordinate system people are using but the underlying principles are the same with dots or other. The other way to tackle this kind of thing is to simply use a hierarchy. e.g.
PlanePitch
- PlaneYaw
- PlaneRoll
- Wings
- PlaneRoll
wouldnt that hierarchy sort of assume the answer to knowing planeroll already exists though lol?
unless this is entirely derived from physics, presumable you're e.g. rotating based on user input? in which case just rotate the separate entities as appropriate. Depends on your specifics
nah, unfortunately its physics
the actual case here is that I'm building a system to approximate the vanishing stability point of a boat as it keels over
the boat attempts to rock back to neutral until it passes a certain point, after which it will capsize because it becomes more stable upside down
the actual calculation for that is super intense involving the geometric center of the submerged part of the hull, but instead I'm using these "bouyancy wings" to approximate that concept
I don't know how well that serves your use case but there are RotationEulerXXX components that you can use if you need a euler interface https://docs.unity3d.com/Packages/com.unity.entities@0.17/manual/transform_system.html
oh do physics entities decompose to those correctly? 👀
No idea I only used them with a custom character controller once
Im okay with it being a one frame delay. I'm assuming that once you opt into that system, your rotation for that entity is tracked in Euler first and then converted at the edge to quaternion
my expectation would be those components are only ever read from, not written to by physics... would be curious if that wasn't the case
ah, yeah, thats a good question. fortunately I don't need to write to it
I keep things strictly read from position -> write to velocity
No I meant... I don't think you'll be able to read the rotations from those components as the physics simulation will never set them. Hopefully I'm wrong though.
ahhh, yeah I see what you mean
because if what I said above is correct, that rotation "is tracked in Euler first and then converted at the edge", then the physics system writing to quaternion wouldn't make any sense
well. I hope that you're wrong, and I'm wrong, and it's magic.
@amber flicker physics system ignores the transform system
sounds like bad news for me, then
I wish there was some way I could deduce this indirectly without even requiring Euler anglers. like, subtracting the current rotation quaternion from the up rotation quaternion..
that would work if it wasn't for the fact that its got other axes of rotation, and I'd get a jumbled signal of roll and pitch
If I could figure out how to pre-rotate it such that it no longer had any rotation except on the Z axis, then that would work
but, its a chicken and egg problem. I'd need to know what its current yaw was to rotate it back to forward...
Doesn’t your boat kind of have water wings on the other axis anyway? Just with different contributions. Wondering if you do actually want to reduce it to just roll. Which… have you tried yet? because I still think it’s what you want…
one sec, work meeting 😛
meeting complete! back to the True Work
General question: I am building a Voxel-style game (there is a fixed-size 3D grid, but the voxels are to simulate space and air, not the ground). Because it simulates simple thermodynamics, I'm looking to do as much as possible in pure ECS. It's a multiplayer game so I'm also looking at NetCode.
To keep things fast, spatial data is dealt with in native arrays and not entities because there could be millions of points of data related to how the grid fits together.
In general, how does 'data ownership' work? I've been told I should try to let systems own data, but for things like the actual voxels, I need a lot of different systems and in-game events to interact with the air.
I'm considering making Sections/Chunks which are like 16x16 areas of the grid, do have entities, and would manage the spatial structs. Would this be the best way to go about it?
so @reef thistle , let me approach your problem from a practical perspective, because I imagine there are a lot of competing dogma about what bits of code should and shouldn't access other bits of code from an abstraction perspective
I think what you're going to find is that as a matter of increasing the potential for parallelism in your code, you're going to want to have the flexibility to control your data narrowly for certain parallel operations. So what I think you'll probably end up finding strategies for is splitting up your data across multiple different arrays which can optionally be processed together.
for instance, instead of an array that holds structs of type AllVoxelData, which has fields like {airTemp, windDirection, convectionProperties{density, fluidity}, particleProperties{liquidSaturation, dissolvedParticles}}, you might have several different arrays for different aspects of the thermodynamic properties you're simlating
thats going to lend itself well to parallelism, because ideally you want all the individual units of processing to be the same amount of computation (you don't want if cases for different types of data leading to variability in the processing of each different types of voxel), but its also going to lend itself to the way you as a developer get the opportunity to design and maintain features one at a time
what you're doing with thermodynamics may very well end up being one massive system with a bunch of different jobs that run with dependencies (allowing other systems to run while those dependencies are resolving in order)
there may only end up being a few pieces of data that are truly external facing in nature. like maybe your thermodynamics system is managing all the attributes of convection and circulation of air, and the only things other systems need to know are the windspeed of any given position in the world, so maybe the only exportable data is the wind speed. splitting this information up into different arrays may allow you to have some external systems accessing that exported final array while the thermodynamics prerequisites calculations are being run on the other arrays
these are all just general thoughts, not necessarily prescriptive but hopefully useful. My final advice is to take a look at the com.unity.physics package implementation, they have multiple large job processing systems that need to coordinate with each other, so its a good place to pick up some useful patterns for dependency chaining, external system access, and intermediate result accumulation. There are three systems - something like buildphysicsworld, exportphysicsworld, solvephysicsworld... or something I cant remember but you'll figure it out looking through the code
oh, also, just an fyi, based on the volume you mentioned you're probably going to be using Jobs more than you'll be using ECS per se.
at least for processing those 3d nativearrays
Hi, I'm getting the following error:
InvalidOperationException: The previously scheduled job PlayerMovementSystem:OnUpdate_LambdaJob0 writes to the ComponentTypeHandle<CharacterController> OnUpdate_LambdaJob0.JobData._lambdaParameterValueProviders.forParameter_characterController._typeHandle. You are trying to schedule a new job NPCMovementSystem:NPCMovementJob, which writes to the same ComponentTypeHandle<CharacterController> (via NPCMovementJob.JobData.CharacterControllerHandle). To guarantee safety, you must include PlayerMovementSystem:OnUpdate_LambdaJob0 as a dependency of the newly scheduled job.
I'm having a bit of difficulty understanding it. Based on how my systems are structured, these two movement systems should never be touching the same CharacterController (the PlayerMovementSystem will only touch the player's entity, and the NPCMovementSystem will only touch the NPCs' entities). I specify EntityQueries for both systems that have no overlap, so it should never be able to happen anyway. Does anyone know why this error would be appearing?
I also have [UpdateAfter(typeof(PlayerMovementSystem))] at the top of my NPCMovementSystem. Does this not work for scheduling an IJobEntityBatch?
ya I would probably make Chunk components which have their own entities
Can anyone tell me what seems to be the problem here? This is what GameObjects vs Converted Game Objects looks like in my game.
How come the gameobjects work fine but not the converted ones?
Hi! Trying to convert some performance-bottleneck code into Jobs. There's a few bits of data to work with 5-10 variables (at least two vector structs among those) per object the original code works on.
Wondering if it's better to make 5-10 native collections to hold each of the variable types or if it's better to make a wrapper struct to represent each object's data, and just have one native collection of said struct. I.e. a context struct. I think I need to write to at least 3 of these variables.
Any suggestions or general thoughts? Pretty new to this so any relevant ideas is appreciated.
Ordering attributes are different from dependency handles. The ordering attributes just tell which system runs in/before/after whatever system, but a job can span longer than the execution of the system.
I don't suppose anyone knows if there's a way of controlling the ordering of converted entities? It seems to change through runs sometimes and I need a consistent maybe even a specific order that the objects are converted in
Uhm just shooting in the dark here, but maybe you could run your own conversion systems. They add some kind of checkpoint tag to a singleton entity dedicated to this. Each new conversion system requires its tag to execute. This way you could build your own conversion chain ? I've not tested such a thing.
Well even easier would be to handle the systems update list of a conversion world
Yeah, that seems like a good way, thanks @karmic basin
is networking supported by Dots?
Unity started to implement a networking solution, called Netcode
which is built on top of their low level transport layer - so you can also just use that
is that hard to integrate with Steam netowrking api
speaking of netcode, what solutions do you recommend ? our studio is looking into photon quantum atm but thats on the more expensive side unless we missed something. anything else ? i heard mixed opinions about the Netcode package
also are there any must have DOTS assets ?
I found DOTSNET and Steamworks V2 on asset store, but haven't given either a try yet
Is anyone using ECS with v2021 ?
No in a unite video they said they are doing an open world multiplayer shooter as their next test/demo project with animation and terrain and performance in mind
check last unite's roadmap video i guess
Oh nice. I think I missed it. I'll look for it this week-end if I fond the time, thanks for the info !
Is there a way to draw rendermesh mesh components in parallel or does that have to be mono
and with Unity.NetCode, the documentation is a bit garbage. If I add an entity to ClientWorld0 - this world exists for both the Server and the Client (the first at least) and that information is networked to the client right
the 6.0 docu relies on a component which is already obsolete
okay that theory is wrong, clientworlds aren't built on the server in server-only mode
hey guys, i have a ground floor plane with a shader graph mat on it. When i set it to a subscene, the shader graph mat when nuts and started flashing on and off, even in play mode
any thoughts on how to fix this?
ECS is not currently compatible with 2021
getting an error ... which is neither primitive nor blittable. when trying to nest one IComponentData inside another , is there a way around it ?
what does the struct look like?
Your public class Variables is not blittable
they won't be blittable because they can have varying sizes (via inheritance), so you need to make it a struct
seems to work thanks
entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
boidArchetype = entityManager.CreateArchetype(
typeof(Translation),
typeof(Rotation),
typeof(LocalToWorld),
typeof(RenderMesh),
typeof(RenderBounds),
typeof(BoidMovement),
typeof(SeperationBias),
typeof(AlignmentBias),
typeof(CohesionBias),
typeof(Celldata)
);
translation, rotation, localtoworld, rendermesh, renderbounds can not be found in the current namespace ?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Entities;
am i missing something ? :b
also what would be a better way of doing this ? seems rather tedious 😛
found what was missing.
okay, found out about blob assets lol, i guess thats what i should use
is there a way to reference a MonoBahaviour inside a system update ?
( to have it in a component data - trying to avoid using static ref )
Check if this fits your need: https://docs.unity3d.com/Packages/com.unity.entities@0.17/manual/hybrid_component.html?q=Hybrid components
can't seem to have CompanionLink ... is it generated in runtime ?
seems useless ( im probably doing it wrong 🙃
You convert the gameObject to an entity but during your conversion process you declare the gameObject as a "Hybrid Component."
public void Convert(EntityManager dstManager, ...) {
dstManager.AddHybridComponent(GetComponent<U>());
}
i see but how do i access the (mono) Component inside a foreach after adding it as a hybrid ?
Just add in your foreach statement
ForEach((Animator anim) => { ... }).WithoutBurst().Run();
Example from a system base
why the emphasis on WithoutBurst ?
because it's a managed object
and therefore not blittable
so you can't use BurstCompiler on it
seems like a step back from dots
Yea - use it when you need it
true
Since i only have a few sprite renderers I can expend using it
public class Controller : ComponentSystem {
protected override void OnUpdate()
{
Entities.ForEach(( ... )).WithoutBurst().Run();
is there a need to Run it ?
its inside a system
You'll get a compilation error
i see
btw you probably want to switch ComponentSystem to SystemBase
afaik ComponentSystem is on a slow path to getting deprecated (still used because GameObjectConversionSystem inherits ComponentSystem)
seems to have similar set of methods for override
thanks
eh... hybrid doesn't want to play nice with physics
funny thing is that without using AddHybridComponent and doing in the normal way doesn't break the ForEach when using a ( mono ) Component
Yea that could also work - Hybrid is mainly if you want a strict Entity -> GameObject kind of pipeline
you need a gameobject but it's "managed" by the Entity exclusively
i didn't understand that last bit
a good example is if you have like your own physics system and want to apply it to like a sprite renderer
so it automatically will create CompanionLink regardless if i use the AddHybrid... or not ?
If you use AddHybrid - the CompanionLink is created
idk about the other way of hooking a gameobject to an entity
dont think CompanionLinks are added
ah right so it just won't find any items to iterate
but there is no errors ( so far this is my de-facto standard of knowing if ECS is working or not ?_? )
If its convert and inject - I think that way is still valid as of now. Idk when it will be deprecated
i need convert , inject and delete
otherwise physics stuff doesn't work for some reason
is there a source code for AddHybridComponent ?
Yeah the source code is all in the Entities package
i might just manually add it to my conversion system function
true
so much complication for a simple dictionary hack ... ( u might be able to tell i don't enjoy over-engineering )
ill just keep a static dict and add int inside a IComponentData without doing 3k lines of code
dang it , ended up doing what i was hoping to avoid ( static vars )
Is there a way to create an entity using script that has both physics and mesh components without instantiating a prefab? I'm looking to create an EntityArchetype for one, but I'm not sure if I can create all of these components using an Archetype:
Might be better to ask if its suggested to create such an entity using an archetype. Or should I just keep using the prefab?
i'm trying out the burstcompile, but on anything i've tried it on it mostly says 'cannot be vectorized'. i've tried online examples, same issue
on jobs that is
i even tried having nothing in the job apart from Execute(int i) and even that wouldnt work!
heres an example off unitys own documentation. result - loop control flow is not understood by vectorizer
[BurstCompile(CompileSynchronously = true)]
private struct MyJob : IJob
{
[ReadOnly]
public NativeArray<float> Input;
[WriteOnly]
public NativeArray<float> Output;
public void Execute()
{
float result = 0.0f;
for (int i = 0; i < Input.Length; i++)
{
result += Input[i];
}
Output[0] = result;
}
}
Output [i]
Does anyone have experience with using Mono vs. IL2CPP with DOTS? I'm exploring DOTS again and I remember this slide from the Unity.Mathematics talk
Entity SpawnBoid(Vector3 position) {
Entity e = entityManager.CreateEntity( boidArchetype );
entityManager.AddComponentData<Translation>(e, new Translation() {
Value = position
});
return e;
}
is there a better way of adding component data ? this seems to create a sync point and i feel like there might be a better solution ?
You can use a command buffer to make use of a preexisting sync point
ill look into that, thank you.
entityManager.AddComponentData<RenderMesh>(e, new RenderMesh()
{
mesh = boidMesh,
material = boidMaterial,
});
Linter yells at me that RenderMesh cannot be used as a type in the AddComponentData method declaration. am i doing something wrong ?
RenderMesh can only be applied to a SharedComponentData, as it is non-blittable
i have it open but unfortunately its not very clear on a few things. ill check out shared component data though then
oh alright, shared component data seems easy enough 😛
In that case, I recommend this resource as well:
oh i did not see that yet, thank you so much!
also i cant quite figure out what you meant by using a command buffer
could you explain ?
unfortunately for a few things in the documentation language barriers make it hard to understand
Instead of calling EntityManager, you can call EntityCommandBuffer, which executes during a premade sync point, instead of immediately
For this, you need an EntityCommandBufferSystem
OH entity command buffer, i was looking at the wrong thing
yeah now all makes a little more sense lol
Would anyone have any advice for this issue? Still trying to figure out the best way to spawn these entities.
Is there something keeping you from creating all of those components? Or do you just not want to add and specify all of the fields for them?
I wasn't sure if it was feasible, tbh. Some of them (particularly those linked to the mesh [BuiltInProperty, etc]) just don't look like normal components.
I can't speak for all of those specific components, but I've created plenty of entities without prefabs. It is just data, after all, so I don't think anything is stopping you. I guess the best way is to just give it a try (add all the components you see there in the entity debug view)
Will try, thanks 🙂
are there any more recent DOTS sample projects
than the multiplayer one from Unity Unite 2019
Entities, H-Renderer & Physics packages samples up-to-date : https://github.com/Unity-Technologies/EntityComponentSystemSamples
Train yourself to port GOs to Entities : https://github.com/Unity-Technologies/DOTS-training-samples
Netcode samples up-to-date : https://github.com/Unity-Technologies/multiplayer
Contribute to Unity-Technologies/EntityComponentSystemSamples development by creating an account on GitHub.
Samples designed as exercises to be ported from Unity GameObjects/MonoBehaviours to Unity DOTS. - GitHub - Unity-Technologies/DOTS-training-samples: Samples designed as exercises to be ported from...
There's one also for DOTS Animations package....
uh this might sound a little silly but i cant find anything in either the docs or online (i might be overlooking it 😅 )
how do i read AND write from/to a component ? i have a velocity component and an accelleration component and i need to read from velocity for the movement and write to it because of accelleration ?
ref Foo readFoo, in Foo writeFoo```
would work, i think, but it seems rather silly ?
ref is read/write not exclusive write
ah okay, docs werent very clear on that but it does make sense, thank you
thank you!
[UpdateInGroup(typeof(SimulationSystemGroup))]
[Unity.Burst.BurstCompile]
public class BoidSpawner : SystemBase
{
private EndSimulationEntityCommandBufferSystem endSimulationEntityCommandBufferSystem;
protected override void OnCreate()
{
endSimulationEntityCommandBufferSystem = World.GetOrCreateSystem<EndSimulationEntityCommandBufferSystem>();
}
protected override void OnUpdate()
{
SpawnBoids();
}
void SpawnBoids() {
EntityCommandBuffer.ParallelWriter pecb = endSimulationEntityCommandBufferSystem.CreateCommandBuffer().AsParallelWriter();
Entities.WithAll<DoSpawnTag>().ForEach((int entityInQueryIndex, int nativeThreadIndex, ref DoSpawnTag dst, ref BoidSpawnData boidSpawnData, in Translation translation ) => {
Random r = new Random((uint)nativeThreadIndex);
Entity e = pecb.Instantiate(entityInQueryIndex, boidSpawnData.boidEntity);
pecb.AddComponent<BoidVelocityData>(entityInQueryIndex, e);
pecb.AddComponent<BoidAccellerationData>(entityInQueryIndex, e);
pecb.SetComponent<BoidAccellerationData>(entityInQueryIndex, e, new BoidAccellerationData() {
Value = r.NextFloat3() * 0.01f
});
pecb.SetComponent<BoidVelocityData>(entityInQueryIndex, e, new BoidVelocityData() {
Max = new float3(0.01f, 0.01f, 0.01f)
});
}).ScheduleParallel();
endSimulationEntityCommandBufferSystem.AddJobHandleForProducer(this.Dependency);
}
}
this system seems to severly impact performance -- why does it do that ?
im doing something wrong i just dont know what im doing wrong 😛
also how would i go about using a "proper" seed for the rng? i wanted to use elapsed time but that only works on the main thread
Well, it's far more performant to do this stuff in batches instead of individually. However, batch-work usually needs EntityManager. The recommended way to do large-scale procgen is to do it in a separate world with ExclusiveEntityTransaction and transfer it over to the main world when it's ready. For more on efficient boid processing, peruse this: https://github.com/Unity-Technologies/EntityComponentSystemSamples/tree/master/ECSSamples/Assets/Advanced/Boids
ill be looking into that, thank you!
yeah command buffer isn't that great currently to instantiate with, only do it unless you really don't want a sync point
entitymanager.instantiate with a nativearray of enitys argument can create a ton entitys really fast
I'm getting the error Library\PackageCache\com.unity.jobs@0.8.0-preview.23\Unity.Jobs\IJobParallelForDefer.cs(77,85): error CS8377: The type 'U' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'NativeList<T>' When I try to install the Entities package, do I need to use Net Standard or something?
make sure all the packages are update to there latest versions?
If I have data which is constant, every frame read, and shared between entities in group fashion, is there any goto to decide to make this data blob, shared, or duplicate with componentData?
Yeah so if I make a new project and import Entities, Jobs, and Hybrid Renderer then I get no error. When I import those same packages to my main project I get the error I mentioned earlier
and both are using .NET Standard 2.0
iirc that error is from using a version of Collections that is too new. 0.15.0-preview.21 should work
speaking of packages, anyone know what's new with Burst 1.6.0-pre.3? it came out on the 30th but there's no entry in the changelog
This worked, thank you!
{
return prefabState switch
{
PrefabState.Hidden => 0,
PrefabState.Unselected => 1,
PrefabState.Selected => 2,
PrefabState.SoftFocus => 1,
PrefabState.HighLight => 2,
_ => throw new ArgumentException(nameof(PrefabState), $"Not expected value {prefabState}")
};
}
will burst not suppor this
on enum
the format that you're using may not be supported (not 100% sure though). the switch shorthand was introduced in C# 8, which Unity only just started supporting a little while ago. Burst only supports a subset of C#. it should work if you style it the "old-fashioned" way. Burst also doesn't support exceptions very well.
public static int ToShaderStateIndex(PrefabState prefabState)
{
switch(prefabState) {
case PrefabState.Hidden: return 0;
//etc...
default: return -1;
}
}
quick question... entity is just an index and a version right... index and version are public.
So can we basically create a List<Entity> of entities which do not exist yet ? I kinda need them as placeholders to resolve later on when more information was received... therefore i need to manually set the index to some unique id... is this possible ?
I don't know if you can be sure that the newly created entity's will match the placeholders could be risky 🤔
Well you are right... probably my approach ist just wrong.
I have a player entity with a inventory. I have items ( inside the inventory ) which are entities too.
The inventory is basically just a List<Entity> to associate the players item with the player itself.
When the player logs in, i send the serialized player with all his components to the client. Then the items. The problem is that the item entities arent there when the player is created.... they arrive later.
can't you just use a dynamicbuffer and add them to that when needed
Yeah but how would the logic behind this look like ? I mean when the player arrives... the items arent there. Later on the items are received. But only the player knows which item belongs to him. So the problem is the 1:n relation where only the player knows what item belongs to him. Guess i need a relation where both sides know each other. But that kinda sucks
I get the feeling that relations between entities are just bad
Does it matter if they arrive a bit later, like how much later is it exactly
And couldn't you just use a unique ID for each item
i cant quite figure out how this would work ? is there any other resource for this ? the unity example seems to use the default world too ^
You need to use ExclusiveEntityTransaction (https://docs.unity3d.com/Packages/com.unity.entities@0.1/manual/exclusive_entity_transaction.html) on a manually-created world (https://docs.unity3d.com/Packages/com.unity.entities@0.17/manual/world.html)
You should really read 5argon's articles I linked you. There's a very relevant one here: https://gametorrahod.com/world-system-groups-update-order-and-the-player-loop/
Anyone knows if DeallocateOnJobCompletion works on UnsafeLists?
oh i see. i was trying to use the Stage flag and EntityManagers !
yeah i did read that article but it was pretty late, maybe i didnt register the important bits, gonna read it again later 😅
Bop still want to know if anyone knows^^
its up to you, though if it is persistent and isn't going to to change through the life of the game then I would probably make it a blob
Even if it's static, I believe managing the lifetime of blobs is pretty much still a pita unless it's associated with a gameobject in a subscene (Though it's been a while since I used them.). In most cases you can just implement it that way though. E.g. a gameobject that references a scriptable object with custom conversion.
don't blobs just dispose of themselves, I've been using them without being associated with a gameobject and havent had any errors so far 😕
I think as long as they're associated with a subscene it's fine? I forget the name of the util that does it - perhaps you're using that? Otherwise... might be good to check for leaks at some point.
I'm using an object with converttoentity with destroy to convert that into a blob that's about it
I think that's fine too.ConvertToEntity is great for getting started in a simple scene and see the conversion workflow doing it's thing, but it doesn't help with improving load times. SubScenes do. Essentially when saving the scene, we also write out a cached entity binary representation. SubScenes is what allowed the megacity to scale, since we only ever load the game object representation for editing a specific part of the world: https://forum.unity.com/threads/new-subscene-converttoentity-workflows.638785/
One question...
Imagine you are developing a tower defense game...
You have a turretbase which is an entity...
And turret-guns which are mounted on top of the turretbase.
So basically a child/parent relation.
You turretbase has a parent component which points towards all the turret-guns mounted on top of it.
How do you pack this turret into a package for being send over the network ? The problem is that the turret and its guns are entities... How would you pack them in an package ?
some metadata to describe the linkage between entities, i probably wont care if they're the exact entity version/index, i'll probably just care if the data is correct
Ayo guys can i just upgrade to dots casually without any consequences?
Like, install dots then poof nice performance...
No
Bruh.. so changing to dots would be hard?
Like i have to change all scripts?
And edit them?
Like i got almost hundreds of scripts and if i change to dots, they would be full of errors and shit?
you'd pretty much have hundreds of scripts which wouldn't be using dots
no idea if anything would break
but you'd have to rewrite things to utilize dots
Oh, damn thats bad
That's a bummer, considering I had high hopes for dots
Well it's pretty much an optimization pass you'd be doing
Well I'm not really that great at coding, so upgrading to dots might be impossible
Also, the reason I want dots is because the game I'm developing is a open world game
Which would require really many optimizations
And it is targeted for mobile and PC devices
@little jasper you can import jobs and burst, find most bottlenecks in your project and try to improve it with using jobs and burst. but not convert whole project to dots including entities package
Oh okay I'll try that, thank you very much
also it could be not great idea to develop such game without knowing coding well enough
Should i use the unity profiler to see it?
Yea you should use Unity's profiler to see where the bottlenecks are
you should use unity profiler in all cases you want to check performance of your systems
I think once you're comfy with that you can use a more precise profiler if you ever need to
Well i mean I'm not a coder that can code anything in around 10 minutes, it takes around 2 hours for me to make a terrain Deformation script
@frosty siren @coarse turtle
Thank you very much with your help...
as well as for me, because i'm never really use such logic, but it is not mean that you are not good with coding. If someone coding terrain deforamtion in 10 minutes, it only means that this person is just experienced in this particular task
all good, use Profiler Markers to start sampling your suspected bottlenecks: https://docs.unity3d.com/ScriptReference/Unity.Profiling.ProfilerMarker.html
Agreed
Okay, I'll start doing that by the start of tommorow
PC turned off, currently at bed thinking about unity optimization
Then DOTS casually popped into my head saying " i am great optimization, use me as i will guide you to make rockstar games look puny " (bad grammar intended)
wish you a dream of a perfectly optimized game 🙂
Thanks :D
yeah, as well as stacking on 2020 unity
Ok imma head back to sleep, thank y'all for helping me
You need to use ExclusiveEntityTransaction on a manually-created world
sorry for keeping bothering you about this but either theres so little documentation on this or im just being plain stupid.
how do i use an EET on a manually created world ? i cant seem to change the EntityManager the EET locks since the EntityManager set field is a non public field.
found this article https://gametorrahod.com/batched-operation-on-entitymanager/
but they dont really talk about how to use it either. i understand all the other parts but the EET itself remains an enigma
i think im just missing a piece somewhere.
@sour atlas ```cs
ExclusiveEntityTransaction transaction = myWorld.EntityManager.BeginExclusiveEntityTransaction();
//do stuff
myWorld.EntityManager.EndExclusiveEntityTransaction();
ah i was trying to instantiate it. that makes more sense 😃
Whats the cleanest way to have two systems reference the same native array? I have one system that needs to grab data from some entities then push that data to a compute shader , which will write the results to a native array once its completed. Another system then needs to grab that native array later on to update entities with it's data.
You can store it on a class component or just use a dynamic buffer which you can reinterpret as a nativearray where needed
Super obscure ECS error I'm running into with Blob assets:
// Prepare BlobAssetReference
BlobBuilder builder = new BlobBuilder(Allocator.Persistent);
/*ref NativeHashMap<FixedString64, UnitBPData> blobData =
ref builder.ConstructRoot<NativeHashMap<FixedString64, UnitBPData>>();*/
NativeHashMap<FixedString64, UnitBPData> blobData =
builder.ConstructRoot<NativeHashMap<FixedString64, UnitBPData>>(); //neither of these appear to work; the former was what was used in the source article
blobData = this.unitBPMap;
this.unitBPMapReference = builder.CreateBlobAssetReference<NativeHashMap<FixedString64, UnitBPData>>(Allocator.TempJob);
builder.Dispose();```
Taken from here: <https://coffeebraingames.wordpress.com/2020/11/29/getting-started-with-blob-asset/>
But I'm getting this error:
```...\UnitBP.cs(41,13): error \UnitBP.cs(41,13): error ConstructBlobWithRefTypeViolation: You may not build a type NativeHashMap`2 with Construct as NativeHashMap`2.m_HashMapData.m_Buffer is a reference or pointer. Only non-reference types are allowed in Blobs.```
I could only find these references to it on the internet:
<https://forum.unity.com/threads/blob-asset-utility-method-error.1043884/>
<https://forum.unity.com/threads/entities-0-17-changelog.1020202/page-2#post-6757471>
<https://forum.unity.com/threads/entities-0-17-changelog.1020202/page-2#post-6759856>
<https://neilmarkcorre.wordpress.com/2020/12/01/working-with-scriptable-objects-and-blob-assets-and-creating-a-utility-class/>
None of which were particularly helpful. Any clue what I'm doing wrong?
well internally nativehashmap contains a pointer and blobs are written to some sort of mem mapped file (I think), so anything with a pointer seems counter intuitive cause you'll be a writing an address which doesn't help you at all
Right, that's what I'm gleaming from those forum posts. I'm not sure what the best solution is then. My goal is to efficiently access the static blob data from components, just like in the example in the forum post:
public readonly FixedString64 weaponId;
private readonly BlobAssetReference<NativeHashMap<FixedString64, WeaponData>> weaponMapReference;
public Weapon(FixedString64 weaponId, BlobAssetReference<NativeHashMap<FixedString64, WeaponData>> weaponMapReference) {
this.weaponId = weaponId;
this.weaponMapReference = weaponMapReference;
}
public int Damage {
get {
return this.weaponMapReference.Value[this.weaponId].damage;
}
}
}```
well you can always allocate initially a static readonly hahsmap and manage that hash map so that you can pass that to your jobs. Or you can write like a hashing function which points to the correct blobarray index based on a FixedString
so it's a hashmap where you already know the size before hand, so the hash function can work on that fixed size
That's the system that I was originally using. I wanted to move everything to Blob assets for better performance and to avoid needing to pass a hashmap into every job in which they're accessed, e.g.
int foo = weapon.Damage;
...
}).Schedule()```
Rather than:
```var hashmap = WeaponDatabaseHashmap;
Entities.WithBurst.ForEach((in Weapon weapon) => {
int foo = hashmap[weapon.weaponId].Damage;
...
}).Schedule()```
Yeah I understand. So if fetching the data and reading from the hashmap is a big bottleneck, then yeah maybe a hash function to map to an index of a BlobArrays might be worthwhile.
I dont really have any other ideas, since the whole pointer restriction makes it difficult to work with especially if all you want is to store a map or set (or some other container)
Yup, it's a head scratcher 😅
maybe a hash function to map to an index of a BlobArrays might be worthwhile.Can you elaborate more on this? I'm not aware of any other mechanism by which to utilize BlobAssets in this context, and the docs appear to be... not quite up to date 😄
Well you can store a blob array into a blob asset iirc. So technically what you can do is pretty much write your own hashing function which given a FixedString64 returns an index in your blob array.
So it's pretty much a readonly hashmap
but built using blob arrays
Something like this then?
UnitBPData[] blobData = builder.ConstructRoot<UnitBPData[]>();
I can convert from FixedString64 -> index into an array no problem, just haven't a clue how blob assets are supposed to work in practice other than what I've been scavenging from forum posts 😁
uh one second - let me open the source lol
var builder = new BlobBuilder(Allocator.Temp, 128);
ref var root = ref builder.ConstructRoot<BlobArray<int>>();
const int count = 100;
var array = builder.Allocate(ref root, count);
for (int i = 0; i < count; i++)
array[i] = i;
Here's an example of allocating a BlobArray @naive ice
the BloblificationTests.cs file in their Testing package pretty much gives some decent examples
Awesome, I will give that a shot then - many thanks 👍
the dynamic buffer is the solution i ended up coming to, thanks 🙂 !
It worked perfectly - thank you again! @coarse turtle 😁
np 🙂
how are people liking the dots experience these days? I've read a lot of mixed reviews about it not being quite ready
for someone who just got started with it, its a mix of "ah thats really cool and a much better way of doing things!" half the time and then "oh god why is it so hard to do this simple thing, all the docs i can find use deprecated functionality 😭" the other
that matches my experience so far
I really want to use it because it seems like an ECS would be perfect for what I'm trying to do
here's a basic question: my entities need to be aware of some shared data, for example, the state of the grid system that they are currently using. Let's just say that is a two dimensional array of entities that tracks which spaces are occupied.
Should I make this grid a singleton entity that they can query from EntityManager?
that sounds like something that I did, I had some grid data, like size of grid and cells etc that I needed so I just put them on a singleton entity, and then you can easily just use GetSingleton etc
good to know!
here's another random question: I'd like to have multiple "zones" where the game simulation is always running in each. Although the player would only ever be in a single zone, they can travel between (and so can other entities). I'm thinking something like Stardew Valley with different areas.
Seems like each zone could be a different World, is that correct? Would it be an issue to have potentially hundreds of worlds?
well the thing about multiple worlds is that your entities are exclusive to the world they belong in. So if you want another world to generate a zone, you'll need to move the entities from that additional world into your main world
I can't just switch my main world to the new world?
If your player exists in the main world, then you'll need to move your player to that new world
seems rather cumbersome imo, but I haven't done much with moving large volumes of entities between worlds
I was only thinking of moving the player and simply switching which world gets rendered, is that possible?
Probably, can't say much since I've only had multiple worlds for server/client and only 1 world handles rendering
I wish I could, like, pay a Unity.Physics developer to give me a code walkthrough
presumably somewhere in unity.physics, there is code that implements limited twist joints -- where once a joint has twisted beyond a certain degree on a certain axis, angular force is applied to move it back to within its comfortable range
and the thing is, in order for that to work, one would have to know what something's rotation is along a certain axis
and by god, if I could just figure out how that is done
I would be a happy dots developer
here's another random question, it appears that certain invokations of lambda functions in SystemBase.Entities.ForEach cause allocations each frame, can that be avoided?
well, I hope the answer to yours is simpler than the one to mine. I'm about 70% sure I need to learn some multi variate calculus to get what's going on
well, I suppose math is infinitely simple. I hope your answer is easier, I should have said.
Isn't that covered in the samples ? I remember you can play with the helper handles at edit time, but didnt dig the code to see what's exposed
yeah it sounds like a simple problem, doesn't it?
I trust you it may not 🙂
lol, basically the issue is that physics doesn't use the part of the transform system thats rooted in Euler angles. its all quaternion based
Maybe I'll have a look tonight, see If I can spot something of interest, but I don't promise anything, didnt open Unity for a looong time ^^
GC is probably through the editor safety checks. Did you try a build or turning off the safety checks?
I have not, that makes sense
Hi everyone 👋 ! I have a question, because i couldn't find an answer to it.
How can i add BuildOptions.CompressWithLz4HC to BuildConfiguration?
I'd love to know, too
Does anyone know how to instantiate an entity in a server world rather than a client world when using the NetCode package? Going through the docs right now to find the answer
I think I need to assign my system to ServerSimulationSystemGroup instead of SimulationSystemGroup and/or declare [UpdateInWorld(UpdateInWorld.TargetWorld.Server)] instead of [UpdateInWorld(UpdateInWorld.TargetWorld.Client)]
how do i get relevant entities to feed into my entites.foreach loop
like if i need all the vehicles in the game and need to feed that into entities.foreach loop that references drivers
You can build an entityQuery that selects the vehicles and iterate them in your drivers foreach lambda by converting them to a NativeArray with .toEntityArray
Scroll to the end of this page https://docs.unity3d.com/Packages/com.unity.entities@0.17/manual/ecs_entity_query.html
how to create create / edit collider mesh in runtime for ECS physics* ?
.
@hollow jolt Don't spam the channel. It's pointless to flag the channel unread for people who already seen it.
Problem here...
Im using dots structs like UnsafeList, NativeList pretty often in my code and components.
I need to make UnsafeList or NativeList implement a certain interface... but those are structs, i cant inherit them... what should i do ?
Any help welcome ^^
structs are just copies of data can you not just copy the data 🤔
Write your own list/vector?
Or make an extension function?
If you really don't need the interface
to answer my own question
public static unsafe BlobAssetReference<Collider> Create( ... )
{
var collider = default(SphereCollider);
collider.Initialize(new SphereGeometry { Center = p, Radius = sphereRadius }, filter, material);
return BlobAssetReference<Collider>.Create(&collider, sizeof(SphereCollider));
}
I need an interface... because of the damn generics of those lists 😦 extensions dont help here
I don't get it how does that stop you from writing your own list?
Well... it does not... but writing my own burst compatible list is a lot of work :p
Oh you can use UnsafeList as a base in your own list
UnsafeList<T> and Native list<T> both implement it
And are just typed struct wrappers around it
@coarse turtle Thats a great idea ! Totally forgot that wrapping exists 😮
So basically like SerializableUnsafeList<T>{ private UnsafeList<T> ... } thanks ^^
Is there a standard pathfinding system for ECS/DOTS?
there are some solutions you can find on forum
Anything as sophisticated as the Unity pathfinding system?
I've got some pathfinding performance issues and I'm wondering if it'd be worth the hassle
But ease of use is important to me
yeah there are plenty of good one's but they arent quite as fully functional as Unitys nav mesh yet
I guess my use case isn't that sophisticated
Any UPM packages?
I had a google but didn't find much
that's why I'm just using the UnityNav mesh with dots
its kind of a complicated mess 
but it works
yeah, I was thinkign that'd probably be okay right?
Like directly querying the navmesh itself?
As opposed to using the build in agents
But I guess that wouldn't give me the performance boost I'm after.
I couldn't figure that out to be honest
I'm just using setdestination with gameobjects, and states and components in dots
it's probably more hassle than its worth but I like DOTS 🤷♂️
at least you can always write your own, which will be most optimized
yeah but doing that takes a hell of a lot of time
I built my own flow field system which took a lot of time, and got to the part where I wanted individual objects self collision/avoidance system and realised that part would probably take longer than it did to create the flow field
Hey I've been complaining on here for a while about how to find rotation along a single axis with quaternions
just wanted to give an update that someone gave me a really great answer on the forums
its called "swing-twist" decomposition
cool stuff
is there any alternative for EntityManager.GetComponentObject to use in a job / foreach?
protected override void OnUpdate() {
var ecb = commandBufferSystem.CreateCommandBuffer();
// Loop over all parents to assign link the childs to the parents each frame
// Easier than also passing the child component via the network
Entities.ForEach((in Entity entity, in Parent parent) => {
for (var index = 0; index < parent.children.Length; index++) {
var childEntity = parent.children[index];
if (HasComponent<Child>(childEntity)) {
var child = GetComponent<Child>(childEntity);
child.parent = entity;
}
else {
ecb.AddComponent(childEntity, new Child {parent = entity});
}
}
}).Schedule(Dependency);
commandBufferSystem.AddJobHandleForProducer(Dependency);
}
Does anyone know why this wont work ? I just wanna use my ecb inside the scheduled loop... it throws weird errors like this :
ArgumentException: The previously scheduled job ParentChildSystem:<>c__DisplayClass_OnUpdate_LambdaJob0 reads from the Unity.Entities.EntityTypeHandle <>c__DisplayClass_OnUpdate_LambdaJob0.JobData._lambdaParameterValueProviders.forParameter_entity._typeHandle. You must call JobHandle.Complete() on the job ParentChildSystem:<>c__DisplayClass_OnUpdate_LambdaJob0, before you can deallocate the Unity.Entities.EntityTypeHandle safely.
Any ideas ?
you need to change this line:
var ecb = commandBufferSystem.CreateCommandBuffer();
to this:
var ecb = commandBufferSystem.CreateCommandBuffer().AsParallelWriter();
it needs to be a parallel writer in order to use it in a scheduled job
Nice ! Could have pointed you to the files involved, but I could not have explained to you what swing-twist is xD Anyway you figured I didnt take a look yesterday, was watching Akira ^^
There is a getter on the EntityManager, but it's editor only (with a pre-processor directive)
So i've learnt that DOTS isn't meant to work on 2021, after installing and working with DOTS on 2021... whats not meant to work?
Like i've been creating entities, running systems on them etc and haven't run into a problem yet?
yea same
I've heard people had problems building on certain platforms. It might work for now, just don't be surprised if you run into an unsolvable issue at some point
So if im not expecting to have to make a build for a while, should be fine?
Yeah I get that, sometimes you just have to watch Akira
you still have a little chance to get unsolvable issue in editor, not only in build. But if all works fine and you use most of features of dots you need for your project, then i think it is ok to continue use 2021. In a BEST scenario in the end of this year dots will be updated to 2021 or whatever version we will have.
cool cool, thanks @zenith wyvern @frosty siren !
there is one more think you maybe want to think about. If in the nearest future dots will be updated with 0.18+ version then this new version maybe will really incompatible with 2021
im okay with staying on 0.17 if it works better
i kinda need urp lit vfx and vfx compute buffer support from 2021
by god it works. I really can't believe I found this. I can now calculate roll, pitch and yaw with quaternions.
I mean, I didn't find it, I was shown it
but I'm so glad the math was so neatly contained in a function
Hey. Is it better to store item data (specifically clothing in my case) in the app itself or on a JSON that's stored in a server?
definitely in a JSON that's stored on a server.
specifically for clothing, that's always where you want to put that kind of information.
I'm sorry, I'm just kidding. That question is just so highly context dependent that the idea of answering it off the bat struck me as funny
Heya, would it be possible to use a job to copy over tiles from one tilemap to the other?
Or does the fact that you need to use a reference a tilemap completely invalidate it?
Odd question but i know you can convert your project from Object Oriented to using DOTS (at least thats how i understand it) is it possible to do the opposite?
Converting a project to DOTS?
No mo converting a DOTS project to regular
Like how theu convert GameObjects to entities is it possible to do the opposite
Yeah im still leaning unity
EntityQuery e = EntityManager.CreateEntityQuery(typeof(AgentTag));
EntityManager.AddComponent(e, typeof(AgentMovementData));
why is this not adding the component to my Agent Entity ?
Is NativeArray<T>.CopyTo(NativeArray<T> dst) already at best performance possible?
Would putting it in a Bursted job get more performance?
this might be faster. havent tested though https://docs.unity3d.com/ScriptReference/Unity.Collections.LowLevel.Unsafe.UnsafeUtility.MemCpy.html
Huh, I just assumed CopyTo is implemented with a memory copy call tbh.
not sure if it does 🤷♂️
Hi everyone 👋 ! I have a question, because i couldn't find an answer to it.
How can i add BuildOptions.CompressWithLz4HC to BuildConfiguration?
Feels like having to profile this is a bit ridiculous, the performance characteristics should be documented somewhere for functions like this, where it's pretty much exclusively used in performance sensitive code.
it is, it just does some bounds checking and then a memcpy
if you can make assumptions about bounds then maybe direct memcpy is a lil bit faster
Thanks, that means Burst wouldn't speed it up either then and I can just leave it outside of a job.
does e.g creating an entity only create a sync point when done in the default world or does it do that for all worlds ?
It would create a sync point in whatever world it was created in, but certainly not all worlds simultaneously
thats good to know, thank you
Is it suggested to put an Entities.ForEach within OnStopRunning? I'm trying to do so and I'm getting dependency issues, and I'm wondering if maybe I shouldn't put this code there
I've never tried to do that. I'm curious whether you're trying to work on the same set of entities in your OnStopRunning as during your OnUpdate. I'd assume that the implicit EntityQuery in your ForEach isn't being correctly accounted for when located in OnStopRunning, but I really don't know. Dependency almost certainly doesn't automatically incorporate OnStopRunning. Anybody more familiar with the source on this?
Ah ok, yeah its my first time doing it too. The entityquery isn't exactly the same. The situation is that I'm trying to set the velocity of my movable entities to 0 when the MovementSystem stops, otherwise they keep moving when the system stops
Are you explicitly adding the job to the system's Dependency?
The dependency issue is from another system, and in that one yes I am
In MovementSystem no
Is there a book on data oriented design patterns for games specifically ? https://www.dataorienteddesign.com/dodmain/node16.html
the first few are kind of a given and the author doesn’t exactly go into detail regarding the "classic" design patterns and how they could be implemented
Design Patterns
also whats the difference between SystemBase and ComponentSystem ? The physics documentation uses ComponentSystem but i cant find the docs for that ?
googling DOTS Component System points me towards the ECS architecture which makes sense given the keywords but isnt what im looking for
testing seems to imply that component system seems to run on only one thread ?
@sour atlas componentsystem is deprecated, systembase is the replacement
it used to be split between componentsystem (singlethreaded) and jobcomponentsystem (jobified) but now it's merged into systembase
that's about it
ah that makes sense, thanks!
should i apply physics impulses before the physics step or after it or during the step ? before the step (FixedStep) it sometimes makes my objects stutter 🥲
Is ECS decently stable?
(There won't be any changes that would require rewriting the entire codebase.)
That's a pretty vague question. Jobs and Burst are fairly well-defined. If you've got a game near completion, you could certainly utilize Burst and Jobs in some optimization passes. ECS is definitely not production-ready. However, some enterprising people are already using it in production games, but if your expectation is to write code that isn't ever deprecated or changed, don't switch to ECS just yet.
before so that your changes are still processed same frame (or during fixedstep group, but before physics systems run), if you have stutter try setting smoothing on physicsbody to interpolation
ill check if interpolation fixes it, thanks!
yup, much less noticeable now!
Anyone know why my extension method does not work? Is it even possible to make a two generic parameter extension method?
somehow I can't post the code as code, it autodeletes
Has anyone come across a situation where a system that has [AlwaysUpdateSystem] just stops running after a while?
I don't think I've ever seen a system randomly stopping to update
That's more likely caused by something setting Enabled to false on the system or the parent ComponentSystemGroup not updating
How do you determine that it's not 'running'?
yeah I think it might be a problem with the editor it doesn't show that its running nor the entitys that its creating, maybe its because the processing is so minimal, and the entity's only exist for one frame
The entity debugger should show that it's running even when the system doesn't iterate over any entities if the system is tagged with AlwaysUpdateSystem..
I did get several points where the system didn't even show up in the editor 
but when it does it shows its running just at 0.0 processing
I think its kind of buggy
Do you have ShowInActiveSystems enabled?
nope
I don't know I restarted the editor and that seemed to fix it 🤷♂️(at least show it back in the editor)
yeah anyway I don't think that's the problem now, thanks the for suggestions
it would help if I could get debug mode working but I can't 
How do I not pause the main thread while using the job system? I'm having to wait until the full job is complete before Unity responds
anyone know how feature complete DOTS animation is currently
"The package is still in an early state and is undergoing continuous change. We will do our best to make breaking changes gradual when it is practical to do so, but because it is an experimental package you should expect that disruptive changes may happen at any time."
Right
yeah starting to lose hope in ECS now
not sure if this is old news as I've been out of the loop - but looks like DOTS finally works with webGL
This should only happen if you're calling job.Complete() before the job is actually done. Check if job.IsCompleted, and only call complete once that's true, then you won't block the main thread.
I think it's funny how many people pop in here just to complain that ECS isn't worth it. If you spent any time looking through the forum, you'd see plenty of amazing things people have already done with it, and it's not even close to finished yet. Is it more work than just using Classical Unity? Obviously, but that's why it's experimental. It's a framework that has great potential.
I've changed the code to look like this:
But now I get issues with allocations which previously werent there:
Would have to see more about the job to know what's causing it. I think that warning can come from allocating "TempJob" containers for long running jobs where you should be using "Persistent" ones
As per https://docs.unity3d.com/Manual/JobSystemNativeContainer.html "TempJob" containers should only exist for 4 frames max
I changed them to persistent and now burst is complaining that it only supports temp memory
So do I kinda have to keep it to 1 frame then
Show the code and the exact error message
If you're allocating containers inside the job yes they can only be temp. If you need a container for a long running job you should allocate it on the main thread as persistent and pass it into the job and reuse it as needed
What classes as a long running job?
I have temp inside and persistent outside and it's still throwing the warnings
A "temp" container can not exist for more than 1 frame. A "tempjob" container can't exist for more than 4 frames.
Ok so if I change all the allocators to tempjob inside the job and that still doesn't work then I should try and pass in a persistent allocation?
Again, if you're allocating inside the job it must be temp
Just temp? Not tempjob?
Meaning any container you allocate inside a job can only be used for that frame
Yes
Ok so does that mean my jobs arent completing fully within 1 frame and now I need to pass in some sort of persistent allocation?
That's what it sounds like yes
Ok thanks
This is a bit tricky I think for my situation. I have 5 nativelists being created inside the job which I need to do outside the job persistently. But how do I make sure each job gets a new nativelist? Do I need a nativearray of nativelists if that's even possible?
You can't nest native containers. If you're handing these out on the main thread you can do a List<NativeList<T>> or UnsafeList<NativeList<T>> or Dictionary<T,NativeList<Y>>, whatever you need to do
As for making sure each job gets a different list, you would have to keep track of it yourself
You might also reconsider how your jobs are structured, maybe you could change from a bunch of smaller jobs to one job that uses a more fitting container like a NativeStream which is really good at processing data in parallel quickly
hey all - just starting in using DOTS... having some trouble setting up a world.. I basically want to spawn in a bunch of prefabs and position them ... what's the best practice for doing so? I setup a authoring component that has an Entity reference for the prefab... but getting structural errors when trying to Instantiate inside a job
should I just an ECB to queue up instantiations inside an Entities.ForEAch?
its best to just use the EntityManager.Instantiate and batch create a bunch using a nativearray
Should that be in a job or just do it in a MonoBehaviour in a sub scene?
you can't do it in a job, just do it in an SystemBase in the Onupdate or a Monobehaviour with the Entities namespace
Cool, will give that a shot. Thanks!
Hm actually if I don’t do it in a job how do I select the data components I need
you can convert the prefab to an entity that you can instantiate
right I get that, what I'm asking is I have a component that has a reference already to an entity I want to spawn
how do I get my component that has that reference without Entities.Foreach
public class GenerateWorld : SystemBase
{
protected override void OnUpdate()
{
Entities.ForEach((in WorldSize worldSize, in EntityPrefab entityPrefab) =>
{
EntityManager.Instantiate(entityPrefab.Prefab);
}).WithoutBurst().Run();
}
}
if its as single entity you can just use GetSingleton(EntityPrefab) or use an EntityQuery
ah! I forgot about GetSingleton
sweet
thanks for your patience
what's the best way to only run a system once? like I don't want to keep generating new worlds... would the best way to be just have a component we write to once we're finished and check that bool inside the system?
there's lots of different ways you can use RequireSingletonforUpate(typeof(comptype)) in the OnCreate method and then create and destroy that single entity in a single frame
you can use a loop in the Onupdate or just set Enabled = false at the top of the Onupdate
yeah maybe, you have to create the entity in another system and then make sure you destroy it at the top of the calling system otherwise it wont work
well it's in a subscene so I think the entity gets created automatically?
instantiating definitely seems to work but I don't see it onscreen yet
(it has a RenderMesh and RenderBounds)
are you using the hybrid renderer?
it needs a localtoworld to I think, but it should have it automatically if you are converting from a gameobject
it does
public class GenerateWorld : SystemBase
{
protected override void OnCreate()
{
RequireSingletonForUpdate<WorldData>();
}
protected override void OnUpdate()
{
WorldData worldData = GetSingleton<WorldData>();
for (int i = 0; i < 5; i++)
{
EntityManager.Instantiate(worldData.CellPrefab);
}
EntityManager.DestroyEntity(GetSingletonEntity<WorldData>());
}
}
this is all I'm doing
yeah that looks ok from what I can tell
maybe the problem is somewhere else, is it a physics object and flying off somewhere perhaps
nope, no Rigidbody, just a simple mesh renderer really
everything should just be at the origin
yeah I don't know then, sorry
np np
anyone know how tore replace raycast with Jobsystem when doing collusions
I year people don't even use physics anymore they use the job system with needing raycasting and so forth
wonder if I need the ecs physics package installed
even though I'm just using colliders
worth a try, but I think it should still render without that
entities isn't supported on Unity 2021
Anybody in here know how the ScalePivot component work? (https://forum.unity.com/threads/how-does-scalepivot-work.1016338/)
I'm so confused, I cannot for the life of me figure out why I cannot install havok's physics in Unity 2021 beta? Does it not support the engine?
I don't know if this applies to Havok's physics but I know that DOTS is currently incompatible with Unity 2021: https://forum.unity.com/threads/notice-on-dots-compatibility-with-unity-2021-1.1091800/
Does anyone know how to discover which job has a leak in a standalone player when the leak does not occur in the editor player? I'm getting Internal: JobTempAlloc has allocations that are more than 4 frames old - this is not allowed and likely a leak and Internal: deleting an allocation that is older than its permitted lifetime of 4 frames (age = 5) spammed in my standalone logs, but not in my editor logs. Need to discover the job and fix it
Check if its a job running in FIxedStepSimulationSystemGroup, if you're running at like 1000 FPS, and you're allocating these tempjobs in FixedStepsSimulationSystemGroup, it'll probably complain as the deallocation happens more than 4 frames ago
If you happen to run at like more than 60 frames per second, try limiting the targetFrameRate to 60 (typically solved it for me for fixed step stuff)
Thanks! In response to your thought I turned on VSYNC to limit it to 60 FPS (was at 300 FPS) but the leak warning still spams the logs
Here's a DOTS thread about it. tertle from the forums asked, "Are you using some type of Fixed[Update|Step]?" which seems similar to your thought https://forum.unity.com/threads/standalone-leak-detection.1153565/
"You need to frame limit or vsync. If your regular update fps goes higher than 4x the fixed update rate you're going to get these leak warnings for the moment. It's a known issue, when the new memory allocator finally lands it'll be fixed" -tertle (Same conclusion as you itsjustblank, thanks again!)
putting this here as a demo but I think some saw a video of it before: https://elliotb256.itch.io/ecscombat
should run in browser now, tested on chrome
Nice !
VSYNC worked by the way. I had failed to turn it on the first time. Thanks a lot!
public void OnMovement(InputAction.CallbackContext inputValue)
{
Vector2 input = inputValue.ReadValue<Vector2>();
NativeArray<Entity> query = entityManager.CreateEntityQuery(typeof(PlayerAgentTag)).ToEntityArray(Allocator.Temp);
foreach (Entity e in query)
{
AgentMovementData data = entityManager.GetComponentData<AgentMovementData>(e);
entityManager.SetComponentData<AgentMovementData>(e, new AgentMovementData()
{
movementDir = new float3(input.x, 0, input.y),
movementSpeed = data.movementSpeed
});
}
query.Dispose();
}
this seems really convoluted, is there a better way to change data for an entity from inside a gameobject ?
@sour atlas dunno about alternative ways but it's better to do query.ToComponentDataArray<AgentMoveData>(Allocator.Temp) and iterate that array if you're not using the entity
oh right didnt even know that was a thing
I had the situation fairly often now that I wanted to set a component for an entire query so I wrote an extension for that
I would like to see something like that from Unity
But I guess we can be happy if we get another update before 2023
i'm worry that probably we will get in next update some sort of brand new like Blob or Subscene complicated thing which will promise great future of dots but won't solve any current problem
horrifying thought, what if unity's spending all their time creating a new demo?
Well at least they would be working on something then 😛
I'm subscribed to unity's blog and the last thing i have read was Plastic SCM (version control integrated to unity and still also have standalone if you want full beauty). I think recent years unity was more about promotion itself instead of engine development. I understand that dots team is separate team and there is no such a thing as unite unity dev team. But as an example: i have seen URP 2D 2 years ago and tons of threads filled with pain about urp's problems and now i see improvements only now in 2021.x unity 2 years past (still can't try because of dots). For me it shows what whole company are working at. I hope i'm wrong.
i regularly submit DOTS specific issues and get help with all of them so surely someone must be working on something at least
ive submitted some bug reports and ever since the forum post on compatibility its crickets as far as follow up
whats the current status on generic systems in DOTS? is the gist that generic implementations are possible if you (i) use IJob rather than ForEach and (ii) make explicit implementations without generic params, eg SelectEnemyTargetsSystem : SelectTargetsSystem<Enemy>?
The same as the status of ECS in general, dead until proven alive
NativeArray<AgentMovementData> data = query.ToComponentDataArray<AgentMovementData>(Allocator.Temp);
what am i doing wrong ? 😛
oh, nevermind
I am having issue trying out Unity's DOTS Example project that was feature in Unite Copenhagen 2019 demo. I think it's because I had the project upgrade to 2020.3, but still, was anyone able to play the level that was demo back in 2019? I couldn't figure out where to start, except launching from Bootstrapper first then play the rest.
Wait, the multiplayer FPS sample ? It's pretty old and discontinued yeah
Best bet is to use the same Unity and packages version, learn from it, then apply the concepts with the new syntax
For what it's worth I heard in another discord that the Devs discuss turbo games dots vids, so they seem to be still working on it
The dev rules are probably similar to fight club, as in you do not talk about dots
Jobs/Burst question - how do people handle needing a list of lists? Can't make a NativeList of NativeLists, so what solutions are there for when you need that kind of structure?
NativeList<UnsafeList<T>> should work
NativeStream, NativeMultiHashMap or UnsafeList<NativeList>
Perfect, that gives me things to look into, thank you very much!
When I tried to use a nativelist<unsafe queue> I couldn't get it to work for some reason 😕
I find it unacceptable to push this tech so much, and then just drop a "wont be supported in 2021, there is no roadmap or news of any kind for almost a year"
From what I've seen on the forums it seems like they're still communicating with commercial devs or devs who have more visible games that are using dots. Sucks for us hobbyists but it is what it is
Yeah I agree it is confusing as hell
not supporting 2021 is definitely annoying, but this massive gap in updates/news is actually worrying
Hello can someone please help me fixing this problem i get this problem after trying to install unity hybrid renderer
where did you notice this?
I don't have links, just have seen random posts from people mentioning discussions with unity devs. Weird considering there's been basically no news since the 2021 incompatibility announcement
I wonder if they are getting new packages from a private address or if its just developer support like what was mentioned in the best practices thread
Project Tiny doesn't use the hybrid renderer, it has it's own rendering framework
Completely separate from what a normal dots project uses
Ok. Thanks 👍
My guess would be just developer support
yeah but the state of things at the moment isnt terribly reassuring. whats the holdup? the longer the delay in any terms of communication or actual release, the more im inclined to think something has gone wrong with development
show vs. tell
I'm mostly curious about this big change they alluded to with the conversion system
Or maybe that will just turn out to be nothing
Who knows since they haven't said anything about anything in months and months
@karmic basin theyve already been showing vs just telling for some time now, I dont really see any point in time where it seemed like hot air vs what I thought was a pretty solid showing of tech
I mean they say everything is okay and will come back at the end of the year but meanwhile I don't see anything
But maybe I'm not on the forums enough
If i told the same thing to my boss & clients, I'd lose my job ^^
i guess i interpreted it differently, that there would still be a continuation of releases this year but it would only be for 2020.x and not 2021+
I think you're right
But the pace is not really reassuring
at the current rate, i think youre right 🥲
yep use at your own risk
I'd like the power of DOTS be available to everyone already 🙂
what the big thing?
I think at one point there was a message here from a dots engineer about revamping the whole subscene/conversion system because the current one is underwhelming
Yeah I think we can expect better editor workflow
I got lots of errors now 😐
Yeah they said something in a video about how they're reconsidering the entire conversion workflow because it's so unintuitive right now
It is 100% true. But i have seen multiple times at forum the idea which i agree with that when you tell people that THIS is the FUTURE even tags like "experimental" can't hold people's expectations
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Entities;
public class Testing : MonoBehaviour
{
private void Start()
{
EntityManager entityManager = World.Active.EntityManager;
entityManager.CreateEntity();
}
}
``` this is the only code i have
I guess they want to better integrate ECS with the editor, according to the video. AFAIK there's been no more info about it since then
Are you trying to make a Project Tiny game or a regular game with dots?
Project Tiny
If you're making a tiny game you can't use monobehaviors or gameobjects
using 2D entites
