#archived-dots
1 messages ยท Page 250 of 1
I wonder if it's a good practice to use DestroyTag instead of destroying entity through buffer
and then destroy in different system
Hmm, I think the double command buffer systems do a similar thing without an extra structural change
You definitely need at least some type of strategy for managing destroying of entities otherwise you will eventually run into timing bugs causing crashes as the project grows. Whether you prefer double command buffer systems or a tag component dedicated cleanup systems that's up to you.
We use the dedicated system with tag component at work but I've found I don't like it as much as double command buffer systems
What is a double command buffer system?
by double command buffer you mean 2 ECB in a row? Like
EndSystemECB
PostEndSystemECB?
I thought of that too btw
but kind of uncertain of what would be a good practice
Avoiding unnecessary components indeed seems good tho
ooof, my workflow with prefabs is becoming really bad
amount of total general components
is getting close to 10
going adding all those components
to all prefabs
feels bad man
Hey, is there any Known Issues for the latest packages of DOTS? I didn't find anything online and it will be really useful to know if one should go with DOTS right now or not...
one shouldn't go with DOTS right now
unless you're a madman and ready to deal with a lot of unimplemented stuff kek
By reading the forums and the bug reports one could get a feel of problems people are going through
Like @rustic rain just said, DOTS as a whole is still highly experimental
Still, one can safely go with Collections, Jobs, and Burst packages. In a lesser extent, ECS and Math are close to ready too
Well there are a lot of threads there, it will be hard to go through it and collect the issues (and find the ones that are related to you)
True
Yeah, I am starting to use ECS, Math, and Animation, I am not sure about the Animation package, but I only use them for really simple tasks
By the way, the Animation package is the only way to run skin animation right?
Animation is far from ready and it looks like it stopped receiving some love :/
The issues tracker Unity has is really hard to work with, so its not that easy to find issues there
It seems all the DOTS package's are at halt, but they posted something about it being in development (DOTS, not the animation package specifically)
Now I am starting t worry that they will deprecate it
and create something built in with the hybrid renderer
Yeah that post from december is the latest news we have as far as I'm aware.
and animation didn't stand out as a priority ^^
:\
Well I hope they'll improve all the packages needed for DOTS because it was pretty hard so far to get correct information about using it...
most of the things are outdated and the docs are horrible (to say the least, the Entities docs are fine I guess...)
I think it's more about getting back on track with editor compatibility and pushing Entities towards 1.0 before anything else (but really read quickly)
Yeah I guess you are right
Yeah because experimental. They doubled-down on the up-to-date docs and even remastered/new samples once it gets further to a stable state.
Which makes sense
We are early, shame on us ๐
Lol yeah
at least
in the end we'll be already somewhat proficient in dots once it's in released state kek
True true
Only benefit of being early-adopter. PLus we're supposed to help shape it for the future (but I'm not weightful enough in the Unity world to be part of that)
well to me personally
OOP world feels bad
really bad
meanwhile ECS is so pog
yet, still manage to get best from OOP, since System classes can work with abstractions
I'm tool agnostic. Whatever works for the job at hand is good-enough for me ๐คทโโ๏ธ
the right tool for the right job.
OOP just feels weird in gamedev.
but in another field (mainly webdev since I previously came there), it's works.
Hello, so i am starting to learn a bit about dots, how i am seeing it now, If i for example would want to make a character controller i would need to store all data in a component type like the walkspeed and gravity value etc. and then make a charactersystem script doing the logic is that right?
Yes. The script is a system in this case. Systems never have any data stored in them and components never have any logic, just data
Then the system only acts on entities which have the components attached to them. If that system doesn't see an entity with all the components it doesn't need, it will no longer run
yeah, it looks good so far, i will wait untill there is an actual release tho to actually start using it
May as well experiment with it. It is a much better way to make games IMHO. Everything is more separate so you don't get really weird bugs and it's easier to plan the execute order of everything
yeah, i do plan on doing that but i first need to get an idea of how i would structure a whole system like a character controller
There is an ECS character controller on the asset store. It's called Rival and is very good. You can check that out for ideas!
theres also a free one in the physics samples(see the pinned messages in this channel)
Hello!
I am an Unreal Engine user.
I am looking to try Unity DOTS.
Is DOTS available for Personal Liscense?
Ok thxs
Here my fork of some open source character controller I made (it was a bit outdated and wasn't working from the box)
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.
utils class is from here (original character controller)
https://github.com/ssell/UnityDotsCharacterController/tree/master/Assets/Source/Utils
dud
We need a ECB that will accept actions kek
from inside job
protected override void OnUpdate()
{
if (GetSingleton<GameState>().state == GameStatus.Running)
{
var playerVelocity = GetSingleton<PlayerVelocity>();
internalCounter += playerVelocity.x * Time.DeltaTime;
}
else
{
internalCounter = 0f;
}
label.text = internalCounter.ToString();
}
Because apparently getting singletons is expensive
this code costs 0.06ms
why not cache the singletons?
how?
never saw any mention of that
(EntityManager.GetComponentData<GameState>(gameStateEntity).state == GameStatus.Running)
Doing that gives same perfomance
or even worse
huh
NativeQueue
that thing I never saw
I don't know what you're trying to do but.
//psuedoCode
public class SomeSystem : SystemBase
{
private GameState gameState;
void OnCreate()
{
gameState = GetSingleton<GameState>();
}
void OnUpdate()
{
DoWorkOn(gameState);
}
}
does this not work???
but that's copy of gameState at moment of creation
no?
Meanwhile my GameState is smth that can be updated through game
and I need to track changes
if you don't destroy the original entity with the game state component on it, this shouln't be an issue
no I mean
I reguraly do
SetSingletone<GameState>(gameState);
with different properties
I think you're right @rustic rain it would cache the component value..
so if I got singleton once, it probably won't be same
I think what you're best to do is cache the Entity that holds the singleton component.. and then grab the component from it with GetComponent in your OnUpdate
if i understand correctly
nah
0 difference
imo
it's not getting singletons
that was slow
but apparently changing UI element text kek
Hehe ok well yeah
Regards the above, i do cache the entity in my systems generally.. so if i have to get a single component or buffer, i generally have a field with the Entity for that buffer/comp cached, and then grab the comp/buffer at the start of OnUpdate.. not sure if it makes much of any difference tbh
yay
Using NativeQueue is pog
with events
it's sort of like
ECB but with system actions
kek
@deft stump I dont think you should be using getsingleton in oncreate, as others said it will never change if it is updated and also tbh im not really sure if entity data exists at the time of the system creation? imo safer to either use onstartrunning or onupdate. can also use cdfe to get the singleton data by using the entity in a job. tertle mentioned something about getsingleton can create "a sync point on writers" but not really sure what that meant.
subscenes converted even before program is run tho
so entities from there will exist
am I forgetting that if you use GetComponent() then if you want to change that component you have to use SetComponent() ๐
@rustic rain as binary data on disk, that doesn't guarantee anything about when its loaded. a simple test of using HasSingleton<T>() on a tag inside of a subscene returns false in OnCreate and true in OnStartRunning
when your managing the creation of your own systems and order it shouldn't be that much of a problem
you kind of have to manage them eventually at some points
I use the default initialization and havent found the need to create/destroy or enable/disable.
tertle mentioned something about getsingleton can create "a sync point on writers" but not really sure what that meant
If I'm allowed to interpret tertle's words, they mean that when you call GetSingleton<T> all jobs that write to T will have to be completed
so people, think this is the week we get 0.50? ๐ค
At half of the quarter ? That's an optimistic thought ^^
But let's cross fingers and hope ๐
im not optimistic though I am anxious ๐
how to properly read entities translation inside a mono script ?
i been using this so far :
var P = World.DefaultGameObjectInjectionWorld.EntityManager.GetComponentData<Translation>( entity ).Value;
but looks like the default conversion system has something more sophisticated for this
translation is Local
LocalToWorld is global
if you always want to be sure you get world space coordinates
look for LocalToWorld component
the is a nasty jitter im trying to solve
the mono position won't sync up with the simulation
(ecs-physics)
using the default components seems to add this " smoothing " system
trying to figure out how to use a similar method
just found GraphicalSmoothingUtility
The translation component is one of many that can be computed as the LTW in the end https://docs.unity3d.com/Packages/com.unity.entities@0.17/manual/transform_system.html
[UpdateInGroup(typeof(FixedRateSystemGroup))]
public class PlayerK_System : SystemBase
{
// logic
}
class FixedRateSystemGroup : ComponentSystemGroup {}
[UpdateInGroup(typeof(FixedRateSystemGroup))]
public class SetupFixedRateSystem : ComponentSystem
{
//const float deltaTime = 0.02f; // simulation rate = 50 FPS
const float deltaTime = 0.1f;
// https://forum.unity.com/threads/fixedrateutils-enablefixedratesimple-sets-deltatime-but-update-rate-is-still-the-same.859072/#post-5706391
bool HasRun = false;
protected override void OnUpdate()
{
if ( HasRun ) return; HasRun = true;
var group = World.GetOrCreateSystem<FixedRateSystemGroup>();
var fixed_rate = group.FixedRateManager;
if( fixed_rate == null ) fixed_rate = new FixedRateUtils.FixedRateCatchUpManager( deltaTime );
else fixed_rate.Timestep = deltaTime;
group.FixedRateManager = fixed_rate;
Debug.Log("[PlayerK::FixedRateSystemGroup] Ready");
}
}
and then in MonoBehaviour :
var P = World.DefaultGameObjectInjectionWorld.EntityManager.GetComponentData<Translation>( entity ).Value;
Oh reading from mono then ? Did you try in lateupdate ? IIRC it should run after ecs systems
The big wall of code you pasted is to slow down the rate ?
Hybrid
well yes , i want a fixed update rate
this way when i log the delta time its always consistent
yeah, thanks I found it
now I wonder how I can remove some UnityEngine components before HybridRenderer gets to them
no
like I want to make my own renderer
meanwhile keeping Hybrid Renderer
for everything I didn't cover
so both of them would work in the same time ?
idk about making a custom hybrid render but sounds like u would need to fork the entities package and change the class names to have a parallel conversion system working
wouldn't it be harder to modify the existing one to support multiple render systems ?
rn I want to try update in group before main conversion group
and DestroyImmidiate
sprite renderer
after I convert
oh why not use your own conversion system then ?
I do use it
you can manually execute all the conversion code
but that doesn't stop from hybrid conversion system to run too
hybrid "conversion" shouldn't run if the root game object has no convert-to-entitiy
well
how else am I gonna convert my entity?
either Subscene, which I don't want to have at this point
or convert component
make your own convert component
its not too difficult
the source code is available
sounds way more complex than it should be
maybe just a different approach
i would just copy/paste everything (inside the conversion system component) and invoke my own render pipeline
if i had one
hybrid *
that's all
I can render everything directly through Graphics API
no need to secretly have all those game objects
why ?
meshes are way more difficult to deal with
compared to using same Quad mesh
when rendering my sprites
u mean the catched polygons in memory or something ?
i would assume you generate the quads on the fly
well there's supposed to be either quad
or plane
and it's supposed to be one for all
unless you need smth extremely fancy
yyyep
and each would need a unique call per unique material
one API call per literally everything in the scene
i see
what if all you have is Sprite-Default-Lit? xD
well u can also have material property for one custom shader that have wide support for many effects
yeah, that was my goal
might not be very efficient for large sprites
idk much about hybrid tbh
sort of using conversion component
im guessing its batching the materials / meshes somehow
delete it lol
or don't use convert to entitiy check box
and make a custom mono-component
even if I make my own convert to entity component
I'd have to rewrite shitload of code
which is just uugh
rn I have this
and I'm thinking if this would be safe to my project assets
kek
I'v read scary things about this method
I have it
but
not doing anything about component
just makes it so both my component
and hybrid are spaned
like this
my component is there, but so is sprite renderer
well... clone the repo and edit the sprite renderer conversion system
to make it stop the conversion process
bbbbruuuh
see for your self
since when ?
wdym?
idk if the hybrid render cares if the component is enabled or not
it does
not just hybrid
everything
it ignores any disabled component during conversion
which is pog
its for the physics - graphics interpolation iirc
hmm, is there any way for Entities.ForEach to return me index of entity in query?
so I can fill my array with those indexes
I do Run Withoutburst anyway
do you mean entityInQueryIndex?
is that same thing as if I for loop of NativeArray of entities from query?
I mean
are those indexes go from 0 to number of entities total?
id expect it to if its run but getting a nativearray is a sure bet
ok, I'll just test
yep
from 0 to total
that's poggie woggie
ah, f
I remember now why I had trouble with it
I need to chunk batch job
since it's the only way to separate separate instances of SharedComponent
should we use System update - ForEach for physics calculations ?
the [UpdateInGroup(typeof(SimulationSystemGroup))] public class MousePickSystem : SystemBase is not using foreach
but just scheduling a burst job
and it would combine dependencies : ( m_BuildPhysicsWorldSystem.GetOutputDependency() )
compared to my system which just runs Entities.ForEach( ( - ( on a single player instance )
im not combining dependencies tho
foreach just gets codegen'd to a IJobChunk in the background if its scheduled. my own rule is if you are modifying the simulation, then it needs to be updated in the FixedStepSimulationSystemGroup
with [UpdateAfter(typeof(ExportPhysicsWorld)), UpdateBefore(typeof(EndFramePhysicsSystem))]
and after your job dependency via endFramePhysicsSystem.AddInputDependency(handle)
it's a good rule
how much restricted is the gameobject conversion, and should I be using it for like ... everything ?
if things haven't changed much, then the only thing that can be converted are transform, rendering, and physics related components (plus custom monobehavious)
also, I got discouraged by the hybrid renderer, as it didn't work with my custom shader (no fancy stuff, just combining textures based on uv data), and I also dislike the bootstrap magic, as it's just slow reflection, it includes everything (even stuff I don't want), and it's run right after the app launch, which isn't always desirable
so I was thinking of separating my project into the ecs part, where the main logic, data, and all the things I can do in ecs be ... and the other part, where gameobjects are accessed, updated, created, destroyed (including components), and both parts would be communicating with each other using event and command entities (with stuff like SpawnHammerGameObjectData in such entity)
(the gameobject side would have it's own system, and those could be in their own dedicated world ? I don't know, I'm just clueless)
best practices would be everything
but your own project determines what is possible
and what are those ?
the best practice would be using conversion on everything
creating entities (from scratch) at runtime is generally not a good idea
and why is that ?
runtime conversion is slow, creating entities in code can be slow as well (and if you do it slightly wrong, you create a lot of extra archetypes). Also you should be striving to make your approach as data driven as possible allowing designers/non programmers construct the entities as they want.
now if you're a solo dev then do it however is quickest for yourself
Me and my runtime authoring 2.1M entities. Hrm
yeah I've create a 1 million in a second or less
if you batch them with a nativearray you can create them amazingly fast
I really need a book or something ...
I'm kind of doing what you want, I have gameobjects as the visual aspect and entity stuff as the code stuff
I don't convert the gameobjects to entity's and things work fine
depends what is fine
I don't want to sacrifice performance in order to make a framework that is just worse combination of both if I don't have to
I mean with the fundamental way dots is, its not to hard to change and adapt things later on
like with the way I have mine setup up I can easily change the gameobjects to dots whenever I want
how do you have it ?
Yep. Hybrid Renderer was a mistake.
I just get the gameobject guid and put that in a component on the entities when I create them
then whenever I want to change anything on the gameobject I just use that unique id
although I thinking about I think there are components that can store gameobjects completely so that might have been a better choice
but still if I went full entities I would still use something like that because it means I can keep the rendering the animations, the gameplay, everything really separate and have them only reference one another when if they ever need to
managed component data do have that option, but I would keep an eye on how the code travels around the memory, as those data are just an index for an array of objects stored elsewhere
yeah I'm not sure mine is the best way but it seems to work ok
like I did this with gameobjects and the unity navmesh and all the of the code is dots, a basic dots state machine, etc https://twitter.com/calabitale/status/1431244778058964998
Finally completed a simple loop of entitys entering, moving along, and exiting queues. #gamedev #unity3d https://t.co/Z5x6jCouUC
I love to complicate things, so I have an array of gameobjects and entities with an int that is the index for the array
sounds simple enough to me if the arrays don't change then should work fine ๐คท
that's the limit
but I intend to pool the objects as well and do all the fancy stuff
yeah my objects are pooled
certainly the navmesh thing is something you can only do with gameobjects, if you don't want to use some third party stuff
I mean you could, but I don't think that can be also done with lighting or so
there are some ways of doing it and there is another dots navmesh in the works, but I couldn't be bothered to figure them out
Can the ECS Hybrid Renderer support skeletal mesh or static mesh only?
What are the guys doing milling around outside the queue? Trying to jump the line?
@civic ermine both
Oh nice!
Need the animation package to do any animation though
hi all, im new to using ecs and i want to know how do i add in trialrenderer and display them into my entity?
also whats the best way to store entity into a list or array so i can reference it back in the future? or is that not recommended?
hybrid renderer is quite literally just dummy game objects that follow entities with classic renderer components tho
you might want to make sure your custom shader works as it is
@zenith garden ะดะตะฑะธะป ะฒะตัะฝะธัั
simple List or array would work
it errors out
when I try to do List<Entity>
well
it depends in what context you are trying to use it
if simply in system outside of job
you can keep however you want
jobs only work with native containers
so i have a class object
i want to create a list and store it in there
is it bad if i keep doing getcomponentdata?
because rn, my frames drops to like 20 fps but it can goes up to 200 fps
so idk what im doing wrong
use profiler
alr
and look up what's eating those spikes
so far, the most expensive thing for me is Tiny's 2D physics kek
1.2ms every frame
for no reason sadkek
ah
also keep in mind entity debugger is extremely expensive
inspector and all of this
build can be about 5 times faster
geez
why would use coroutines with dots kek
im in the process of implementing it actually
im trying to optimise this project
so i should convert all coroutines to jobs right
uuugh
jobs are just black box calculations
I'm not sure if you should compare them
you put data in job, job does it's magic, you take data out of job
i see
i have some doubts btw as well
whats the difference between schedule and schedulepararrel
ah
it's only useful when either you have way too many entities or your job iterations are so expensive that splitting them will overcome schedulling overhead
ah alr
also if i want to access data from another class in a systembase (job) script, how would i do that?
use a gamemanager instance?
World.GetOrCreateSystem<T>()l
Ah
also
since im doing Entities.ForEach to loop through all the entities right
could i do another for each inside?
because i want to compare each entity against every other entity and check their distance apart each other
no
oof
so you just grab data you want to compare beforehand
and use
WithReadOnly(yourData)
GetComponentDataFromEntity
alr gotcha
var entityArray = GetEntityQuery(typeof(Translation)).ToEntityArray(Allocator.TempJob);
so i gotten the array right
do i loop through that array in Entities.ForEach?
o right
entitiy itself is just integer that points where it exists
yeah, you do that
alr
and that would be array of all entities of that data
which you access by entity
so translations is the array that im gonna loop through right
so im trying to compare
all of the entity with each other
to compare their position
and then
move the current entity if they are too far etc
so like align them up into a flock
its a flocking system
ah
if you only care about translations
ye
well i do need other component data as well
like speed etc
i still dont get how to access component data in the entity loop oof
translations[entity]
ah
any idea how I can reference this HybridEntitiesConversion class?
I can't find what assembly it's in
as my Unity doesn't see Unity.Rendering assembly
so my systembase script starts running instantly when i start the game, is there a way to only start a job only when my main thread invokes it?
or to put in simply
so i have multiple flocks
i want to start one job for each flock so it can multi threads but idk how to do it
wanna clear some doubts about job systems
so from what i know, i can create a job system using systembase class script and do entities.foreach and schedule it
so when i do that, am i creating one single job?
the ones that i watch just shows me about systembase
so thats why i thought this is the only way to create a job
is it the jobcomponentsystem?
it does some compiler generated jobs
Entities.ForEach is kinad just interface for developer
i see
you can always do jobs the way they were initially introduced
and for some cases you have to
most tutorials
are actually explaining this
correct me if im wrong, so every single onupdate frame, im creating 1 single job for each entities right?
afaik, job is like a thread
that is task to do something
to ease the stress of the main thread
look up code monkey
he has a lot of vids
on job system
and how to use them as hybrid for classic OOP projects
ah alr
for now i have used systembase for my movementsystem which i think its correct because i want it to move every frame
is running an ijob in a coroutine not recommended?
how to get componenetdata in an ijob
but how do i get the specific component in that entity
different entity has different data
before i schedule the job, i dont have any access to them
entity manager has them
i mean i do, but only to one entity
i did
o wait
but entitymanager is read only
when i passed it in
o waittt
read the error, it probably will tell what's wrong
it tells me to make it readonly oof
MoveRandom.manager is not declared [ReadOnly] in a IJobParallelFor job. The container does not support parallel writing
o ye i remember now, i need it to setcomponeentdata
so i was using maanger.setcomponentdata
soo theres no way to get the component data within the job?
just define it before job even starts
ah
i see
so instead of passing entity arrays
i should pass in the component data array
right?
since my project is fully in DOTS, I get away with entites.ForEach
ah
gotcha
dont think the data is actually being set welp
o ye anyh idea how to rotate mesh to the direction they are moving to
Im using the hybrid approach and well, i need to turn all entities invisible which are outside a certain area...
// Hides entities which are outside the movement area for not showing them to the user.
Entities.ForEach((ref Entity entity, ref LocalTransform lc, in GameObject go) => {
// Provide support for different renderer types.
Renderer renderer = null;
if (EntityManager.HasComponent<MeshRenderer>(entity)) renderer = EntityManager.GetComponentObject<MeshRenderer>(entity);
else if (EntityManager.HasComponent<SkinnedMeshRenderer>(entity)) renderer = EntityManager.GetComponentObject<SkinnedMeshRenderer>(entity);
var vec2 = (Mapbox.Utils.Vector2d)lc.pos;
if (renderer != null) renderer.enabled = movementArea.InArea(vec2);
}).WithoutBurst().Run();
However, this in incredible slow... 800 entities take like 0.7-1ms each frame.
Any ideas how i could speed this up ?
You just want the mesh to stop rendering?
Yep, just wanna turn it invisible
I think you can add a disabled component that stops the renderer from doing anything
Can't remember how to do that but I am pretty sure that is what you want
Also with the hybrid approach ? My MeshRenderer and SkinnedMeshRenderer here are... well the unity mono ones
Oh so you aren't using entity renderer?
Nope, im using a hybrid approach... entities are just the data in my project while prefabs still do that rendering stuff for me ^^
I basically tie them up, attach the gameobject to the entity and stuff like that
Oh I see. I would cache all the data you need to access since getComponet is expensive
You could set up a hashmap that used the entity as the key and the value references the mesh renderer in some way
You'll still need to disabled on the main thread though. You can just do all the expensive calculations in a bursted job
You want to end up with an array at the end of the frame that is a list of what to disabled and what to enable. Does that make sense?
Alright i see, theres no easy solution ^^ Thanks... im gonna try to cache it first.
Damn i hope they allow us to run multithreaded mono stuff with dots some day
Yep basically ^^
They probably won't. That is super hard cause game objects are all about references everywhere
Well that makes sense, but they should leave that to us. The example above could be scheduled perfectly, because those processed entities do not interact with each other ^^ But i guess unity thinks we are too stupid and wanna guide us instead
Burst just doesn't work with references. Lots of reasons for this but yeah they are also trying to make it easy for users not to screw up.
There are some geniuses but most programmers are average and this is about making it easy not to introduce insanely hard to track down bugs
You may be able to write c# threaded stuff if you really want
But I have no idea how to do that
Oh well, guess the caching stuff works... well its not really caching, but i transformed the previous code into 2 seperate loops...
// Hides entities which are outside the movement area for not showing them to the user.
Entities.ForEach((ref Entity entity, ref LocalTransform lc, in MeshRenderer meshRenderer) => {
var vec2 = (Mapbox.Utils.Vector2d)lc.pos;
meshRenderer.enabled = movementArea.InArea(vec2);
}).WithoutBurst().Run();
// Hides entities which are outside the movement area for not showing them to the user.
Entities.ForEach((ref Entity entity, ref LocalTransform lc, in SkinnedMeshRenderer skinnedMeshRenderer) => {
var vec2 = (Mapbox.Utils.Vector2d)lc.pos;
skinnedMeshRenderer.enabled = movementArea.InArea(vec2);
}).WithoutBurst().Run();
And now its blazing fast
Like 6 times faster... only because i removed those if conditions, crazy
If conditions are the devil apparently
Totally ^^ guess im gonna start a petition to ban those if conditions entirely
Oh you may have issues. in should be for readonly and there you are setting it.
Oh you are right, thanks ! But unity doesnt like ref or out with those mono components on entities... atleast it tells me that :/
I think it's about calling HasComponent not IF itself
Thanks, that makes sense ^^
uh so can anyone help with setting componenet data in ijobs?
i still cant find anything bout it
What do you have right now ? Usually you would write to a native container to extract data from an IJob
But yes with ECS you can write to components through command buffer to avoid sync points
well i dont wanna use systembase
read those
o
oh okay so not from ECS but raw Job
ye
this is my code so far
k lemme read
mTest is an entity list (i only want to update the data in these entities)
i didnt comment it so uh mb
the job is in the coroutine coz i only want it to run every TickDurationRandom
You want to get back targetdirections and targetspeeds ?
yes
or even better, set the data directly in the job
but if i cant, then getting back it and setting it on the main thread is fine too
OK, then just try job.targetdirections[indexYouWant]
yup, it's the native array you passed IN
alr
you just get it back from the job once it's completed
nah the collection is just here to retrieve the values. You dispose of it at the end anyway
i mean in the
ijobparallel
TargetSpeed += speed * weightSeparation;
TargetSpeed /= 2.0f;
because im only setting the placeholder
oh yes
alr
ight
btw is this actually efficient xd?
like we're running setmanager on the main thread
the job thread is really doing much
or keep them persistent if you know the size and always the same and then you can dispose on application quit or whatever
ight
I swear I hate the way the did quaternions in dots
it's awful
every time I need to go back into GameObject world
I have to cast quaternion into Quaternion
ok welp this isnt gonna work xd
float4x4 into Matrix4x4
my frames drops to 20 ever second
just to get correct rotations
you would have to test with your number of entities, see if you get benefits. I guess you could have heavy computations for a lot of flocking entities ๐คทโโ๏ธ
honestly never tried a job in a coroutine
eh
so im trying to run this job
every randomtick
u got any suggestions other than coroutines?
what is goal?
so why do you need coroutine in the first place here?
well i wasnt using jobs in the past
so coroutine was to seperate a thread
and to do this every tick
tick is like 1s
so uh what should i do for this case
you can do ticks by simple time comparison
lastTime += delta;
if (lastTime>= interval){
lastTime %= interval;}
or smth like that
alr ty
different ways to do that without much of an overhead
imma move this to basesystem ecs then
systembase*
also do u know why my mesh is doing a global rotation
not a local one
oh then if you use ECS I would recommend using IJobEntityBatch to iterate whole chunks
ight
i hope it will solve this issue
frames drop to 20 every 1s
when it moves
you'll get the entities from the entity query and the components from the chunk instead of doing getcomponentdata which should already provide more speed
alright
manual is pretty helpful on those https://docs.unity3d.com/Packages/com.unity.entities@0.17/manual/ecs_ijobentitybatch.html
gotcha ty
worth reading 2 to 3 times while you implement it to get the max out of it ๐
you're welcome, have fun
i have never touched archetypechunk
well manual should help understand but basically batchIndex is your current entity in this iteration
nah
it's the chunk you're iterating
can have a few, the Execute method from the job will run on each chunk
ah
FROM it you'll get your native container
i uses entityquery to get the chunk right
yes
alr
the entities selected from the query and passed to the job will be the ones iterated upon
the query is passed as a parameter of the schedule call, not as a field of the job struct
and same for components you need to access, instead pf passing them as fields, you retrieve them from accessors from the chunk
ight
(because of the query you know you only get entities with that components, so don't need to get on an individual basis, should be faster :))
alr
see here, the query is a param of the schedule https://docs.unity3d.com/Packages/com.unity.entities@0.17/api/Unity.Entities.JobEntityBatchExtensions.Schedule.html
but it should be well explained on the manual page ๐
Have fun ๐
Oh and last thing, don't know if you already saw that, but Unity showcased their own Boids implementation a while ago with a public github. Probably uses deprecated stuff now, and was quite messy at a first glance, but maybe can give you ideas ?
not sure if it was called "classic"
i can find the link if you want
because this is actually an assignment
we are required to optimise that game
so i decided to implement DOTS
could have been ๐
Oh I'm dumb it's actually in the samples repo, under advanced usage: https://github.com/Unity-Technologies/EntityComponentSystemSamples/tree/master/ECSSamples/Assets/Advanced/Boids
damn
i see
but i really hate how dots is in development since 2018
so alot of tutorials are invalid considering how unity loves to deprecate methods every day
Yup the wait is painful
like systembase was the 3rd implementation of jobsystems
Yeah but it's getting better, API is gettnig more stable
Wait for ISystemBase xD
we're expecting 0.50 this quarter
i see
That's okay you'll be able to transfer knowledge ๐
then they intend to push towards a 1.0 release
so when i converted it to ecs, i can only seem to render meshes
so does this mean, particle effects, trial renderer etc arent possible?
my lecturer told me something like coding my own custom shader and i have 0 idea on that
trial as trail renderer ?
Yeah full DOTS is not ready
i see
so theres no way to render trails for now right
unless i uses custom shaders or something
ECS, Jobs, Burt, Collections are pretty good to go
for particles, light, audio, and such, you'd need to go with gameobjects
I'm not expert in rendering, didnt see how far the hybrid renderer can go, so I shouldnt answer this ๐
they talk a little about it with what they called companion objects https://docs.unity3d.com/Packages/com.unity.entities@0.17/manual/hybrid_component.html
oo
i was thinking of creating another entity just to render the trail but i doubt thats efficient
Because I was apparently drunk, it's the index of thebatch as the name implies, my bad
o
i see
alr
also in that manual
they did the entity query in the oncreate
for me i should do it in onupdate if i want to get the newest info every tick it runs right
o wait im dumb
i should only get it once no matter what
@karmic basin sheesh its fucking optimised (for me)
Nice ๐
uh anyone knows how to rotate ecs meshes to the direction they are moving to?
quaternion.LookDirection
There are many examples of this - likely even the whole genre of game you're trying to make. There's a reference project a friend made here if it's helpful: https://github.com/ElliotB256/ECSCombat
Vector3 targetDirection = TargetDirection.Value;
targetDirection.Normalize();
Vector3 rotatedVectorToTarget =
Quaternion.Euler(0, 0, 90) *
targetDirection;
Quaternion targetRotation = Quaternion.LookRotation(
forward: Vector3.forward,
upwards: rotatedVectorToTarget);
Quaternion smoothRotation = math.slerp(rotation.Value,
targetRotation, RotationSpeed.Value * dTime);
rotation.Value = smoothRotation ;
this is what im doing rn
and its rotating globally
ah alr
hmm
@karmic basin hey, for the unitybatch job right, is there anyway to not loop through chunks but instead an entity list?
because i have different flocks right, and each flock has their own entities, so i dont wanna update all of the entities, just the ones in each flock
(well i do need to update all the flock, so essentially i need to update all the entities, but different flock has different data so idk how to identify which entity the flock is in and use that data accordingly)
actually i got an idea
Yeah the purpose of the batch job is to iterate chunk
You can go back to a simple EntitiesForEach to iterate entities from a query and it will write the job for you
i see
i think for my case its more effiicent to iterate chunk since i need to iterate all the boids
i just need to know which flock they are in and apply the specific flock data
I would probably try using SharedComponentData as a first naive implementation, but I would also look at the entity debugger how much space entities in my flock take in the chunk, just to make sure the SCD doesn't fragment the chunks more than iI had
no point iterating over the flock list and then do entitiesforeach on the entity list
since both is iterating over all the entities whereas the 2nd way is more inefficient
i see
you could also have a previous job that stores entities in different container for different flocks
ah
what im doing rn is
i have an entity list
when i generate a new entity
i add it to the lis
how do i check this btw
like which area do i look out for
๐คทโโ๏ธ if it was me I would just reach a first working implementation first, then begin to optimize starting from the worst, but I'm no expert ^^
looks like standard garbage disposal operation.
Could be something else creating garbage.
Oo nice
I'm still in the middle of doing it but I can't seem to get the movement to work
Did u use unitys physics system or ur own?
I had a horrible time with unitys physics system, my code was running at 7 fps... But i think that was mostly because of me using Getcomponents in the update loop lol
It doesn't really have a physics system. It's actually an old code and I'm converting it to work with ecs
The old code uses transform.Translate
Which ecs can't access transform methods
I did this
Not sure what ecs is tbh
Im a noob
Ah it's the entity component system, which I think it can't access unity api like transform functions etc
Oh
So I need to convert it to transform.positon +=
Same for rotation
The old code uses RotateTowards which I can't use it too
So I need to convert to either lerping or some other way
Old code as in, it used to run on a old version of unit
Or was it just something u did before
I need to learn about ecs lol will do it next weekend
Yes
It's running on the game object classic system
And our job is to optimise it
So I thought of implementing unity DOTS
// Update is called once per frame
public void Update()
{
Vector3 targetDirection = TargetDirection;
targetDirection.Normalize();
Vector3 rotatedVectorToTarget =
Quaternion.Euler(0, 0, 90) *
targetDirection;
Quaternion targetRotation = Quaternion.LookRotation(
forward: Vector3.forward,
upwards: rotatedVectorToTarget);
transform.rotation = Quaternion.RotateTowards(
transform.rotation,
targetRotation,
RotationSpeed * Time.deltaTime);
Speed = Speed + ((TargetSpeed - Speed)/10.0f) * Time.deltaTime;
if (Speed > MaxSpeed)
Speed = MaxSpeed;
transform.Translate(Vector3.right * Speed * Time.deltaTime, Space.Self);
}
so ye i need to convert this script
are you both students? is dots an assignment or something?
im a student ye and im trying to implement dots
just hoping your professor didnt assign dots specifically ๐
nah, he said to optimise a project, i just decided to implement dots
protected override void OnUpdate()
{
float3 playerPos = GameObject.FindGameObjectWithTag("Player").transform.position;
Entities.ForEach((ref CellComponent cell, ref RenderMesh rMesh, in Translation translation) =>
{
rMesh.mesh = CellLODMeshGenerator.generate_mesh(
new int2(16, 16),
0,
new Texture2D[]{
new Texture2D(16, 16, TextureFormat.RFloat, 1, true)
}
);
}).Schedule();
}
it says Entities.ForEach uses ISharedComponentType RenderMesh. This is only supported when using .WithoutBurst() and .Run(), so where do I put the .Run? (and also can I use the burst compiler on the generate_mesh function if it's just a static function elsewhere?)
Entities.ForEach((RenderMesh mesh) => { ... }).WithoutBurst().Run()
highly doubt you would be able to make generate_mesh burst compatible. Pretty sure Texture2D is not a blittable struct unless it's your own custom struct.
Oh does burst compilation need to have blittable data types? Hmm
hey
if i create new entities on user input, and i want to update new entities created, i need to do an entity query on every update right
How can I destroy an entity?
ยฏ_(ใ)_/ยฏ
anyone know why the entity is rotating but the sprite is the same direction
EntityManager.DestroyEntity(entity) or similar via EntityCommandBuffers @white island
Yes, but how do I do it within a system? (inherit systembase)
entitymanager is a property of the system
if you mean within foreach, you need .WithStructuralChanges and .Run
pretty sure u can access entitymanager by doing this in system but correct me if im wrong
okay, got it, thanks. i heard using the entitymanager to remove things can cause blocking problems?
anyway to access public variables in other scripts (monobehaviour) from systembase?
You just do it normally
how?
o wait
hold up
ye idk how
normally would be to do a public variable, put in the script and drag it in using inspector
so uh can anyone help
Bring a firehose to a super soaker fight
can i use GameObject.Find() in systembase?
Yeah, it's static method
It's really inefficient though. So be careful.
So well rn, I have a flock system, each flock has their own rules so I want my system base to retrieve these rules however these rules are stored on a monobehaviour script so do u guys have any advice for this?
don't store them in a monobehaviour ๐
can i schedule 2 jobs in a systembase at the same time
you can schedule as many jobs as you want
alr
o
well i store them there coz i can edit them in my inspector instantly
So I saw some mention
that GetSingleton
causes all scheduled jobs to complete
if they use that component
is that true?
is it possible to use entityquery to filter out only entities with a component and a particular value in that component?
yes
you can avoid syncs by using GetSingletonEntity in the system and passing it to the job and using GetComponent<T> within the job to get the component
only shared components, really not something you want to do
i see
so rn im using ijobentitybatch where it uses batches from an entity query right, but because mine is a flocking system, i would like to schedule one job for each flock. i currently already have an entity list that stores all the entities in each flock,
so what kind of ijob should i use to loop through an entity list?
so I need to pass ComponentDataFromEntity?
to jobs
so they create dependency and all?
var playerVelocityData = GetComponentDataFromEntity<PlayerVelocity>(true);
var player = GetSingletonEntity<PlayerVelocity>();
//float velocity = GetSingleton<PlayerVelocity>().value.x;
Entities.WithReadOnly(playerVelocityData).ForEach((Entity entity, ref Translation translation, in BackgroundMovement backgroundComponent) =>
{
var velocity = playerVelocityData[player].value.x;
translation.Value.x -= backgroundComponent.MovementSpeed * delta * velocity;
}).Schedule();
}
like this?
Commented - before
all lines with var are after
you can just do GetComponent<PlayerVelocity>(player )
inside job?
yes
yes
var velocity = GetComponent<PlayerVelocity>(player).value.x;
//var velocity = playerVelocityData[player].value.x;
so
it just codegens to GetComponentDataFromEntity under the hood
welp, thanks a lot
so many code optimisations to do now
I will prob reduce amount of lines by 10
simply because of this
what about EntityManager btw?
does it force incomplete jobs to finish too?
I assume yes, since it seems like the only safe solution...
yes
ah damn, silly limitation
if I have foreach with component type
with write access
I can't do that GetComponent
the alias issue
Is there just any way to run threaded job without burst that works with monos?
when you know 100% it's thread safe
kind of disable all those limitations
pretty much nothing in unityengine (i.e. monobehaviours) can be used off thread
you can totally use classes etc in a threaded (non-burst) job
but yeah, not unityengine stuff
I can assign fields or change transforms
pretty sure
you can assign fields because that's not using anything in unityengine
you should not be able to write to transform unless you use transformaccessarray
actually yeah that's probably true, might not let you pass in managed memory
you'd have to pin the memory and pass it in as a pointer
bbbrrruh
how to deal with this
I need to keep game object for animator
yet if I convert to entity
obviously it won't keep any info about GameObject prefab
and thus no animator
on respawn
eh how would i go around updating all the entities in an entity list on every tick (1s or so)?
would i use ijobforparrallel or is there a better way?
entities.foreach
entities referring to the entitylist right?
wait you mean you have actual List<Entity>?
which kind
i tried ijobforparrallel and its giving me this error
IndexOutOfRangeException: Index 0 is out of restricted IJobParallelFor range [24...24] in ReadWriteBuffer.
ReadWriteBuffers are restricted to only read & write the element at the job index. You can use double buffering strategies to avoid race conditions due to reading & writing in parallel to the same elements from a job.
Unity.Collections.NativeArray`1[T].FailOutOfRangeError (System.Int32 index) (at <9baebf9af86541678fd15bfdbf5f26eb>:0)
Unity.Collections.NativeArray`1[T].CheckElementReadAccess (System.Int32 index) (at <9baebf9af86541678fd15bfdbf5f26eb>:0)
Unity.Collections.NativeArray`1[T].get_Item (System.Int32 index) (at <9baebf9af86541678fd15bfdbf5f26eb>:0)
FlockingSystem+FlockJob.Execute (System.Int32 index) (at Assets/Scripts/Testing/FlockingSystem.cs:226)
Unity.Jobs.IJobParallelForExtensions+ParallelForJobStruct`1[T].Execute (T& jobData, System.IntPtr additionalPtr, System.IntPtr bufferRangePatchData, Unity.Jobs.LowLevel.Unsafe.JobRanges& ranges, System.Int32 jobIndex) (at <9baebf9af86541678fd15bfdbf5f26eb>:0)```
alr
ok I'm extremely dissapointed by perfomance of full dots 2D solution
Wait we have a 2d dots now?
I took 2d physics from Tiny
180 fps on PC, 30 on mobile lol
for extremely simple graphics
and game logic
Let's be real the whole dots is yet another half baked feature that they overhyped, pushed out way too early and then backtracked and it will now be a zombie like the input system(s) the UI system and many others.
Heck the newest editor release does not even properly save your progress anymore.
