#archived-dots
1 messages ยท Page 228 of 1
I think the physics shape conversion system adds a CompositeScale component to the target entity
As far as normalizing a gameobject's scale, I dunno. If I ever needed that it was only in terms of the mesh, so then I went into Blender and scaled it and exported it so it would be the size I wanted in Unity with a scale of 1,1,1. If you want the apply the scale to more than that then I'd need to know more details
I know about Blender, but its a super hassle.
Should be a single button in Unity
Ty for the composite scale. I'll look
Is there an IJob type with TransformAccess that will execute on a worker thread in the order the transforms are added to the TransformAccessArray? I want to get some transform update logic off the main thread but the transforms are in a hierarchy and need to be updated in a specific order.
Possibly an option is - scale your object how you like, then make it a child of a new object which has same global pos/rot but 1/1/1 scale.. so that the child is scaled but you only reference the parent
actually, looks like there's a Child dynamic buffer component too... not sure what the difference is, but it seems likely that this is what you actually want. It's inside the Unity.Transforms namespace, Parent.cs.
Yeah i think those are accessible the only issue is it's really difficult to know which entity is which when you have children of children etc.. I've ended up using Timboc's suggestion:
So basically i add an ICD to the root of the prefab with a public Entity myTargetObject field
drag my child gameobject onto that and it becomes referenceable at runtime
oh nice!
Turned out it was because I was setting the velocity directly of drones instead of adding a force aka acceleration. I am able to use: ApplyLinearImpulse in a Systembase, but cannot figure out how to use it in monoBehavior. My monoBehavior for setting PhysicsVelocity just uses SetComponentData.
Anyone know how to add acceleration to an entity via monobehavior script?
Maybe I am trying to get too eloquent. I'll just slap an ECS component on it.
Yes - don't use a monobehaviour script ๐
Well I know its funny
But...
The proper design pattern is to never reuse a function
So when everyone has their old player controlers in their game they've worked on for years.
And they want DOTS levels
The best way is to have all the enemies enviro be dots
and the player to still be controlled by same script, with a few if statements to see what mode you in
It's pretty awesome, high level design pattern stuff, not sure others know about this.
I'm not above making a hacking system along side it, I know the devs are doing what they can, but I'm going to do an extensive tutorial when I'm done with my game(very soon!) on how everyone can use DOTS/ECS easy and even in their existing games.
If you make two playerController scripts... It is bad:
then every time you update one, you update the other, cumbersome and bug ridden. I want to teach everyone how to do this the best and most eloquent way possible.
This is kinda cool now that I have force based thrust, collisions handle better, but more needs to be done: https://youtu.be/tJ30xXE43Aw
Would you like to know more? http://www.youtube.com/c/goodnewsjim
You can also come to like the only positive zone of the Internet I know: www.twitch.tv/VGMCrazyJim The Bro Zone Layer. (temp)
The #1 video gamer who ever lived with proof! I just missed tourneys due to life problems(college for Starcraft thinking my email invite to Korea was a ...
How do you get System.DateTime.UtcNow in burst? I tried a singleton in a monobehavior that stores it every update. When I access that in .burst, super slowdown.
If you slerp a rotation to lookat, that's fine,but you want 4 seconds after a collision for it to tumble, so you need time
I'm probably missing a core concept of accessibility of variable scope. I've known about multithreads since the 90s, and know of race/memory corruption if done wrong... I know why you'd want to protect variables. I just ain't sure exactly some of the finer points of UNITY's implementation.
DateTime appears to be a struct with only blittable members, so that's likely not the issue. it could be an issue based on how you access it. if you're trying to retrieve it from the singleton while inside the job, that's an issue. you should be passing it into the job when creating + scheduling it
i'd still try to pass in just the values that you need though, to eliminate any possible issues with DateTime
Ty Ryan!
That's what I figured
Also accessing SIngleton Monobahavior statics from outside the job is bad for performance too right?
Whoa, found and fixed bug was weird... Was giving an Error of System.DateTime, and I assumed it was in the Jobs and SystemBases I was editing, nah in code I wrote weeks ago in an IComponentData I was reading in. No line numbers or file names on error message: https://youtu.be/DsUxuHb-fL0
It was complaining about System.DateTime, which I assumed was in my Jobs ObsticleHitSystem, no, it was some very old IComponentData I was reading in a SystemBase. No line numbers on error means headache. But we got through it!
Would you like to know more? http://www.youtube.com/c/goodnewsjim
You can also come to like the only positive zone ...
I'm still not able to change an IComponentData in a Jobs Execute tho. I need to set the time that the collision happened. I do not know how.
Fixed in 0.20.X
https://issuetracker.unity3d.com/issues/when-exiting-playmode-blobs-leak-memory
๐ฅณ
It seems like BlobAssets converted in subscene memory are never released after exiting playmode. Slack: https://unity.slack.com/arch...
it's entirely not supported. accessing any object not passed directly into the job causes the job to run on the main thread
oh wait
i misread
accessing monobehaviour statics outside of the job should be fine
Little question, How would I convert Vector3 array to float3 array, and Colors array into float4 ? Ofc i could write for loop, but is there some dedicated method ?
I missed a word "array" in your question. I think there is 2 possible ways: use regular loop to fill float3[] with values from Vector3[] OR try to use NativeArray.Reinterpret<T>. You can also dig down to source code of Reinterpret method and write your own low level extension.
positions = new NativeArray<float3>(mf.mesh.vertices.Length,Allocator.Persistent);
colors = new NativeArray<float4>(mf.mesh.colors.Length,Allocator.Persistent);
positions.Reinterpret<Vector3>().CopyFrom(mf.mesh.vertices);
colors.Reinterpret<Color>().CopyFrom(mf.mesh.colors);
It works, thanks
Is there an easy/shortcut way to take the float3 position from a LocalToWorld 4x4 matrix?
current way is:
float4 pos4 = GetComponent<LocalToWorld>(myEntity).Value.c3;
float3 pos = new float3(pos4[0],pos4[1],pos4[2]);
my target object is a child, so Translation isn't helpful as it only seems to reflect local position
ltw.Position
Damnit why didn't i see this! Thanks haha!
Careful relying on ltw.Position & ltw.Rotation - if you have any scaling, they're likely to be not what you expect/wrong
Ah ok i'll bear that in mind thanks
Hey guys I'm just starting with the job system (with regular code for now no dots yet) and i keep getting this error InvalidOperationException: M7.EntityData used in NativeArray<M7.EntityData> must be unmanaged (contain no managed types) and cannot itself be a native container type. I know it has to do with the types used in my EntityData struct... are Vector3 and Quaternion managed types?
Try with float3 and quaternion instead
will be Burst compatible ๐
Do you have a NativeArray inside a NativeArray ?
@karmic basin Mmm... not inside EntityData for sure
I'm a bit confused, I changed my vector3 to float3 and it still doesnt work
Are arrays allowed?
ok thanks
arrays are pretty much only allowed if you pin them and get a pointer
otherwise yeah use native containers
What's the best approach to look at or measure how long jobs are taking etc, performance measurements etc?
Using the Profiler
currently i can see the ms times of systems in the Systems tab
ah really!
If you scrolla little down you should see the worker threads
Yup Timeline view is your friend!
i thought there'd be an ECS specific way maybe hehe
going to bed, see ya
okay, yeah i'm quite familiar with Profiler for non ecs stuff - thanks!
Unity keeps crashing when i try to play with Deep Profile enabled in Profiler - does this happen with anyone else?
I don't think jobs are visible without Deep Profile
Ah i do see the systems in Hierarchy view.. i was expecting to see jobs in the modules/graph windows
Can you change an Entity's name?
Forums are saying you can't. So how do you search for an Entity who's data has changed in Entity console debugger?
I'll try and only ask one more question today after this.
I have hundreds or thousands of entities with same name. When a rare random event happens, I want to see the data change to see if my code works. It would be trivial to change it's name, then search in ENTITY_CONSOLE_DEBUGGER by name, then see Inspector data.
I think if you search for a Component in the Entity list view it will show entities that have that component.. so maybe add a component only on the case of that rare event, even just for debug
A worekaround, I thought about that butw anted to make sure I wasn';t missing a way to change entityy Yah... or... having a global dummy entity you can change too
That way you never have to search non stop, just stay in the global dummy entity to see changes
It wouldn't be the first time someone said,"Unity made strange design choices on DOTS.", but were thankful there is anything at all.
I think they did a great job on making multithreaded sane
Whats funny is that I actually asked on /r/unity3d forums if there is a multi threaded library or if I had to write my own.
Cuz I was 100% going to sit down and write something.
I was right again on predicting big tech, like always, but to get it right on the same years, that even surprises me. Most of my ideas for big tech is like 5-20 yrs in future.
Last question for next 6 hours: How do I get component data from a job assuming I have an Enity reference like Entity entityA?
On the forums, everyone is asking this question with no answers, lol
I was able to set component data with an EntityCommandBuffer
But That is useless unless I have old data to modify
I can get components from Systembase and Monobehavior
I guess Jobs is the last frontier.
Sark says it is slow... hmmm
Maybe I want an actual component for almost every variable
Then I won';t have to read it in...
That'd be more in line with the deisgn
I'm just gonna trust that UNITY did proper memory arrays and hash tables n stuff that when I add dozens of components, no slowdown happens.
like this LocalToWorld targetTransform = GetComponent<LocalToWorld>(target.entity);
tyty
Severity Code Description Project File Line Suppression State
Error CS0103 The name 'GetComponent' does not exist in the current context Assembly-CSharp D:\unity\projectfiles\StarfighterGeneralOnSteam\Assets\Scripts\DOTS3\ObsticleHitSystem.cs 61 Active
Says Getcomponent doesn't exist in the current context
I don't need that question answered, I think it is better for DOTS to not grab it
what version of entities are you using?
Question I'd rather have answered, how do I get System.Date in a Job Execute?
I can't grab it directly
so I could set it in the Job globals, a singleton, etc
But I don't know how to break into any of those
.17.0-preview.42 Entities version
any data whether it's date, month, name, integer anything has to be made local in the Onupdate of where the job is
like you would any other variable ๐
Like the system is outside the class
JobComponentSystem is old I don't mess with them anymore
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I want a variable from onUpdate to be accessed by Execute. Not sure how.
In the above code, I'm trying to link long rightNow; [ Millseconds since 1970 epoc], from Update() to Execute()[when a job collision occurs]
Ok, I need both variables to be static
And it works
I hate monkeying with code, but sometimes you gotta if docs n stuff are poor
Here's the working code for collision(has custom components, but you can edit em out) https://pastebin.com/SqmZrywN
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Declare your variable as a public property of your Job struct. Then on update of the system, pass the variable to the Job when you Schedule
I had that already
What I was missing is that my data variable in Job Execute Struct was not static
where my global for class was
So when I made em both static, it was ok
Ty Mr. K tho, all you guys super helping
I ain't lying when I say if I make it big, which is a decent chance, and you track me down, I hook you up in person with the manilla.
Uhm shouldn't have to make it a static
Here ```cs
inputDeps = new CollisionJob()
{
soldierComponentData = GetComponentDataFromEntity<MovementDataEntity>(true),
ed= GetComponentDataFromEntity<EntityData>(true),
//obstacleComponentData = GetComponentDataFromEntity<ObstacleTag>(true),
commandBuffer = _endSimEntityCommandBufferSystem.CreateCommandBuffer(),
// Here you miss a line like this:
rightNow = rightNow2
}.Schedule(_stepPhysicsWorldSystem.Simulation, ref _buildPhysicsWorldSystem.PhysicsWorld, inputDeps);
Based on your rightNow and rightNow2 variables
oh good then ๐
And I am not in game making for money, just to help people and make em happy, so like if you guys ever track me down, I manilla all you helpers.
I lagged behind, time to read all the stuff ๐
Please do not come at me weaponized ๐
I got you man
You're too busy helping. You don't have time to read! Mr. Jesse Ventura K.
Totally true I should get back to work
ya, amen
The worst is the hate bots, when they twist what you say. Normal social media is dead
You can't get the voice out, it gets twisted, and censored.
Its alot like preinternet days now
Lets work
God bless. May God help all you guys make cool games.
It is? What's the new expectation?
No more input deps though? So that's just all done from the underlying job scheduling?
you can do it manually if you want but yeah its auto handled mostly
Good to know. Thanks! How does one even keep up with all these changes? Is there somewhere they document the new expected uses? Or is it just "just keep following the example git"
that link I posted you can view the changelog on there, and they update the docs sometimes
Appreciate the info.
It's basically identical except InputDeps was replaced with the Dependency property
Works the exact same way except you assign to Dependency instead of returning inputdeps
I think probs the easiest way to keep up is inside package manager, when you click on a package theres links to docs and changelogs for each package version
Some fairly obvious high level stuff I feel still needs docs or explanations, such as when you create a GetEntityQuery and use it to fill an array like with ToComponentDataArray, when does that query get filled is it a job that's run internally or what.. some things are a little confusing
you can find quicklinks here too ๐
Ahhhh got it. I didn't even know that existed.
I've got one of those new guy questions your afraid to ask...: With the job system, when passing data to a new job, should I pass it multiple NativeArrays for eanch value (ie.: pos, rot, scale, etc) or should I pass in a native array of a Struct containing multiple values? i.e. : public struct MyStruct{ Vector3 pos; Vector3 rot; Vector3 scale; }
?
You can do that, or just pass in a float3x3 matrix
FYI I just use the job system no DOTS
Man you are awesome, that was my next question hahaha
So there is no performance difference between the two? The whole data still gets cached by the cpu?
Depends, the CPU cache isn't exclusively used by your game, it's a shared resource. So if it can attempt to utilize your CPU cache, then sure your data will be copied into your L1/L2/L3 cache depending on available size
And if I may ask another easy one: When I pass a NativeArray to the job (when creating it) does it "copy" the data in the the job's internal native array?
I remember reading something about a poointer but im not 100%
No native arrays are structs that point to a block of memory
so you just copy the address, not a deep copy of the data
Oh ok so its kinda like a ref but to a memory address?
yea pretty much like a ref
ok so there is no perf lost feeding in values to or taking values from the job
thats great... you have no idea how lost I was hahaha
Thank you so much!
Yo is dots cross platform deterministic or no?
@raw shadow did you read this? https://forum.unity.com/threads/what-is-the-current-state-of-the-cross-platform-determinism-of-unity-physics.918878/
Or rather, does that help?
Yep
Did anyone here try the latest 2020.3 version out yet?
I remember seeing a DOTS forum post about something being broken in 2020.3.16 but I'm not sure anymore
@north bay Google has a lot of hits on "broken 2020" but nothing specific to 2020.3.16. Usually whatever breaks if it's not in the official notes it's an edge case so my experience may not be your experience. Your best bet is always to test it on a copy of your project. I learned to do this the hard way. I do this for every major version changes, for point upgrades I don't bother, I'ts easy to revert, I use Plastic SCM.
Yee just wondering if something major showed up like some obvious incompatibility before I go on idle for 2 hours
FYI I had no problem with that version but I havent done much in it either.
If you checked the forums for something that would affect you I dont think there will be any trouble
the only t hing I seeis https://forum.unity.com/threads/input-getkey-regression-in-2020-3-16.1156397/
I normally just look for DOTS specific stuff, all other engine issues are normally fixed quickly ๐
Thanks for the responses, I'll try to update and see what happens ๐คทโโ๏ธ
I'm on 2021.1.x and it seems to work, although I'm not using things like Physics/Hybrid Renderer
I honestly tried updating to 2022.1.a the other day and dots still seemed to work too. Can't vouch for Physics/Hybrid renderer, but transport layer seemed to work also
Job system question: When setting a new job's data ie.: NativeArray<Vector3>, since it's set using a memory pointer this means if I modify the array within the job, similar to a ref the value gets changed outside of the job too right? (in the NativeArray I feed it)
Oh really?
And I get my data out using a [WriteOnly] nativearray as the output? I can allocate it as temp in the job but could I also create an "output" NativeArray as persistent outside the job, assign it to the internal [WriteOnly] native array when creating the job and get the data just by writting to it inside the job?
Yea
Awesome thank you!
i saw Entities.WithName().ForEach being used somewhere but i can't find out any information on how it's used exactly..
assuming it should use the specified name for the job in Profiler or something?
or do i have this totally wrong it's actually filtering the Entities query by name
this, just for debugging/profiling purpose
yeah how do i use it?
i have three jobs running inside a system and trying to find which one is causing slowdown
Entities.WithName("HowYouWantToCallTheGeneratedJob").ForEach( /* as usual */ ).Schedule();
yeah i got that far ๐ where do the job names show up though i can't see any in the profiler etc..
strange i'm not seeing them at all, just seeing the system name in the Main Thread
does anyone know what the ColliderKey is in a RaycastHit is?
it's used to identify a specific part in a compound collider.
I'm not sure but I think it would default to zero if it's just a single collider shape.
So thanks to you guys, I have drone way points in and it is cool! https://youtu.be/d7TiaferQRw My next question is: Wait what was I going to ask?
Would you like to know more? http://www.youtube.com/c/goodnewsjim
You can also come to like the only positive zone of the Internet I know: www.twitch.tv/VGMCrazyJim The Bro Zone Layer. (temp)
The #1 video gamer who ever lived with proof! I just missed tourneys due to life problems(college for Starcraft thinking my email invite to Korea was a ...
Ok, none of you could answer what question I was gonna ask? I had to google that. Google said my question was,"Can we only send up to 9 components in a for each?"
I need to add more data in my program
and I want to add a new component
but if I can't
I need to make memory management strategies to overlap data stored into less components
Nothing major, just need a lil guidence
I have my MOBA out tonight or tomorrow
Likely tonight
Then MMORPG less than a week from that!
Is MOBA a game you're working on?
I made it in DOTS years ago
took me 2 weeks after learning rollaball tutorial
10v10 MOBA, but couldn't find testers, so I kept making different things to attrract userbase
now I am finishing a MMORPG
But realized the MOBA would be one of many space dungeons
and i need that tech to make MMORPG engine
So Moba today, MMORPG tomorrow
I got another fun video in a few sec afteryoutube proceesceeds it
Would you like to know more? http://www.youtube.com/c/goodnewsjim
You can also come to like the only positive zone of the Internet I know: www.twitch.tv/VGMCrazyJim The Bro Zone Layer. (temp)
The #1 video gamer who ever lived with proof! I just missed tourneys due to life problems(college for Starcraft thinking my email invite to Korea was a ...
Now with new networking, it is infinite vs infinite players same zone
Good thing dots came along to help with more things on screen
That video isn't just fun to look at, I actually make some jokes, so I'm not sure if it is better or worse.
Anyway, I bring entertainment in hopes someone answers my .foreach question: We limited to 9 components? Can we get more components some other way? Or do we need to stuff components with data that belong in multiple components?
Come back in January :P
Dunno but they said compatibility with editor versions past 2020.3 will last to at least end of the year
My sentence makes no sense but you get it
I'm on the phone
Anyway I expect everything to stay stalled at least 'till january
But who knows ๐คทโโ๏ธ only Unity employees
JohnOT, what you need to remember is this cutting edge technology only works on older versions of UNITY
lol
hold still, this week I unlock the key to enlightenment in DOTS ECS on youtube
even take your old game and say,"Game, B ECS"
and Game will be like,"I don't want to, but okay." Then later game will be like,"Hey, this is great. Glad I thought of it."
Check my youtube by this friday
youtube.com/c/goodnewsjim I promise I'll get you a tutorial or your money back
They told many times they want to streamline the workflow, so we're sure they're concerned about it. But man it sure take a looong time
I'm off, see ya guys ๐
JohnOT it is simple
but you gotta be in the know
I am gonna make a tutorial this week, you'll LOOOOOVE It
I already helped a dude weeks back and he loved it. I have a download if you want to try raw
Well that was a year ago
I'm a forerunner now man
I have 150,000 hours gaming,coding, design
I'm like beyond a rockstar for general programming
Just cuz you ask questions, even very easy questions, doesn't mean you're a nub. Hell, Einstein didn't even know how many feet were in a mile.
Anyway I wrote that 4wumbla for a guy months ago who requested personal help. Its a raw and basic project
I didn't come to boast, but to say I'm not a noob that could help you, but I do have signed cards, where do I mail em? ๐
CrazyJim ex #1 Starcraft,War3,D2, C&C3, SC2 2v2, etc: https://crystalfighter.com/achieve/starcraft/achieve.html
Been #1 world every online video game I played, just missed tourneys, lol
I got proof if you come to stream, Soul gamer since 1980.
But if you don't want my help, you know, you can figure it out right?
And I didn't make myself great, it was the God of Love who binds the universe together so we can achieve peace through Jesus.
I don't boast of myself, but my Creator.
Hello everyone, I'm trying to get advantage of Jobs system, but seems like I'm missing some key parts, is there anybody experienced in that?
It's clear that only struct are valid for jobs, but what if I have tree data structure, where each node has an array of it's children?
structs that contain pointers or you turn your tree structure into a native array
or any other feasible NativeContainer
Struct can't contain pointer (unless it's unsafe code)
if you're comfy with writing unsafe code, yea you can pass it into a job
Do you think it worth it? Maybe there is a more elegant solution?
you can try to transform your tree structure into another data structure that's supported out of the box
So.. Like flat list of elements and another one map with index => array of children indexes ?
sure, whichever works for how you want to set up your tree
You can also take a look at FixedList in the collections package if you can utilize that
Alright, I'm going to test right on, thanks a lot!
Anybody any idea what EntityCommandBufferManagedComponentExtensions is
Based on the naming, a bunch of methods so ECB's can work with managed components
๐
Hehe yeah, just trying to figure stuff out
so i guess it's used internally when using for example ecb.AddComponent to add a managed IComponentData to an entity
Yep
Hello, quick question about design. I'm making a factory game where each building is an entity. I need to make a storage container which has a set number of item slots, let's say 64. Each slot of the container is represented by a 16 bit integer for the item ID and an 16 bit integer for the number of items in the stack. That's a total of 256 bytes. From what I understand, this is rather large for a component and could result in worse performance. Is there another approach I can take that avoids using large components?
I assume you're putting this in a dynamic buffer?
If you're concerned about archetype size you can just add a [InternalBufferCapacity(0)] to the IBufferElementData struct to make the buffer live outside the chunk
Alternatively if you want to live in the chunk for performance, you should optimize it with [InternalBufferCapacity(64)] as you know the exact size the buffer needs to be
<@&502884371011731486> seems like message above is advertising of financial fraud
!ban 380690564036689920 Scam
Baianoloko#2692 was banned
Not sure if it's relevant to your case and i haven't looked at or tried this myself but i saw this method of using blob assets for data storage:
https://www.youtube.com/watch?v=PeTcIzoaTEA
๐ Download the full project files: https://tmg.dev/BlobAssets ๐
๐จโ๐ป Code/Scripts from this video: https://tmg.dev/BlobAssets-Code ๐จโ๐ป
๐ฌ Come chat with other DOTS/ECS devs: https://tmg.dev/Discord ๐ฌ
๐ง Resources Mentioned ๐ง
- Code Monkey video on Blob Assets: https://youtu.be/7_rZhp6V8ds
- My Singletons in ECS video: https://youtu.be/oSj6w8AeeAg
...
I guess not actually as this is generally for data that does not change or update throughout your game.
I just noticed that the player.log for my built project is not showing full GPU vram whereas editor.log is showing the correct amount:
Anybody noticed this?
x64 in editor and you're prob building x86
That's true yep.. i never thought of that, so an x86 build doesn't give access to full VRAM?
depends on graphics api and how unity implemented it but i guess not
I'm trying to wrap my head around hybrid approach. I am using Convert and Inject Game Object conversion since I am using standard rendering and some monobehaviours for visuals. Will I be able to avoid runtime conversion If I save it as a subscene (Subscene = Entity Prefab?) and instantiate from code?
What is standard rendering ? Built-in pipeline ?
Using subscenes will save you the conversion at runtime. It will do the conversion at editor time (when you close the subscene). What it does is serializing your entities to disk, this way the loading into memory will be faster
With subscenes you don't need the Convert&Stuff anymore, nor to instantiate
I've noticed that some of the code in Unity samples creates entities with empty component array like this:
Entity entity = entityManager.CreateEntity(new ComponentType[] {});
Does this avoid some default component creation or something?
no, just creates an entity without any components
so its just blank?
sure
so no difference to just Entity entity = entityManager.CreateEntity();
or perhaps that would throw some error, i've never actually tried, was just curious tbh
Supposed to work without parameters, I don't know why they do the line you shared ๐คทโโ๏ธ
Another stupid question but i rarely ever see this and have no idea what these curly braces do:
I guess it encapsulates the scope of the work being done..?
it's pretty much an explicit constructor
var vec = new Vector3 {
x = 0,
y = 1,
z = 2
}
yeah i use that convention often but this threw me off as Entity head; ends with the semicolon
oh
after Entity head; the curly braces introduce a local scope
similar to nesting functions
fair enough i guess
i guess if nothing else at least it can be collapsed in a code editor
i guess also it's actually useful for creating local variables and discarding them
like the CollisionFilter filter = is created/used within the braces for the head entity, but then it's created and used again for the torso entity a few lines down..
so it avoids having to track variables you've already declared previously
how would i go about implementing jobs into something that uses classes
rewrite your classes to be unmanaged structs
hi -- can you programatically spawn a prefab with authoring scripts inside a subscene (at runtime)? I have a problem with that
"within" a subscene doesn't make too much sense in that context. You can spawn an entity that has the parenting/hierarchical components that point to entities in a subscene, yes. But the subscene itself it just a file on disk. You can't load more things into that file. When you load the subscene into your world, it's not in a subscene, it's in your world. hopefully that helps heh
is there a way not to check for Physics while doing RaycastCommands, I know it could have old version of the world, but I am mainly targeting static geometry
@rotund token whats the difference between a struct and a unmanaged struct
just a struct with no managed components - the requirement for burst
by default structs can have managed fields, like List<T> etc but burst can't use this
Is there a reason why float3 result is empty when job is finished? debugging results[0] after the job is done gets me actual value.
Writing to NativeArray<float3> of size 1 does the job, but is it as fast as using just float3?
The only way to retrieve data from a job is via a native container. You can use NativeReference instead of nativearray for single values
thanks, will look into that
There's NativeReference<T> for this
It's because the struct is a value type
How do I copy a rotation of an entity to a gameobject? I see: CopyTransformToGameObjectSystem , but I see no example code online.
I can do it in mono, jobs, or systembase, doesn't matter. If there is a way to just change rotation, that is fine too.
This is how the system does it https://hatebin.com/qlprzonhcs
TransformAcces is a special component meant for doing a lot of tasks in parallel. If you want to do it for one object only I would write another system I guess.
The idea is to retrieve the rotation from the LTW and give it to the transform.rotation
of the gameobject
My question is a little more basic syntactically. I have an Entity and a GameObject reference How do I call it? I have not called Transform before in entities. To get a reference to a transform, is it like: transforms = GetComponentDataFromEntity<LocalToWorld>();
I think i'm getting it
The meat is:
bot deletes two lines of code
transform.position = value.Position;
transform.rotation = new quaternion(value.Value);
There, just need to post them dif lines
Thank you again Mr. K.
I was grabbing translation which also seems to have rot and pos
Instead of transform
Are there any docs for the Animation package i'm struggling to find anything
like anything, even a basic api reference with what's in the package
thanks!
They have samples. But yeah it lacks documentation.
I',m not even sure they have a graph based authoring tool ? Last time I checked it looked like it was only a coding API. Some people here (like thelebaron, don't want to tag him) might have fresher news
I'd look on the forums, or blog posts if you're lucky ๐
There is an Animation Graph under Window>Animation>Animation Graph but it only has access to two nodes, Animation Clip and Mixer..
I know there is also an NMixer node and possibly a bunch of others in the package but they don't seem to be exposed to the visual graph
I saw thelebarons posts about ragdolls i have to say i'm curious how he did that
i currently have skinned ECS characters animated using blended clips via unity.animation thanks to PhilSA's nice work on his Rival dots character controller package
i also have a basic dots ragdoll setup working
but i'm investigating how to possibly connect the two somehow
currently my ragdoll is literally just a collider/body setup and is not driving a skinned character at all
Oh didnt even see that
most of the nodes you need to make use of stuff are missing last I checked with the animation graph ui
to modify the skinning buffer you need to write to the AnimatedLocalToRoot buffer, by using the SkinnedMeshToRigIndexMapping
https://gist.github.com/thelebaron/6f83365e881aead5f2a3d7e6beefa09f is my system for doing that
@devout prairie
Ahhhhh thanks for sharing your work.. i was actually just re-reading the posts you had written about the ragdoll stuff, and also digging into some of the code inside the Animation package
I'll have a look through this shortly, looks really useful
Hmm this is very cool.. i'm wondering if it'd be possible to do something similar but feed the ragdoll translations into an animation graph and do the work there
bear in mind this is very abstract high level thinking at this point with very little frame of reference for whether such a thing is even remotely possible ๐
from what i understand, the animation clip and mixer nodes use a data stream called AnimationData
i wonder if it's possible in some way to feed translation data into this
what is required to convert a skinned mesh? I'm making a ragdoll, I attached physics bodies with colliders to bones in a subscene. The bones move, but the mesh is not deforming at all
i haven't got that far yet.. my ragdoll isn't attached to my rig/mesh.. i think thelebaron's code above can help but i'm not sure exactly what his gameobject hierarchy is yet
he sortof explains it here - https://forum.unity.com/threads/unity-ecs-physics-dots-animation-concept.1095292/
thanks. I'm also looking at the skinned mesh samples by Unity
pretty sure you could do it that way too, just get the buffer and read it and do the work in a node. personally easier for me to make sense of things in systems and jobs though
I'm reading. it seems complicated. I'd love to know if it is even worth it, if the skinning in DOTS is more performant than it is with hybrid approach
but for simple stuff like timing, ie make a character instantiate a bullet at a specified frame, there's nothing to handle animation events, and the cognitive load to continue to do everything in nodes is just too much. i think its probably better to wait for the next release which i assume will have a working visual graph that will greatly simplify things
@rugged grove set the AnimatedLocalToWorld(its a buffer of all the skinned joints that correspond to deforming a skinned entity) like I did in the gist
also have to remember unity physics either will merge a collider if static or unparent and disconnect everything if its dynamic and you have to manually manage the connections and disabling/enabling a kinematic or dynamic state or even disabled depending on how you want to do things
id ultimately say wait for the next version though as painful as waiting may be
yeah i think from what i can see also when creating and updating graphs there's some work on the main thread so it might not be any quicker either
I guess I'll just declare skinnedMesh as hybrid and just copy physics positions to the game object bones
thanks for the info
definitely complain on the forums though, try to get a response from the devs ๐
What is the best way to destroy an Entity after a set amount of milliseconds?
Google drawing a blank. Dots/ECS forums UNITy style drawing a blank
I see people with these atrocious update functions checking against the time every update
When a better solution would be to have one systemBase that hashes the destruction time
That way you have one check per cycle instead of hundreds or thousands.
Does Unity already have such a systembase already in? Probably not. I'll start system architecting it. Let me know if anyone knows if UNITY devs did it right already
So I want to start with one of those bad solutions... Except when I send simply one destroy message to an Entity Commnd Buffer, it starts giving errors: https://pastebin.com/DRcF3M75 in code: https://pastebin.com/5yj8vuGE. I think one of two things is going on: Either my .ForEach((Entity e, ref DOTS_DESTROY_AFTER_TIME dat) isn't getting a reference to the Entity e, or maybe I am not closing down my CommandBuffer correctly and it keeps getting called. I ecb.DestroyEntity(e) only one time, but errors keep happening, about the time to destruction and doubling their rate each time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
you might be surprised how fast this is in burst
i'd benchmark it before spending a lot of time on something else
i could be wrong but i don't think you need the AddJobHandleForProducer after your job
afaik because it's a .Run, it'll execute the ECB on the main thread anyway
but i think that's maybe a separate issue
kinda hard to say what's going on with your timer code as it's a liiiitle bit hard to follow but for that stuff i generally try and simplify as much as possible
so for example set one float on your DESTROY component, called say 'remainingTime'
and decrement that each time
or even 'startTime' and init it to Time.Elapsed time
then just do a read on it, and if Time.ElapsedTime - startTime is greater than your countdown, kill the entity
atm you have john, timeSpawn, lifeTimeMS, destroyedOnce
i think i follow what you're doing but i'd simplify it
I plan on making it burst later, but for now I turn burst off to debug.
Oh, the destroy gets called
I threw in the boolean so it only gets called once, and I have hundreds of objects that would be calling it
yet despite only one destroy being called, it triggers infinite error messages, spaced 1 for the time of despawn, 2 for the next time, 3 for next, etc
destroyedOnce is just a debug variable to isolate it to only one time a destroy ever gets allocated into the EntityCommandBuffer
It will be removed later.
long john; is just what I call my ms elapsed since epoc 1970
and timespawn is when the entity is spawned, individual to each entity
and lifeTimeMs is set earlier for how long
that part is all a red herring
hehe john is a good name for that
If you make it memorable it is searchable through all filesable.
The only part that matters is: How do I destroy an entity properly?
I tried doing it without Entity Command Buffer and I think it was mad too.
It is definitely reading entity data from timespawn and lifeTimeMS, so it is a valid entity
Does .forEach(Entity e, ref whatever), give the entity of the whatever ref? or is there a chance it is null?
maybe your system needs to be in the Init group, as your buffer is set to fire on EndInitializationEntityCommandBufferSystem
Let me look into that, thank you.
That was not the case.
A separate issue... I can't seem to get arrays working in IcomponentData, this one, when I access ts.pointx, it is the same value for all entities with DroneDataEntity. https://pastebin.com/NZacepGN I thought I'd have my MOBA launched today, but some very minor details hung me out, and 25 crashes of UNITY held me back. I have them on video if any devs want to see, but won't publish to youtube cuz I want to promote Unity not showcase its flaws. In fact after I launch this MOBA, I'll do a BOSS youtube on how to use ECS very easily.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Solution: I tried IComponentData off the codemonkey tutorial, but it was throwing errors. https://www.youtube.com/watch?v=XC84bc95heI
Revisiting it, Yeah, that fixed it! The problem I had was my .foreach had 9 elements and I needed more... But you are limited to 9 which isn't fun. I ditched one I didn't use anymore, and put it in. My last attempt, I was trying to nest a buffer inside an icomponentdata which is a nono.
โ
Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=XC84bc95heI
Let's learn about Dynamic Buffers so we can store multiple values inside our Unity DOTS ECS Components. (Array, List)
Unity DOTS ECS Playlist
https://www.youtube.com/playlist?list=PLzDRvYVwl53s40yP5RQXitbT--IRcHqba
If you have any questions post them i...
If you're reaching those limits, maybe you should try chunk iteration. https://coffeebraingames.wordpress.com/2018/11/25/unity-ecs-basic-chunk-iteration/
What is the proper way to use float4x4.LookAt as a replacement for Transform.LookAt in a IJobParallellForTransform job struct?
Hi. how to use unity dots + mlapi?
Any tipps on how we could deal with conditions in ecs ?
Lets say i have an mob entity. That mob should be invisible once a certain condition is true... like when it reached a spot, when it has some certain item in inventory and stuff like that... how would that look like ? I cant imagine this in ecs yet :/
afaik theres no special compatibility for mlapi and dots, you will need to treat it like regular a hybrid workflow @halcyon plume
@stone osprey, conditions should be handled with existential processing: https://www.dataorienteddesign.com/dodbook/node4.html
Existential Processing
Thanks im gonna take a look at that ! Is there some sort of summary ? ^^ This looks like a lot of very specialised text and english is not my mother language ๐ ill give it a try but ill probably will not understand that much
Or any example on how this would look like applied on an entity ?
Ah, sorry, yeah, this is more like the academic theory behind how you might do this. It's not a great practical example as it's written in c++, but it describes how to clearly handle conditional processing using database entries instead of if-statements and booleans - essentially what we do in ecs
Ah i see ^^ The example however is a bit odd... well i can understand how it helps to reduce iterations in this particular case.
But lets say we want entities to hide/stop being rendered in different situations. How would the entity structure look like ?
I had something like this Entity{ Renderer, InvisibleWhenOnSpot{ pos }, InvisibleWhenItemInInventory{ itemType }} in mind with a system iterating and disabling the renderer when one of them is "true"... or probably even Entity{ Renderer, InvisibleWhen{ enum[] conditions }} or Entity{ Renderer, InvisibleWhen{ ICondition[] }}...
Based on a short insight of that paper i would assume that the first variant is the best ?
In abstract, there's an even better chapter on that specific problem ("what to show") - https://www.dataorienteddesign.com/dodbook/node6.html - however, in your specific example, I would personally use tags to trigger such a thing, but there's no real consensus as to whether it's better to use tags or components with booleans to control behavior at this time. In the future, we might be able to add/remove tags as bit-flags without changing an entity's archetype, but at the moment it is a structural change
Hierarchical Level of Detail
Thanks ! So you mean this ? Entity{ Renderer, InvisibleWhenOnSpot{ isTrue, pos }, InvisibleWhenItemInInventory{ isTrue, itemType }} and then two seperate systems processing WhenOnSpot and WhenItemInInventory to set the bool state and one other system to render that entity based on those bools ?
I think tags are no option here becasue i want to add data to the conditions which may change ^^
I understand wanting to do that. However, without tags, you wind up checking every entity every frame for the conditional values. You can by all means have component data that determines the transitions, but I recommend using tags to control the conditional processing. For example, an entity that's disabled only needs to check if it should be re-enabled
I need a simple trigger for dots physics and found TriggerGravityFactorAuthoring.cs from dots samples. Seems like a lot of boilerplate, so I want to make sure that this is the current way of doing this?
Ahhhh thanks ! ๐ I assume you mean a component that marks an entity with "trigger" ?
Then our archetype would kinda look like this : Entity{ Renderer, InvisibleWhenOnSpot{ pos }, InvisibleWhenItemInInventory{ itemType } and two systems iterate over WhenOnSpot and WhenItemInInventory to add a Invisible component to the entity to symbolize the condition... then we just have a InvisibleSystem which basically iterates over the invisible triggers/tags/markers - Components ? ^^
Anyone know how to solve the error: "All entities passed to EntityManager must exist". One of the entities has already been destroyed or was never created. [Hint, it happens when destroying Entities in EntityCommandBuffer. Hint #2: Things worked before back in my old project so maybe it is a ComponentSystemGroup order thing]
@stone osprey, a tag is just a componentdata that has no member fields. There's no reason you can't use components with data as if they were tags (to query them as the conditions for running a system). I think of this as almost a kind of state machine with the component tags as representing transitional states. For the moment, let's imagine our archetype is just Entity {Position, Inventory} and assume it's in a chunk with rendering shared component data. If I were simply enabling and disabling renderers, I would have at least two systems - a DisablingSystem and an EnablingSystem. The DisablingSystem would only run on entities without the Disabled component (which is what Unity uses to hide renderers). In turn, the EnablingSystem would only run on entities with the Disabled component. In each of these systems, we can check the Position and Inventory of each entity. If the Disabling System finds an entity that meets the criteria to become invisible, it can add the Disabled tag to that entity. If the EnablingSystem finds an entity that meets the criteria to become visible again, we can remove the Disabled tag. This is a simplified example, but it would accomplish this one task at least.
Thanks a lot ! ๐
I think I need that web page that says Burst Compiler Order of Operations. What I think is happening is an Entity is slated for delete, but another Job or SystemBase tries to reference it.
It is likely a system group ordering issue, as ECBs are read-back at a later point, so whatever entity references you're using have been invalidated by the time of the playback - https://docs.unity3d.com/Packages/com.unity.entities@0.17/manual/system_update_order.html#default-system-groups
Thank you Draveler
I was looking at pages similar to this, but not this one.
Deletion happens in: [UpdateInGroup(typeof(InitializationSystemGroup))] &BeginInitializationEntityCommandBufferSystem ERROR thrown in: [UpdateInGroup(typeof(FixedStepSimulationSystemGroup))] & EndInitializationEntityCommandBufferSystem
I'm personally a big fan of tagging entities that should be destroyed and only have one system around that is responsible for deleting entities tagged with that component
That way you don't have to get a headache thinking about EntityCommandBuffer order when your code base starts growing
And all AddComponent/RemoveComponent/SetComponent whatever calls you do through the EntityCommandBuffer are guaranteed to be safe
Yes Script, I literally have a single system to delete entities
But when I do, it throws an error
In fact places in other systems that used to delete fine
Now they can also not delete
Ie, I found this script a while ago: ObsticleHitSystem.cs
It had destroys in it and it was cool.
I removed em tho.
Then I went back after I couldn't destroy to see that old ObsticleHitSystem and why it worked...
Turns out it throws errors too
Well I have DOTS_DRONE_AI in this error, maybe I can gut it.
Hello all. Is there a way to convert a single Monobehaviour component into an Entity component? Or do I have to create a GameObject, attach that Monobehaviour component, and then Destroy/Convert it into an Entity?
I am trying to take this and turn it into an Entity component.
Yeah as far as I remember, lot of verbose code to use collision/trigger event buffers and such. I don't think tehre's a shorter way right now
Isn't physics shape by definition entity? It is somehwta analogous to rigidbody in a way
Physics Shape is (in the code) named PhysicsShapeAuthoring
it is a Monobehaviour script
You're looking at the authoring component (monobehaviour)
I am wondering if there is a way to cause that authoring component to convert itself to an Entity component without spawning a gameobject and destroying it
it will indeed put these values to a PhysicsShape component on the entity converted from this gameobject
more like collider ๐
rigidbody would be the PhysicsBody or whatever it is called
@karmic basin say I don't want to create a gameobject and have it destroyed. Say I already have an Entity and just want to copy this Authoring component's info to that existing entity.
is that possible?
the Entity is pure ECS ?
yes the Entity is pure ECS
it is a more complicated story than that, but the Entity is pure ECS for the sake of not going into the long story
lemme see, first thing that comes to mind is having a system grab the values from this proxy entity, apply it to the entity you're interested in, then delete the proxy
or you could maybe grab a reference to that entity during conversion and apply the component to it ๐ค (more hacky IMO). <--- Nah bad idea the entity doesn't exist yet
i want to avoid creating a game object with this component just to destroy it
i was hoping there was a method to be like "hey, convert just this component and return the result"
but maybe there is not
component don't exist on their own
they need an entity
if you're going pure ECS, then why not go all the way and add the component from code ? ๐
it's just a struct you init the values and add it to entity
there are examples to create physics colliders from code in the PhysicsSamples repo
they don't, no. but let's say I have a GameObject loaded in memory (in my case from an AssetBundle). I already have an Entity created ahead of time, and I'd like to say
"Hey, GameObject I loaded from an AssetBundle, give me that single component you have there and let me throw it on this Entity that already exists."
Otherwise, I'll have to create a copy of the GameObject from that AssetBundle just to destroy it to then copy that struct that gets generated.
or Create a blank gameobject, and copy the physicsshape component, and let it be destroyed
in any case, I am trying to avoid creating a gameobject to do this at all
Then I'd do this ^
because I could be doing it several thousand times every few seconds
in my case there is no proxy entity
there is an entity, and there is a GameObject with the PhysicsShapeAuthoring component
Convert the one the physicsShape is on, from your screenshot
yes, that's what I am asking about
is there a way to do that without putting it on a GameObject that is destroyed?
Or is that the only way to convert a PhysicsShapeAuthoring component?
Creating and destroying GameObjects is expensive
lemme re-read your questions, looks like very specific setup
if you are not using subscenes to create entities beforehand and you will need to create colliders from code by the thousands, I think that will be expensive
If data is always the same he could eventually use Blob Assets ๐ค
But same hassle yo uhave to write conversion code
Did my question make more sense after a re-read?
Basically I am asking if there is a way to convert individual components and shove the result onto an existing Entity, instead of the workflow I am familiar with, where you have components on a GameObject that gets destroyed/turned into an entity and its components turned into Entity components.
yeah he could use blobs, not sure if hes making unique colliders or not
I get that you're tied to GO's from an AssetBundle so you don't do what you want, but still, in this case going the 100% pure way makes your life harder than choosing the hybrid approach with Subscenes, and Companions and such
i can't do that because this is all runtime streaming of AssetBundles
I guess I may have to look into examples of this
correct
so yeah, my collision info won't change (though each assets has its own unique collision info obviously)
i'm worrying about that part when I cross it
yeah so the component you screenshot doesn't even exist, right ? you can go the 100% runtime route and add the component via code
it exists on the AssetBundle
ive never bothered with assetbundles but creating physics entities through code is simple enough, the ragdoll example is the one that comes to mind but simple geo is like
public PhysicsCategoryTags belongsTo;
public PhysicsCategoryTags collidesWith;
//
var filter = CollisionFilter.Default;
filter.BelongsTo = belongsTo.Value;
filter.CollidesWith = collidesWith.Value;
var groundCheckCollider = Unity.Physics.SphereCollider.Create(new SphereGeometry
{
Center = float3.zero,
Radius = groundCheckSphereRadius
}, filter, Material.Default);
dstManager.AddComponentData(bodypartEntity, new PhysicsCollider { Value = groundCheckCollider });
and then add the other physics components according to whether static or dynamic etc
i dont know how optimized it is for runtime in large quantities though
thanks everyone for talking through it with me, and for the assistance
would i be wrong in thinking, you're looking for a way to convert an asset to entity via code.. so like this:
Entity prefabEntity = GameObjectConversionUtility.ConvertGameObjectHierarchy(gameObjectPefab, conversionSettings);
which will convert the gameobject hierarchy, including components like Rigidbody's, Colliders etc, into an Entity hierarchy
Yes Built-in pipeline. If I place the gameobject to subscene, the gameobject is not rendered.
It happens with any primitive gameobject. I guess it is not meant to be used with hybrid approach and unfortunately there wasn't really any documentation about this.
If it's hybrid are you adding a companion component?
conversionSystem.AddHybridComponent(someGameObject.GetComponent<MeshRenderer>());
// Get the mesh filter and such
...
I was just testing with primitive gameobject with ConvertToEntity component and "Convert And Inject Game Object" selected
Oh alright, I will try that
Yea dunno about that
I thought you were trying subscene
Since you don't need ConvertToEntity on gameobjects in subscenes
Yes I tried to place that object to subscene, but then it is not rendered. I guess the subscene conversion works differently
And by hybrid I meant Hybrid ecs, gameobjects for rendering and effects, and logic for rest. Didn't mean Hybrid rendering ๐
Yea, idk much about hybrid rendering since I don't use it
thanks @coarse turtle , works like charm:
class ConversionSystem : GameObjectConversionSystem
{
protected override void OnUpdate()
{
Entities.ForEach((MeshRenderer renderer, MeshFilter filter) =>
{
AddHybridComponent(renderer);
AddHybridComponent(filter);
});
After a few months break, I've reinstalled unity. I see nothing has changed... which means my project is perfectly fine. The bad: DOTS is dead. The good: my project using DOTS that I put in the freezer has been defrosted after a 4 month break has 0 errors and compiles correctly. Gotta take the good with the bad.
Quick question on the forum if anybody wants to chime in.. https://forum.unity.com/threads/jobs-vs-entities-foreach.1172897/
One idea, if you're in control of the gameobject authoring / asset bundle creation is to just have an SO in the bundle as well/instead with the settings you care about - then create the ICD on the entity via code using those settings perhaps?
Is this referring to e.g. IJobChunk, IJobEntityBatch etc? There's mostly one very compelling reason to use them instead of ForEach (lambdas) - though there are other reasons too.
The main one is that you can check data on the chunk level and e.g. early out. For example, if you want to early out if a certain component exists. In a lambda, you need to check every entity (using HasComponent<Blah>). In a manual IJC/IJEB etc, you can just check the first entry of the chunk as you know that every chunk contains only entities of a specific archetype. That make sense?
Hmm yeah that makes sense.. with ForEach lambda and EntityQuery you can specify All or None etc to grab only entities with/without exactly what you need right.. just trying to wrap my head around whether there's a reason why that's less flexible than the early outs thing with jobs..
Sometimes you still want to process the entities but treat them differently based on e.g. the presence of a combination of components. One way is to write many ForEach's with a lot of copy/pasta code. Another is to write it out in it's more full form. There are also other reasons to use the more full form (ForEach just compiles down to IJEB basically) but they're more subtle I'd say. Depending on your situation too, scheduling more ForEach's could well be more expensive than the work done in a single one (esp with low entity count off main thread).
Cool yep i think i can see where you're coming from there.. i think once i come across some concrete use-case/examples i'll have a better understanding of exactly where that could come into play.
For me it just comes down to compilation times
The IL weaving that makes Entities.ForEach work can become a major iteration slow down the more your project grows
Ah that's an interesting point..
after two days of learning about dots and how it works, I still don't know what to use it on
I know I'm not supposed to use it for making a full game using it
what could I use it on?
I don't see how I could use ECS for physics since, that would turn the players into entities as well-
in order for them to work-
since I'm making a multiplayer horror game with AAA graphics, I thought I could use this to somehow get more performance
if you have an answer please ping me
Do you have/anticipate any cpu bottlenecks?
I'm using HDRP so the only problem I'm experiencing atm is constant high cpu times
like 10 - 20 ms
... due to?
I actually don't remember
I'm gonna check hold on
cause another major problem was the amount of draw calls and everything surrounding rendering because of HDRP
rendering is just very slow for some reason
nvm, I now checked again and it's mostly the editor adding a lot of overhead
the amount of draw calls is still ridiculous tho
but again, I was just asking what ECS is usually used for
I see that it's used for multithreading and stuff?
considering my project, should I use it?
as I stated above, it's a multiplayer horror game that I aim to use modern graphical features in
It depends what your bottleneck is. Integrating ecs into an existing project isn't trivial. Just using jobs/burst without ecs can give a huge performance boost in a lot of cases
And is a lot easier to integrate
how could I do that?
If rendering is your bottleneck, the hybrid renderer might help depending on how your objects are structured. It's great at rendering lots of entities that share the same mesh. If you have really complicated scenes with lots of different meshes and fancy lighting and effects then I'm not sure it'll be much help. Probably the opposite as the integration with urp/hdrp is not great yet from what I hear
from what I can tell
it's just installing the package and adding the script dependency thing
and it says throws a message in the console saying
Hybrid Rendered V2 is active
something along those lines
so, that means it works and I don't have to do anything else, right?
No. Whatever impression you have that this is something you can just easily drop in your project, that isn't correct. If you want to integrate ecs it's a very slow process with a lot of learning.
And the documentation isn't ideal in a lot of cases
I see
Fwiw in your case I'd recommend staying away from DOTS for now. Probably looking at how to reduce your draw calls etc will get you a lot more ROI.
I don't know why it's like
a plane, a cube and a sphere with lighting, have like 500 draw calls
I'm thinking of just editing the render pipeline or something
I have one last question about dots tho
would it help at all if I were to use it on items?
in my game you will be able to drop items on the ground for example
if there were a couple thousand items, could dots help in any way?
I saw someone using it to spawn thousands of entities at once
I'm not sure, that's kind of an abstract question. Objectively speaking, if you spawn thousands of gameobjects in one frame, Unity isn't going to like that. If you spawn thousands of entities, Unity won't care. But if those entities need to be rendered, it depends. Do they share the same mesh? Is there lighting? Do you need to process them every frame or something?
let's say I wanna leave glowsticks so players know where they've already been to
I don't have a better example
Also you're going to have a real headache if you try to have some parts of your game as ecs and some parts not. I really can't stress how nontrivial it is to integrate ecs into an existing large project. And even to get to the point where you can do that probably requires a few weeks of learning from examples and smaller scale ecs projects from scratch
I know that, I was just wondering if I could use it for independent stuff that won't require much adaptation of my current code to work with it
Assuming you don't have previous experience with ecs/dod that is
I guess I won't have a use it for now
I'm very interested in it, but seeing how it isn't complete, idk
I have just one question tho before I leave
can I use it for rendering only? would taking the time to implement it to work with rendering be worth it?
nothing else, just changing to rendering using it
If you're interested you should go through the manual and the dots samples repo to get an idea of how it all works.
yeah
but could I do this?
It's not going to do you any favors as far as rendering goes. Like timboc said you're better off just going through the normal process of fixing rendering bottlenecks with gameobjects
From the little that I've heard HDRP is really only viable targeting quite high end hardware.. have you considered URP or just standard to begin with and switching later
theyre all so different I think you would waste a lot of time to use one and then switch later, unless you are using it only in its most simple form of just slapping textures into materials and calling it a day.
I need features that only hdrp provides
sadly
so I was thinking of just remaking some of the render pipeline
is that even possible?
ok, it is
I just found it online
In my experience, ECS / DOTS is used more for simulations. Think particle based fluid mechanics or primitive neutron transport in nuclear engineering. Where an overall general trend and pattern emerges from the distribution of data and there are no "relationships" between individual entities.
wait, I could use this for water simulations?
like, if I wanted to add realistic water to my game?
Kinda... not really. This is more like "research" fluid mechanics where you want hyperrealistic water physics using fundamental forces of electrostatics and chemical bonds rather than an actual game mechanics like a shoreline.
well, I meant that-
like, could I technically implement some more realistic water into a game, rather than the simple ones that work on your cpu
that kinda just look like honey
Where in the forces are being applied to each entity based on a spacial partition of entities that are individually independent but come together to form classical fluid dynamics in a tube.
aight
If you want more realistic water in a video game, you're far better off using the typical divergence and integral methods of fluid field calculations. DOTS on the other hand would be great in confirming the proofs of these deterministic methods via stochastic simulation.
||that's a lot of words for a commoner like me||
The problem with DOTS is that video games rely on relational connections between different data points / contextual array values. If a value changes on one array value, then multiple others in different arrays should change as well. And that goes against the array method and vectorized bursted calculations DOTS is optimized for.
Have you taken undergraduate fluid dynamics yet? Its... simple enough for a surface level understanding.
nope
Hrm okay. You want a horror multiplayer game? Dont use DOTS. It wont help.
I figured that out
I only wanted to like know if it helps having some objects as entities
Nah. Entities only really help over objects if you have thousands to tens of thousands of objects of the same class but different data values.
well, that's kinda what I meant
Like water particles. It's the same H2O with the same fundamental forces but different positional and rotational values.
like, let's say I need 1000 items on the ground with translations, rotations and a script to hold a scriptable object
1000 objects is reaching the borderline of conversion to Entities but you also need to think about how those objects are being used.
Entities are great when you have one function / method that needs to be applied to all objects universally, taking in the object's data as parameters but otherwise operating on them all universally.
If each object on the ground must interact differently based on a scriptable object, using DOTS wouldnt help.
Just using a standard Object Oriented system would do the exact same thing without the overhead of DOTS
ok
I see!
what if I need to have something like glowsticks, they all just have to get rendered and sit in a place
no script, just translations, rotations and rendering
and bounding boxes
Rendering is far different. DOTS is more memory data-side with contextual information. What you want is a compute shader.
Compute shaders are like DOTS in a way. Where pixel and vertex information replace entities. With similar downsides of high performance cost of relational data.
yeah
I don't need them yet
I'm not working on world generation at the moment
I'm still interested in working with Dod in the future
but for now, I think I should just stick to OOP
and make my own render pipeline
Honestly DOTS is in a very tight squeeze between standard Object Oriented and pure Compute Shader powered GPU simulation.
There is a very small margin where DOTS will actually assist in improving performance over figuring out a way to shove everything through a compute shader
then what's the benefit of making a whole game with dots?
I know it's not recommended unless it's a certain type of game
but you can do that, from what you described, I see no reason to use it for games
Terrain generation, compute shader, graphics processing, compute shader, fluid simulation, compute shader (or regular graphical shader).
I can see it being used for networking where rapid turnaround is required. Shifting information to and from the GPU is very expensive (relatively) and doing simple mass array operations within the CPU and memory cuts down on that.
I am using networking but uhh
good luck with trying to convert mirror to it lol
or make your own
so
for now, my biggest problem is just, hdrp having way too many draw calls
Honestly I cant help you there. My graphics consist of a blank quad with text on it for debugging. I'm staring more at the entity debugger with float information to verify that my mathematics is working.
Have you tried asking on #archived-shaders ?
I don't know how it would help asking there-
Or maybe #archived-hdrp . Trust me, making your own is literal pain.
I'm more thinking of removing features I don't need
Shaders and render pipelines interact a lot with the overall graphics processing.
and maybe spending a couple weeks making some changes
to like, how bloom is calculated for example
You can turn them off. Dont need to start amputating HDRP and then trying to maintain it on your own as Unity with their 100+ employees move ahead with more integration.
uhh-
yeah-
idk how to do that tho
it still says the same amount of draw calls for them
idk really
Turn off unity built in bloom then apply a shader onto the material that generates bloom yourself.
oh yeah! that could work!
it's just that some stuff has a lot of draw calls
I said bloom specifically because it has 18
-.-
but yeah
I'll look into what I can do to optimize this!
thank you for the explanations!
๐
If you want to reduce draw calls.... you might need to start looking into manually merging mesh generation and shoving it into the render pipeline itself.
It took me 2 weeks to figure out how to render a 2d triangle that rotates.
โ๏ธ Works in 2020.1 โ 2020.2 โ 2020.3
๐ฉน Fixes:
โบ Make sure your source mesh has read/write enabled in it's asset importer inspector.
Compute Shaders are scripts that run on the GPU! They're very powerful, allowing you to leverage the GPU's unique abilities and generate meshes to draw procedurally. There's not a lot of information on using them, ...
oh
idk
I'll look into this
It's a deep deep rabbit hole of linear algebra and matrix operations.
I really need to squeeze as much performance as possible-
hopefully-
I can get medium settings on 2K with like
155 fps
somehow
idk how
There are entire PhD degrees built around this. So I wish you a lot of luck.
and on high like 120 or something idk
lol, thanks!
It's good to have high ambitions. So when you miss the goal, you'd have learned a lot in the attempt to try again or formalize a more solid destination.
We're all solo developers with projects that will 99% never see the light of day to the public. I've long since abandoned my confidence.
SAME
but now I'm working with a team
and we're planning to release features as we go
like, chapters after release
new features and graphics
more optimizations
so like
it's released
but we're still heavily updating it
Ah. Well performance is usually the problem of your C# game logic code. 90% of the time at least. The 10% is graphics. I highly recommend that you and your team first dig through and refactor your logic code first. What is required to happen every frame, can it be delayed to once every other frame or more.
for me it's just
rendering atm
like, I'm at a point where I can write optimized code so that I don't have to worry about it later
yes, exactly
I've made sure to cut as many continuous updates as possible
the codes I have control over are not a problem
the only ones that are more unstable are ones like SteamManager which just initializes Steam
Yea, this is pretty much the limit of my experience with draw call management and render pipelines. Again, ask in #archived-shaders and #archived-hdrp . The ones who frequent that will know far more.
Hey.. i have the following code, creating a local MultiHashmap, passing it into a job and writing to it, then trying to pass it into a second job.. However it's throwing an error on the second job saying the hashmap has been deallocated..
NativeMultiHashMap<Entity, int> myMultiHashMap = new NativeMultiHashMap<Entity, int>(count, Allocator.TempJob);
var handle = Entities.ForEach((in MyComponent myComp) =>
{
// add some stuff to multihashmap
}).Schedule(Dependency);
Entities.WithReadOnly(myMultiHashMap).WithDisposeOnCompletion(myMultiHashMap).ForEach((Entity e) =>
{
// do some stuff
}).Schedule(handle);
How would i pass the results of the first job ( ie the hashmap ) onto the second job?
I dont remember if WIthDisposeOnCompletion works with NativeMultiHashMaps
but typically, the way you're doing it is how you pass datastructures between lambda jobs
Instead of DisposeOnCompletion(myMultiHashMap) you can also try Dependency = myMultiHashMap.Dispose(Dependency)
you would probably have to add Dependency.Complete if you did that though
Well there's Dispose() and Dispose(JobHandle), iirc the one with JobHandle is a scheduled Dispose
oh really, cool
Yea it just schedules a new job
interesting I heard another method is to just place all that stuff after your jobs in a Job.WithCode also
.WithDisposeOnCompletion() only works with NativeArray<>(). So you cant do that with myMultiHashMap.
Ahhh yeah i just tested with NativeArray and it works as expected
You used .WithReadOnly(), good. That's all you need to capture the variable. You can now just use var firstValue = myMultiHashMap.GetFirstValue(e, out var iterator) or something like that inside the body of the second foreach
How then would i dispose the hashmap after job completion?
After the second ForEach, use handle = myMultiHashMap.Dispose(handle);.
I dont quite recall the syntax for getting the first value of a key from a NMHM so it's something along those lines.
yep i have the keyvalue logic ok
thanks gentlemen ( and women/others ) the help is much appreciated
Dispose(handle) is a nice touch
so you're passing a job dependency into the Dispose call so that it disposes exactly when you need it to
nice
Excellent that seems to work perfectly, thanks again
10/10 for logical solutions that make sense
Is there a way to check if a buffer exists on an object, similar to HasComponent
Currently getting an error with var childs = _entityManager.GetBuffer<Child>(rootEntity);
HasComponent<Child>(rootEntity) just seems to always return false
You have to use BufferFromEntity.Exists
Hmm i'm not doing it in a system it's just some setup code inside a mono
well i guess this works -
var childBufs = World.DefaultGameObjectInjectionWorld.GetExistingSystem<GameObjectConversionSystem>().GetBufferFromEntity<Child>();
tiny bit overkill ๐ฎ
You want to use EntityManager, not the system itself. Store World.Default(bla bla bla).EntityManager at OnStart(). Then use the EntityManager in mono to GetBufferFromEntity.
EntityManager is static so it can be passed around
Yeah i'm using EntityManager but entityManager.HasComponent<Child>(myEntity) seems to always return false
EntityManager doesn't have GetBufferFromEntity
em.GetBuffer<T>(Entity)
yeah the problem is - i need to check if the entity has the buffer first..
em.HasComponent<Child>(myEntity) is returning false, even where i 100% know the entity has the Child buffer
Why ? ๐
there's an IsCreated prop, would em.GetBuffer<T>(Entity).IsCreated suit your needs ?
hehe i know right..
basically i'm doing some setup stuff inside a mono, really i'm just testing out some ideas..
so i'm iterating a bunch of entities that are children of a converted prefab
some of them have the Child buffer, but the 'leaf' entities dont ( as they have no children )
so i'm iterating the Child buffers recursively, if there's a child buffer, i then iterate the children, and then the childrens children
i think this would not be a problem if i was doing it in a SystemBase
but i'm getting these weird issues trying to do it from the mono
currently i'm moving my code over to a SystemBase
i'll just apply a Setup tag to my converted prefabs and do the work in a system
avoid all this crap
yep don't fight it ^^
Anyone ever make a system manually using world.GetOrCreateSystem() and it just disappears lol
the OnCreate function runs but i can't find it in the dots system window and the Update function doesnt run even if i use the [AlwaysUpdateSystem] attribute
If this is a system that has [DisableAutoCreation] you can add it with https://docs.unity3d.com/Packages/com.unity.entities@0.17/api/Unity.Entities.DefaultWorldInitialization.AddSystemsToRootLevelSystemGroups.html
i was setting up my new project, now im stuck with unity.collections 1.0prerelease
- how can i go back to 0.15 for unity.entities while unity.transport requires it?
- unity package manager does not show older version of unity.transport and unity.collections
Because you know which version you want to target , did you try to add them to your manifest.json file ?
the manifest says im on 0.15
but package manager and the error logs show otherwise
i had this issue a few months earlier
the only solution that works is to start a new project
I had a somehow similar issue when starting a new project since a long time where I didn't know some of the dots packages were now included as dependency and didn't require you to add them manually anymore. So I ended up with compatibility errors and yeah I had to uninstall every dots package before conflicts could resolve
will try
๐
it's tricky but it's definitely possible to fix dependency issues
by editing manifest etc
Does Adreno 618 fully support Hybrid Renderer V2? Cause i get black screen with this gpu 
@safe lintel I got the ragdolls working although i've spent a stupid amount of time trying to get around the flat hierarchy thing
Is there an interface which gets called once an struct component gets removed ? Something like IDisposable ?
also need to look into the bounding thing
Is there an interface which gets called once an struct component gets removed ? Something like IDisposable ?
My problem is that i wrote a system which removes a bunch of tag components after exactly one frame... it works kinda generic and some of those tag components contain unsafe/native lists which i need to deallocate when being removed.
So is there some sort of interface which gets called once a component gets removed to deallocate stuff ? Or any other techniques ? I saw for jobs there is an attribute which takes care of deallocation
Anyone ? ^^
Technically, if a component has any data in it at all, itโs no longer a tag.
Thanks... kinda ugly and requires a lot of boilerplate code but if theres no other solution :/
Alternatively, you can create components that exist on a different entity for watching specific structural changes
Yup it's pretty terrible. In bevy it's built right into queries so you can just add Removed<Whatever> to your query and it will just work. No such luck in Unity
Than its not a tag...
I have an Inventory and i need to symbolize that the inventory was updated... like something was added, removed or updated to/from/in it.
So i planned Entity{ Inventory, AddedToInventory{ List<Entity> updated ...} } to react on those updated properly. But well the dealocation isnt that nice because i wrote a "OneFrameSystem" which removes certain components at the end of the frame... great for real tags without any data inside... bad for when allocation happenend
you could track item updates by storing a current and last version number inside the item. Increment the number when you update anything about the item, and set the last version to the current version when you would have otherwise removed the components
Just need to be careful about when that last version number gets set
Ideally itโs the system that is watching for changes that is also setting the last version number.
Thanks im gonna try this !
Does anyone have a working reactive system based on those damn StateComponents ? I just want a kinda generic system which basically does this :
Entity{ TComponent } -> Entity{ TComponent, State, TAdded } -> Entity{ TComponent, State } -> ( After removal of TComponent ) Entity{ State } -> Entity{ State, TRemoved } -> Entity{}
So i can easily loop over TComponent, TAdded to processes added components... or TRemoved to process removed components
My own implementation sucks and wont work correctly... and i dont get why
If someone is interessted in my reactive system... it works now but when i remove the desired component... i kinda want to save the state into my state struct. Any example how this might work ? I could loop every frame over them to copy the state... but isnt this overkill ?
Wait... i can not use generics to iterate ?
Entities.ForEach cannot be used in system ReactiveSystem3 as Entities.ForEach in generic system types are not supported.
Is there any way to bypass this ?
There's a decent example of simple reactive systems here: https://www.effectiveunity.com/ecs/06-how-to-build-reactive-systems-with-unity-ecs-part-1/
Why do you need reactive systems? Your systems donโt live alone all by themselves. What one system changes, may be of interest for another system.ย For example, if you build a strategy game you will most likely need to know where your units are in the game world. If your game world is a 2D grid, you could realize this with a GridPosition componen...
And, in general, generics are not easily supported at this time
// Copy over state
Entities.ForEach((ref Entity entity, ref T tc, ref State state) => {
//var tc = EntityManager.GetComponentData<TComponent>(entity);
state.component = tc;
}).Schedule();
Is there a way to loop over entities with "T" and state without using generics ? Unity prevents me to use generics here...
primarily because generics are necessarily not "data-oriented" as the data is unknown
Hmmm... any other efficient way to loop over a set of components ? ๐
That T above is my generic
yeah, by identifying which components you want to loop over, and doing it
the problem is wanting to solve for all possible combinations simultaneously
Well i know which component... T but its generic ๐
There's no reason for it to be generic, as I assume you'll be doing different work depending on which component you're actually working on
Yes theres a reason... to save me boilerplate code
And no... its not doing different work
It just should copy over a damn value for the state ^^
This is perfectly fine in my architecture... trust me
Is state just some kind of memento? I.e., a compressed histogram
Its a generic reactive system which works... atleast till the point of the state. Thats what i need the generic for... to copy the state. And it would work, if unitys check wouldnt prevent me from running it.
Currently it does not copy the state into the IStateComponent which is kinda bad... because i need to deallocate some stuff
In case someone is interessed
And it works perfectly... to the point where i need to copy over the TComponent into the state for cleaning it up later
So any idea how i may iterate over all entities with (TComponent, State) to copy the damn state ? ๐ฎ
I feel like maybe you don't really get the intended purpose of ISystemStateComponentData... I'd recommend reading the article I linked above at least
Trying to get generics to work with ecs is somewhere between swimming upstream and bashing your head against the wall, and I don't advise pursuing that
Well i just wanna have some sort of callback once a component was added and removed. Thats all i want. Which is not possible in unitys ecs by default. Thats why im using those ISystemStateComponents to simulate this which works... it really does and its pretty performant.
I actually think i just create a Query ( which is possible with generics as far as i know because i only need the type ) and loop over a NativeList<Entity> to copy the state.
I have a flattened NativeArray<Matrix4x4> that contains data for each LOD levels for each entities [not using ECS]. I also need to pass a range from this array to DrawMeshInstancedIndirect but whatever I try to extract a range from this, either using Copy, NativeSlice, etc. I end up with a lot of garbage collection and huge GC spikes very few seconds. Does anyone have a suggestion on how I could avoid that?
Use an array and convert the array to a NativeArray without doing a mem copy. This can be done by pinning your array and taking the pointer to construct a new native array
@coarse turtle it doesn't use memcpy? Do you know of any example. I don't know how to do this.
T[] someArray; // T must be blittable
var gcHandle = GCHandle.Alloc(someArray, GCHandleType.Pinned);
void* ptr = gcHandle.AddrOfPinnedObject();
NativeArray<T> nativeArray = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<T>(ptr, length, Allocator.None); // This is b/c you are handling this resource through GCHandle
gcHandle.Free() // Unpin the array when you're done with it
@coarse turtle NICE! Thank you for that code
Otherwise a custom struct with a T* ptr , length would be enough as you can override the bracket operator. You might also need [NativeDisableUnsafePtrRestriction] if you go down this route
now you've got a basic struct wrapper that can be treated as an array
@coarse turtle that's a pay grade above me, I only half understand what you just said ๐ฆ I'm going to have to google it
thank you!
is it possible to get a buffer from an EntityQuery?
like it is with components for example myQuery.ToComponentDataArray<ComponentType>();
I don't think so, if you just need the data in a nativearray type then you can create a job to put the into the array
Do I need to create a new Unity.Physics.Collider for every PhysicsCollider component?
yeah i've just used var AnimatedLTWs = GetBufferFromEntity<AnimatedLocalToWorld>(true); and passed it into the job
depending on how you are using the data it can be more performant to just put it all into a nativearray and use that, instead of using getbuffer
don't suppose it matters much i guess i figured it might be slightly quicker inside the job to go var aLTW = AnimatedLTWs[myEntity] and select from an array that's been reduced by the query, rather than ALL altw buffers
yeah i'm guessing there's pro's and cons to both
Ah wait just rereading that.. instead of using getbuffer - do you mean for example run a job that populates a nativearray of buffer values?
indeed, that's what I've done before and it worked a lot faster
ah interesting, thanks
Can there be made any improvements to this here in terms of performance ?
// Once at system creation
copyEntities = GetEntityQuery(new EntityQueryDesc {
All = new[] {ComponentType.ReadOnly<TComponent>(), ComponentType.ReadOnly<State>()}
});
// In System update
var entities = copyEntities.ToEntityArray(Allocator.TempJob);
for (var index = 0; index < entities.Length; index++) {
var entity = entities[index];
var cmp = EntityManager.GetComponentData<TComponent>(entity);
endCommandBuffer.SetComponent(entity, new State{component = cmp});
}
entities.Dispose();
It takes about 1.30ms for about 1000 entities... which isnt that great. I cant use a Entity.ForEach loop here because generic code is involved.
Is there any other direct acess to the component arrays which does not require a "Query.ToEntityArray" ? Or any other ideas ?
So Entities.ForEach is out, but you could use IJobChunk or IJobParallelFor, which would both be much faster. are those available to you?
@stone osprey
I haven't worked much with generic code, but I don't think there's anything stopping you from using those structures, since they're not macro magic like Entities.ForEach is
And also, a question of my own to anyone here:
Are there any good efficient noise function implementations in the DOTS packages I could grab?
oh. duh. theres a whole "math.noise" module
okay, I guess my question is answered.
That actually sounds like a good idea ! I have never used those before ๐ But ill look into them... thanks !
There should be some good examples in the samples, but if you're having trouble I can help out. I end up using that kind of thing pretty extensively in what I'm working on
I'd try that first
I don't understand why would IJobChunks work and not Entities.ForEach ๐
Generics... In my example Above "TComponent" is a generic... and entities.ForEach dont like them :8
Thanks ! ๐
oh I see
I'd definitely be interested to see a sample if you do get it working with generics.
I've been doing a bunch of copying and pasting lol
Yep... thats exactly why i try to make that damn system generic ๐ Im sick of that boilerplate code...
doing heaven's work
Yo. my dudes. Keep this in your back pocket:
sin(2x)+sin(PI * x)
its a proven infinite 1d noise function!
thats pretty much blowing my mind haha
Thanks a lot ! I tried that chunkIJob and its working with generics... and its working just fine and its blazing fast ๐ A copy job for 1000 entities in just about 0.03ms each frame
oof
error DCICE007: Could not find field for local captured variable for argument of WithReadOnly. Seeing this error indicates a bug in the dots compiler. We'd appreciate a bug report (About->Report a Bug...). Thnx! :heart:
For all those interessted in an working reactive system... here you go.
Its actually pretty easy to use. Imagine you have a Inventory component and you want to do something once it was added or removed.
You simply extend that attached system like this :
[assembly: RegisterGenericComponentType(typeof(ReactiveSystem<Inventory, InventoryAdded, InventoryRemoved>.State))]
namespace Script.Client.ECS.Systems.Reactive {
[BurstCompile]
public struct InventoryAdded : IComponentData { }
[BurstCompile]
public struct InventoryRemoved: IComponentData { }
/// <summary>
/// A reactive system informing via callbacks if a <see cref="Dirty" /> was added or removed at a <see cref="Entity" />
/// </summary>
public class InventoryReactiveSystem : ReactiveSystem<Inventory, InventoryAdded, InventoryRemoved> {}
}
And then you are ready to run Entities.ForEach once the Inventory was added or removed to trigger logic like a REAL reactive system.
Entities.ForEach((ref Inventory inv, ref InventoryAdded iva) => {
// Runs once, some cool logic to trigger something
}).Schedule();
Entities.ForEach((ref Entity en, ref InventoryRemoved iva) => {
// Runs once, great for triggering logic or cleaning up stuff.
var state = GetComponent<InventoryReactiveSystem.State>(en);
state.component.items.Dispose();
}).Schedule();
Well it still requires a bit of boilerplate code but much better than writing one IStateComponent-System for each damn Component you wanna listen too.
Heres the "snippet" aka my whole system ๐
saved for later plagiarism! when the day finally comes that I lose patience with my boilerplate haha
thanks! and congrats!
Nice ๐ we are all here to help each other so feel free to copy and use that code... even if its not the cleanest and thanks ! Finally a nicer approach to listen to added/removed components.
Seems good should post it on the forum..
Actually listening for added/removed components SHOULD be one of the easiest tasks in an ecs...
Like a "EntityManager.AddListener<T>()"...
Thanks, if you think so im gonna post it ^^
Yeah i didn't realise that wasn't possible, i thought maybe listening for 'change' would do it
to listen for components that have been added, you can use Any inside an EntityQuery right.. so you could say have one system that looks for all your 'event' tags for example, and maybe has some logic that uses HasComponent to branch to different callbacks or methods.. but i guess listening for them being removed is potentially difficult right
Just a reminder to check in a build if you aren't already. Generics behave differently in builds.
Thats what IStateComponents are for :) i use them in my ReactiveSystem otherwhise its hard to listen for destroyed components as you mentioned.
Wait... Really ? :o damn havent checked that yet... Thanks !
Just posted it on the forums https://forum.unity.com/threads/reactive-system-for-everyone.1173812/
yea it's actually quite a pain - sometimes you think things are working then build and... nope. ๐ค hopefully you'll be fine - usage looks pretty simple
Yeah :/ i alsp have those problem without using dots... I can remember a university project which worked fine on desktop and in the editor and was completly messed up on all other platforms.... We actually used generics quite heavy in this one.
And i havent build my code for ages... That will be fun i guess
Managed to fix the bounding issues.. @safe lintel
Is it possible to parallel write to a NativeHashMap.ToParallelWriter() and then pass it onto another job were it is read only?
I'm trying to do something like this - the jobs are chained together by dependency, the first one fills the hashmap and the second reads from it.. The problem is there's no indexing or GetKey etc on a .parallelwriter but i'm unsure if there's some other way to maybe cast the hashmap back to a readable one or something.
NativeHashMap<Entity, float4x4>.parallelwriter RootMatrixMap = new NativeHashMap<Entity, float4x4>(count, Allocator.TempJob).AsParallelWriter();
var handle0 = Entities.WithAll<SourceTag>().ForEach((Entity e, in LocalToWorld ltw) =>
{
RootMatrixMap.TryAdd(e, ltw.Value);
}).ScheduleParallel(Dependency);
var handle1 = Entities.WithReadOnly(RootMatrixMap ).ForEach((Entity e, ref Translation t) =>
{
// read from RootMatrixMap //
}).ScheduleParallel(handle0);
are there any decent debug drawing tools for DOTS?
Aline on the asset store @tight blade
I bought it, same guy that does astar pathfinding project, quite handy
ooh, nice, I'll check that out. That must be hell, writing something for the asset store based on alpha packages
afaik its just job and burst compatible, so no specific ecs hell to support though i dont envy being a store publisher
any other good dots ecosystem purchases I should consider while I'm shopping?
erm, @safe lintel you don't know offhand how to use that builder from Entities.ForEach, do you?
doing it with a job would be straightforward, and of course I always regret using the Entities.ForEach macro
ParallelWriter is just a wrapper around the underlying container. Declare your hashmap as its own variable, pass the writer into the first job from that, pass the original container into the second job
Can I make a IConvertGameObjectToEntity convert before my system's OnCreate or OnStartRunning?
https://forum.unity.com/threads/see-all-versions-command-was-removed.1008619/
this solved problem 2 @karmic basin still thank you
Great ! I'll keep that in mind. They make it sound like it's something you wouldnt want to mess with though :/
It's because Entities.ForEach is just code generation in disguise. The code generator probably can't handle generics yet. This is why we seldom use it. We always use IJobForEach or IJobForEachWithIndex. It's more future proof because that's the translated code when using Entities.ForEach.
Hello, I have a project running Unity NetCode and I wish to extend it using Unity SubScenes. Is there somewhere an example of a proper project structure?
The store asset called Rival is a dots character controller which has a few sample projects one of them is an FPS shooter built using NetCode..
@devout prairie Thank you will check it out
Hmm thanks I'll look into that
Conversion happens in its own world before the destination world and its systems (your gameplay/runtime systems) run. So it should already be the expected behaviour. Unless the system you're talking about is a custom conversion system or a LiveConversion one in the editor, trying to convert on-the-fly at runtime and things like that. Maybe I didn't understand well your issue ?
But trying to answer because no one did yet :p
Anyway If I remember well, IConvertGameObjectToEntity is deprecated so should be replaced by a subscene workflow at some point in the future.
Whats the difference between IJobChunk und IJobForEach ?
Which one is more performant or does it depend ?
They're the same but IJobForEach is the new API as it has Schedule() and ScheduleParallel()
IJobChunk will be deprecated
Ah thanks a lot ! ๐ I thought they might behave different
Hi, I have a team and we were wondering about making the transition from classic to dots, however, most of Unity's documentation seems from 2019 ๐ค
Is this still the future of Unity?
all we know now is that dots team are keeping silence
Thx! I'll take a look
I actually thought IJobForEach<T> was deprecated and Entities.ForEach(...) codegens into a IJobChunk
My bad, I meant IJobEntityBatch
Ah yea - no worries
I updated Entities from 0.16 to 0.17 with packages: Jobs, Entities, Collections and Burst to latest. Now I got compile error
Library\PackageCache\com.unity.entities@0.17.0-preview.42\Unity.Entities\Serialization\BinarySerialization.cs(47,81): error CS8377: The type 'T' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'NativeList<T>'
Should I not update packages to latest but rather use certain compatible versions?
Yeah some of the packages are merged now. I would uninstall every DOTS related package. Start with the HybridRenderer one if you're using this pipeline, else the Entities one. Then, still from package manager, I would check dependencies in the inspector and manually install only the missing ones
That's how I fixed my cmpatibility issues anyway
Thanks a lot, I will try it.
I removed Collections and Jobs and now it works. Thanks again 
@gusty coyote yeah I think you're better off not considering it ๐ฉ
GetComponentData<T> does it return a copy ? I think so... right ?
Is there any way to get a reference to the passed generic instead ?
Yes it's a copy. If you want to modify it, you can always call SetComponentData<T>() or use ComponentDataFromEntity.
What would be the best approach to using a GetComponentDataFromEntity inside a parallel ForEach for reading and writing?
or rather, not using a GetComponentDataFromEntity as it doesn't support parallel writing
it's useful as you can access it by Entity, whereas just a nativearray of components would have to be accessed by index right
i have a feeling i'm going to have to start writing Jobs as opposed to ForEach, i just can't be bothered with all the boilerplate
maybe I don't understand context, but why GetComponentDataFromEntity over fetching the component via ForEach or chunk iteration?
basically i need to fetch the LocalToWorld component from separate entities that are not included in the ForEach
Use a command buffer for the write
man i strongly dislike command buffers ๐
i guess they are useful but, one issue i have with this is -
i'm chaining more than one ForEach job together through dependency
I feel ya. But for parallelism I think that's the best practice
so really the second job relies on the first ones results etc
yeahp
there's workarounds for this, mostly involving 'writing more code', but i was just hoping there'd be a simpler way to get something like a GetComponentDataFromEntity and be able to use it in a parallel context
You can be more granular by manually storing stuff in an array and doing the updates in a second loop. But I don't think that is great either
yeah
essentially i think the answer is rewrite my system as full jobs, with all the boilerplate etc
Heavily relational/ordered stuff is where ecs paradigm struggles it seems
Yeah sounds like it
yeah i can see with ForEach there's some sacrifices to get the convenience and ease of use
coming at ECS / DOTS and being able to use ForEach is a hell of a lot simpler than the old job component system stuff
it's kinda like what c# is to c++
but i can understand why people dislike ForEach and prefer to write everything out manually
well i think once unity moves over to .net 6
and source generators are fully integrated, lambdas would be bearable
fwiw i dislike lambdas in general c# as it seems a bit of a performance killer
long way for a shortcut
well lambdas here are just codegen in their struct counterparts, but otherwise I don't have too much of a dislike of lambdas coming from a functional background ยฏ_(ใ)_/ยฏ
ooft functional