#archived-dots
1 messages Β· Page 93 of 1
I read the first part of that and got excited lol. I'll join you with wishing
lol same here
is today the day?
I got a question, I've asked it before but no one responded
I have a situation where I'm generating a few million raycast commands
its for analyzing a scenes structure
and i found that populating the NativeArray<RaycastCommand> too more time than actually executing the Raycasts
I'm executing the raycasts in a batch, and so its being executed in parallel
however, I'm populating the NativeArray sequentially in a loop
is it possible for me to populate that NativeArray in paralell, via jobs or something?
few million actually meaning about 200 million
ideally, though it will likely end up being less
yeah you can populate nativearrays in jobs
noice
Hey everyone, I'm looking for some info that may or may not exist (I'm asking before making a thread and after searching).
Is there anything saying that we should reduce the number of components on the same entity ?
Also anything about the size of the component itself (let's say all the fields are always used by the system) ?
Thanks!
Iirc the recommended limit for the amount of component fields is 100 bytes. I've heard that It's better to have a lot of components with a few fields than one component with many fields
For your first question I'm not sure and also interested in an answer
Yeah heard about that too but didn't know about the 100 bytes
I do notice that when I have many components on an entity, chunk utilization goes way down
Might be me assigning correlation to the wrong thing tho
I will post a thread ~tonight and see if I can have some answers from the unity devs
Ok can you let me know when you do?
Sure!
is there any solution to lack of NativeArray<NativeArray<T>> / NativeList
you could flatten it for array case
nope, this is not for 2d array
i need a proper jagged array and it looks like implementing it myself is the only way which is really frustrating
would it be possible to use native multi hashmap instead, thats what i do
i also read somewhere about using entities with buffers like 2d array
i mean jagged*
i mean my use case is for managing sub-meshes for mesh generation
ill try multi hashmap, im not making very large meshes yet so performance will probably be fine π€·
It's fast, and yeah that's the tool I use for jagged arrays, works well with the matching job to visit values
is there a way i can extend the math.random class? i want to add a simple method but not sure where i can find it
basically a chance method
so if ( Chance(2) ) {}
ref extension method should work @onyx mist
public static class RandomExtensions
{
public static int Chance(this ref Random rand, int inp)
{
}
}
wouldnt extension methods not work in jobs because they are static?
no they are fine
NICE
you should just avoid accessing static data
oh so even normal static methods would work?
like everything in the Unity.Mathematics.math class is static right? but obviously those are all fine to use
ok thank you!!!
yes methods are totally fine, just make sure to not access any shared static data and you're all set
you can read static readonly data if it's burst compatiable, but such data will get backed into constants access by bursted functions
you can't write to static data, as others have pointed out
well static readonly struct fields are immutable by design, but its good to know that Burst/Jobs won't complain about them
"but such data will get backed into constants access by bursted functions" sorry could you elaborate on this?
im not sure what that means
@stable fog you can probably pass nativeslices of that array and populate in parallel
@onyx mist - this article explains it in depth: https://jacksondunstan.com/articles/5274#more-5274
is there a way to disable transform conversion system?
While Rotation component allows to rotate and Translation component allows to move, which component should be used for scaling an entities appearance. Probably the rendered mesh needs to be scaled, as it sounds weird that the entity has a scale itself. But I can't find a property for RenderMesh that reflects a rendered scale. Sry, probably a dumb question.
LocalToWorld component has the scale
But i don't know how to modify the matrix to scale it
yea Scale or NonUniformScale (IComponentData's) are probably what you're looking for @prime cipher
Is there any better way of creating an Entry point for coding in the DOTS world instead of a monobehaviour attached to an empty gameobject. I am trying a JobComponentSystem class with a EndSimulationEntityCommandBufferSystem var in it. Is there a better way?
@digital scarab @amber flicker THX, works like a charm.
[BurstCompile]
[RequireComponentTag(typeof(SpaceObject))]
struct OrbitingJob : IJobForEachWithEntity<Orbit, Translation>
{
public float DeltaTime;
[ReadOnly] public ComponentDataFromEntity<Translation> Translations;
public void Execute(Entity entity, int index, [ReadOnly] ref Orbit orbit, ref Translation translation)
{
Translation pivot = Translations[orbit.Focus];
float3 dir = translation.Value - pivot.Value; // get point direction relative to pivot
dir = Quaternion.Euler(0f, orbit.Speed * DeltaTime, 0f) * dir; // rotate it
translation.Value = dir + pivot.Value; // calculate rotated point
}
}
protected override JobHandle OnUpdate(JobHandle inputDependencies)
{
Debug.Log("SpaceObjectOrbitingSystem::OnUpdate()");
var job = new OrbitingJob()
{
DeltaTime = Time.deltaTime,
Translations = GetComponentDataFromEntity<Translation>(true)
}.Schedule(this, inputDependencies);
return job;
}
shouldnt that work for the ComponentDataFromEntity? I get a weird exception: "InvalidOperationException: The writable NativeArray OrbitingJob.Iterator is the same NativeArray as OrbitingJob.Data.Translations, two NativeArrays may not be the same (aliasing)"
you can't have a CDFE take the same type (Translation) as the Job itself
you can remove Translation from the IJobForEach and use the entity passed into execute to get it from the CDFE instead
@amber flicker Oh I C, I thought it would be the combination of refs, so that Translation is different than Orbit+Translation
However, as I have the Entity also, I can simply get the Translation from the CDFE too
I think it's because there's nothing to stop you getting the same Translation (from the CDFE) as the one that would be passed as ref into the job so guaranteeing safety for writing is why that restriction exists I'd guess
Yes, but now I need to declare the CDFE to be writable π¦
yes
ironic I'm trying to do something similar to the example above but I need to iterate through all the CDFE in a for loop
I dont think I can do that though, I'm guessing I need to use an EntityQuery instead
Accessing components via CDFE is all rand access so it can be vastly better to iterate over a query if possible (which it should be)
hi all, can anyone advise how to change which Material an entity is being rendered with? I can't seem to use RenderMesh in ForEach like I can with the Translation component...
for each entity I need to iterate over all other entities and check the distances between them so EQ converted to nativearray I guess would be best
@glad grail the reason you can't iterate over them is because every RenderMesh is a SharedComponentData which puts each entity with a different mesh into a separate chunk.
oh so all entities instantiated from the same Prefab share the same SharedComponentData
@pliant pike not sure the best way to do that - you can't avoid rand access - nativearray method probably works as good as any - only thing that occurs to me is you may not want to calculate the distance from A to D as well as from D to A
@glad grail if the prefab has a RenderMesh, then basically yea, they'll all be entities with a SharedComponentData (RenderMesh) with the same value/hash - you can actually iterate over the entites, just not using foreach<RenderMesh>
Thanks @amber flicker can you recommend a good way to change material (to show unit selected in RTS)? Or maybe show/hide a second child mesh?
I haven't done anything with materials and it's quite implementation specific but in case it helps point you in the right direction, you could e.g. add a 'Selected' tag to your unit and then do something like (psuedo code)myQuery = GetEntityQuery( ComponentType.ReadOnly<Selected>()); entityManager.SetSharedComponentData(myQuery, new RenderMesh(){ //your new values e.g. mesh = unitMesh, material = highlightMaterial .. }) This is a batch method. Otherwise you could iterate the query in a system and do e.g. var renderMesh = entityManager.GetSharedComponentData<RenderMesh>(entity); renderMesh.material = highlightMaterial; entityManager.SetSharedComponentData(entity, renderMesh); @glad grail
that's really useful I'll look into that thanks @amber flicker
For the second snippet, is renderMesh an object? i.e. if I change it will it affect all entities using that RenderMesh, or will it assign a new one just to the selectected entity?
tbh the first approach looks like it will fit better anyway, just interested really.
so the first approach relies on you setting e.g. all the query results to have the same mesh (useful when you do want to change all in a bulk way but maybe not what you want a lot of the time). The second does assign to just one entity after getting the current values. You could mix them and e.g. get the RenderMesh from entity 1 then use a query to set the shared mesh for a bunch of entities at once. Not sure if that helps/makes sense.
Yep that answers my question, SetSharedComponentData will assign a new data to just the one entity in the second code snippet.
How can I change the scale of an Entity using the new ECS?
EntityManager.SetComponentData(entity, new Scale(){Value=1.0f});
I tried that but I just get this error: ArgumentException: A component with type:Scale has not been added to the entity.
@dry dune
I'm not a big fan of the way it works - there's two things that could be going on here - both visible via the entity debugger. I would guess your entity doesn't have a 'Scale' component. It likely either has a) no Scale component or b) a NonUniformScale component. If a) then add a Scale component. If b) change the NonUniformScale instead.
then replace set with add
how does it look in the entity debugger?
And then when I spawn the entity I call
m_entityManager.SetComponentData(glitter, new Scale { Value = Random.Range(0.1f, 10.0f) });
are you trying to set the scale of a hybrid entity or a pure ecs entity?
because scale wont have any effect if you are using the old transform
also.. adding a Transform component? does that do anything useful?
Yeah I believe hybrid @safe lintel
Also @amber flicker
Removed Transform
Didn't do anything, no
well if you continued using the transform, it would be most optimal to change scale via a ComponentSystem
like
Entities.With(m_GlitterQuery).ForEach((Entity entity, Glitter glitter, Transform transform) =>
{
transform.localScale = newScaleVariable;
});
I got rid of the transform
So should I not be able to just add the NonUniformScale component?
Sorry, very new to this way of programming so it's confusing me haha
That's the entity debugger
the pinned message has good info, also the docs especially relating to the transform system shows in depth how it all works, its a bit much on first glance but just read it slowly and it will begin to make sense https://docs.unity3d.com/Packages/com.unity.entities@0.1/manual/transform_system.html
Thanks for the help @amber flicker @dry dune @safe lintel I got it sorted in the end. I used CompositeScale and setting the matrix manually. Probably not the best way to do it but it works haha
We're moving to the end of the week, and still nothing :' (
Such is development life, or at least the ones waiting on releases.
I'm they're all working as hard as is reasonable (possibly even more than that) to get it out as soon as they can.
hopefully friday's the day
Is it good practice to have a dynamic buffer on entities with a lot of fields in order to save on memory in the chunk? Only a single buffer so an entity wouldn't have more than one of these
Example: a bufferelement of personality with int fields like greed, kindness, pride, extroversion, etc
are you actually running out of memory on the chunk?
i currently have a lot of components on my entities so any reduction on that would be great
the ability to clump all the personality traits into one buffer that stores its mem on the heap sounds lovely
basically i wanna know if what i did for personality here is ok
and also if i can add more fields or if thats already too many
dont see any reason that there would be anything wrong with doing that, more curious how many components and fields in total you have?
ill send a pic in a sec
still trying to find ways to minimize the amount but a lot of it are tags
did you set the internal buffer size to something low? ive never personally tried it with zero
i didnt set the buffer size at all since i assumed it would make it so it would push all of it onto the heap
and i read buffers could be gigabytes in size if need be so hey why not lol
well my understanding is the internal size is whats stored in the chunk, and above that it goes to the heap
oh right i get what you mean, wasnt sure if there was some hidden default if you dont happen to specify
hm im not sure π€
but all in all, id personally just store it as regular components until i ran into a problem, unless theres a particular reason you are trying to have the chunk store as many as possible?
if you are regularly iterating on them arent you giving up all the benefits of linear memory layout?
isnt that the ideal? all i know is i saw my chunk utilization go from 803 at the start of the project to 34 now and i got worried
premature optimization isnt ideal π
true
and it might not be an optimization at all in your case
i dont know if theres a way to view cache usage, but the megacity project has a really high usage of chunks and i personally dont have any problems with it
i gotchu
guys, I have been following the ECS unity tutorial on youtube. and it uses IJobProcessComponentData to filter which entities to work on. But i am trying it in code right now, and it doesnt seem to have IJobProcessComponentData anymore. Am i mistaken? if not, whats the best other subsitute for it? IJobParralelForFilter?
that tutorial video also mentions the [computejoboptimization] tag which my editor doesnt seem to recognize.
here precisely https://youtu.be/j2z5KRWZTDA?t=326
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
That is a very old tutorial
Changed to [BurstCompile]
Recently I watched official videos about ECS: https://unity3d.com/ru/learn/tutorials/topics/scripting/introduction-ecs
In videos there are...
https://www.youtube.com/watch?v=BNMrevfB6Q0&list=PLX2vGYjWbI0S1wHRTyDiPtKLEPTWFi4cd is a generally good place to start with up to date video tutorials around DOTS
ah, thnx @magic frigate and @solar spire
Jeez, even that video might be partially out of date in a matter of days
oh wait, no.. I am not converting from gameobjects, I am making everything new from code
I think the title means more to convert the way the game is written rather than just the conversion workflow
oh ok
It's a whole playlist of all of the DOTS content from Unite Copenhagen
gotcha, so weekend full for 43 minutes videos each :p
Pretty much π I have all of them in my watch later list
lol
Website
https://unity.com/dots
Megacity: https://unity.com/megacity
Project Tiny: https://unity.com/solutions/instant-games
DOTS Best Practices
https://learn.unity.com/course/dots-best-practices
Forums
https://forum.unity.com/forums/data-oriented-technology-stack.147/
Physics: https://forum.unity.com/forums/dots-physics.422/
Netcode: https://forum.unity.com/forums/dots-netcode.425/
Graphics: https://forum.unity.com/forums/dots-graphics.641/
ECS 1.0
https://forum.unity.com/threads/experimental-entities-1-0-is-available.1341065/
Videos β’ GDC 2022
Authoring and debugging workflows https://www.youtube.com/watch?v=p4ct4vHWYt0
Path to leveraging DOTS in production https://www.youtube.com/watch?v=KJOhIhOv2EI
β’ Unite Copenhagen 2019
https://www.youtube.com/watch?v=BNMrevfB6Q0&list=PLX2vGYjWbI0S1wHRTyDiPtKLEPTWFi4cd
Guide
https://github.com/Unity-Technologies/EntityComponentSystemSamples/tree/master/DOTS_Guide
Documentation
Entities: https://docs.unity3d.com/Packages/com.unity.entities@latest
Mathematics: https://docs.unity3d.com/Packages/com.unity.mathematics@latest
Burst: https://docs.unity3d.com/Packages/com.unity.burst@latest
Unity Physics: https://docs.unity3d.com/Packages/com.unity.physics@latest
Havok Physics: https://docs.unity3d.com/Packages/com.havok.physics@latest
Job System: https://docs.unity3d.com/Manual/JobSystem.html
Graphics (Formerly Hybrid): https://docs.unity3d.com/Packages/com.unity.entities.graphics@latest
Netcode: https://docs.unity3d.com/Packages/com.unity.netcode@latest
Animation: https://docs.unity3d.com/Packages/com.unity.animation@latest
2D Entities: https://docs.unity3d.com/Packages/com.unity.2d.entities@latest
DOTS Samples (Entities & Physics): https://github.com/Unity-Technologies/EntityComponentSystemSamples
@dull copper your legacy will always be remembered o7
for those wondering about this, the old pinned message couldn't fit all the info on single message anymore, so had to be repinned (with extra message to reserve more space)
@solar spire I saw that post and was like YES AN UPDATE!
... then was saddened to just see it is book keeping with having all the latest links available
why do you play with my heart so?
If Discord allowed me to reorder pins or post messages larger than 2000 characters I wouldn't be here relishing in your pain
Loool
No worries
Im on standby development wise until they release the next update
Everyone's waiting on that networking sample!
Networking will be fantastic! Though Im assuming they dont have a TCP handle at all
which in my case wont assist if they dont but wont be surprised if that is skipped over π
I read Soaryns message "YES AN UPDATE" and got excited π
If I choose Convert and Inject Game Object with Convert To Entity, can I access the injected game object having the entity at hand?
can we have fps sample release today pleaseπ₯Ί
Does anyone have ideas how to draw gizmos for component systems and entities without using monobehavior?
In-editor you use mono for just about everything, so I'd assume you can't.
Though, all you'd need mono for would be the drawing itself; you could make some system basically output the exact inputs the gizmo drawing system uses. I suspect it might be easier to just have a mono class that reads entitycomponents and draws from that directly, though.
@prime cipher yes you can
You can grab the component object via entity manager or using the query builder
@frank knoll For that I use a Singleton, which allows to add Actions. The MonoB iterates over the Actions in OnDrawGizmos and invokes them. In my Systems I can then call the add method with anonymous body using the Gizmos.Draw* methods.
But yes at least for drawing you need the one MB to hook onto OnDrawGizmos
I'm creating pure entities, not instantiating gameobjects and converting them
But how can I add Physics Body to it?
And Physics Shape Authoring
And to set values, i.e. dynamic and mass = 10
the Physics Body is a simplification of the actual components that go into creating a rigidbody equivalent. here are the ECS components that go into it (plus a link on creating it through code, for good measure: https://docs.unity3d.com/Packages/com.unity.physics@0.2/manual/getting_started.html )
Ah brilliant, so I can add those components separately
like a normal component
and set the values that way?
yep. exactly
Thanks for your help π
just to make sure we're on the same page, it's an ECS component, not monobehaviour
Yeah, extending from IComponentData, right?
Brilliant, cheers
so, i have added a "toGenData" component to my entities and im just using it as a tag to generate some data for the entity. In the relevant JobComponentSystem I have a IJobForEachWithEntity<> job setup. At the end of this job's execute function I want to remove the toGenData component from this entity. I see i need a EntityCommandBuffer. and most examples i see, they are attaching it to a EndFrameBarrier. Is this appropriate/best way of doing it in my case?
mind you, this data only needs to be be generated the first time for every entity, even newer ones. hence using this tag
By endframebarrier do you mean like end[insert-system-group-here]barrier? Or postupdatecommands?
like World.GetOrCreateSystem<EndFrameBarrier>(); and m_EndFrameBarrier.CreateCommandBuffer(), and the link from where i got it https://docs.unity3d.com/Packages/com.unity.entities@0.0/manual/entity_iteration_job.html its the last code snippet on the page
Ahh I didn't know that was a thing. I usually just use the system group ECBs
Yes
I have a similar system to yours with a "toBeUpdated" tag. I usually do that in the beginsim ECB and haven't had any issues so far with it
are u using JobComponentSystem class with IJobForEachWithEntity job to perform logic on your entities?
Yes
Tho remember to take my words with a grain of salt since I didn't know about endframebarrier π€ no idea how that differs from the group ECBs
hmmmm, what do you mean groups's ECB's?
But as I said even iteration over tens of thousands of entities I haven't had an issue with my datagen tag
These ECBs
Keep in mind I'm abysmal at terminology
oh.. i didnt know about these ECBS
Wish I was home so I could just show you the code for my system π
Ah
Looks like we learned something new about command buffers from each other
please do when you do get home! lol, I could use all the insights i can get specially if you are doing simialr code
endframebuffer is supposedly the postupdate command buffer thingy for JobComponentSystems
as you dont get a postupdate command buffer for the JCS
but in my Execute, i cant seem to get anything about of the EntityCommandBuffer π¦
Maybe the group ECBs are for more specific frame timings
Here's how I got my command buffer in a different system
lol, I just check for group ECB in the code and wow... there are so many of them!!!!
how i paste code? cant seem to paste code here lol
Usually I just screencap it
it's best to use 3 backticks (`) around block of code
you can put "cs" after the first set of 3 for basic syntax coloring
EndInitializationEntityCommandBufferSystem endinti = new
EndInitializationEntityCommandBufferSystem();
EntityCommandBuffer ecb = endinti.CreateCommandBuffer();
ecb.RemoveComponent<nodeToGenTag>(et);
ok thnx @craggy orbit but i think i got the cs part wrong hehe
there you go, you are correct, the first line just needs to be the backticks and cs and the code starts from the next line
Is there a way to make sure that a job component system gets the job of another system as it's dependency?
Why would you want to do that?
not to be rude or anything, but attempting to do so sounds like you might be doing a bad pattern
kinda have to do it for some of the physics system queries so its already a thing
if you search the physics code for FinalJobHandle you can see how they implemented it
I have a job which serializes the messages of a connection and another one who send the messages.
I can probably just put them into one system and schedule them with the other one as a dependency.
Depends how you want to separate your code. You can also have two systems and use the UpdateBefore or UpdateAfter class attributes.
Is the update here?
no
I'm super curious if they finally fixed the unity physics timestepping
because they did use it on the upcoming shooter sample
and they definitely can't make networked shooter's physics dependent on rendering speed
@dull copper what do you mean fix physics tinestepping? Are you talking about dots physics?
The net sample uses simulation and render loop already.
dots physics yes
I think they use simulation group for it but it's ran on each update
You can check line 111 and forward. https://github.com/Unity-Technologies/multiplayer/blob/master/sampleproject/Assets/NetCode/ClientServerWorld.cs
I'm getting nightmares of this if endif stuff here π
there has to be cleaner way to do this
Anyone know how to get the length / byte array from a BlobBuilder or BlobAssetReference<t>?
I want to store it manually, outside of any subscene, and manually create a BlobAssetReference from its bytes:
BlobAssetReference<BlobData>.Create(bytes);
The data is in there, and the unsafe ptr is exposed, but not its length: "BlobAssetReference.m_data.header->Length" that is internal.
[FieldOffset(8)]
public int Length;
I could just grab it manually I guess
Current solution:
public unsafe static class BlobAssetExtensions
{
public static Type BlobAssetHeaderType = typeof(BlobAssetReference<>).Assembly.GetType("Unity.Entities.BlobAssetHeader");
public static FieldInfo LengthFieldInfo = BlobAssetHeaderType.GetField("Length");
public static int LengthFieldOffset = LengthFieldInfo.GetCustomAttribute<FieldOffsetAttribute>().Value;
public static int SizeOfHeader = Marshal.SizeOf(BlobAssetHeaderType);
public static int GetLength<T>(this BlobAssetReference<T> reference)
where T : struct
{
var ptr = IntPtr.Add(new IntPtr(reference.GetUnsafePtr()), -SizeOfHeader + LengthFieldOffset);
return *(int*)ptr;
}
public static byte[] ToManagedByteArray<T>(this BlobAssetReference<T> reference)
where T : struct
{
var ptr = new IntPtr(reference.GetUnsafePtr());
var length = reference.GetLength();
var managedArray = new byte[length];
Marshal.Copy(ptr, managedArray, 0, length);
return managedArray;
}
}
is there anyway to disable transform components getting added to entities?
you can make a conversion system to handle it after the fact, its a little clumsy but it works
Hello, what can I do if my system is not visible in entity debugger?
@plain cloak
[UpdateAfter(typeof(LegacyBoxColliderConversionSystem))]
[UpdateAfter(typeof(LegacyCapsuleColliderConversionSystem))]
[UpdateAfter(typeof(LegacySphereColliderConversionSystem))]
[UpdateAfter(typeof(LegacyMeshColliderConversionSystem))]
[UpdateAfter(typeof(PhysicsShapeConversionSystem))]
[UpdateAfter(typeof(LegacyRigidbodyConversionSystem))]
public class PhysicsAdditionalConversionSystem : GameObjectConversionSystem
{
protected override void OnUpdate()
{
Entities.ForEach((RemoveVelocity removeVelocity) =>
{
var entity = GetPrimaryEntity(removeVelocity.gameObject);
DstEntityManager.RemoveComponent<PhysicsVelocity>(entity);
}
);
}
}
RemoveVelocity is just an empty monobehaviour. someone mentioned a better way which was I think to set the entity to an archetype but I never tried it personally
@stuck hatch does your system not have entities to process? it wont show up if so
I have disabled one and an entity query which includes disabled
I also use World CreateSystem and I see the debugger runs into OnCreate but no OnUpdate
@safe lintel i see, it would have been better if i could just disable it but i guess this works too. thanks
if I use GetEntityQuery in a system, is it correct that this defines a scope for the system?
i think its also tied to whatever job that system also schedules
For some reason EntityQueryOptions.IncludeDisabled does not work, I tried with entityMgr.SetEnabled(entity, false) and entityMgr.AddComponentData(entity, new Disabled()); not both together, the query could not find the entity, now I am using EntityQueryOptions.IncludePrefab, with Prefab Component, that works
hey guys, I posted this the other day but I'm still not able to figure out what's up.
I have 2 systems:
Vendor Transaction - Finds transactions, deducts currency from wallet component for the transaction then adds a Dead Entity component
Dead Entity Cleanup - Finds Dead Entity component entities and deletes them
When I run the code with 2 entities that have transaction components I get the following happen in sequence:
Add dead entity component to entity 1
Add dead entity component to entity 2
Add dead entity component to entity 1
Add dead entity component to entity 2
Delete entity 1
Delete entity 2
followed by exception: DeadComponent has already been added to the entity
wondering if anyone can help me? Sounds like the the request to add the component via a buffer is happening twice before the actual buffer runs, perhaps?
you should exclude DeadComponent from your PurchaseQuery
or
run the dead entity cleanup some time after end simulation barrier
@rare umbra the problem is when vendor transaction runs you add the entity at end simulation barrier and dead entity system misses the query for the current frame. When next frame comes dead entity system queues destroy command for end simulation barrier again so vendor transaction runs again since vendor transaction component is still there. And you get 2 destroy requests for the same entity which causes the error
another solution is not using command buffer for destroying the entities and doing in at initialization system group or something using EntityManager batched operations. This should also be more efficient
@plain cloak
you should exclude DeadComponent from your PurchaseQuery
Iβll probably do this, sounds pretty straightforward, thanks!
Or run the dead entity cleanup some time after end simulation barrier
Not sure how to do this tbh but I would like to know for the future. I tried having each of those systems run barriers in different steps but didnβt have much luck. Any particular examples youβd recommend trying?
[UpdateAfter(EndSimulationBarrier)] Or something like that.
In this case, it sounds like you want to put it on the system that does dead entity cleanup
Iβll try that too, thanks! Wonβt be in front of my PC until tonight but will let you know how it goes
Iβll try both but Iβd rather the second fix because the frame delay is unwanted
@rare umbra i had the same problem before and what i do is, I run DestroyDeadEntity system at InitializationSystemGroup and I use entityManager instead of command buffers. You could also use EndInitializationCommandBufferSystem aswell though.
I think I tried to use entityManager but the compiler didnβt like it. Like it wasnβt in scope or something
Does entityManager need to be passed into the job?
you can only use entitymanager on the mainthread
but unlike the commandbuffers, you can pass in nativearrays or queries to create or destroy entities
Iβm finding that systems are a little hard to fathom if youβre not that familiar with threading / jobs
I have this "maybe" problem that I have a NativeMap of an ID to entity. This entity will undergo some loading of data, and can be requested to be created by multiple entities same frame, hence I want to add it to the map to be able to check if it's created in a single threaded way. So.. to the problem is that using buffers to delay will not give me the final entityID when used, so I can't add it directly to the map, is there a way to manually remap this to the correct one at the same sync point?
I'd love to know this too. Deferred entities are killing my brain cells
Hmm, I think my specific problem can be solved by simply adding a tag to the created entity to add itself to the map funny enough.
Yup that's the workaround I ended up going with in mine
is there no way to add a dynamic buffer to a deferred entity like how i want to do so here
usually id have it so a separate job runs on the children that makes them add themselves onto the parent but this is a special case where doing that would result in a lot more work
is childrenBuffer meant to be a buffer on the child entity from the command buffer?
oh wait never mind read the code again π
Don't know a way to do that no
ok so I think to get around this you need to make another entity that acts as an event, with a component that stores the child you are creating and the entity with the buffer you want to add the child to.
and then another job or system that processes that event entity
time for bed, i hope to wake up to a plethora of new dots packages! π
I don't see how much different an event entity would make over leaving a Component (to add itself) on child though.
The component will cause 2+ Archetype changes. The event entity will only cause 1.
So how is 1 entity creation and destruction vs 1 additional archetype change?
I don't see where the event creates an archetype change though, since you add to existing buffer. Similarly component on entity to add itself would already exist in archetype, only a set required, so only 1 archetype change on removal, which can be done on query.
anyone got experience using unity.physics?
im trying to figure out the best procedure for creating complex compound collider bodies that can have their colliders changed.
Errr.. wow? https://forum.unity.com/threads/are-unity-subscenes-and-lwrp-compatible.717422/#post-5180879 - "the team is focused entirely on making HDRP + Hybrid work well; they're planning to look at URP after that, hopefully in the middle of next year"
Wow what
How is hd more important than universal since universal is more needed
I suppose they need to improve hdrp to "sell better" unity
I have a GameObject that I convert into an entity, it has a Physics Shape and Body script attached and I added a NonUniformScale to it when I instantiate the entity, but how can I change the size of the Physics Shape? It's too big for the now scaled down entity
Afaik physics colliders canβt scale at runtime
@amber flicker you know the best way to create physics bodies at runtime?
sorry, not actually done anything with Unity.Physics yet - just remember reading some related forum posts
Hehe same, is all kinda contradictory tho
still v early days.. I'm an early adopter but I think I'll still be avoiding it for the foreseeable..
I totally agree with Unity on focusing first to HDRP on Hybrid Renderer
actually wrote a post on that thread too now
I mean, I'd agree if they did it first for URP as well
but it does make a lot of sense trying to tackle it first for one system rather than trying to solve everything at once
this is what they do with DOTS anyway already, build systems iteratively
and they are slowly getting dots ecosystem expanded
just feels a little contradictory to all the talk of perf by default, dots on mobile - megacity on mob etc... like, I get it. They have finite resource. Still.. 'starting to look mid next year' means another year before use. I'm also quite anxious about how divergent hdrp & urp are and when built-in will suffer from not being developed.. but that's a more tangential concern.
well
right now
if you pick latest versions
hybrid renderer doesn't work with anything properly
so wanting it to work with everything is bit of a stretch
I mean, people can want things, but there are realities to face here
they also have their reasons for doing it hdrp first vs urp first, but we wouldn't know it
in past they used to do lwrp support first simply because it was simpler to play around with
As for me, I'm just disappointed that a) the RPs are fundamentally very divergent (not talking full support, just basics working), b) it will consequently take a long time before anyone can use dots on mobile and c) this is the first we're hearing of it.... but disapointment != disagreeing with their decision
I feel like the current state of Unity is really confusing and frustrating for a lot of devs since they see all of those videos talking about DOTS being the future and all the cool things you can do with it but they end up in a in-between state of not being able of using old stuff because it doesn't work with DOTS but DOTS not working because most of it is not ready yet
yeah I guess they could be more transparent on the future predictions
And you end up throwing away DOTS, having to implement a lot of basic stuff by yourself or just wait nonexistent release dates for your issue to get fixed
if you follow up the dev more closely, it's pretty clear most of the DOTS ecosystem will not be complete in few years
Yeah but that's not what they say in all the talks they do
even then, people expected to have fully functional ECS editor by now
they do say these things are going to previews when they promo them, so it's not like they lie to users
Well URP or LWRP is out of preview right now isn't?
LWRP is out of preview, URP isn't released yet officially
it's kinda weird setup
URP is technically out when 2019.3 releases
Also ECS is gonna be out of preview technically in 2020.1 but since Physics for example is a different thing, we don't know if that's gonna be out of preview as well
Yeah but URP and LWRP is the same
Or i'm missing something
a lot has changed
like URP now has dedicated post processing
of course the core of it is still the same
but there are big changes still
Well that's what i mean about confusing then
Entities "core" is out of preview first
it's not same with the whole DOTS ecosystem
you should totally expect dots packages still be in preview or experimental state when the entities package releases
I wouldn't even expect hybrid renderer to be production ready with hdrp by then
more like at the summer earliest
also would totally expect them to slip from the last roadmap estimates :p
Yeah but my main concern is how they prioritize the different packages and the decisions they make, i mean is not wrong to make the decisions they are making since a lot of stuff is still in a very early version but, as i said, they show it to us as "look at this shiny new thing we have that you can use" and people go ahead and try to make real games with something that's not ready yet
The problem comes from devs for being missinformed but i feel like unity could express better the fact that all of this is still an early version a lot of can change
And if you want to make stuff with it you should expect redoing the same thing multiple times because the API has changed or the workflow has been modified
I mean.. we're all battling with similar things so I hear what you're saying @slow epoch however honestly I think most devs dabbling in this stuff do know it's preview and what that can mean. I think @dull copper may feel that a lot of us are impatient about it all despite that - which I'd agree with. DOTS is clearly a huge undertaking. I also agree that it's pretty confusing right now. Even if you're very up to date with the state of everything in Unity (which is hard), choosing what technologies to use right now is actually very hard. Do I start a new mobile project using URP? Gotta think pretty darn hard I'd say. I guess we can all agree that the direction they're going is quite promising overall but the next few years are likely to be pretty tricky to navigate.
It's crazy how different DOTS is, I feel so dumb asking for help for what sound like extremely basic things, such as how to change the scale of an entity. It's so alien to me. I feel like a beginner all over again
Speaking of, how can I set the parent of an entity to a GameObject in the scene so when I move it, the entities move with it? Is that even possible?
@civic bay there is the Parent component (if your gameobject already have a child and converttoentity component this parent component is added automatically), but it's basically a parent component with the Entity ID set to the parent
Whenever I add the Parent component my entities just don't even show anymore
Even though the entity debugger they're spawning in
Nevermind they're under the map
if you are creating a prefab with ConvertToEntity you don't need to add the parent component
manually adding that is only necessary if you are parenting during runtime
Using any of the new stuff (ecs, burst, srp, etc) for a game that actually needs a launch date and be economically viable is a huge mistake atm
doing that here π
All my tests of urp/hdrp have ended in "oh so this is still broken, ah well"
Every single time
@hollow scroll I'm basically spawning in a bunch of entities from the sky, and when they hit the floor I remove the physics components frmo it so they don't keep updating
But I need to parent them to the floor, because the floor moves
So I need the entities to move with the floor
@civic bay ah ok.. so adding parent component in that case is ok
Am I going about it the right way by adding the parent upon Instantiating the entity, but set the parent after I remove the physics components?
Or adding the component and setting it actually
At that time
Because it doesn't have a parent while it's falling
@civic bay you can add the parent component when you remove the the phsycis component that it's when you mention that needs to be parent to the ground
in my experience, if we count hybrid issues out, main things causing people pain with SRPs are just feats that are missing or don't have 3rd party asset to implement something, sure there are still tons of bugs but it's not like the built-in renderer didn't have those too
But how can I get a reference to the Floor Entity in that ComponentSystem?
hdrp is more all around package tho, you shouldn't miss that many feats with it
@dull copper no, just stuff being broken, crashing, etc.
i would not say either urp or hdrp are production ready from my tests, its very easy to brake both of them
@civic bay you can have another query in the jobsystem that gets the ground entities, and then get the entity from that query in a job or however you prefer, and use that for the job that adds the parent component to the entities touching the ground
if talking about individual feats, I feel like shader graph itself is most fragile thing
then srp batcher comes next
and thats not even counting platform specific issues i have not even bothered trying to examine, if it doesn't work flawlessly on windows, then im not even gonna attempt to run it on switch/ps4/xbox/android/ios
most things breaking for me has usually been either one
@hollow scroll Thank you for your help, much appreciated π
@dull copper i mean unity is betting everything on dots, we'll see if it pays of in 2022 π
lol
but it's still good to have targets
getting jaded? π
because with 2025 target they'd just slip further away
I mean, anyone who's followed Unity's scheduling and estimates know it's true.. but they usually get there eventually
I don't think they planned ECS core to take this long either
my main... woudn't call it worry.. but issue/concern with all this is that the old system (GO/MB) basically seems abandoned internally at Unity, but anyone that wants to build a real game today still has to use it... but they don't seem to be updating anything relating to that anymore at all.... is this gonna go on for 2-3 years now?
anyway, this is why I'm not pissed at all at Unity for not shipping production ready packages next year for all dots feats
because it's just not realistic at all
well, technically the old system has been there for what, 14 years?
like, it's still going to keep working
they updated mono, c# and made incremental GC
those were the biggest wins for it
I don't really see point on trying to implement new stuff for the old setup at this point at all
would rather see them putting those resources on dots
obviously they will not let the old monobehaviors completely break either before they get dots done
Yeah but you are not trying to build a game and ship? There's tons of shit that just issues going on get fixed it seems, because dots.
I am but not focusing with dots with it
like, there's no realistic hope on getting hybrid rendering done in time for me
and frankly, I don't even care about that before you get rest of the dots systems fully functional, maybe for some upcoming projects then...
anyone know what does this NativeFixedLengthAttribute class do?
Nvm. Got it to work. But still doesnβt make it blittable lol
Is there a way to get the entity ref from ConvertToEntity.ConvertAndInjectOriginal(gameObject);
@civic bay you can check how the guy do it here: https://youtu.be/BNMrevfB6Q0 (I think it's around minute 19:30)
Jesus christ, after 3 days of trying to understand ECS, it finally clicked
It's like trying to ride an inverse bike
Congrats!
and soon the old way will feel like the inverse bike π
"soon"
anyone started a multiplayer project with dots around ?
most are probably waiting for the new packages still π
waiting for the bike update
i'm just like, trying to make awssdk play nice with dots π©
its enough of a struggle just doing singleplayer π
@main glen yes
hey all
question: is there a specific build recommended to play with a stable(ish) release of DOTS? i know when it was ecs it seemed to break every update.
0.1.1 version of entities package with 2019.2.12f1 is as stable as it can be.
so sticking to 2019.2? i did install the latest 2020 beta and had menu's and items and stuff i hadn't seen before. is there anywhere with actual documentation you can follow? every tut or article i find on the net seems to be from some obscure build.
2020 is not really stable.. its in alpha. 2019.3 is also in beta. 2019.2 is the latest stable version
Should probably wait for the new package to come out if you are just getting started
The APIs and workflow is going to change with the new update so its going to mess you up again with the old tutorials! π
that's exactly what's been going on. i figured with the supposed stable release set for what? 2020.1 release? they would at least have solidified their workflow somewhat
Thats a tentative date. nothing is set in stone yet.
enjoy the preview packages for now π
yeah just assuming they'd have an idea what the finishline is looking like when they mention it. but no bother. I was looking at the DOTS-training-samples and giving them a shot, but if i have no real place to start... I don't know enough about ECS to try to blindly work it out
@amber flicker @slow epoch the ecs systems are useable on mobile now. There are a few aspects which require some imagination, but even if you just have gameobject puppets following your entities around, it improves calculation speeds.
I .... actually dont need a renderer on my main ecs systems tho hehe
@golden heron what do you use ecs for? ai stuff? that's the type of thing i'm interested in
Well, first ill show an old video.
This is messy, from literally my first few weeks in unity.
Each of those white dots is a solar system. That will be simulated on a central server, whilst players receive data and react in their own small spaces.
@golden heron sure, there are lots of things dots can be useful for... just a shame if it doesn't cover rendering. Also unsure if dots animation package will require hybrid renderer? Animators are sometimes the bottleneck for me and would like to be able to use the dots version.
Yeah, everything would be better in dots hehe
But, im finding that people have... kinda missed another aspect of how to use ecs.
yesssss! that's the stuff i like to see! backend simulations are where my mind jumps with ecs.
All the consideration of huge numbers of entities catches attention, when people could be instead creating a smaller number of complex multiple entity objects to make the game with.
i've always been interested in trying to do world sim in the background while just rendering what's going on in the player's area... stopping the "the world is frozen, unless the player is interacting with it" most games have
Yeah, my game is intended to be a realtime universe simulation which is always ticking over irrelevant of players.
It'll respond to players, if trade economy is affected for example, but generally most of the systems will be in a data only mode, updating less frequently with minimal information, whilst the physics and collisions will only be considered in player systems.
There is another aspect of large number of entity management people forget - if you update every entity per frame, you hit your limit real quick, but if you only update your entities every other frame, and stagger them, you can almost double your ftotal entity scope.
Now, imagine the scope of a game which updates its background entities once every 5 seconds?
yes! are you finding it plausible to handle that much data? can you essentially do limitless number of entities just by increasing that delay?
Well no, there is still the limit between memory available and a little overhead for the staggering, but you definitely can achieve a similar increase in useage numbers as you get from pooling in standard unity
I found i could run a million entities at about 25fps on my old dual core 2.2ghz - old one too, core 2 duo i think
Cross-post from the forums:
Hydrogen.Entities update:
After some work and life induced delays, I have made some samples and scene setups outside of the testing environments. These samples are based on the various requests people made and each has it's own readme file that goes over the different parts of the samples:
https://github.com/periodyctom/Hydrogen.Entities/releases/tag/0.2.0-preview.3
Also bug fixes and some optimizations/minor enhancements.
feedback appreciated
@untold night have you used unity.physics much?
Part of my push for getting this done was to play with Physics more
nice. that's still a lot. i was assuming i'd have to generalize things from individual units to say overall faction status when out of a specific range of the player... but sounds like it could be an increasingly large radius if i lower the update ticks
Hehe well im having trouble getting an adaptable physics body working, i need to add/remove colliders or recalculate compound colliders at runtime and it doesnt seem easy atm.
@winter veldt mind if i send a dm? I just finished a mk1 design you might appreciate.
I believe they're working on an API for altering colliders at runtime but I don't know what the timeframe for that is
Well i guess its rebuilding afresh for now then hehe
with the latest DOTS packages you can at least rebuild in a burst job
fortunately it can be a change which happens instantly
@golden heron for sure!
@untold night could you outline what kinda helpers are in your "Hydrogen" api?
There's a lot in the documentation and now in the samples, but heres a quick run-down:
- A pipeline for Converting ScriptableObjects to DOTS Blob Assets, running on the back of the Game Object Conversion pipeline
- A pipeline for loading Singleton ECS data components from files or scenes, originally for converting config data to make it usable in jobs/component systems.
- A pipeline built on top of the other two that helps you convert ScriptableObject singleton data (as there's quite a few people who use the SO as a manager/singleton pattern) and migrating that data to ECS. Which handles a lot of the memory management and boilerplate for you.
- full test coverage of the above.
If I created a subscene, how would I be able to instantiate it in a script? Using it as a template for creating lots of similar entities, editable as a subscene.
@golden heron - Documentation starts here: https://github.com/periodyctom/Hydrogen.Entities/blob/master/Documentation~/index.md
Each sample has it's own Readme:
A collection of helpers for work with Unity's ECS framework, used in our games. - periodyctom/Hydrogen.Entities
A collection of helpers for work with Unity's ECS framework, used in our games. - periodyctom/Hydrogen.Entities
#nasa
I've not messed with multiple worlds since the earlier dots days. This currently works with the default live world and conversion world stuff.
anyone has any idea on the latest update on entities package ?
dumb question - how do I get the entity from a component? My job is using NativeArray<PurchaseRequestComponent> but because I want to add a component to the same entity I need to grab the entity reference
{
for (int i = 0; i < PurchaseRequests.Length; i++)
{
var purchaseRequest = PurchaseRequests[i];
//Need to reference the entity that purchaseRequest is attached to ```
is this an IJob?
yup
how are you passing the component data to the Job in the first place? Are you using EntityManager or System Queries?
or are you operating with Chunks on the System level then passing to IJobs?
{
All = new ComponentType[] { typeof(PurchaseRequestComponent),}
});```
Not sure if this is the best way, just the way I'm currently doing it
why aren't you using IJobForeachWithEntity<...> which probably fits your problem better.
Although you can get a copy of the entity array out of a query
I'm using it in another system, not sure why I'm not here
lemme convert it over
Would it have any impact on the other data I'm trying to grab?
public ComponentDataFromEntity<VendorOfferComponent> VendorOfferComponents;```
Probably not, as long as you're not writing the same entities you're reading from concurrently with another job.
if you really need to do it in an IJob for some reason, you can use ToEntityArray:
Which has both a main thread version and a version that collects the entities from the query on a thread you can then pass as a dependency to your job.
bah, can't seem to fathom what I'm missing in the OnUpdate having switched over to IJobForEachWithEntity
can you show your job signature and Execute function?
sure, 2 secs
InvalidOperationException: VendorTransactionJob.Data.WalletComponents is not declared [ReadOnly] in a IJobParallelFor job. The container does not support parallel writing. Please use a more suitable container type.
you declare two of the job, assign the fields of one of them, then launch a blank one
you also need to add [ReadOnly] before the ref PurchaseRequestComponent purchaseRequest
So it should look like this:
public void Execute(Entity entity, int jobIndex, [ReadOnly] ref PurchaseRequestComponent purchaseRequest)
so I tried to assign the fields to the second job (first one is legacy) but couldn't find the correct syntax for the assignations within the new VendorTransaction declaration
as an additional optimization/change, you can schedule the Job by passing the PurchaseQuery as the parameter to the schedule instead of the system this, it will then use a hotpath to operate on the query data
make sure you're using the [ReadOnly] attribute from Unity.Collections and not the one from one of the System namespaces
did that help?
I see what the problem is
WalletComponents needs to have the attribute [DisableParalellForRestriction] assuming no other threads can access it at the same time, since you're writing to it.
You can also mark VenderOfferComponents as [ReadOnly] as well
you don't need to mark CommandBuffer.Concurrent as [WriteOnly] either
I can only use
[NativeDisableParallelForRestriction]
Is that the one? the other one is throwing a compile error
well that works now, yay
can I get rid of the PurchaseQuery now that the component type is specified in the IJobForEachWithEntity?
you can if you don't need the query for any other filtering, such as excluding components or the any/none fields.
What will happen is the query will get created in the background the first time you schedule the job with the system and will then use the cached Query when you schedule it every time after
Is it possible to access entities in a JobComponentSystem, im trying to loop through a set before starting the job but cant seem to access the entities in the OnUpdate? I tried creating a new EntityQueryBuilder but that caused a null reference.
new EntityQueryBuilder().WithAll<Comp>().ForEach((Entity entity, ref Comp comp) => {
data.Add(comp.Value);
});
i dunno about the entityquery way but you can use IJobForEachWithEntity instead of IJobForEach and pass in Entity as first param to the Execute
I got the Job the way I want it, I just want to populate a readonly list prior to the job executing.
What would be the way to create shaders for a material used in RenderMesh component? From the default URP shaders, some work, some show just a flat pink. I created a simple shader (basically only color to albedo on master node) in shader graph, which results also in flat pink
Figured it out, IJobComponent has GetEntityQuery so when I used that it worked better!
@prime cipher i recently found out that PBR materials don't work with DOTS yet. you have to use Unlit shaders for now.
@craggy orbit yes, creating an unlit shader graph asset works. Thx. So no lit shaders, no particles -> no real effects in DOTS π¦
yeah. definitely a bummer. but we're anticipating the next DOTS release sometime this month, or so i've heard. that might bring support
Is .2 coming with the DOTS fps sample? I forget
Ugh, why is InitializationGroup not bound on same loop as Simulation x)
Same loop?
Yeah. It's run 1:1 with PresentationGroup.
That's good to know
@magic frigate you mean the 0.2 entities or 2019.2?
all in all, would expect next packages to launch along with the fps sample as they've only given estimate for the fps sample and it relies on all these packages
and it'll be 2019.3 compatible
Is it possible to instantiate an entity inside a Job?
@trail burrow How can I go about that?
@civic bay Create a commandBuffer from a CommandBufferSystem which acts as a barrier/sync point at different points in your gameloop. The usual way is to use this system as a private varaible in your system, note the system and not the commandBuffer - it needs to be created each "frame" it's used. Use in in the system "as" you would use EntityManager. If using paralell jobs, you want to use EntityCommandBuffer.Concurrent, simply .ToConcurrent(), on your buffer when passed into Job. After you've scheduled your job you have to add a dependency of the job to the commandBufferSystem (so it knows it is completed) do calling AddJobHandleForProducer.
At which point in the gameloop are all the jobs completed?
At certain points like CommandBuffers, at the end of the frame?
Executing the commands in an EntityCommandBuffer invokes the corresponding functions of the EntityManager. Any structural change, such as adding or removing entities, adding or removing components from entities, or changing shared component values, creates a sync-point in your application. At a sync point, all Jobs accessing entity components must complete before new Jobs can start. Such sync points make it difficult for the Job scheduler to fully utilize available computing power. To avoid sync points, you should use as few entity command buffer systems as possible.
@slow epoch a job finishes when it completes its work or if you call .Complete();, theres not a hard set time compared to barriers
But if you have a Destro/Create/AddComponent/RemoveComponent in your barrier all jobs will complete?
Then a job can end up completed 2 o 3 frames after scheduling it if nobody told it to be completed?
you know thats a good question
And if it doesn't require a Complete if it only uses SetComponent, then how does it know the dependency between jobs using that component so it have to wait for them to complete until it can set component.. hmmpf.
I though there was some kind of point where all jobs were completed because certain jobs that don't have any kind of dependencies but can take a huge amount of time don't have a determined end point
maybe the commandbuffer is skipped a frame if the job takes a particularly long amount of time? this would be good to test out
I would imagine there is a Complete at the start/end of each gameloop to start next for the JobComponentSystem jobs.
i think multiframe jobs should be supported, i do recall reading that there were issues a long time ago regarding them(leak issues) but this was back during times of using Inject to get queries so assuming thats not the case now
Would it be at the end or the start of each frame/gameloop?
Yeah, I don't know. At some point the main thread is used for jobs as well? I've no idea where that is either π
I'm curious about the approach to this since i've stumbled with similar problems in the past working with only jobs
Not having a clear idea if they need to be completed at the end or at the beginning of the frame
Well, it's more like "what is the best" but i suppose as always it depends
I usually don't think about it, since data/entities that are dependent on each-other will sort itself out.
Can ECS can save me from that latence ?
When NavMeshAgent
try to go to other side
They have path one by one
I want them all react fast like at start of video
That's because the pathfinding is async
You can use CalculatePath so it's calculated in the same frame
same mate
CalculatePath + setting the resulting path is the same?
Right now there are not a lot of options for pathfinding with ecs besides NavMeshQueries which are incomplete at the moment
Unity said pathfinding will come for the next year
You can't use the current NavMesh inside jobs
Also you can change NavMesh.pathfindingIterationsPerFrame to your needs
I think is maxed at 500
minor correction in that they said they would start work on navigation next year, who knows when a useable package will be released
Ty @slow epoch I will try
If I have multiple GetEntityQuery calls in my OnCreate of JobComponentSystem, what decides if the System runs it's update or not? Do the queries && , || or always update when multiple?
|| afaik
Hmm, so I'll have to manually check IsEmptyIgnoreFilter or is it better to let the systems setup "empty"?
that looks like &&
Oh, so it doesn't add to the m_RequiredEntityQueries
Ok, but still use GetEntityQuery to create them I guess?
how do jobs complete in relation to command buffers? if a job takes x frames to finish, I assume it can potentially skip the barrier x times too?
@safe lintel the barrier will call .Complete() on the job handle afaik
It calls Complete on all handles you've added to the AddJobHandleForProducer at least.
i think jobs from componentsystems will always be completed next frame, only jobs that are started outside ecs can run multiple frames
@safe lintel depends on how you .Complete() the job. If you added its handle to the return value of a JobComponentSystem.Update() the job will be Completed by the next sync point (either barrier or mainthread ComponentSystem, or EntityManager operation).
If you want to have a job run over multiple frames you have to manage its handle on your own so it finishes when you Complete() it manually, barriers have nothing to say in this case (but the safety system will kick in if you do something icky)
@worldly pulsar Do you know where the handle is passed to the Barrier then from the JobComponentSystem?
public abstract class JobComponentSystem : ComponentSystemBase
{
JobHandle m_PreviousFrameDependency;
JobHandle BeforeOnUpdate()
{
BeforeUpdateVersioning();
// We need to wait on all previous frame dependencies, otherwise it is possible that we create infinitely long dependency chains
// without anyone ever waiting on it
m_PreviousFrameDependency.Complete();
return GetDependency();
}
interesting...
So basically each system loops around it's dependency to be completed next frame.
oh? does that mean that if your jobcomponentsystem runs late in the frame, it'll complete() late in the next frame as well?
thought it might complete all running jobs at the start of a frame somewhere
I don't fully get it though, shouldn't all systems be dependent on previous barrier since it can change the structure etc?
@mystic mountain pretty sure this is just a failsafe, there is a "complete all JobComponentSystem handles" method somewhere, but I don't remember where
for EntityManager operations this would be EntityManager.CompleteAllJobs() (which is called from BeforeStructuralChange() )
But what is the point of AddJobHandleForProducer, if we still need to complete all jobs?
(edit) nvm, ofc we need to know we got all buffers..
But then again, we could still complete all..
I'm a bit rusty on this part of the code, but if I remember correctly the CompleteAllJobs() only completes jobs returned from JobComponentSystem.Update(), so if you schedule something and don't return it from Update() (like, you have a job writing to an ECB and you want that ECB to complete at some specific barrier) you need to AddJobHandleForProducer
I need to read what exactly happens to the handle returned from Update(), it was always a bit magical for me to be honest
The only thing I can find is that it does this after it's update with the handle
unsafe void AddDependencyInternal(JobHandle dependency)
{
m_PreviousFrameDependency = m_SafetyManager->AddDependency(m_JobDependencyForReadingSystems.Ptr, m_JobDependencyForReadingSystems.Length, m_JobDependencyForWritingSystems.Ptr, m_JobDependencyForWritingSystems.Length, dependency);
}
and that AddDependency inserts the jobhandle into all the related type Read/WriteFences. EntityManager.CompleteAllJobs (which is called by the EntityCommandBuffer.Playback()) goes through all Read/WriteFences and completes them
Any news on the release @digital scarab ?
My safe bet now is 13th of december >_< The 2018.3 release date from last year
Seconded
how do i set the component of a value within an icomp within an icomp? ala
commandBuffer.SetComponent(index, baby2, new Parents { Mother = entity });
https://puu.sh/EGARd/bb6af459ee.png
i get this error upon attempting this
managed to get around it by doing this!
not sure if its optimal but hey
ok new question regarding the same "Family" compdata. While parents is a compdata, the others are buffers. How do I access these internal buffers? https://puu.sh/EGBdV/a6358d1c04.png Using this creates an error on the first line.
ArgumentException: A component with type:Children [B] has not been added to the entity.
all relevant entities definitely have the family component
[NativeDisableParallelForRestriction] public BufferFromEntity<Children> childrenBuffer;
and heres the declaration
so If Entity A and Entity B. and I have A.neighboutEntity = B. Now does my system have 2 entities or a total of 3 entities?
if a.[x] is an entity variable than you'd be passing around a reference so the system would be 2 entities
awesome! thnx π
np!
Hi i'm trying to learn ecs ( again ) looking at this sample code now:
https://github.com/Destrayon/Unity-DOTs-and-Physics-Example/blob/master/Assets/TestJob.cs
Why is he using Jobs here ? What are the benefits over the standard component system ?
is there a benefit for using a job for a single entity ? Like for example there will only be one player that will have one component, system and entity ?
@hollow sorrel
I guess in that case the issue would be the job overhead vs potential burst savings?
well yes, i wonder were to draw the line
like what if i have 10 unique entities
would they benefit using the job system ?
or rather should i just keep those 10 unique "things" in a classical Mono-Behaviour way ?
I have no informed opinion but my best guess is that it depends if they have a nontrivial performance cost or not
@magic frigate how do you organize your scripts ? I was going for something like this.
PlayerFolder:
Player_Spawner.cs-- ( entityManager init and set data )Player_Data.cs-- ( ECS : Component )Player_System.cs-- ( ECS : Job Execute )
I've mainly been reading sample stuff and trying to learn. Haven't made anything substantial enough to merit organization yet
@hollow jolt yea there is a cost to scheduling a job, but no idea how much
docs state use non-job systems when The amount of work the system performs is less than the small overhead of creating and scheduling a Job.
but that doesn't give any numbers
rule of thumb i've been following is if something is so insignificant it barely even shows up on profiler (like 0.05ms), i'd put it in a regular componentsystem
simple systems with one entity usually fall under that
i've been waiting patiently for the dots multiplayer sample to drop, but then i built this over the weekend π https://github.com/gamedolphin/dots-multiplayer-sample
What would be the best practice, if I need to run the same system for different combinations of components, inject the EntityQuery as parameter for the job or create a wrapper system per combo? This is needed, as the same system calculation needs to be parametrized per combo additionally
- create separate systems. 2. create separate jobs that chain @prime cipher
i feel like i'm i'm missing something
can someone tell me why this is causing 136 bytes of GC.Alloc (with leak detection turned off)? deep profile isn't helping either
oh and Player here is just an empty component
maybe it's normal and i just didn't notice it before, but other systems don't seem to have this
@hollow sorrel it might be because you're capturing an external variable within the lamda; if memory serves that causes the function to be compiled/handled differently which is probably the GC you're seeing. More info: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/lambda-expressions#capture-of-outer-variables-and-variable-scope-in-lambda-expressions
Guys. Whatβs the best way to have a linear fixed length array in an entity. Donβt want a ishared one. Cuz this array might be changing every frame. Also this array will be unique to every entity. I think dynamic buffeted array. But mine will be fixed size so still use dynamic buffer or something better is available?
@languid stirrup https://github.com/fholm/unsafecollections
you can stick an public UnsafeArray* MyArray; in a component
yes they are done in a C-style API, take it or leave it π
But but itβs unsafe! It says I need unsafe switch to compile it. What are the implications of this unsafe? I will have about 10k if these entities with about 800 array size.
implications of unsafe is nothing really
Of int btw.
@mint iron do you know if there's a way to get rid of the lambda altogether? seems entityquerybuilder isn't usable in regular componentsystems
Really? Will I still get detailed stacktraces for debugging?
and passing a method to ForEach doesn't seem to work
@languid stirrup lol yes
i mean if you try to de-reference a null pointer
your game will crash ofc
especially in burst
but yeah if you dont wanna use dynamic buffer
u dont have a choice
atm
You can also just use unsafe context and fixed array in components e.g.
unsafe struct MyData : IComponentData
{
public fixed int data[100];
}
Hmmm. Either the whole entity will be disposed. But the array wonβt be reassigned it anything. It wil always be accessed via its elements. And burst is cool with unsafe stuff? Does it burst still boost speeds? @trail burrow
@mystic mountain the runtime tends to buck and choke quite hard when putting really really large structs on the stack
it's the one reason i tend to not use it
@languid stirrup the array needs to be free:ed manually
yes burst supports unsafe stuff
I donβt have a prob with dynamic buffered if they are fast and burst friendly.
@mystic mountain you can for example make mono corrupt the stack if you push enough stuff on the stack
making all kinds of fun stuff happen π
I've been there x)
So @trail burrow buffer array good too? I want a suggestion of what is faster with burst. If itβs buffered array Iβll gladly use them.
Dynamic buffet array. Yes
use whatever you want, i have never benchmarked any of them against each other
if you need absolute speed just do a public int* MyArray; and public int MyArrayLength; and allocate the memory by hand
and burst can work with that yes
Oh. Hmm ok. I might benchmark them then.
Yea but pointers are unsafe again. Lol. Thnx for the discussion @trail burrow
yes it's 'unsafe', it's completely fine
I will bench and see
all of the ECS uses unsafe code internally
Lol ofc. Without pointers u canβt have any proper software :p
@hollow sorrel modern c# versions should be compiling a lambda that doesn't have external references to a straight method call, they're not as nasty as they used to be. That said, Unity is doing a whole lot of stuff behind the scenes there - https://hatebin.com/akgdzsiujs. You could consider converting your code into a job.
yea but docs say it's better to put things in ComponentSystem if it's smaller than scheduling job overhead
which i imagine would be the case for a 1-entity with just assigning a value
also kinda weird if gc alloc in non-job systems is by design
i vaguely recall i read an official post about in on the forums a while back that they were aware of it and intended to get rid of it before the final version.
i've been away for a few weeks, have they released the new entities version from Copenhagen? cause they were supposed to be changing Entities.ForEach to be compiled as a job behind the scenes.
also, the ToEntityArray() inside ForEach is already running a job π
Hmm I've no idea if they did
whaaat
Been gone for a week too
also no new releases no
at this point i wouldn't be surprised if new version is released with 2019.3 stable release
This topic made me think, how do you translate an Attribute to an authoring class?
How do you compile that?
@mint iron ComponentSystems run jobs too? dunno why they mentioned using it to avoid job overhead then
@hollow sorrel one option is to decompose the process used inside ToEntityArray() to have an early out when runnign the job is not nessesary, and copy the data to a persistent array rather than using temp storage. (this is older code that i think needs to be updated but shows the basic idea: https://hatebin.com/mwevdqczdp)

Oo I've been wondering about creating a template that can do that
any good ECS physics tutorials? I sorted navigation fine (for space game), but rather have actual physics for collision detection then my crazy math that I try to optimize more and more
So wait. For smaller tasks like shifting elements of an array or simple logic on an entity is better to be implemented in ComponentSystem and only stuff on larger array of an entity should be implemented in IJobComponentSystem?
i caved and turned it into a jobsystem btw, seems no more garbage now
my interpretation of what they've been suggesting is to start out with Entities.ForEach and focus on getting your game to work; because ForEach mirrors IJobForEach it should be relatively easy to convert to jobs for performance later.
also went from 0.05ms to 0.03ms which implies it's better even for small stuff but dunno how much of that is editor overhead and profiler accuraccy
@trail burrow do those unsafe collections have an option to be stored on the heap like dynamic buffers do? My buffers can get really big and I don't want the stack to explode or anything
@onyx mist they are all stored on the heap
they work like the regular .NET collections
Oh wow that's great!
except, only deal with structs/pointers/native mem etc. ofc
And they show up in the debugger?
debugger?
The entity debugger
no i doubt they do that
Ah oki
hi, I have a component which has a unique identifier. Something like struct Foo { int uid; } which I use to link DOTS with another system.
Is there a quick way of finding an entity which has a specific uid in the Foo component?
Currently I have this:
protected override void OnUpdate() {
Entities.WithAllReadOnly<Selectable>().ForEach((Entity e, ref Foo f) => {
if (f.uid == targetUid) {
// do stuff
Seems like there might be a better way?
Maybe I should keep an external dictionary of uid->Entity ?
if you're finding them one at a time, a nativehashmap would do, @glad grail
what's the best way to compare a float3 to another float3 in a job?
f1.Equals(f2) or math.all(f1 == f2). Burst should produce the same code for both.
thanks @worldly pulsar finding this stuff in the docs is kind of difficult
at this point source code is better than docs tbh
yeah except I'm no good at reading the source code
yeah that does not work, well it doesn't work in a if, it returns a bool3
Quick question. I understood the CodeMonkey tutorials on ECS. Can someone give me a basic idea of a project I should try and develop using ECS?
Counterquestion: Do you want to develop a project in ECS?
If so, I'd suggest something mechanically simple, like tower defense or simpler. Most arcade games (asteroids and such) would fit, too
Yes! I'm trying to familiarise myself with this, so i assume learning it on a basic poject would be the best way to go
could recreate a demo unity project, so its less about coming up with new ideas and more about translating work to using ecs+jobs
have a look at https://github.com/Unity-Technologies/DOTS-training-samples
Then my suggestion above is what I'd go for. Aside from that, you should try to make a hello world (hello cube/cubes) project if you haven't
Any Pure ECS handling mesh manipulation examples Apart from boids example?
okay thanks! I did the hello world thing initially. I'll have a look at the training samples and try some
Also search for Unity ECS sample and youβll get a link to git repo of projects and itβs docs
Currently breaking down the ESC Physics sample
Doh canβt find the Unite 2019 talk that has the new less boilerplate stuff. Is it βconverting scene data to DOTSβ?
do you mean what was shown in the keynote?
Ah yes I think it was in the keynote yes
https://youtu.be/gyqIZP_zLtU?t=1811 Timestamp to the beginning of keynote's DOTS talk
Exciting updates including Data-Oriented Tech Stack (DOTS), Unity Simulation, Scriptable Render Pipelines, multiplayer services, our new 2D tools, and much m...
Thanks!
hey guys, quick question.. is there a way to pass LocalToWorld back to a GameObject?
The transformsystemgroup should have systems which copy the LocalToWorld or (TRS) matrix back to the hybridized gameObjects
as long as the gameObjects are converted the entities should be set up properly to sync entity data to transform gameobject data
I think you want CopyTransformToGameObject
yep that was the system π
copytransformtogameobject seems to be obsolete, it auto-adds GameObjectEntity script, which uses Transform instead of LocalToWorld, and transform no longer exists
you need to use the actual component with conversion instead of the proxy component
I had a dream last night that 2019.3 was released with new updates on all dots packages... π’
I dreamed about driving a submersible.
That dream sounds better
multiplayer repo got an update... nothing really new, just CONTRIBUTING.md, but maybe it begins π
btw. first commit from joeante...
At this point they are teasing us
it's a sign
time to invest in unity stock
i know this isn't a meme channel but it's hard to resist
as stoked as I am about DOTS and the road ahead, I think it will take some time to get all current devs onboard that train π
quite a lot of devs are not too happy about the focus on dots. So hard to say what will happen to stock π and they haven't gone public yet have they?
I need help
can you be more specific? π
umm
@mystic mountain Hereapplesy? π (j/k)
#solved
What have people been using to pass on a collection of native arrays to a job? I got a case where I want to run a parallel job that each processes a native array of floats. My current plan is to copy all the arrays into one big array and have a native array of structs with offset+length data in them.. but it just feels so.. unnecessary? (and no nativearray<nativearray<float>> doesnt work)
With that I can use NativeDisableParallelForRestriction to allow writing at the same time into the same array since I guarantee the jobs wont alias.
Maybe the unsafecollections fholm posted yesterday solves your problems?
@flat talon also, try using WriteOnly tag on your output array, that way burst will not have a problem multiple threads writing to the same array
unfortunately in this case I need read/write :/ since I'm adding to existing values in the array
and do other threads need to read from this array?
I guess I can have a separate input and output though
reposting so you don't have to scroll https://github.com/fholm/UnsafeCollections
if not... then i suggest breaking the arrays into input array and output array
they do need to read and write, but not in the same sections.. ie one job doesnt need to read the output of another thread. So it makes sense to have two arrays for input and output
each job has its own section in the array that others wont touch.
I was just wondering if this is the only way to do this? Currently I need to do a bunch of copies from multiple native arrays to combine them, and after the job the same to split the big array into smaller ones. Seems.. not great π
there are always better ways of doing things, thats why we ask others hehhe
are all your float array same size?
Is it possible to use GameObjectConversionUtility.ConvertGameObjectHierarchy(prefab, World.Active)); with EntityManager.CreateEntity();
@flat talon also another thing that makes it faster, when allocating memory to output nativearray pass it the the option of NativeOption.UninializeMemory
Like I convert the prefab on Start() but I need to create thousands of these entities
that way, allocation doesnt require time
If I use Instantiate it seems to take a performance hit?
But the prefab has the physics shape / body set up on it
So I need to convert it
well... once you have converted to Entity, then using instantiate defeats the prupose of ECS
unfortunately not all are the same size no :/
@civic bay you will need to add new compoents to your ocnverted object, using ECS components
But ConvertGameObjectHierarchy only converts the prefab to an entity one time
How do I make thousands of them?
and never instantiate, cuz instantiate cannot benefit from ECS
for loop π
best to be done in a Job i think
you can use a conversion system. There is also a way to "mass instantiate" with an array iirc
Yeah I tried to set up a job haha, didn't work well
and yea, there is a way to mass entitize a prefab in an array, i dont rem what syntax tho
But is using EntityManager.Instantiate not ECS?
Surely I shouldn't be converting 1000's of GameObjects to Entities?
i think you should convert once and then you can mass instantiate a bunch of copies of that entity with a nativearray method in entitymanager
@civic bay read about this i think
If you do the conversion inside of a subscene, the conversion is just run once and the result is saved in the subscene
yea, you only convert from a prefab ONCE, then just make an archetype of it and create an array of those entities
How do you create an archetype out of it though?
use the GetPrimaryEntity method thing.. whats it called again
That's what he did? I think you're confusing him with mixing archetype and prefab entity x)
So I convert the prefab on Start()
And then on Update I spawn 10000 entities by using EntityManager.Instantiate(ConvertedPrefabEntity)
why not use a conversion system or the interface?
How so?
I really recommend you watch this talk :)
https://www.youtube.com/watch?v=BNMrevfB6Q0
In this video, learn about what's involved in migrating existing game code to the new Data-Oriented Technology Stack (DOTS), which comprises the C# Job Syste...
Yeah I did but he uses instantiate too?
he's using the Convert() function and conversion systems, not start/update
x)
Would it even matter where the conversion is called from? Doing it with some ConversionSystem to add it to your Component or in Create of System, wouldn't the result be same in the end?
the Convert method (from the interface) is useful when converting GO->entity one object at a time. In the case you want to do 1/n->1/n a system is generally more useful.
Btw regarding prefabs, the conversion basically creates an entity that is used as a template to create further entities of that prefab. And as above there's a way to create a ton of entities at once.
Or am I missing where you are stuck?
@mystic mountain afaik the result is different if you use a subscene.. I dont think it would save the conversion result there if you just use start
So instantiating a prefab from a subscene lives in the subscene as well then?
Also in the Convert interface you should declare references to prefab objects, perhaps you are missing that step?
@mystic mountain if you do it as part of the conversion flow, then yes the resulting entity is saved in the subscene asset
This confused me a while ago, since I expected the conversion to run every time you start the game
But if I have a spawner in my subscene that references a prefab. Will the spawned entities belong to the subscene in runtime?
if the spawner isnt using the conversion flow to instantiate the prefabs then no
however the original (converted) prefab entity will π
So my set up is:
Prefab Spawner -> On Start() ConvertGameObject(prefabToConvert)
prefabToConvert -> is a gameobject that has PhysicsBodyAuthoring and PhysicsShapeAuthoring scripts on it
PrefabSpawner -> Update() -> m_entityManager.Instantiate(ConvertedPrefab)
Is this not correct?
I don't need to have the Convert to Entity script if I do it manually, right?
The Prefab Spawner is just a gameobject in my scene
I would use the Convert method in the Prefab Spawner, rest sounds fine
and the prefabToConvert is just in my project view
But how do I get a reference to the Entity via PrefabSpawner
If the Prefab converts itself
you could store it in an entity singleton for example
But the GameObject doesn't exist in the scene
some people use static fields
It's just in the project folder
yeah that is fine, an entity is still created that is the "template"
not as a GO no
So if I make a prefab and put the Convert script on
It will convert to an entity regardless if it exists in the scene?
uh no, then nothing will trigger the Convert script.. hence why that is on the PrefabSpawner GO? or is that not in the scene?
That's what I mean though
PrefabSpawner GO is on the scene
Which just has a ref to the prefab in the folder
yes that is all fine
So do I still call ConvertGameObjectHierarchy?
Just put the Convert script on the entity prefab?
And it'll somehow convert it and instantiate it as an entity?
conversionSystem.GetPrimaryEntity(prefab)
ooooh
ok here is what you do
Implement IConvertGameObjectToEntity and IDeclareReferencedPrefabs on the PrefabSpawner monobehavior
yes
in the Convert() method (from the interface) you use:
conversionSystem.GetPrimaryEntity(prefabFieldFromYourBehavior)
Then in DeclareReferencedPrefabs() you declare the reference to a prefab, so it can track it correctly
one sec, see if I can find an example for you
Thanks
btw even though the prefab doesnt exist in your scene, you are still referencing it (from a folder) in your script as a GameObject type yeah?
ie the field
Yeah
perfect
anyone know how do i give a fixed lenght for dynamic buffers in the IComponent struct? or do i give it a fixed length somewhere when i initalize it?
the entity contains this ICompoentData btw with the dynamic buffer
@civic bay see the first code example in this thread, it does more or less what I mean and it saves the converted prefab entity into a component
https://forum.unity.com/threads/instantiating-prefab-entity-on-input.713846/
Thank you
@languid stirrup I've never used a dynamic buffer inside an IComponent, is that even supported?
IComponentData* and i guess so, i think lol, lemme see
@civic bay Here's a blog with loads of more information if you are interested. Please not its from March so might have some outdated info
https://gametorrahod.com/gameobject-conversion-ecosystem-code-tour/
@languid stirrup Normally a dynamic buffer is added directly to the entity (like a component), but that ofc means you can only have one of each type of buffer on entity
Awesome, thanks for your help. Will have a look at them both now
Sorry if I seem dull, I thought I got the hang of ECS, turned out I hadn't
np and good luck! Also the upcoming 0.2 release will make some of this a bit easier π
no worries, Im still getting the hang of it and the damn thing keeps changing constantly!
Haha, all the best buddy! π
I need help in #π»βcode-beginner
weren't you told not to crosspost, your question has nothing to do with DOTS
@flat talon oohhh. Yea I need one type of array. Cool. Iβll try that.
you can even read buffers from other entities in a similar way you read components, getting it as an array you pass to the job
Hey @flat talon quick question
I set up the component system like in that forum and I got it spawning in my prefabs
Should OnUpdate on my SpawnSystem : ComponentSystem be called every frame?
At the minute it only spawns 1 prefab, I can make a for loop to spawn 100, but I want it to keep spawning forever
depends on your needs? keep in mind that if you want to spawn more than 1 in a frame, instead of a loop there's a way to do that all in one call and you get back an array of entity IDs you can use to set position on etc
Yeah I wanna do the 2nd option I think
someone posted that command here above earlier
How can I set up the component system to always update?
Just to see how this looks first
var entities = new NativeArray<Entity>(spawner.count, Allocator.Temp);
EntityManager.Instantiate(spawner.prefab, entities);
but if I put 1000 in there, won't it just spawn 1000 straight away?
it will update if there are entities in the query
yes it will
hence I asked if you need to spawn more than 1 in the same frame π
ahh
OKay so what I'm doing is making a pourer
like salt
So I need like 5 per frame
Like every update, spawn 5 entities
If I have
EntityManager.Instantiate(spawner.prefab, entities);```
Won't that just spawn 5 and then stop?
As far as i know, OnUpdate should be called every frame unless you modify the query from the system
In which case it'll only be executed when there are entities matching the query
Is the system active in the Entity Debugger?
What was the issue?
How are you defining your system, do you even have a query set?
btw.. since you are doing a "pourer", I've fiddled with similar system when I was doing a particle emitter. It can get a bit.. interesting where you want a consistent flow/sec but the delta time can differ π so you need to figure out how many to spawn on every update/tick based on how many are left to spawn in that time slot so to speak
does [WriteOnly] have any benefit? or is it the same as no attribute?
afaik it does help the system figure out potential memory aliasing, so it can allow multiple threads writing to the same array at once
i see, thanks
@slow epoch I was doing the component system inside the spawner GO
I split everything up
can you post your system? Are you setting up a query in OnCreate() or using a foreach query to run it?
public class ParticleSpawnSystem : ComponentSystem
{
int spawncount = 1000;
int spawned = 0;
protected override void OnUpdate()
{
if (EntityPrefabSingleton.Instance.Entities.Count > 0 && spawned < spawncount)
{
int amtToSpawn = 5;
Entity entity = EntityPrefabSingleton.Instance.Entities[UnityEngine.Random.Range(0, EntityPrefabSingleton.Instance.Entities.Count)];
NativeArray<Entity> entities = new NativeArray<Entity>(amtToSpawn, Allocator.Temp);
EntityManager.Instantiate(entity, entities);
for (int i = 0; i < entities.Length; i++)
{
EntityManager.AddComponent(entities[i], typeof(ParticleTag));
EntityManager.AddComponent(entities[i], typeof(PhysicsStatus));
EntityManager.AddComponent(entities[i], typeof(LocalToWorld));
EntityManager.AddComponent(entities[i], typeof(RenderMesh));
float3 spawnPositon = new float3(0, 10, 0);
EntityManager.SetComponentData(entities[i], new Translation { Value = spawnPositon });
EntityManager.SetComponentData(entities[i], new Rotation { Value = Quaternion.Euler(UnityEngine.Random.Range(0.0f, 360.0f), UnityEngine.Random.Range(0.0f, 360.0f), UnityEngine.Random.Range(0.0f, 360.0f)) });
spawned++;
}
entities.Dispose();
}
}
}
@flat talon
that is a component system with no entity query, so not surprising it doesnt call Update every frame π
It is called every frame π
then Im confused, and I thought you said somewhere above it wasnt?
anyways, you got things working then? π
Oh yeah it wasn't working because I got lazy and put everything was inside my MonoBehavior script that converted the prefabs
So because I had the Convert to Entity script on, it was destroying the GO and the Glitter Spawn would only run once before it was destroyed
But now I've split it out into separated .cs files, it's working now haha
generally a component system is supposed to process a set of components, and not be "open ended" like that one. For example you could create it to query for Spawner entities in your world, and for each one you would spawn new entities
Well when I convert my prefabs, I do dstManager.AddComponentData(entity, new ParticleTag)
So should I have an Entity Query in my component system (the spawner) that just contains Particle Tag?
that is the particle, the system you pasted here is really the spawning logic.. so it would query for and process each emitter/spawner
The ParticleTag is on the entities you are spawning "from the emitter"
What is the spawner entity at the moment?
I assume you are tracking that in EntityPrefabSingleton.Instance.Entities.Count ?
By having a component on it and making the system respond to a query for that component, you can remove the usage of "EntityPrefabSingleton.Instance.Entities.Count"
No, that's just a singleton to keep a reference to the converted prefabs to entities
ah ok
I have 3 particle prefabs that I emit from this spawner
So your "prefab spawner" is just a gameobject holding a reference to the prefab, but is never converted into an entity?
The spawner has the Convert to Entity script on it, but set to Inject GameObject
If you change that into what I suggested above, then you can support multiple spawners at once
Only need 1
ok then place a component (with relevant info like spawnrate) on the spawner entity, or a tag if you dont need any data
And then on the spawn system, add that tag to the entity query?
yes
Brilliant, I'll do that now
it would result in about the same as what you have now, but with a bit more flexibility. But can be more easily extended, ie support more than 1 and you can have data on it like spawnrate and even keep what prefab to spawn on that component instead of the singleton
np
alright, still not sure how to pass localtoworld back to transform. all copytransformtogameobject gets me is a Transform component attached instead of localtoworld, which i can't find anywhere
I think it depends on whether the object being converted has a parent or not? I think I remember reading that somewhere
no parent, just trying to have a go move around so i can attach a camera to it
oh you're writing data from entities back to GOs? I think Joa recently commented on that on the forums, that the conversion workflow wasnt really meant for that
I believe they are even going to remove some of the old stuff there to support that
i see. well i'm just at a loss of how to set up a camera in pure ecs then. i was hoping to not have to write my own thing.
I've seen ECS code manipulating the camera
I believe it was on the main thread though, not in a job
lets see what 0.2 will offer, their plan is to be able to convert all object types into entities
oh if i don't make it a job i can just edit GO's directly? i.. didn't think that was supposed to happen.
There wasn't back in the old days something like IJobTransform?