#archived-dots
1 messages Β· Page 71 of 1
just tried with 10k and unity crashed π€
Nice, i think in my project in late game i can have more then 10k
oh it was cause i had no ram left, its alright now, but yeah got some spikes
Has any of you guys tried BlobAssetReference with BlobArray specifically ?
I would love to see an example as well. How and for what I can use BlobAssetReference?
Unity Physics uses them
@knotty radish @crystal zephyr
basically they use it to store Colliders and JointData there atm
Hey all. If I get an entity in my game and use Instantiate(entity) does it create another unique entity of that type?
@upper tiger this should have description for everything that happens there https://docs.unity3d.com/Packages/com.unity.entities@0.0/api/Unity.Entities.EntityManager.html#Unity_Entities_EntityManager_Instantiate_Unity_Entities_Entity_
woah theres actual documentation now
that api doc is bit outdated for some things tho, they haven't yet updated it to the p30 release I think
right so its basically like copying the structs that make the componentdata then giving it a new entity (id and version)
makes sense. And it works too!
regular manual here btw: https://docs.unity3d.com/Packages/com.unity.entities@0.0/manual/index.html
again, not yet updated to p30 changes
the one I linked here is just where you get if you hit the "view documentation" link on the package manager for entities package
Unity is moving all package docs so they work this way
thanks @dull copper
bunch of DOTS talks from Unity booth at GDC now on youtube:
https://www.youtube.com/watch?v=yuqM-Z-NauU
https://www.youtube.com/watch?v=QbnVELXf5RQ
https://www.youtube.com/watch?v=0_Byw9UMn9g
https://www.youtube.com/watch?v=3xzNs1JkyJk
Hear about the journey of taking Havok's AAA physics engine from C++ to the land of C# and the Data-Oriented Technology Stack (DOTS). Learn about the archite...
Watch to learn what's involved in migrating existing game code to the new Data-Oriented Technology Stack (DOTS), which comprises the C# Job System, the Entit...
Unity's new ECS features enable huge performance improvements over traditional object-oriented ways of designing game systems, but data-oriented design is a ...
Getting the Megacity demo to run on mobile was a major challenge, with 4.5M mesh renderers, 200K unique objects per building, 100K audio sources, and 5K dyna...
Before 2019.1 RenderBounds component was added automatically?
And why LocalToWorld not added automatically now?
Can u give me an advise?
I have a map consisting of hexes. Each hex can have 6 neighbors (sometimes hex can have less then 6 neighbors, for example when it place in the bound of a map). To get data of neighbor hexes i see 2 approach:
- Use some algorithm that takes an index of central hex and return array of neighbors indexes. (i use it now)
- Just store neighbor indexes (or entity) in IBufferElementData.
So my question is:
What approach u think is more efficient? (regular map have size 100x100 and contains 10k entities)
@dull copper nah they cheat, it's not the real blob asset reference, see BlobArray.cs in that package, it explains why it's not the real one
I believe you π
And it's not that I need an example, it's more like I think there is something that doesn't work and I was wondering if anyone else had that issue π¦
I'm still very ECS noob, jut tinkering around with it
I feel like that if I take the time to make a repro projet they may just say that they know this issue and it's already fixed in the next update x)
watching the ECS conversion talk from Unity booth right now, they use really ancient ECS version here, they still have position component here
I think everyone is the same on that point, no ECS expert here
Yeah but can you blame them ? That major update came like one month ago (or something like that) you can't prepare a GDC talk that fast
I dunno, how long it takes to update the demo project and talk? π
maybe I have unrealistic expectations
roll a dice
2 days
it's not a big deal, just wondering
Well I think that there also is the slides validation by the GDC crew
ah
well, these are from Unity booth but yeah
they could pass these through some internal checks
So they have to send them earlier ? Saw someone talking about that but not sure how long nor if it applies here since it's Unity booth
since it's on their booth, this isn't archived in the GDC Vault
so you'd think you could do whatever your company lets do there
@frosty siren sorry for burying your question but short answer: don't exactly use ECS for that, I mean for the grid representation. It may work but won't be as fast as doing the grid outside and just use ECS / Jobs / Burst for the algorithm
@dull copper Yeah they may have more loose since it's their booth. So many lazy devs smh (<- joke)
@knotty radish I am very grateful to you for paying attention to my questions.
I use entities for representation of my grid because i store data about hexes that need to be updated every frame.
Like I said, you can store your data some other way but then iterate with a job to update these values
But why not use ECS?
@frosty siren one possible approach is similar to the boids example if every cell needs to know about its neighbouring cells? I'd probably ask what I wanted to do this info about neighbours once I had it? For example, would it be enough to store a byte per hex cell that uses a bit-mask per side to store whether the relevant neighbour is occupied or not? If to be used for pathfinding etc. If you store all neighbouring entities per cell entity, you may want to think about flattening that structure at some point for L1 cache coherency at some point anyway as it can get costly to lookup other entities within a job.
hmm ecs added a bunch of features and now there this "EntityCache" folder that pops up in the project. Wondered what does it do?
it's probably for the the subscene serialization
I'm back! Again with a longer post. With more abstract questions of how to design my systems. I have a leftClick action, I want to for e.g. use my current equipped extinguisher to start removing flames - but it can be other items with their special things as well, or barehanded.
I already have a component when the player is holding something with a field of the entity it is holding. I currently add a tag for when the leftClick have been pressed to the player entity.
I was either thinking A: When I receive the tag for LeftClick I add a tag to the entity I'm holding that it should be used. - However, it might need references to e.g. head(camera) for aim etc. that the player entity have, so I need some reference back to the player entity?
My B option would be in some way to add a tag to the player when I pick up and remove an item. This can then be used in combination of the leftClick tag to trigger various systems. However I'm not sure how I would add a specific tag based of one entity to another? Maybe some lookup with an ID as field of a component?
Anyone who could give some feedback in my thoughts?
@frosty siren like @amber flicker said, access to neighboring cells is costly if every cells are entities. ECS performance would show when you use data from the same context (i.e the same entity) otherwise it usually means that you need to manually fetch things around which is slow.
@mystic mountain how about a, not so small, change on your system
So let's forget about Tags
Each starting frame, update a InputSystem (you need to create one) that will fill for each players a CharacterInputs with all your input actions state inside
CharacterInputs is a ComponentData on your character entity
Now, you could have a system that will update your items (which also is componentdata on your character if it's equipped) and will also get CharacterInputs (still the same entity)
You have access to the state of your LeftClick Action (let's call it UseAction) so you know that you need to do something with the item
So that's for the CharacterInputs but the same could be done for CameraInputs (since it should be one camera per Character)
Fill out the CameraInput component in the same sytem as inputs or in another one (up to you, I use the same system)
Fetch it in your Item System
Use it
Now this has a few downsides about the ItemSystem:
Either you have a buffer of Items on you but they all use the same master component of death with as many fields as you need (may work if your items doesn't need much additional unique data) or you have one system per item but that means the item needs to know if it's equipped or not
That second solution is overkill (a lil bit) if you only have like 1 entity of each items and no other players for example
Does that answer your question ?
@knotty radish Thanks for the long reply! May I DM you for some question to not flood the channel?
I don't mind the DM but I feel like sharing here may also help others. Also like I said just before, I'm no ECS expert ^^
also, there's no other discussion going on here so no need to worry about it
usually going for DM's is limiting they eyes that can see your problem
also worth remembering that people here help and answer on their own time for free, going for one on one support is kinda stretching what people signed up for here π
Sure, yeah - I guess its sort of a double edged sword if no one's interested in my specific design problems ^^ So - you kind of went similar with my B option here. And it might be that I left out some information. The items can be picked up and thrown around as rigids so they are entities on their own. I don't really follow the "Either you have a buffer of Items on you...", and "one system per item but that means the item needs to know if it's equipped or not" is kind of what I was thinking because there might be many different items and in turn on many entities on server. But I'm not sure how I would add a ComponentData to the player that would trigger a specific system based on what entity I picked up?
It's a bit different from what I thought
If you have access to the entity of your item, adding a component (with enough context data like direction, force or whatever you need) for triggering it may work. Then in the item system just fetch that component since it will be on the item entity
And like I said if it's many the number of different items is bigger than the quantity of each item then go with one system handling them all
Just make custom component for the triggering and additional data
Ok, so that's basically my A, but I thunnel all required data for that specific item system to run through the componentData instead of just a tag.
Yeah basically
You cand reduce the size of that component data like this
struct ThrowTrigger : IComponentData
{
float3 direction:
float force;
}
struct ConsumeTrigger : IComponentData
{
}
So let's take that extinguisher for example, in that item system you can make multiple different queries : one for item + ThrowTrigger and one for ConsumeTrigger
That way you can create 2 different jobs. reduce size of your structs (better for the cache) and handle unique behaviours without impacting other common behaviours
still remember that you are limited to one componentdata per type on entity
Cool, thanks for the input : ) The only problem I see is that the systems will get dependencies between each other if I don't make a generic "ConsumeTrigger" for all, e.g. Extinguisher might need CameraDirection, another one might need Health of player and so on.
You could always create systems to reduce your dependencies
So basically each time I create a new item, I need to modify the system throwing out the Triggers based on input.
It's just that specific systems will run on less entities
Yeah in order to handle that item specific logic
You need to change the system only for new triggering handling, for example if you want to add a trigger then throw logic then you need to update the system but if you create a new item with existing triggering logic then no changes needed
yeah better to just post your issues in the channel, people will pop in and out and there's not usually much going on here anyway.
dont suppose anyone knows what the dots equivalent of InverseTransformDirection would be?
yes please π
math.Inverse() ?
ah that seems to be it
I'm still loading up the IDE π
they really need a Mathf/UnityEngine to math guide
pretty sure I had to use RigidTranform for it
hmm didnt use rigidtransform(havent run into that at all yet)
quaternion rotation = math.inverse(math.quaternion(localToWorld.Value));
float3 localVelocity = math.mul(rotation,velocity.Linear * 0.016f) * timeScale; ``` finally worked for me to be the equiv of ```
Vector3 localVelocity = transform.InverseTransformDirection(m_FPController.Velocity * 0.016f) * Time.timeScale;```
its pretty nice to work with once you get used to it, they have a million overloads for everything.
// Perform computations in the local space of the second hull.
RigidTransform transform = math.mul(math.inverse(transform2), transform1);
ah yes, you don't need the transform since you only get direction
ugh for the life of me i cant remember how to use discords code highlighting
use cs
also put it on the first line after ticks and nothing else
if cs is on the next line, it will not work
oh well its in there
got as much anxiety about discords code highlighting as finding equivalent mathematics functions
I've been thinking... What if I want a NativeArray stored on each of my component instances, how would I manage them?
I mean, how do I create and dispose them when a component is added or removed?
Is there even an API for that?
well you cant have arrays or native arrays in componentdata if thats what youre asking
there are DynamicBuffers as a replacement
do you recommend using components for tagging? for instance, lets say i want to apply some logic to every jumping enemy, i would add a Jumping component to the entity whenever the enemy is jumping, and i'd query entities with Enemy and Jumping component to apply the said logic
would that be better than having a single Enemy component with flags indicating whether the enemy is jumping, walking, or whatever?
i seem to recall a forum discussion that came to the conclusion its best not to be adding/removing tags every frame for stuff like that
easier to use a bool, a component tag would be best suited to indicate something is for example Dead
i'm gonna dig the forums to find more about that, so basically if the state wont change for relatively a long time, it's fine π€
well components can change quickly
but not sure just how quickly you are making your enemies jump or do other potential component tag shuffling
hmm i may be wrong, found https://forum.unity.com/threads/should-i-change-my-componenttag-design.637753/#post-4272793
theres a response by joachim "Next release supports adding tag components & shared components to whole chunks without moving any data."
That's on chunk-level, though, and you still wouldn't want to do it particularly often
As a rule of thumb, I'd only use tags if they're one-way (ie starts with, can be removed, or starts without, can be added, but not the other way round) and a bool component otherwise.
Of course, there's a gray area somewhere in-between, but you should probably only use add/remove tags at timescales measured in seconds (>=0.1s, but preferably >1s), and if the target archetype has many entities (say, a horde of enemies), it should probably be no more than once per frame on average at most?
As with all things perf, it depends on any number of variables, and you'll just have to see. If it's an option that saves you from having to do a lot of work or something cumbersome, sure, but in this case a simple bool-component can do the job, so...
hmmm, interesting
checked the Burst changelog
## [1.0.0-preview.12] - 2019-04-09
- Fix crash when accessing a NativeArray and performing in-place operations (e.g `nativeArray[i] += 121;`)
## [1.0.0-preview.11] - 2019-04-08
- Improve error logging for builder player with burst
- Fix NullReferenceException when storing to a field which is a generic type
## [1.0.0-preview.10] - 2019-04-05
- Update known issues in the user manual
- Improve user manual documentation about debugging, `[BurstDiscard]` attribute, CPU architectures supported...
- Fix an issue where burst callbacks could be sent to the editor during shutdowns, causing an editor crash.
- Improve error messages for external tool chains when building for AOT
## [1.0.0-preview.9] - 2019-04-03
- Fix an auto-vectorizer issue not correctly detecting the safe usage of NativeArray access when performing in-place operations (e.g `nativeArray[i] += 121;`)
- Add support for dynamic dispatch of functions based on CPU features available at runtime
- Fix issue when running SSE4 instructions on a pre-SSE4 CPU
- Fix write access to `NativeArray<bool>`
- Remove dependencies to C runtime for Windows/Linux build players (for lib_burst_generated.so/.dll)
- Updated API documentation
- Update User manual
- Static link some libraries into the burst llvm wrapper to allow better support for some linux distros
this is the interesting part for me: ```
- Add support for dynamic dispatch of functions based on CPU features available at runtime
- Fix issue when running SSE4 instructions on a pre-SSE4 CPU```
so far, Burst compiled games have just crashed on old Athlons and Phenoms due to lack of SSE4
alright thanks (: @tawdry tree @safe lintel
what the best way to deallocate NativeMultiHashMap that used in job?
The Megacity demo is a futuristic cityscape β alive with flying vehicles, scores of highly detailed game objects and unique audio sources β that showcases wh...
btw, Burst 1.0.0p12 seems to be stable with Unity Physics now, so it must have been that crash the changelogs told was fixed in p12
I propose 2 more DOTS talk name puns:
- Dipping into DOTS
- LOTS and LOTS of DOTS
More dots, more dots, k, stop dots
I prefer the term DOTS over ECS because it covers ECS plus the other technologies like burst and so on plus it's more fun to write
but the coding is ECS
I mean broadly speaking about it
also - ECS is an overloaded term if you're also doing server stuff π
When do those get released?
what get released?
Extra coffee system
This is hopefully a fairly simple question I'm just struggling a bit... on the main thread I'd like to 'get all entities with a component matching a certain value'. I'm thinking something like a ComponentSystem that I manually update that populates a NativeQueue with results or something?
And I understood you can not make a query which is filtering based on a value. You can do a change filter to get only components where the value changed, but this not sounds what you want.
If you have to split up your queries based on a value it might be an indicator to split up into two different components.
thanks @crystal zephyr - yes I'll have to check the values within the system.. none of this is ideal and should happen irregularly - for now I just need to get it working ... thinking about it I wonder if I need a system at all
I think you have to do different things for different values it could be that splitting up in 2 components is worth it. If you want to test it quickly I would still query all entities with that component and iterate through all of them and do an if around the thing that you want to do.
This is where I'm at so far: https://pastebin.com/dy4L0m70 but on line 18, I get invalidOperationException: The NativeArray has been deallocated, it is not allowed to access it
at a quick glance, my two guesses are... a) not every chunk actually has MyTag, i can't tell because i dont know what TweenEntityManager is. b) maybe you don't need to dispose entities and tags individually? iirc the native arrays you pull out of chunks like that don't need a dispose
Thanks @manic aurora - not every chunk has the tag but thatβs what βif(chunks[i].Has(tagType))β should do - TweenEntityManager is just World.Active.EntityManager and youβre right about not needing the dispose on the nativearrays however I still get the same exception without them. I guess itβs because itβs not in a system and when the code runs part of the Ecs code might be moving things around and invalidating the memory there? Not sure
oh i skimmed right over the .Has sorry
since this all runs on the main thread i wouldn't think other code has the opportunity to invalidate your chunk array
Hmmm the reshuffling of chunks must happen at some point when the systems arenβt running though?
sure any time entity manager makes a change to an entity it gets invalidated, but that can only happen on the main thread, so it's not like something else is going to execute during this block we're looking at. afaik a job can't invalidate stuff like that
Yea you make a good point... wonder why I get that error then.
do you get that error on the first iteration of the loop?
Oooh yea I think we might be thinking the same thing - I think that static function must be triggering a chunk change... thatβd explain it
that'd do it yeah haha
π not the first time Iβve fell into that trap damnit haha.. thanks @manic aurora
thanks for giving me something to goof off with instead of writing boring tests for work π
Haha I have plenty more if procrastinating is desired π - like in easy way to determine the equivalent of βischildofβ for an entity π¬... gunna leave that for another day probably
oh yeah i saw that topic π€· got me there
FYI confirmed working now - hopefully the last time I fall for that π
is there a way to hide a rendermesh or toggle its visibility?
Have we some API that allows us connect some main thread code with job completion by dependencies (like it can be done between 2 jobs)?
thought the point of ECS job setup was that you don't have to deal with that manually, it sorts out the jobs dependency order for you based on what data each system depend on?
you have UpdateBefore tags too to control it
(for the systems)
please correct if I got that wrong π
I'm not entirely sure what you mean, but you can save a jobhandle if you want a job to run across frames, I think
I thought the question was about chaining jobs
@frosty siren can you explain it further?
Ok. In my system i have "chain" of jobs. Between jobs i have some main thread code that prepare data from job1 to job2. I don't want to write single job for it because it's very tiny computation (i think). So to make this i call Complete() on first job. I want to make it without using Complete(). Also i call Complete() on the second job because i need to deallocate native containers in the end.
Job1.schedule().Complete() ... Main thread code ... job2.schedule.Complete() ... Deallocate containers
so are you asking if you can chain the jobs automatically?
if so, you can see example here https://docs.unity3d.com/Manual/JobSystemJobDependencies.html
just get the handle of first job on schedule, then feed it to the next job, finally call complete when you want it to execute the whole chain
there's full example at the end of that page
You should probably still put that extra bit in a job, as there is some perf cost to pausing/starting jobs, as opposed to having them just chain.
Or put like this, of
System1 runs JobA, then JobB, then JobC
System2 runs JobA->JobC->JobC chained
System2 is faster. Obviously, if you're running them purely sequential with nothing inbetween there's no reason not to just chain them, but if you have, as you say, a tiny computation in between, just make that into a job and insert it in the chain.
Assuming jobifying that code isn't a lot of work, of course; often dev work>perf
I'd better ask about this
Is there any difference between using Complete() in the chain of jobs and make it automaticly. For example:
//automatic
var jobA = new JobA();
var jobAHandler = jobA.schedule();
var jobB = new JobB();
var jobBHandler = jobB.schedule(jobAHandler);
//manual
var jobA = new JobA();
jobA.schedule().Complete();
var jobB = new JobB();
jobB.schedule();
That's basically what i was talking about, there is some cost to completing and scheduling new jobs vs having them chained and scheduling once (but it's been a while since I saw the talk, so I forgot the specifics)
So yeah, automatic here should be faster than manual
EDIT: Quicktip: Write csharp(or cs) after the triple backtick in a code block to get C# formatting
@tawdry tree I'm sorry, I saw your message only after I typed my. Thank you, this information very helpfull.
I'm helping! π
The bad thing that in main thread code i define NativeMutliHashMap and i need data from previous job to compute capacity of HashMap, so i must us Complete() =/
Well, that sounds like a case where you might actually need to use the main thread, yeah
@tawdry tree
EDIT: Quicktip: Write csharp(or cs) after the triple backtick in a code block to get C# formatting
I tried but it's not works
//Are you sure you did it correctly?
public static void Main(string[] args{
//You to put them right after the backticks, kinda like
/*
* '''csharp
* '''cs
*/
var str = "IIRC I've had issues with using the short variant(cs), tho.";
}
Like this:
```csharp
[code here]
```
Ta-dah!
ok, now it works, thank youπ π
oh thats awesome, didn't know you could get formatting
wonder if that works in slack π
It's not all that useful when you're doing just the contents of one method, but if you're copying a class or entire method it can be more helpful
+It also supports some other lanuages
-Like 'diff' I'm using here
See more about formatting at: https://discordia.me/markdown#inline-code-blocks
Welcome to The Discord Wiki!
one important condition that u must make new line after csharp
Oh yeah, forgot that part. And no space after the language. Though, it's pretty clear that you've done something wrong, as no formatting is applied and you see the language code
@safe lintel i'm also looking for a way to do that, didn't found anything yet sadly ):
could you please let me know if you find an answer?
i think ill just have to set the position out of sight of the camera π¦
current problem is just fps weapon models so for me that is stupid and gimicky like the fallout train hat but works until I find something better
yup that should do the trick, thought there should be another way
if you're going to use .Schedule().Complete(); its slightly faster to just .Run()
@wintry birch, @safe lintel u can define your own IComponentdData with no fields and use it as subtractive component in RenderMesh system.
If i understand correctly.
hey does anyone know of a good way to run a system just once? say to set the rotation of a bunch of entities randomly when they spawn.
I think what you need is not a system but modify the rotation once you spawn each of them
@frosty siren seems like that would do, will try that later (:
thanks
but how to only make it run once?
@solar hill you could have a look at the spawning examples I guess
there you have a system that spawns some entities and then deletes the "spawner entitiy" so it will never run again
yeah okay. i guess that makes sense
I'm a bit confused here. I have a system A that add a tag on a component after a set of time. Another system B use this tag to destroy the entity.
If I use [UpdateInGroup(typeof(UnityEngine.Experimental.PlayerLoop.FixedUpdate))] on A and [UpdateAfter(typeof(UnityEngine.Experimental.PlayerLoop.FixedUpdate))] on B they both end up in normal update by the entity debugger? But if I use [UpdateBefore(typeof(UnityEngine.Experimental.PlayerLoop.FixedUpdate))] on A they both end up in FixedUpdate.
Is there a way to change an entity to another entity or do i have to destroy the original and create another
@upper tiger afaik you have to destroy and create another.. but depending on what you're trying to achieve there may be a more efficient way to repurpose the existing entity
@mystic mountain sorry can't help much except to say I think ecs doesn't have the same concept of FixedUpdate and that as of a month or so ago they changed how the timings work and in some time they'll be changing it again. I would guess that if you're seeing UpdateBefore result in them being in FixedUpdate, that's likely more due to coincidence of timing than anything purposeful.. but I could be wrong.
WTF my code has been working fine for days. I make one change which causes an error so I revert back to the exact same working code and now get perpetual spam of : A Native Collection has not been disposed, resulting in a memory leak. Enable Full StackTraces to get more details.
when I get full stack trace, the error is triggering off nearly every single system I have
After I converted my simple objects which just have a mesh renderer the hybrid render renders everything with flickering red, blue, green squares. I using LWRP. Any idea?
@upper tiger sorry if this is obvious but make sure you restart your editor if you see something like that unexpectedly
com.unity.physics @ 0.0.2-preview.1 on staging now
I'll post here too: ```
[0.0.2] - 2019-04-08
Upgrade guide
- Any assembly definitions referencing
Unity.Physics.Authoringassembly by name must be updated to instead referenceUnity.Physics.Hybrid.
Changes
- Renamed
Unity.Physics.Authoringassembly toUnity.Physics.Hybrid. (All of its types still exist in theUnity.Physics.Authoringnamespace.) - Radius of cylinder
PhysicsShapeis no longer non-uniformly scaled when converted.
Fixes
- Fixed exception when converting a box
PhysicsShapewith negative scale. - Fixed incorrect orientation when fitting capsule, cylinder, or plane
PhysicsShapeto render mesh. - Fixed convex radius being too large when switching
PhysicsShapefrom plane to box or cylinder. - Fixed calculation of minimum half-angle between faces in convex hulls.
- Fixed collision/trigger event iterators skipping some events when iterating.
- Fixed memory leak when enabling "Draw colliders" in the Physics Debug Display.
Known Issues
- Physics systems are tied to (variable) rendering frame rate when using automatic world bootstrapping. See
FixedTimestepexamples in ECS Samples project for currently available approaches. - IL2CPP player targets have not yet been fully validated.
- Some tests might occasionally fail due to JobTempAlloc memory leak warnings.
- Swapping
PhysicsShapecomponent between different shape types may produce non-intuitive results when nested in hierarchies with non-uniform scale. - Some
PhysicsShapeconfigurations do not bake properly when nested in hierarchies with non-uniform scale. PhysicsShapedoes not yet visualize convex hull shapes at edit-time.- Drag values on classic
Rigidbodycomponents are not currently converted correctly.```
they still haven't fixed the framerate dependency by default
I mean, it's 10 lines of code to do the workaround, so it's not a big deal
also probably what they have on the next examples
now only need to wait for it to release on regular registry so they have to update the ecs samples repo π
got also answer to my Burst question on the forums, basically just confirming that the Burst change log entry said what I thought it said
My Q: ```Does this mean Burst compiled desktop builds no longer crash on old Athlons and Phenoms that don't natively support SSE4?
What does the dynamic dispatch per CPU features cover today, say on Windows build using Burst? SSE2, SSE4, AVX?Staff A:Yes, it should not crash anymore, as it will fallback to SSE2.
AVX is currently not supported, not that burst can't, but the Unity runtime might have some problem if burst started to use it, this is a known issue and we will see how we can mitigate this. So we have disabled AVX at runtime for now. So on an AVX capable CPU, it will just fallback to SSE4
So basically, if SSE4 is available (technically, the exact requirement behind is SSE4.2 for burst), it will use it, otherwise it will fallback to SSE2. ```
this is great because those 10 people with the ancient rigs aren't our problem anymore
I mean, the game will not run on their computer well, but they'd complain if it straight up crashes
so, that's now covered π
What does abbreviation DOTS mean?
UPD: Answer - Data-Oriented Technology Stack
Data-Oriented Use Google
DOUG
It used to be called Capsicum, those were the days
Unity DOUG, the generic ECS-Burst-Jobs man
Back to my topic about the nice color flickering when using converted entites. It was the SRP Batcher. Seems it's not working together with the ECS Rendering System.
MegaCity used it afaik, but might be issue with the specific versions you have in use
or some HDRP setting
You are right, they said they using the SRP Batcher. Hmm so the different is that they used HDRP and I use LWRP.
And btw the conversion to entity is totally missplacing my objects on mobile.
LWRP works with the Hybrid Renderer?
I mean, they did show megacity running on it but always thought it was some custom LWRP build π
i always thought it was hdrp for megacity but i have no basis for that assumption
oh, megacity we got is HDRP, but the one that nordeus ported for mobile was running on LWRP
ok, the new physics package and new burst now regular registry π
still waiting for the ecs sample update to drop for the physics pack
whats supposed to be different in an updated ecs samples pack?
only the physics samples
they update the rest on next entities release, don't expect changes to that side now
they actually uploaded the physics samples now
oh i thought you had some insider knowledge of new features π
## [Unity.Physics 0.0.2] - 2019-04-08
### Changes
* Character controller now has a max slope constraint to avoid climbing slopes that are too steep.
* Character controller now does another query to check if position returned by the solver can be reached.```
nah, I have access to all same sources as you π
was mainly curious of this: Physics systems are tied to (variable) rendering frame rate when using automatic world bootstrapping. See `FixedTimestep` examples in ECS Samples project for currently available approaches.
but it's not there
like, if they have some different workaround for it than what people use now
@amber flicker thanks, right on point. it seems that [UpdateInGroup(T)] doesn't work for fixedUpdate, https://forum.unity.com/threads/why-is-simulation-the-default-system-group.639058/#post-4289911
does anyone else have issues where the entity debugger shows entities with the same name inside components?
Hi I have question what is a replacement for EndFrameBarrier and ECB from it?
Is it just End now?
@plush dock https://github.com/Unity-Technologies/EntityComponentSystemSamples/blob/master/ReleaseNotes.md is great for upgrade guide
- EndFrameBarrier has been removed; use the End barrier in the appropriate system group instead.```
that's happened some while ago
I have big break from using ECS
I am using private EndSimulationEntityCommandBufferSystem _EndFrameBarier;
but I get an exception when I am calling job.CommandBuffer = _EndFrameBarier.PostUpdateCommands.ToConcurrent();
the exception is InvalidOperationException: The NativeArray has been deallocated, it is not allowed to access it
ok I should use CreateCommandBuffer() π
gah hybrid renderer causing crashes for me after upgrading to ecs preview 30. unexpected...
Hey all. I'm getting the error "A Native Collection has not been disposed, resulting in a memory leak. Allocated from: ...". With full stack traces on, this error occurs in every single system on the line that uses Allocator.TempJob. My system was working fine for days until I made a minor change that I have since reverted but still get the error. I do not believe the error is in every single system but that something is misusing the Allocator somehow. Any ideas?
found the issue
not sure why it didnt blow up sooner since i've been doing this a bit
I've been writing things like
var s = m_BuildingTypesQuery.ToComponentDataArray<BuildingTypeSpawner>(Allocator.TempJob)[0];
since I only wanted the first element. Problem is the container doesnt get disposed anywhere since its not passed as a collection to a job. I fixed it by grabbing the entire container, passing the [0] element where I need it and disposing the entire container at the end.
if I have a job and that job uses methods inside it or accessing static methods outside of it, do I need to use BurstCompile for each method too or does it automatically get burst compiled?
Pretty sure you need to use the attribute for everything that should use burst, but can't you do that at struct level?
what do you mean at the struct level?
[BurstCompile] <--
struct SomeJob : SomeJobType{
//Some job contents
}
oh yeah but I was wondering if you also needed
[BurstCompile] <--
struct SomeJob : SomeJobType {
void Execute { DoStuffA(); DoStuffB();DoStuffC();DoStuffZ();}
[BurstCompile]
void DoStuffA() { }
[BurstCompile]
void DoStuffB() { }
[BurstCompile]
void DoStuffC() { }
}
[BurstCompile]
public static void DoStuffZ() { }
or is having the BurstCompile on the "job only", good enough for all the sub methods?
By default all methods inside the struct will then be BurstCompiled. Use the BurstDiscard attribute for methods you don't want to be compiled with burst.
https://docs.unity3d.com/ScriptReference/Unity.Burst.BurstDiscardAttribute.html
ah fantastic thanks @umbral latch
Is there any way to use the ECS design pattern without having to exclusively use entities? I'd like to work on a 2D game using the ECS pattern but Unity Physics 2D isn't done yet. If not is there another library that supports this?
I'm specifically interested in being able to query for all things with certain components
are you specifically trying not to use hybrid ecs?
Am i able to interact with physx physics from within systems using hybrid ECS?
yes
with the new conversion pipeline, you can Inject the original gameObject into the ECS world and everything will be preserved. ComponentSystems can access the MB components in addition to the Entity Component data.
just note the new injection workflow doesnt do hierarchies(while destroying does).
(also destroying is to create pure entities not hybrid stuff)
you can manually do the code work to inject sub-hierarchies I believe, haven't played too much with hierarchical GOs using the conversion workflow as I've mostly been using it to hook management objects into ECS world
what sort of collections can I put in IComponentData
I cannot figure out how to retrieve an entity. I have my player with a ConvertToEntity and a MonoBehaviour in which I'm trying to get the entity of the player. Someone have the solution?
post some code
@mortal crow Unity Physics samples have examples for this on the ECS sample repo
for example raycast vehicle demo uses these scripts for it:
https://github.com/Unity-Technologies/EntityComponentSystemSamples/blob/master/UnityPhysicsExamples/Assets/Common/Scripts/EntitySender.cs
https://github.com/Unity-Technologies/EntityComponentSystemSamples/blob/master/UnityPhysicsExamples/Assets/Common/Scripts/EntityTracker.cs
this lets you keep the entity ref in the gameobject side even once some object is converted into entity side
check the actual sample for example how to use it
I think other samples use it as well, probably the char controller(?) but I've not really looked at other samples that much
I just know it's used in the vehicles
for the batch part, that's pretty much what all those foreach and foreachjob things do all the time
not really sure what's the full question
ah, that makes more sense now
have you checked how the FPS Sample compresses the data?
it uses ECS for netcode
I dunno if the compression is on the transport or actual sample, I'd guess it's on the sample side
as the transport feels like it's just generic component for that part
https://www.youtube.com/watch?v=k6JTaFE7SYI could help a bit too
Take an in-depth look at how the netcode of a fast-paced multiplayer shooter like Unity's FPS Sample works. Learn about snapshot generation and compression, ...
can't remember if they covered the compression on that tho
@gusty comet
I could imagine that you could do something like store the data from the entities in some of the new native containers and then when all entities have done processing, do another system to process through that container for packing the packet
you don't really pay similar cost on ECS side here tho
allocations are super fast
but if you keep the data all the time on native container, it's not really a copy
it's the container for all your data
well, don't take my comments as advice, I'm total ECS noob still
just throwing out random thoughts π
if you want more educated opinions, maybe ask again here when the europe guys are awake
I mean, it's 5AM where I live now π
there's any way to add/remove components from a job?
In runtime? You would probably need to have two different jobs, and have the system decide which to execute
@wintry birch - EntityCommandBuffer (if all operations on a single core job)
EntityCommandBuffer.Concurrent (if operations can run on multiple jobs/one job is spread across multiple cores)
If you use the Concurrent version, make sure you use EntityCommandBufferSystem.AddJobHandleForProducer() to ensure the job completes before the target ECBS runs.
https://docs.unity3d.com/Packages/com.unity.entities@0.0/api/Unity.Entities.EntityCommandBuffer.html
https://docs.unity3d.com/Packages/com.unity.entities@0.0/api/Unity.Entities.EntityCommandBuffer.Concurrent.html
https://docs.unity3d.com/Packages/com.unity.entities@0.0/api/Unity.Entities.EntityCommandBufferSystem.html
There's some examples in the ECS Samples Hello World project
NOTE: Burst is not yet supported for Add/Remove Component operations on ECB
thanks, will try that (:
Oh derp, add and remove components while IN a job, of course!
Yeah, you use https://docs.unity3d.com/Packages/com.unity.entities@0.0/api/Unity.Entities.ConvertToEntity.html to move the gameobject to entity system
the samples are the best place to start if you need examples https://github.com/Unity-Technologies/EntityComponentSystemSamples
I think there is a misunderstanding. I'm not talking about runtime conversion of gameobjects, but rather retaining the default monobehaviour setup on gameobjects with iteration done from ECS side
You know, the whole "gameobject entity" thing that a script provides
I've seen a bunch of samples from year ago or something, but now it seems to be completely remade or deprecated
Those samples I linked are the most up to date available. That script does exactly what your asking for as far as I can tell. It makes an entity from the gameobject that you can reference in the ECS system. Those entities have all the data you would have in the mono representation. For example I do this to covert a user with a player camera to ECS:
public class UserComponentProxy : MonoBehaviour, IConvertGameObjectToEntity
{
public Camera PlayerCamera;
public void Convert(Entity entity, EntityManager entityManager, GameObjectConversionSystem conversionSystem)
{
Entity e = conversionSystem.GetPrimaryEntity(PlayerCamera);
entityManager.AddComponentData(entity, new UserComponent { ViewCamera = e });
}
}
You can then get the UserComponent Entity and work with the camera as you would in an mono script
There is still misunderstanding. What you are talking about is defining a gameobject so later it would be fully converted to an entity with tied components (afaik). I am talking about having a gameobject, have it retained fully, have the ECS system create an entity representing a part of that gameobject and iterate on gameobject itself from the ECS side
No gameobject gets destroyed nor converted.
You can set the convertToEntity script to retain the gameobject in you need it to retain its mono representation.
GameObjectEntity still exists
Yes, I was talking exactly about that script. How do I work with it? I don't think I fully understand it.
Do I just get those monobehaviours like with ToComponentDataArray? That seems somewhat wrong
what do you want to do with it?
I feel that Unity itself wants people to use the newer conversion workflow
you can still track your entities on the gameobject side
there are examples about that on the physics samples on the ecs samples repo
Well, for example, I want to interact with a textmeshpro component, from the ECS itself. I don't want to setup singletons for that or dedicated monobehaviours, I just want to interact with them from the ECS side just for the sake of it
ah, then you'd probably use the GameObjectEntity still
I dunno if there's any up-to-date sample for it
there's been naming changes recently
I think the GDC talk may have had example?
Welp, yeah, exactly. Just for those select few moments, where I don't care about jobs or burst.
I'll look into that
gimme a moment, I'll check it out
Watch to learn what's involved in migrating existing game code to the new Data-Oriented Technology Stack (DOTS), which comprises the C# Job System, the Entit...
yes, it still uses GameObjectEntity
Thanks
that's not from start to finish sample tho
you use EntityManager.GetComponentObject<TextMeshPro>(gameObject) in a ECS system to get the TextMesh component
I think this may be a bit more straightforward.
But still, I'm not sure if I'm doing it correctly
That should be fine, but you still need to put the CovertToEntity behavior on the GameObjects you want otherwise the EntityQuery can't see them
convert to entity = converts the things to entity and destroys the gameobject immediately after (unless you have the option to preserve the GO after conversion)
gameobjectentity = hybrid which exists on both monobehavior and entity worlds simultaneously, you still need to sync it yourself
sync?
if you need stuff like transform to update on both sides
there's scripts for that in ecs packages
Ah, in case if data exists on both the component and monobehaviour sides, yeah?
I dunno the typical cases other than for syncing the GO transform if you have rendering components on the GO side
then you'd need to update the entity position to the GO
as @dull copper pointed out, there's an option to preserve the GO, I can confirm it works fine and you can use it with any mono Component derived component.
I've used this for maintaining the behaviour of the New Input System Player management Prefabs while still taking advantage of ComponentSystem and JobComponentSystem
I've been thinking... You remember that one article, pointing out some problems with vanilla Update methods on MonoBehaviours?
It was pointing out how Update magical functions can make your game run a tad slower when a lot of those functions persist, thanks to C++ -> C# calls, safety checks and whatnot
Does ECS has something similar or is it way, way more lightweight to calling OnUpdate()?
@fringe sinew if you remember the article, whole point of it was to have less expensive update callbacks and update bunch of gameobjects from one update manager. you kinda do this on ecs loops anyway: system updates all entities that have select components to it so it is not one update per entity in the first place, only only update per system
Yeah, I know, I've just been wondering if those individual calls are heavier or not than a single Update call
Yeah, tbh I dont know about onupdate cost specifically, but I doubt you'll ever have so many systems that it would really matter
When people benchmarked the GO update cost, they had huge amount of GO's in the scene
for the ref, this is the article: https://blogs.unity3d.com/2015/12/23/1k-update-calls/ (there was also third party blog post about the same thing before that)
afaik, ECS deals with OnUpdate dispatching itself, so I doubt they've made same mistake twice
I'd be super surprised if they did, considering all the focus on the perf now
i imagine in a naive ecs you can get into problems just as easily with many systems that iterate entities and do work unnecessarily every frame. Most of the examples floating around are not using any kind of checks on for only things that have changed.
i guess in some cases the changed check itself is more work than the work you'd be doing.
Yesterday, I posted this pic of a monstrocity to show how I achieve hybrid ECS workflow. I think it's not quite efficient, because it directly accesses the monobehaviour components and operates on data directly there.
Some said that it would be better to, instead, have corresponding data persist in the ECS world (as components for entities that are tied to respective gameobjects), operate on them there and then just readback from ECS to monobehaviour as a separate system.
The question is: how do I do that? Do I need to explicitly make additional structs for every monobehaviour to represent it in the ECS world?
And, well, do I need to afterwards explicitly attach components based on monobehaviours attached to a gameobject?
If you want to use GameObjects and ECS this would be the approach. You would need a component for the game object and the data component in ECS worlds. Your component system can work on a group which is mixed of components and data components.
But the best way would be to find the things that you really have to read and write. Keep as much of your simulation in DataComponents.
So, everything's manual here regarding the data, component instantiation and copying. Ouchie
Do I properly understand that ComponentDataProxy doesn't really create data on the ECS side and just uses the struct data tied to the gameobject?
I mean, this. It sure appears on entities, and modifying it on gameobject leads to modifications on ECS. This is not optimal, correct?
it wouldnt be much different from transferring data from two monobehaviours on the same gameobject using your hybrid approach. also if you used the component system Entities.With(entityQuery).ForEach lamda it would be easier
I think the proxy system is deprecated. But if you using GameObjectEntity unity generated already IComponentData with the name like the component for example Transform. This is kind of a link to the component and in a Component System you can query them with ToComponentObjectsArray instead of ToComponentArray.
Then you have access to the component on the game object.
Sure this gives you no benefits regarding avoid cache misses etc. because it has to access the component somewhere in memory. But the nice thing is you can already you the Dots strcuture.
What do you mean "you have access to the component on the game object"? The way I do it finely accesses components on the gameobjects and modifies them
What's the difference between those two methods then?
But, well, in any case, the simplest way of having the data persist across both the monobehaviour and ECS sides is to define a unified struct and have monobehaviour create that struct as a component on the ECS side, in order to have them decoupled. Then you manually manage readback and whatnot. Is that correct?
Yes. And I guess what the others mean is to not doing it with everything. It is hard to find an example. For example instead of using that method in 10 systems and all of them reading the position from a transform it might be better to having a system which is reading the position from the transform into a Translation ECS component. Then all others system can operate purely on the data component. And maybe in the end you have a system which write back the Translation to the transform.
Well, yeah, to avoid cache misses. And, well, to also avoid ComponentDataProxy, which as far as I can see, just points to the monobehaviour data
Exactly and the other systems can be even job systems then and if you just calculate stuff you could even burst compile them. π
So many ways to shoot yourself in the foot
wooh, finally actually fixed the render system causing crashes, but despite fixing it, i have no idea what the underlying problem ever actually was π
I've been wondering... How would one handle entities with multiple components of the same type?
I find the idea of creating a separate entity that targets another entity and its components for write changes to be very dubious
What even is exactly the overhead of dynamically creating entities and components? I heard that it's a bit high
you can't have same component in same entity twice
Yes, exactly. How one would handle this situations where, virtually, multiple components affect another, single component?
How stable is ECS atm?
you can also put multiple same type components on structs
So, create entity, give it a component, fill it with data and give it a target component?
In that case - are they really cheap to dynamically create and fill with that data?
Again, I heard that it's not that fast
make prototypes, benchmark π
What about GC in that case? Hitches in performance?
@fringe sinew it entirely depends on what you're doing. It performs well but obviously the more you can avoid creating interdependencies between different types of entities, (broadly speaking) the better. That said, there are often times when you need to but for anything that's going to result in creating 1000's of entities in a single frame, I'd say it's a good idea to think of an alternate way to achieve a similar result. Whether that's using native arrays, pooling etc.
Isn't pooling the sole hideous thing that is not advisable in ECS because something like that will require you to constantly do checks or adding ignore components?
Also, how in the world can you make this behaviour in native arrays? Are you talking about systems writing some data to it so later the component could behave like multiple ones? I also don't find this to be something of use, it's management hell
what's your actual target here?
not necessarily.. I don't think you're going to get very helpful answers if you're looking for rules.. it's similar to asking 'when should I use a Game Object?' or 'is creating a new Game Object bad?'... obviously it depends. I think if you have a particular example in mind that could help a lot.
No target. Just want to understand the workflow.
better not complicate the thing if there's no issues on default implementation
also, Joachim will laugh at you when you mention ECS pooling π
For example, the poisoning system, where multiple components target a single one.
it feels like you try to force ECS into gameobject model
Well, I mean... You get an entity, you deactivate it by adding an ignore component or a check in system itself. Boom, here's your pooling by definition.
But, well, I mean... How in the world would you do something like that then? Have a component be affected by multiple other components that write to it? This is essential to game development, the sole dynamic interaction of multiple entities and their components.
You can't make a game where 50.000 ships go down the screen at 60 FPS and call it a game, same with boids that have only a couple of singleton objects/entities to avoid
...that doesn't sound like pooling to me?
Pooling is when you reuse the objects themselves from a pool. the purpose of this is to not have to instantiate and destroy them, as that can be expensive. Thus, you start your pool with a certain amount of those objects (say, 10 enemies).
Objects can either be active and in use, or inactive but still in the pool. As long as there are inactive (free) objects in the pool, you simply set the properties of those objects instead of instantiating a new one. Depending on the implementation, you might also have an elastic upper cap, so if you try to spawn enemy #11, you either just add that enemy object to the pool or raise the cap (to, say, 20).
@fringe sinew Firstly I should clarify that I can relate to your frustration. Having all players affected by e.g. a 1000 poisonous plants on screen isn't totally trivial. There are multiple ways I might consider tackling this depending on constraints. Let's say any plant within a certain radius of a Player should affect that players health. I guess most solutions start with a system that iterates over the plants, the trick (I guess what we're talking about) is how you get the other player positions & health into the system. One way is for a "Player system" to populate a NativeArray with Entities . Let's say this system populates a NativeArray<Entity> AllPlayers- in your poison system you can access PlayerSystem.AllPlayers (incorrect syntax - just for illustration) then use e.g. GetComponentDataFromEntity<Translation>() & GetComponentDataFromEntity<Health>() and then in the job you could modify the health component attached to the player.
And maybe then have another nativearray/nativehashmap to store the duration of those effects, each counted by entity
I guess that could work
Yes possible - or I might prefer a 'Poison' component that sits on a player entity that you modify e.g. 'duration' and another system that takes that and modifies health
But then that itself would need to store a hashmap of entities that affect it. This also can be quite hard to manage
I think how exactly the poison works is a separate thought - if every time you touch something it poisons you even more, maybe just e.g. +1 to a 'magnitude' that's incremented when you hit one and then the Do Damage system each update resets it to 0 or whatever
You could borrow from physics and do a rough pass (get all players vaguely in the same area) followed by a proper pass (which is where you get health and such).
Obviously this wouldn't make sense if you don't save any perf on doing rough then fine pass, but the data from the rough pass could potentially be used in multiple systems.
In pseudocode:
GroupingJob{
foreach [entity to group]
use position to find a WorldChunk position or something (thus splitting the world in so-and-so big chunks)
}
GroupUsingJob{
foreach [thing that affects grouped entities]
if [groupedEntity.group] is not near
continue;
do the actual work
}
hmmmm, new math lib dropped the preview label on staging https://bintray.com/unity/unity-staging/com.unity.mathematics
1.0.0 and 1.0.1 there today
i wish you could modify variables in the entity debugger
I just can't wrap my head around to how ECS can be fast in certain situations
Let's say that I have a tweening library.
Creating entities and adding components to existing ones is expensive and should be avoided.
That means that I'll create an entity and fill it with my tweening components from the start, which I have about 50.
So, I'll have 50 systems iterate over them, and that'll be a bool check at best to see if I'll even need to do tweening
How can this be even remotely performant?
components != systems
I mean, hooray, zero cache misses. But at the same time it's >100.000 bool checks, for example
Yes I know, but I have tons of components and systems iterate over them.
There are 50 component types, systems iterate over them. Nothing wrong there.
i expect your tweening animation stuff to stay longer then a few frames, at this point i would say its fine to add and remove components to avoid the bool checks
But isn't it, like, super slow?
depends on your definition of super slow
Enough to cause a 0.5ms hitch on nintendo switch
well i would just go setup a small benchmark scene there you add/remove the expected amount of components to some entities coupled with some systems which emulate your tweening system and see what the performance is like. And if its good enough for the amount of tweens you need to add/remove at once.
if thats not the case i would start thinking about more complex solutions.
But from my experience i would go with add/remove components also to keep it simply as long as the performance is sufficent
its not like you always find a general solution which fits to every scenario so it really always depends, but in this case to answer your question it should be quite simple to setup a benchmark.
also as far as i remember i already found an ecs tweening engine on github, cant remember its name tho. It worked with adding/removing components and the performance was quite impressive in comparison to his monobehavior based implementation
50 separate components? why so many?
@fringe sinew as it happens I'll hopefully soon (TM) release my tweening library and I've had to solve a lot of these issues to get something that works for hybrid, pure, complex behaviour (like nested sequences & looping), tweening independent dimensions for an entity at the same time, allowing you to add extensions for your own classes etc etc. There are a lot of systems and I solve part of the problem through code generation. At times it's hard to balance flexibility with raw performance but never-the-less I can e.g. tween about 200k cubes (on my i5) both position & rotation and at least half that time is rendering. It's fully multithreaded so obviously that helps but nevertheless even with 4 cores it can be ~5-6 times faster than e.g. DOTween (which is already an awesome, heavily optimised tween lib).
How would one create a manual version of Entities.ForEach?
Just don't ask why, I just wonder how
Is it just for loops that you iterate on nativearrays of component data?
If that's so, how do I modify data of components?
Also, this is a test system that I made to repeatedly add and remove components from entities, and in my case it generates a ton of garbage from adding and removing those components (35k per 50 entities per frame). What's the deal with that?
If it generate garbage - why even bother? Garbage should never be acceptable at runtime.
And thus we come back to the original problem: we either add and remove components dynamically to indicate behavior, or add bool checks.
Pick your poison.
So far, I just can't understand the deal with ECS. Well, yes, you get organized memory, iteration is fast, but at what cost? The cost like this, of dancing around the system to force linear memory?
If so - I don't get it. What worth does it have if handling dynamic stuff, with interactions, multiple components and dynamic behavior, is a pain like this?
I'm still not sure how they expect people to use those noise functions in the math library
I was hoping they would do a pass on that for 1.0, but that doesn't seem to be the case
@fringe sinew https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&cad=rja&uact=8&ved=2ahUKEwju-JzNj9ThAhVLbVAKHdkdD2EQFjABegQIBhAB&url=https%3A%2F%2Fforum.unity.com%2Fthreads%2Fis-it-good-practice-in-ecs-to-frequently-add-and-remove-components.577126%2F&usg=AOvVaw1vkDycLGS3sQWts8tUCb6k
https://forum.unity.com/threads/flagging-for-filtering-better-to-add-remove-empty-component-or-poll-over-component-data-int.599200/
in my opinion it's better to add/remove components so you can write very specific queries instead of "get all entities and then check if something is set"
Well, yeah, but this leads to garbage
@fringe sinew you shouldnβt see that garbage in a release build - it comes from the safety checks
Oh wait, is it?
I think even a debug build attached to an editor you wonβt see most of it
Youβre right that thereβs a lot of either bools or adding/removing components. I use a combination. Esp as add/remove doesnβt work with burst right now, it can be a bit slow if youβre dealing with thousands of entities.
Also, I just looked at your code - couple quick things: 1) If you want better performance you should use a concurrent entity command buffer as part of a job system and 2) You should use archetypes where possible when creating your entities and avoid 'addcomponent' where you can - hope that helps
- I'm not sure exactly what's going on but you should probably have two systems (or jobs at least) that require
InitialPositionOffsetor require an absence of it (rather than doing some ToComponentDataArray then checking in an if/else)
Hmm, but then how should I operate on an entity? AFAIK to get all the entities you are required to make a query and use toentityarray
Have you checked out the examples? They're not exactly what you want but are up-to-date at least: https://github.com/Unity-Technologies/EntityComponentSystemSamples/blob/master/Samples/Assets/HelloECS/HelloCube_02_IJobForEach/RotationSpeedSystem.cs
Yes, I did. AFAIK, you can't physically get the correct entity to operate on right here
And I mean the entity itself, which is required if you want to add or remove a component
if you want the entity you can just use IJobForEachWithEntity
fwiw I tend to use IJobChunk a lot where in the execute part of a job you would do something like NativeArray<Entity> entities = chunk.GetNativeArray(EntityType); where EntityType is defined in the job as: [ReadOnly] internal ArchetypeChunkEntityType EntityType; and is set in the job update: EntityType = GetArchetypeChunkEntityType()
is DOTS meant to be used with Input (in the future)?
@cunning perch my understanding is that eventually there won't be any part of Unity that isn't touched by DOTS... but we're talking 2021+ - i.e. I'd expect to be using Unity as normal for Input for a long while yet (especially given how it's been prioritised historically)
I'm imaging that you're right and that there will be a System in place where the default initialization of the Input will be a system of itself with hooks for you to customize if needed.
Burst 1.0.0 @ staging now :)
Any changes of note?
is there anything like AddOrModifyComponent?
i believe thats what SetComponent do
@junior fjord fyi SetComponent won't add it if it doesn't exist - I would guess that it's not an api Unity would like to create as it's much preferred to create entities via archetypes and it would be costly to e.g. wrap an component existence check in with every SetComponentData call
ok good to know
if some kind of window shows some information (for example how many ressources you have) and I need a system that gathers this information (you have to do a few calculations to actually see how much gold the player has) when the window is open, how would you do that?
would you just do it from monobehaviours or would you somehow create a system that only runs when that window is open (== the information is needed)
if it's a lot of data to process, I'd certainly try to collate the data and do calculations in a job... as for controlling when that happens, either you can enable & disable systems or you can add/remove components
sooo, user opens UI window -> monobehaviour activates system -> system updates some entity which has the wanted data -> monobehaviour uses that data to show information in UI?
yes - with the caveat that there are multiple ways to go about it. It's probably going to be a long while before doing UI with native entities is a thing .. so I'd say that flow sounds about right to me. Though for that reason, unless you're making a generic system or something that will handle many items, want to save battery on mobile etc, it's worth considering if it's better to keep it all in monobehaviours.
burst 1.0.0 and mathematics 1.0.0 on regular registry now π
probably out for the 2019.1 release which just happened now
no deterministic float yet π¦
I feel they wanted Burst released first
it'll come
at least they finally got the CPU extension fallback right before release
so our games wont just straight up crash if the players cpu doesn't have SSE4 support
in which language is the ecs stuff written? I just stumbled upon project tiny which is somehow ecs but written in typescript (?)
tiny prototype is an exception, unity ecs is all in c#
tiny mode will be c# soon as well
so they convert the typescript stuff to c# somehow?
I don't really understood why they took another language
no I have nothing in typescript
I just find tiny very interesting (want to do 2d stuff) and am thinking if I should switch
at this point, it's better to wait for the C# version tbh
actually i just watched a talk about tiny and they said they picked javascript cause its the king in the web
as there's no future on the existing thing
so they build a completly parallel ecs structure in typescript with the same api basically as a prototype?
and now decided to do it in c# nevertheless?
yes
it wasn't always clear they will only have one system
but they decided at some point it makes more sense to have all under same setup
was typescript always a unity language or is this the first time they did something in ts?
c# support was always planned tho
TS is only supported on current Tiny Mode (not in rest of the unity)
I dunno if you can run some additional JS with webgl builds tho?
ah so basically earlier they thought that it is maybe a good idea to have another ecs in typescript to just make it work well on the web? and now they redecided and thought better to have everything in c#?
afaik, they never planned to ship with typescript support
that all sounds very weird to me
why should they do a complete prototype of something they have in a language they normally don't use and then not even plan to ship it
well, Unity is all c# now, it makes sense to stick to it
because it was faster to implement?
doing a prototype in another language is also a good forcing function to throw it away
(if thats an intent)
ok and the experiment they did was if they could make a really tiny ecs-based runtime, right?
it worked, so now they'll just do the same thing in c#
here's blog post for first Tiny preview release: https://blogs.unity3d.com/2018/12/05/project-tiny-preview-package-is-here/
Unity is working on bringing extremely high performance to C#, such as with our Burst compiler work. We are also working on allowing developers to write C# code while still resulting in small code size. While Project Tiny currently uses Typescript for writing game logic, it will be replaced with C# during the Preview period. With C#, we will be able to produce even smaller codes size and better performance, as well as provide an improved debugging experience. Weβll also be able to take advantage of technologies such as Burst, even when targeting the web. It is important to note that we will be removing Typescript once support for C# is ready.
thanks @dull copper
I dunno if they originally wanted it to be typescript only thing, but they've communicated for a long time it's only temporary
ok and when tiny c# is ready I can basically expect to have a lot of new premade systems/components (for 2d physics etc.) available to the c# ecs I am already using?
or is there even more to it?
I don't think there's any proper ETA for it
they have 2019.3 target for DOTS standalone player and that's most likely to land first for Tiny, so would expect to see something for 2019.3
but that's not granted
what is a DOTS standalone player?
means a runtime player that doesn't have ANY monobehavior stuff in it
so you can only use DOTS libraries for things you run with it
basically that means zero hybrid code
is tiny just a bunch of systems and components for the ecs or is there more to it?
these things tend to shift
ok
technically it's only that once they have it done
but I do not even need much physics or anything, all I'd like is to better understand how ecs and UI integrate at the moment. besides that I am pretty fine with the state of the ecs
From https://github.com/Unity-Technologies/multiplayer/blob/master/sampleproject/Assets/Samples/Asteroids/Mixed/NetCode/netcode.md: The client presetation and separation are separate groups, and simulation needs to run at a fixed frame rate. In order to allow presentation to run at a different frame rate than simulation we have an early prototype for interpolation of transforms. The interpolation will always interpolate between two existing frames, so it does introduce one simulation tick worth of latency. The code for the interpolation is available in RenderInterpolationSystem.cs and RenderInterpolationComponents.cs .
This would be handy on Unity Physics too
anyone know how to not have more than one Unity.Entities.SceneBoundingVolume when using subscenes?
InvalidOperationException: GetSingleton<Unity.Entities.SceneBoundingVolume>() requires that exactly one Unity.Entities.SceneBoundingVolume exists but there are 8 got one error for each subscene in my scene, each subscene only has pretty basic prefabs
ok its something to do with it not liking multiple ConvertToEntity scripts coexisting with subscenes I think
Well, I ran some tests for adding and removing components at runtime. It's not pretty.
It generates a ton of garbage, no matter the runtime and settings. Both build and editor.
So, well, I don't believe you guys that adding and removing components at runtime is an adequate approach to reactive behavior
As such, can we maybe perhaps somehow exploit SharedComponentData in order to sort entities which need iteration and which don't?
Again, let's imagine a tweening system that has 50 types of components. Adding and removing them generates garbage, bool checks and flags are not advisable. What do you think?
I must've gotten very hard on your nerves by now.
why isnt using bools advisable? sounds to me you're just trying to make your life harder. adding or removing 50 monobehaviours each frame per object sounds terrible as well but if that worked for you previously i guess stick with it?
You probably meant components, but yeah, seems like bool checks are the only thing that will allow me not to generate garbage.
But, well, at the same time it'll require 50 systems to work at the same time, checking each entity with those tweening components.
Let's just say that hypothetically all of them can work at the same time
I don't quite believe that can be fast either, with so many systems running at the same time, each fetching their own queries
I agree with @safe lintel - it sounds like you're happier with the way monobehaviours work which is perfectly fine - plenty of fine games have been made with them. That said, on the subject of tweens (near and dear to my heart), yes, you have to pay the cost of a bool or of adding a component. Just because monobehaviours hide this doesn't make it less efficient. I choose to add components when something happens (e.g. you create a tween or a tween completes) but for the rest of the time I essentially use bools. This does have a cost but I don't think you can get what you're after for free.
im curious how this system works in its current state tbh
So, in the end it's "bite the bullet but don't worry, it won't be that bad"
id understand if it cant be shared but im just having trouble understanding the problem when its like all vague hypotheticals
With my library once you have tweens created, it can e.g. tween 500k entities positions over time and then stop with 0 gc over that whole time. There will be hitches/gc if I choose to destroy the tweens and free the memory... I'm yet to work out if I can do that better but still... this is like 100x better than I could achieve with monobehaviours
I bet UT will come up with how to solve this dilemma in the future with relative efficiency.
anyway if you find yourself genuinely running into roadblocks with this, you should post this on the ecs forums so joachim and the rest can take note, maybe its an ecs design flaw that needs fixing?
yeah we could probably all be a lot more helpful with a concrete example
Each time they update I always have a hard time finding the changes, and the new ways of doing stuff. Especially regarding hybrid since they removed the examples from their samples :/ Anyone who knows where to find like the deprecated doc and update doc? :S
@mystic mountain Hybrid looks like it's been left by the wayside?
Not seen any big updates to the 'hybrid' api/functionality at all lately
Yeah, I donno. It all worked fine with the ComponentGroup, but I cant see any good sources of how this kind of flow should be changed, or if the concept is gone.
Honestly I wouldn't expect them to put a lot of effort into hybrid since their goal seems to be to do away with as much as possible of the old system
Yeah π I understand that, and I'm moving my stuff to their new systems when they're ready, but in the meantime it would be nice to have some hybrid stuff to work with.
@mystic mountain https://github.com/Unity-Technologies/EntityComponentSystemSamples/blob/master/ReleaseNotes.md is great for each versions Upgrade Guide's
Oh wow... they are moving Simulation to player loop?! ._. Well guess I'll revert my refactoring x)
And now I wish they made collab reverts easier...
is there any tutorial on what hybrid actually means and how to use it?
I understand that I can use the entitymanager from monobehaviours etc., is that all there is to hybrid?
atm, anything that's not pure ECS is hybrid (when used with ECS)
uhm. NativeHashMap nas no setter indexer, just TryAdd(), can values not be set? what am i missing.
If each Entity of Archetype A has a reference to an Entity of Archetype B and I need to calculate some number for each pair (entA, entB) (ent A has Archetype A and entB has Archetype B), how do I do this?
A system can always only iterate over either Archetype A or Archetype B, I do not understand how I should do this "double-for loop".
you can pass in the chunks directly, get the entity comppnents by ToComponentDataArray, or use HasComponent
@safe lintel thank you
but if I want it jobbified I need to make a copy of one of the archetypes?
basically I have a many-to-many relationship where I want to calculate a weight for each relation
how can I require only entities that have a DynamicBuffer of a specific kind?
your intial archetype A is jobified(assuming you are using something like IJobForEach), but within that job you would loop through archetype B manually
@safe lintel but I thought I cannot actually read the other components in a jobbified job?
only buffer some commands using the ecbuffer
struct AddForces : IJobForEachWithEntity<PhysicsVelocity, PhysicsMass>
{
[ReadOnly][DeallocateOnJobCompletion] public NativeArray<Impulse> Impulses;
public void Execute(Entity entity, int index, ref PhysicsVelocity c0, ref PhysicsMass c1) {
for (int i = 0; i < Impulses.Length; i++) {
if (Impulses[i].Target.Equals(entity)) {
c0.Linear += Impulses[i].Force / c1.InverseMass;
}
}
}
}
//OnCreate
m_Impulses = GetEntityQuery(typeof(Impulse));
//OnUpdate
var job = new AddForces
{
Impulses = m_Impulses.ToComponentDataArray<Impulse>(Allocator.TempJob)
};
thanks very much!
simple example to work with more than one query, if you wanted to change the data of the secondary query you either need a commandbuffer or to use chunk iteration instead of tocomponentdata
thanks @safe lintel this helps me very much
the readonly on the nativearray is only to help the compiler?
yeah i think it helps with burst, it would work without it, but with chunk iteration some things require the readonly attribute
actually it might not work without it, cant remember but it usually throws an error if it doesnt
ok, thank you π
I think readonly is mostly for dependencies - i.e. if you have two jobs reading from the same array, they can run at the same time provided another job isn't also writing
can I pass BufferFromEntity to a job (and does it make a copy?)
@amber flicker you mean in case you use one and the same nativearray across multiple systems?
yes - though the nativearray like e.g. chunk.getnativearray() is just a pointer to some aligned memory so it applies for e.g. multiple jobs that read certain component values
if they are only reading, as many jobs as you want can in parallel be reading a components value
does anyone know how to configure visual studio (or any other ide you'd recommend) to actually go to the source code and not only "infer from metadata"
so that I can for example look up if something makes a copy or returns a pointer
and thank you @amber flicker, I think I should get into chunk iteration. Until now I stayed with the simple ForEach stuff
np - also I find chunk iteration much more straight-forward than the other methods tbh - if I was teaching ecs I'd insist on getting comfortable with that before using the other shortcuts
specifically I am asking myself how BufferFromtEntity<> and ComponentDataFromEntity<> work and if they make copies or not
yes I overlooked the examples using it once and it seemed like something I could understand when I need it but I am now going to check the example again before continuing
they don't make copies but when you look up data via an entity it can cause an L1 cache miss.. so it's totally fine and necessary a lot of the time but it's also good to try not to use them super-heavily is my understanding
can I use them in jobs then?
yes
ok since it seems as if it is not threadsafe if I can just modify and read and everything
but I have no clue how this works, it is just a feeling
ah but probably unity will notice that I need these components and just manage it like it does with the rest, nvm
ok thanks for taking all the time @amber flicker π
I'm off to the chunk iteration example
glhf π - also caveat that this is all my understanding which could be flawed
is using fixed size arrays frowned upon. I need to have an inventory and my first try was to have a DynamicBuffer of
public struct InventoryItem : IComponentData { public Entity Good; public int Amount; }
but this has a lot of problems. It is much nicer for me to have something like
unsafe public struct Inventory : ComponentData { public Entity[MAX_ITEMS_PER_HUMAN] Goods; public int[MAX_ITEMS_PER_HUMAN] Amounts; }
or
unsafe public struct Inventory : ComponentData { public int[N_ALL_ITEMS] Amounts; }
since I need to calculate a lot of functions on the inventory where I need to query a lot of things like, does this human have this group of items and with the DynamicBuffer approach this results in nested loops
can't help too much I'm afraid... for better or worse I've decided in these situations to have e.g. an entity per Good and a component on each good which stores the corresponding Inventory entity
I think I'll just go with the dynamicbuffer for now maybe and wait until I actually have performance problems
unsafe only works if I switch some settings and I am afraid that the thing then maybe won't run on restrictive systems like ios...
hey, am I missing something or where did Entities go from the package manager?
I'm on 2019.1 stable
that was stupid of me, thank you very much
huh, after the whole "we dont know if we'll support generic components" bit i started messing with T4 to do code generation instead, surprisingly good reward/effort ratio. finally will be able to specify all my networked components in one place and automagically create the classes i need for them!
@manic aurora what is T4?
templating engine
Attempting to render textures on quads similar to sprites in ECS, apologies if off topic but has anyone figured out transparency sorting using RenderMesh? LWRP doesnt seem to allow me to set a sorting axis anymore either.
so I've been having some trouble getting shared components to work. it keeps thinking every entity has different data despite them being the same. So when i call EntityManager.GetAllUniqueSharedComponentData(m_UniqueTypes); I just get a list of all the entities with the shared componenet attached. Here is the component code (btw this is an implementation of boids for ecs very loosely based on the unity example ```C
using System;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
[Serializable]
public struct MainBoid : ISharedComponentData
{
public BoidAction[] boidActions;
public NonBoidAction[] nonBoidActions;
public int group;
}
public class MainBoidComponent : SharedComponentDataProxy<MainBoid> { }
[Serializable]
public struct BoidAction
{
public BoidActionType actionType;
public float range;
public float weight;
public bool divideByNearby;
public float viewangle;
}
[Serializable]
public struct NonBoidAction
{
public NonBoidActionType actionType;
public float range;
public float weight;
public bool divideByNearby;
public float viewangle;
}
//Actions which involve checking other boids
[Serializable]
public enum BoidActionType
{
Alignment,
Cohesion,
Seperation,
}
//Actions which do not involve checking other boids
[Serializable]
public enum NonBoidActionType
{
Fleeing,
Targeting
}```
Any advice about what's happening would be appreciated.
Uniqueness of ISharedComponentData is calculated by its hash of members. But if the member variable is object type, its memory address is used instead of its value. So if you created new array[] for every sharedcomponent, it doesnt shared.
the parallelization inside of one jobsystem is always chunk-wise (one chunk is not subdivided), right?
It is obvious in IJobChunk, I just want to be sure it is the same for the other interfaces
Hey guys I have questions how to approach a certain problem with ECS. Let's say you want to spawn some entities which is fine so far. Now I want after a certain time to fade them out. How you would make the fade. The rendering used a shared compomnent for the material or better said the renderer, which has this material. If you would change the alpha value you would change it for all of them at the same time right? How you would approach the problem if you want to have them fade individually. Mean at a time they have maybe 100%, 80%, 76%, etc.
Note the grqphics side of DOTS is still under development. At the moment, to do that you would need a custom render system
I believe I remember Joachim mentioning it would be nice to be able to control things such as color etc via a component, alas Im on my mobile so unable to dig up the forum post.
@solar spire thanks! I searched here https://docs.unity3d.com/Packages/com.unity.mathematics@0.0/api/Unity.Mathematics.float4.html and did not find it
even a full power function π
I already thought I'd need to approximate x^0.1 myself π
is there a way to find out what is more expensive: x^0.1 or atan(x) ?
you can see the output of the burst compiler in its window but I have very little idea of how to compare IL, etc
you can also just run a thing a couple of million times like normal performance comparisons
ok, thanks again. Maybe I'll just switch out the functions in my own game and check if it makes a difference
@junior fjord you look in wrong place
in new math lib, most of the types are just structs with very little function other than storing the data in them
yeah I saw that the api version was fixed at 0 somehow, it is what I found on google. next time I'll be smarter
most of the thing are in the unity.mathematics.math
yes thank you
np
I hate how you can't seem to easily find the latest package docs page
you can find the sqrt there too
is there a way you can just not write the version and it just figures out the latest
if I call a function from a jobbified system and add [ReadOnly] to the method parameters, is burst able to get that?
and is it fine to have a NativeArray<float> buffer on a job that I reuse all the time? Or is that a problem since the job could run on two archetypes simulateously and try to access the buffer on both threads?
can I iterate through buffers in IJobForEach or do I have to use BufferFromEntity?
Hey everyone! Just recently I started having some spare time and I would like to start on ECS, do you guys know any good tutorial or starting point?
@safe gate read the docs at https://docs.unity3d.com/Packages/com.unity.entities@0.0/manual/index.html, then examine the samples and readme's at https://github.com/Unity-Technologies/EntityComponentSystemSamples
those are the two most up-to-date resources you'll find, altho docs are still for the previous Entities package, there's been name changes on the latest
https://github.com/Unity-Technologies/EntityComponentSystemSamples/blob/master/ReleaseNotes.md is your go-to doc for seeing the changes between the releases, it also got upgrade notes
unfortunately, this is the state new users get today, but believe me when I say current day docs are already way better than what we used to have π
especially the API evolving so fast makes it harder to get into current Unity ECS
almost all tutorials you find online will be outdated by the time you read / watch them
those samples are kept up-to-date tho π
@dull copper thanks a lot! And yes, most things I initially found were really outdated
Your post shoud be pinned here!
should have put them in one post then π
btw https://forum.unity.com/threads/api-deprecation-faq-0-0-23.636994/ is there for explaining why some things got deprecated
You should definetly compile all this in one post and get it pinned! It is really helpful
here's also API docs for ECS: https://docs.unity3d.com/Packages/com.unity.entities@0.0/api/Unity.Entities.html
You're on fire π₯
there's similar docs for Unity (ECS) Physics package as well if that's your thing
I think I should get something going with ECS, later then I will dive into physics
I'm really hyped about all the doors ECS opens
yeah, physics package is super early now too
yeah, but I mean, Unity ECS has been years under development already, the physics package is brand new, we just got first version of it on this GDC
Entities have been around for quite a while already
so the point I was trying to make was that the physics package is super raw still, still going through it's early iterations π
can I query for entities that have a specific buffer? I can't find it anywhere
yeah, same as querying for a component, just use your IBufferElementData type instead
@manic aurora thanks very much
but the only way to access the buffer afterwards still is BufferFromEntity right?
yeah they said they would eventually offer versions of IJobForEach that support buffers, but for now, that's all we got
ok thank you for the help π
Github
DOTS Samples (Entities & Physics): https://github.com/Unity-Technologies/EntityComponentSystemSamples
Documentation
Entities: https://docs.unity3d.com/Packages/com.unity.entities@latest
Mathematics: https://docs.unity3d.com/Packages/com.unity.mathematics@latest
Burst: https://docs.unity3d.com/Packages/com.unity.burst@latest
Unity Physics: https://docs.unity3d.com/Packages/com.unity.physics@latest
Havok Physics: https://docs.unity3d.com/Packages/com.havok.physics@latest
API
Entities: https://docs.unity3d.com/Packages/com.unity.entities@latest/index.html?subfolder=/api/Unity.Entities.html
Mathematics: https://docs.unity3d.com/Packages/com.unity.mathematics@latest/index.html?subfolder=/api/Unity.Mathematics.html
Burst: https://docs.unity3d.com/Packages/com.unity.burst@latest/index.html?subfolder=/api/Unity.Burst.html
Unity Physics: https://docs.unity3d.com/Packages/com.unity.physics@latest/index.html?subfolder=/api/Unity.Physics.html
Havok Physics: https://docs.unity3d.com/Packages/com.havok.physics@latest/index.html?subfolder=/api/Havok.Physics.html
Changelog
Entities: https://docs.unity3d.com/Packages/com.unity.entities@latest/index.html?subfolder=/changelog/CHANGELOG.html
Mathematics: https://docs.unity3d.com/Packages/com.unity.mathematics@latest/index.html?subfolder=/changelog/CHANGELOG.html
Burst: https://docs.unity3d.com/Packages/com.unity.burst@latest/index.html?subfolder=/changelog/CHANGELOG.html
Unity Physics: https://docs.unity3d.com/Packages/com.unity.physics@latest/index.html?subfolder=/changelog/CHANGELOG.html
Havok Physics: https://docs.unity3d.com/Packages/com.havok.physics@latest/index.html?subfolder=/changelog/CHANGELOG.html
Website
DOTS landing page: https://unity.com/dots
Megacity landing page: https://unity.com/megacity
Forums
DOTS: https://forum.unity.com/forums/data-oriented-technology-stack.147/
DOTS Physics: https://forum.unity.com/forums/dots-physics.422/
Thanks @dull copper! You're awesome
np π
hm, anyone manually bringing in a more up to date version of System.Runtime.CompilerServices.Unsafe? i have other .dlls that rely on this newer version, but it causes a conflict with the version of the S.R.CS.U imported by Unity.Collections. the only workaround i've found is deleting the .dlls from the Unity.Collections package folder while Unity starts. if i don't do this, all my Unity namespaced packages fail to compile and none of their namespaces are visible
Hi everyone
Iβm a long time ECS user and I felt like unity ECS was starting to come together more so now would be a good time to learn it but there was some features that either itβs missing or I donβt know how to do yet
Are you able to edit entity component values in inspector ?
And are their reactive systems that only react when the data in a component is changed ?
there's still no ECS editor and you can't edit the values at runtime afaik
basically currently it's pretty much that subscene loading and conversion workflow
so you can set the values on gameobject side, then convert to entity side
would be fancy to finally get the proper ecs editor like demonstrated on Tiny Mode
I think you could make a reactive system by having a HasChanged { bool Value; } component and a system to reset it that runs after literally everything else, but not built-in.
technically you can have systems run on change, but change detection is at the chunk level, and i have a confirmed bug open regarding it - the functionality doesn't work right atm π’
Either way, the method I outlined should be pretty simple to set up and flexible, and no particularly cost-intensive. The caveat of course is that you need to manually toggle the bool when changing something, but it's something.
Ahhhh I see
@tawdry tree I see yeah thatβs basically a makeshift reactive system
Also whatβs tiny mode? @manic aurora
If it works, it works :P
Motto of the engineer
Tiny mode is a work in progress ECS-only 'mode' which creates a very small runtime (small enough to load as an ad). Gimme a moment and I'll have a link
I guess Iβll just keep using entitas as my ECS framework I feel like itβs hard to really use unity ECS if I canβt modify the component values of entities
Oh please link Iβd love to see
Talk from last year's GDC: https://www.youtube.com/watch?v=TvP5XtaAffI
Sykoo video about it: https://www.youtube.com/watch?v=o9m4JXjx1xU
March 19, 2018 (San Francisco) - Unity is everywhere you want to be. Ralph Hauwert (Head of Platforms) shares details on the new core runtime which allows de...
How do you make small and quick mobile and web games using Unity 2018.3 or Unity 2019? Well, using Unity Tiny, or Project Tiny will be helpful! Unity just re...
Iβm surprised that you canβt modify component values in editor is it a design hurdle for them?
Well, it will take some work(no idea how much) and with ECS still being somewhat in flux I assume they have simply decided to focus their efforts elsewhere so far. I think ECS editor was slated for Q2 or Q3, but don't quote me on that.
At the moment Tiny Mode uses Javascript(Typescript), but they're working on switching to C#, ETA Q3. At that point it will enforce pure ECS with a bunch of minifying defaults, and probably not give you access to 100% of the various modules (at first) and also most modules should be opt-in (aka not available unless you explicitly turn it on)
Again, this is just my understanding, and contains several assumptions. I have not particularly researched it.
Gonna watch the GDC talk in rn I watched sykoo first
Also based on the header of the GDC and the name βtiny modeβ is it only for light weight projects so that means a full on project of pure ECS doesnβt have a time scope currently ?
i mean their timeframe for "you can do everything in ecs" is 3 years from now
well, if you use the conversion workflow, you CAN set the initial component values in the editor
just can't tweak them while the game is running as they get converted to ECS side
can the scheduler not figure out dependencies for IJobForEach<T>? i wrote the equivalent non-generic job and it plays nice with other systems, but the generic version throws the good ol "both jobs trying to access the same blah blah complete one of your jobs"
Linking to this because comment because that graph is very helpful:
https://discordapp.com/channels/489222168727519232/497874303463850004/563862129007132673
See also the discussion below it, but the TL;DR is that many projects can probably go mostly pure ECS in late 2019, in late 2020 most projects should be able to go mostly pure ECS, and in 2022 it should theoretically be possible to do everything you want in ECS.
Ready to deliver games that don't require installation? Learn how Project Tiny will let you connect with players instantly. Technical Evangelist Arturo Nunez...
@dull copper nice, thanks
if I use the UpdateBefore and related tags, do the corresponding jobs of the JobComponentSystems also update in that order?
UpdateBefore & UpdateAfter only work in the context of systems within the same group... i.e. both in the same [UpdateInGroup()] - note as well that just because one job is after another, doesn't mean the first will have finished/completed... to ensure that you have to call .Complete() on the job
@amber flicker thank you. How would I call complete for the Job? The systems are in the same group
Can I just directly access the job struct from the second system and call complete on it?
yes - either you can append .Complete() to your .Schedule() in update or else when you create the job, you can assign it to a public JobHandle in your system that the second system accesses and then calls complete
@amber flicker thank you very much. I have one more question: How do I access the instance of the other system class that unity is using?
If I understand you correctly, in OnCreateManager in the second system you do e.g. firstSystem = World.Active.GetOrCreateSystem<FirstSystem>(); then later you can: firstSystem.currentJob.Complete()
@amber flicker yes thank you, that helps me π
in the entitydebugger when I scale up not my systems take longer but the EndSimulationEntityCommandBuffer take longer
does it mean that the stuff that I put into the commandbuffer just takes very long?
just a really short question:
for a rollback system I want to copy an existing world with entities and components, eventually also serialize them.
Is it easy to work with multiple worlds? or does anyone know good examples?
and since everything is just structs, are there convenient ways to memcpy components/entities (provided they only hold value types and if there are pointers - those need to be reset and repointed to the copies then I guess)
Maybe a little more info:
I want to store a value copy of all dynamic entities at some point during the simulation.
then continue the simulation, after a few frames, I want to instruct the game to restore the entities / the world like it was when taking the snapshot
I'm pretty sure there is an example which saves world state to demonstrate physics <that word which means that you get the same result every time>.
Might have been part of the pool thingy?
do you think it is a part of the official entitySamples? I know they have added some physics examples since they released their physics package, if there is something there, I will check it out.
I didn't think it was in the official samples, but physics examples sound about right
how can the EndSimulationEntityCommandBuffer always take 10-30 ms even though I don't have any active systems using a commandbuffer?
@minor sluice I haven't checked it out but the ecs multiplayer sample could have something to help there
also FPS Sample
with former, I mean this https://github.com/Unity-Technologies/multiplayer/tree/master/sampleproject
thanks!
I wasn't aware of the multiplayer example (just the new multiplayer package and the fps sample)
thank you!
it mentions the samples further on that file
and yeah, I don't know if there's anything relevant to your thing there, just pointing out that exists
just in case π
does anyone in here understand why the EndSimulationEntityCommandBuffer always take 10-30 ms even though I don't have any active systems using a commandbuffer?
@junior fjord is that true in a build and with vsync off?
@amber flicker hmm don't know. I never build until now and did not change any vsync settings (no graphics yet, everything happens in the entity debugger until now. it is a simulation game)
but thanks for the hints, I will find out how to do that and maybe get a bit better at profiling
yea it could just be that you're fixed at e.g. 60fps and it's filling the frame with emptiness essentially... also if you're profiling in editor at least disable all the safety checks etc in the Jobs menu otherwise things will be quite off
ok thanks for the suggestions
id try to check in a different project, doesnt sound quite right if you arent using it and its at 10-30ms
@safe lintel I have one system that uses it exensively, but that system only runs one time at the beginning. I also am not sure if the "filling emptiness" is the problem as @amber flicker suggested, in the profiler it looked as if that happens before the systems are even executed. But I have no clue how to debug this and I first wanted to maybe watch a view tutorials on the profiler before I try to understand it
I have a different question too. Is the way suggested by joachim ante here ( https://forum.unity.com/threads/update-interval.523628/ ) still the way to go if I want a fixed update frequency (like 1 time per sec only)
it looks really complicated π
The simple way to do that is to have the system keep track of when it last ran, more or less the same way you would in non-ECS.
Something like
//Uses:
float LastUpdatedTime = float.NegativeInfinity;
float UpdateFrequency = 1f; //1 second in this case
void SystemRuns(){
if (Time.Time - LastUpdatedTime < Updatefrequency){
//Not time to update yet
return;
}
//Do the stuff you wanna do
LastUpdatedTime = Time.Time;
}
Oh, it seems to me as if the docs where updated https://docs.unity3d.com/Packages/com.unity.entities@0.0/manual/job_component_system.html
Of course, you're still stuck in the player loop, so it's not going to be perfectly every X time, but if your goal is simple to run it less frequently, something like that should work just fine.
at least they look differently and if I remember right they did not have the JobForEach yesterday but still the ProcessComponentData thing
@tawdry tree Basically one time step in my game is "one day" in the simulation world (think europa universalis, crusader kings, stellaris and the other paradox games). One Day should never have a frequency similar to fps or anything but just depend on how fast the player has set the game speed
You can choose where to put the variables, too; either using an entity or just making them static (or const in the case of updatefrequency, but then no time controls)
Is this the circumstance where I should have a second World? I did not get to really understand what they are for yet but it seems as if it is maybe the right thing? Or what do you mean by "stuck in player loop"?
The player loop, update loop, or game loop is the basic structure which runs the game. The simplest possible game loop is as such:
while true:
do stuff
But of course, nowadays you want to have your graphics and simulation framerate separate and whatnot, and a dumb while loop isn't goin to cut it, but my point is that the Loop is simply what makes the game run, y'know, as a game, as opposed to a one-time as-fast-as-possible simulation
The way I suggested should be quite fine for your purposes, though doing it that way concentrates a lot of simulation in one burst, so you want to be careful.
That said, the Paradox games actually have more than just one interval, and I believe they actually have some code which runs as per normal (with deltaTime, of course)
@tawdry tree thanks as always for the kind explanations. My simulations would have some timestep and nearly all of my systems would only run once per timestep. These timesteps should happen at most (fastest game speed) I guess a few times a second.
It would be absoloutly optimal if that would not infer with the player and framerate at all (when one timestep needs a bit longer I don't want the screen to lagg or anything, it will just take longer).
I could do what you said (or maybe I would rather have a global int which gives me a timestep and each system keeps track of the last timestep it updated instead of each making float calculations. Then only one TimerSystem makes float calculations and increases the int timestep). Should I maybe also look into having a second World only for my simulation which runs much slower or is that a bad idea?
Overall their Update looks something like:
void Update(){
if (gameDate.MonthJustEnded &&
MonthlyCalculationsNotDone(gameDate.lastMonth)){
MonthlyCalculations(); //Economy stuff
}
//Progress moving units and such.
}
If basically everything runs at the same timestep, I'd probably use an entity for that. This will take a moment to write down, please bear with me...
ah nice, do they actually have devlogs?
it would be interesting, allthough they seem not to be to bothered with performance π
PDX? yeah, but not that technical. Just google <PDX game> dev diaries
ah yes I read a few dev diaries but they where always more aimed at the players
but it seems that you think that a second World is a bad idea?
Well, I haven't touched worlds at all, but if (and it's a big if) putting the stuff in a separate world means you can simulate it separately from your rendering, then it sounds like it could be worth it.
As with all things optimization, I'd say don't bother with it at this point. Instead make something that works, and if you see that you get lagspikes, look at options and see which one is best
Rules of optimization:
#1 - Don't
#2 - If you have to, profile first
#3 - Go for low-hanging fruit
π haha ok thanks
yeah I have big problems with not overthinking stuff
@tawdry tree when you said "use an entity" you just meant that I should either emit an entity when making a time step or update an entity with a "CurrentTimeStep{ int value }" component?
the second one is what I was originally planning if not using a second world
Use an entity that holds this (and possibly other gamestate stuff).
Almost done writing...
ah you are doing an example? That is very nice of you, thanks. No hurries
Okay, so exactly how you should do it has me scratching my head as I realize I really should play around more with ECS and get more used to it, but:
struct TimeStepInfo {
int CurrentTimeStep = 0;
bool UpdatedThisFrame = false;
}
Put ^ on a gamestate entity, or make a new one if none exist (a tag might be appropriate once multiple gamestate components are added, but if you only have this you don't need that)
public class TimeStepperSystem : ComponentSystem {
//Slightly dirty, but easiest way
private float _lastUpdatedTime = float.Negativeinfinity;
private const float _timeStepInterval = 1f; //1 second
struct TimeStepperJob : IJob<TimeStep> { //Nothing fancy
public float CurrentTime;
public void Execute(ref TimeStepInfo info){
info.UpdatedThisFrame = false;
if (CurrentTime - _lastUpdatedTime < _timeStepInterval){
return; //Not time for a new step
} //Implied else
info.CurrentTimeStep++;
info.UpdatedThisFrame = true;
}
}
protected override void OnUpdate(JobHandle inputdeps){
var job = new TimeStepperJob {
CurrentTime = Time.time;
};
return job.Schedule(this, inputDeps);
}
}
This would need to run before everyhting that uses the timestep, so make sure it is a dependency and you .Complete() it.
Then, for everything that depends on the timestep, just check UpdatedThisFrame, and you can have stuff run less often by checking against CurrentTimeStep(for example if 1 step = 1 day, you could run something ever 10 days)
Also, haven't actually touched ECS in a long while, so parts might not be valid ECS code, but I hope I at least convey my intentions here
hmm getting strange hiccups when unparenting stuff, should I not be doing this? sigh wish there wasnt so much boilerplate code to write for doing simple stuff
@tawdry tree thanks very much. The bool is a good idea. I thought about all systems having a last_updated member instead and checking it against CurrentTimeStep but I guess I could just make that check in the time system as you did
but does it need to be a job system? I mean it does something very simple on one entity, I guess the overhead of creating a job could be bigger than the benefit of that bit of code running in parallel with other systems
The key part is that you need the TimeStep to be synchronized between all systems that use it, so if you think you have an easier way, go right ahead.
And in this case all systems that update every timestep would update whenever UpdatedThisFrame is true, while systems that runs every X timesteps would have a lastUpdatedTimestep variable. For example, maybe you want to have the season change every 50 steps, then the relevant system could have a lastUpdatedTimestep, and when UpdatedThisFrame == true && CurrentTimestep - lastUpdatedTimestep >= 50 then it runs. Or just use modulo, I guess (run when (CurrentTimestep - lastUpdatedTimeste)%50==0)
@tawdry tree yes I understand the idea. Thank you for taking the time to write it down π
Can someone please point me in the right direction to understanding IRecieveEntity and the EntitySender?
Or rather, I don't understand what it's for.
wouldn't worry about it since it's specific to the physics samples (though you may find it to be a useful pattern). if you open up the immediate mode demo ( https://github.com/Unity-Technologies/EntityComponentSystemSamples/tree/master/UnityPhysicsExamples/Assets/Demos/6. Use Cases/ImmediateMode ) and look at the "Balls/Ball.White" GameObject, you can see it has an Entity Sender script attached, and specifies the "Trails" GO as a recipient. what this means is that when the white ball is converted from a GameObject to an Entity, any IReceiveEntity components on Trails will be given the white ball entity as it's converted (so it can be used in the logic of the receive scripts attached to Trails)
I assume calling SampleHeight on a terrain object is a no no inside a Job?
trying to figure out a way to thread a bunch of SampleHeight calls
suppose I could just do raycasts inside the job
@manic aurora when you word it that way, it makes a lot of sense. Thank you!
Even so. I can't seem to really see the value in it beyond maybe helping it interact with classic Unity stuff like DrawGizmos(). Or maybe that is just what it's for.
yeah i did something similar to the pool sample and just didn't find it necessary
does unity ever plan to phase out the game object model? or will it just coexist with ecs in the long term
coexist. i assume if in 10 years down the line nobody is using gameobjects they might do away with it, but its still their bread and butter
kinda what i figured. would probably alienate a lot of developers by deprecating GO. but they like to tout their goal of "performance by default", so i had to wonder if eventually "ecs == default"? haha
who knows, that roadmap was super vague. i was kinda disappointed they werent going have an official system for animation shader instancing when they answered one guy's question about the nordeus demo
I think it would be worth talking to unity staff about an official instanced animation shader in shadergraph. if it can't do it, that is. I think it can, so really the question is: creating the texture
it's just offsetting verts based on a texture you read
the tooling is a boring pain
yeah, what i wouldn't give for a roadmap with a detailed breakdown. but i assume that document doesn't exist, and they just have some high level goals and are winging it / doing things as they come up. it sucks from our perspective, though. feels like progress kinda trickles in (i've been following since ~preview13), confirmed reported bugs sitting in limbo, questions about basic (to the user) things like "do we allow generic component types" are still on the table.
i know there's all kinds of work going on behind the scenes (see, Unity.Physics showing up out of nowhere), but when i bought into the hype a year ago, i envisioned being in a more mature state today, haha.
hm, i'm most excited for the gains this will bring unity engine
unity's able to optimise over it's own implementations currently
don't get me wrong, i'm as excited to write performant game code in mostly regular c# as the next guy. just be nice to know what to expect. seems like the small ecs developer community is a pretty driven group of people, we could be writing plugins to fill in the gaps if we knew where they'd eventually be. plenty of times i've had a moment of "do i write this, or wait for it to get released?" (see: my half finished SAT solver i started a week before Physics appeared from nowhere)
hm I never even thought about shadergraph. time to do some research
Ummm. Isnt there already unity demo that does bake the animation data like that?
I mean:
https://blogs.unity3d.com/2018/04/16/animation-instancing-instancing-for-skinnedmeshrenderer/
https://github.com/Unity-Technologies/Animation-Instancing
As developers, weβre always aware of performance, both in terms of CPU and GPU. Maintaining good performance gets more challenging as scenes get larger and...
@safe lintel
oh right, this still requires skinned mesh renderer which we don't have in ECS
do I need m_EntityCommandBufferSystem.AddJobHandleForProducer(job);? I do not want unity to wait until my systems complete but that command would force it to wait.
Ifyou are using a command buffer, you need to inform it of your job
other wise it will not function as intended
I still wonder why the ConvertToEntity doesn't set the old gameobject name by default as the old scene conversion tool did it
oh, it does have it, ConvertToEntity just set the ConversionFlags to 0 which prevents the entity naming automatically
so, swapping the relevant line to: ```cs
var gameObjectWorld = GameObjectConversionUtility.CreateConversionWorld(World.Active, default(Hash128), GameObjectConversionUtility.ConversionFlags.AssignName);
im confused why some of the demos use both ConvertToEntity and the old GameObjectEntity. i think even the megacity does this in places
@solar ridge so basically when I use a commandbuffer I have to finish all my work in the same frame? No way around this?
Commandbuffers are specifically to get more perf while doing, well, commands, by collecting all commands (changes) and applying them together, at the end. I don't think it would make sense to have it cross frames, though if you need to do that you could just not use it.
you mean by manually implementing the functionality myself?
have a second system do the adding of the components on the mainframe
No, I mean by just making the changes without the buffer
then I would have to give up on the jobsystem
That would also load the work onto the main thread as I understand it
hmm ok maybe I could add all the components beforehand and just modify in that system
Are you sure you specifically need commandbuffers?
Ask yourself: What do commandbuffers do that you need to do? Can you do that any other ways?
Because I've never used those, so take what I say with a pile of salt
@safe lintel physics examples do this as well.. in those Unity uses GameObjectEntity for things that exist on both worlds and ConvertToEntity for things that are fully converted to ECS but they still sync transforms with those using those custom EntitySender and EntityTracker scripts
for example the vehicle sample puts physic body and colliders with ConvertToEntity (this has sender + tracker additionally to sync the RB position on GO side). then they also have raycasting and vehicle forces done using GameObjectEntity
it's kinda weird mix tbh, they could had done that fully on ECS side
but I think they wanted to demonstrate the hybrid approach on physics
yeah its just a strange lack of coherency
I do like the sample tho as it shows many different approaches in one to sync the data around
Is Allocator.Persistent is correct way of allocating memory to Nativelist because I am getting index out of range error when I try to use Nativelist.Add() function .
@neat magnet only if you plan to make persistent array and not some array for job temporarily
error on add sounds like you haven't initialized the the array but actually error message would help more
@dull valley I did initialize list and it works but once range goes above 100 it start giving error like index is out of length. when I try to use Nativelist.Add
I am initialize in start like this
nativelist = new nativelist<int>(Allocator.Persistent)
Anyone able to use a UdpNetworkDriver.Concurrent driver in a [BurstCompile] job? getting: Unexpected exception Burst.Compiler.IL.CompilerException: Error while verifying module: Call parameter type does not match function signature!
@neat magnet it should work, but if you would post exact code and error messages it is easier to understand
@junior fjord I fixed it for now by changing it to nativearray, I will upgrade to 19.1 soon so I can allocate from job
can anyone point me to an example showing how to instantiate new renderable entities via pure ecs?
just started looking at this yesterday, but still can't figure it out. do game objects need to get involved...?
well, at its most basic, you need to create an entity with these components: RenderMesh, Translation, Rotation, NonUniformScale, LocalToWorld. the render system will pick up and display that entity.
you may not want to add those components in your code directly, though. recently ECS has added a "ConvertToEntity" workflow that will take a game object in a scene, and convert it to the ECS equivalent at startup. assuming you have a regular GO set up for rendering, you can just add the ConvertToEntity component/script to it and it'll get converted into a usable state. i highly recommend you look at the examples here ( https://forum.unity.com/threads/new-subscene-converttoentity-workflows.638785/ ). actually open them up and look at how they use ConvertToEntity, it's probably the most frictionless way of getting something renderable
is there a performance penalty for using this ConvertToEntity method?
well it only does anything at startup, after that it's as if you created the entity manually.
oh sweet
if you create a primative(capsule etc) and add convert to entity with destroy, you can view that entity in the entity debugger and see exacvtly which components get added from the conversion process
make sure to check the pinned message here for good stuff to read through!
well got thing appearing and moving now heh. Feel like I have to relearn even basics now.
using the mathematics class, how can I get a float3 direction from a quaternion, assuming i want to rotate around some forward direction.
vel.Value = rot.Value * new float3(0, 0, 1); It seems I cannot multiply a quaternion by a float3 like you could with Quaternion and Vector3....?
ah it's explicit in the mathemathics class I think, via mul
no more operator overrides or something I guess heh
there is also the possibility to make your own render system and make batched draw calls and maybe alter the properties per instance by passing a material property block
the quaternion class has a EulerXYZ function
maybe you can use it and pass a float3 to get your rotation from a float3
quaternion also has a mult function
so I guess multiplication could be:
quaternion.mult(yourQuaternion, yourFloat3)
you could look into the classes and check if there are suitable functions for your needs
https://github.com/Unity-Technologies/Unity.Mathematics/blob/master/src/Unity.Mathematics/quaternion.cs
if it is not there, try to look up the mathematical implementation of the method you want to use and implement it yourself
I might just be missing something obvious in the documentation, but how would I do something like PhysicsWorld.ApplyImpulse() in a job? Trying to access the RigidBodies Native Slice makes Unity yell at me.
if you figure it out do share, ive just been adjusting the velocity manually but it feels wrong
Lemme tinker with this some more. It seems to have something to do with the order the systems execute.
Anyone getting InvalidOperationExceptions thrown from TypeManager.ClearStaticTypeLookup after updating to preview 30?
You'd need to have either generic IComponentData structs or IComponentData structs nested inside of a generic component system
What will be more beneficial multiple nativearray with character info like position, rotation etc. Or single array of character struct with its all relevant information
anyone got a favourite way to getting random values inside ecs jobs?
is mathematics.Random thread safe?
the values I am seeing are not random lol
most random implementations take seed input for making it more random
https://docs.unity3d.com/Packages/com.unity.mathematics@0.0/api/Unity.Mathematics.Random.html#constructors shows it does input seed as uint
just put anything that changes there, like current milliseconds etc
@minor sapphire
thanks, i ended up using the index of the entity as the seed with a random offset passed in from system update
@minor sapphire the values are never really, random. And do not use a seed everytime you call rng, that will not give you actual random values. You seed it one time you start your job and afterwards just reause the same rng
I actually only seed once per system, each system has its own rng
@neat magnet that is the struct of arrays versus array of structs question, you can google that and find some input. In general struct of array is preffered since it keeps data together that is used together (all rotations together, all positions together etc.). But actually when you use an ECS, you should just have position, rotation, etc components and that will in term be handled by unity like struct of array underneath
@junior fjord my first instinct was just that, to have the system have it's on instance of Random, and for that instance to be passed into jobs
but, is it thread safe?
it didn't result in randomness as I expected...
so random number generators work this way: they give you a long sequence of numbers which have the right properties (for example if they are random from [0,1] then 1/10th of them is in [0,0.1], 1/10th of them is in [0.1, 0.2] , etc.) and are as unpredictable as possible
but they need some kind of starting value to let this random sequence start somewhere
yep I'm aware of this much
because there is no true randomness in the computer. they could always give you the same sequence but that is not what you want
so you input them one number (the seed) which is their "randomness" for the start of the sequence
with the same seed you always get the same long sequence
yeah I know
but seeding it every time will always just give you the first same number of different sequences
and these numbers do not need to have the right properties
I'm using different seeds based on entity id and time
yes but you should never seed it every time you get a random number
actually the rule of thumb is to use as few different seeds as possible
I'd like to seed it once in the system, and have all threads pull random.next
but
that is what I do
I think so, as it is in Unity.Mathematics
yeah that would be helpful
I'm assuming you just pass in the instance of Random to the job
this is much less random now though hmm
yes
their spawn positions are meant to be random horizontally
@minor sapphire https://pastebin.com/xViwxD5W
I do not really understand what is going on on your picture
just basically it's evidence it's not random. the green and red bits should be horizontally uniform
your code is cut short a little
did you only initialize it once in the onCreate of the system?
but I assume on the next line you are passing in the rng from the system
yes I edited it
yes, I'll paste my code too
now its the full code, dunno what happened there
hmm that looks pretty good to me
the commented bits were how I was doing it before
and you say it behaves different when you initialize a random every time?
and it resulted in this:
I have no idea why the top spawning is more uniform than the bottom spawner though
the green and red dots still look different though to my eyes
the first one is actually how you should do it, the only thing I could imagine is someting with threads as you said
I'm gonna try generating a bunch of values in the system and passing them into the job to see the difference, but I prefer not to take that method
maybe post that to the forums? I would also be very interested
yeah, I'm just thinking maybe it's not thread safe
I always thought Unity.Mathematics is thread safe but checking there github page it actually did not specify that
did you try changing the seed in the first example?
I mean with a very low probability your sample looks exactly like what you posted allthough I don't think that π
I'll try changing the seed good idea to test
in case you go to the forum please send me a link, I am very interested in the answer too
you normally get pretty good and fast answers on the forum
changing seed didn't help
does it look exactly the same or different and still bad?
Looks like I'm not the only one thinking about it
https://forum.unity.com/threads/efficient-random-values-in-job.565651/
I'll do a bit more reading
hmm but his suggestions are kind of weird I'd say
an rng for every random entity seems like a very complicated thing to manage and an rng for the whole game would be nice but also hard to manage. Isn't an rng per random system pretty much the obvious solution?
I really don't want to generate a list of random numbers in the system heh
yeah, just in highly parallel jobs... thread safety would theoretically slow it down so maybe they didn't want to go that route
I have actually wondered if unity does set parallel execution of the same job or only different jobs
I think it's the same job due to the whole dependency chain
Oh god this guy ended up using lists of pregenerated random numbers
https://forum.unity.com/threads/mathematics-random-with-in-ijobprocesscomponentdata.598192/
but yes if the same job runs parallel and they have to lock the internal state of the rng that could slow things down.
Another idea would be to do chunk iteration and initialize one random thing per chunk, that you at least pull more than one value from each rng