#archived-dots
1 messages ยท Page 147 of 1
as I thought the destinationworld is null
I guess I have to put some other world into the GameObjectConversionSettings here: GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, null);
Unsure - You may find that even if you get that to work it might not work happily with livelink etc ala CreateAdditionalEntity etc. Let me know if you work it out.
It works ๐
Is there a "proper & approved" way of getting an IComponentData to reference another Entity ?
For example, I want to make a teleporter system across my map, with each teleporter pointing to a destination-entity (I have lot of moving platforms, so I can't just use a pre-defined position). Or to setup Monster A to follow Monster B, and Monster C to follow Monster D.
But with the ConvertGameObjectToEntity workflow I can't think of a clean & easy way to bind a component's behavior to another specific Entity.
@pulsar jay what did you parse to .FromWorld in the end?
I just messed up the order while moving some lines. DefaultWorldInitialization.DefaultLazyEditModeInitialize(); just has to be executed before. That seems to make it the DefaultGameObjectInjectionWorld
All the systems also need the AlwaysUpdateSystem attribute
Groovy ๐
@scenic oracle maybe tag the entity?
Tag the entity as teleportEntity
ForEach them and get their tranlations
Store them in a dynamicbuffer somewhere.
Them use that dynamicbuffer so you could teleport around.
(there's probably a better approach imo, but im curious of the answer since i too am facing the same dilemma)
@scenic oracle you can just have a public Entity field in your component. The ECS examples do just that to store the converted Prefab in the Spawner_FromEntity component
Yeah but how do I author that, since the Entity doesn't exist (yet) in the Editor ?
And using tags and making a search was kinda what I thought of too, but it feel so ... "not-as-intended" that I was wondering if there was a cleaner way somewhere.
I see thats a problem. Are you using conversion Workflow or creating the entities from code?
I'm using mostly the conversion Workflow.
My top two favourites involve a little bit of custom tooling. 1) Have a component with an enum - sets either a value or tag on ICD, 2) Use scriptable objects behind a nice UI.
Don't think you'll find one standard way of doing this type of thing.
I was just worried that there was some "official" way of doing this that I had missed.
I don't think so - the same way there's no one official way of doing this kind of thing in Monobehaviour land either. Good tooling helps with all of this.
Well ECS as a paradigm isnt anything new.
You could look up other ECS approaches to your use case and implement them in Unity's ECS
@amber flicker I would consider public GameObject fields the "official" (if not always best) way to do this with monobehaviours
^
hmm I don't like the hierarchy inter-dependency that creates and doesn't work well for e.g. prefab instance <-> scene. That's partly why there are other things like tags, findbytype, class references, unity events and such. That said, public GameObject fields work fine in conversion workflow I think?
That said, public GameObject fields work fine in conversion workflow I think?
@amber flicker Do they? I guess that would be an easy solution then?
I've not used it but I think with the generate authoring attribute if you have a public gameobject you can reference another GO and get hold of the entity version? Someone here must have done this and can correct me.
Fields of an Entity type in the IComponentData are reflected as fields of GameObject types in the generated MonoBehaviour. GameObjects or Prefabs you assign to these fields are converted as referenced prefabs. is what I was referring to
Thats nice. Sounds like it would just work!
It's for GenerateAuthoringComponent attribute
But anyway with custom IConvertGameObjectToEntity there is also no problems with this at all
Oh yeah, GenerateAuthoringComponent does simply replace the Entity by a gameobject field.
Well damn, that make things way simpler.
Seems I was a little bit hasty. Spawning and rendering the entities in edit mode does work but they wont rotate as the RotationSpeedSystem does not seem to update
Looks like it runs and it should work but it doesnt
Yea you may need to update the world on Editor Update - ideally only when you need to
if(!Application.isPlaying && this.rotationSystem != null) UnityEditor.EditorApplication.update += () => this.rotationSystem.Update();
#endif```` I tried that but it does not seem to change anything
@scenic oracle conversionSystem.GetPrimaryEntity will do the trick if you will write your custom IConvertGameObjectToEntity, this is how codegenerated GenerateAuthoringComponent doing that under hood. They just generate GetPrimaryEntity for your game object field.
I think you need to call EditorApplication.QueuePlayerLoopUpdate(); if you want the world and editor view to be updated. Otherwise if just game view I think you can just update the world? If you only update the rotation system bare in mind that the transform system won't run and set the LTW matrix (+render bounds etc)
Right I should have thought of the other systems ๐คฆโโ๏ธ I guess I just assumed they would work as the renderer does also work obviously. I should see a change in the inspectors rotation component however and it does not change. Will have a look at QueuePlayerLoopUpdate
yea.. I'm not sure if e.g. the entity debugger has a system that also isn't running so it can be a bit tricky to know what to trust in that regard.
Does EditorApplication.QueuePlayerLoopUpdate trigger EditorApplication.update? Or should it be the other way round?
my workflow... load mapdata from disk into buffer(1) --> populate Buffers(2,3,4) for verts, Tris, Uvs --> Populate Mesh Componenet
But I guess it should be executed anyway if I move some object in the scene so I should at least see it updating then
Do I need to clean up the buiffers to save memory? There all just componenets DynamicBuffers on entitys
@pulsar jay I'm calling queue from update so I'm pretty sure queue doesn't call Update as I would likely get a stack overflow ๐ - my assumption from the name is that calling queue 100x in one frame would still result in a single redraw the following frame - but that's not clear to me from the docs and I haven't double checked that assumption
Ok sounds fine to me. Just wanted to make sure before I freeze my editor with an infinite loop ๐
Well done if you do all this without doing that at least once ๐ฌ
is there like an ECS LineRenderer? https://docs.unity3d.com/Manual/class-LineRenderer.html
I should learn to import someone elses github who has made one ๐
@amber flicker sadly calling EditorApplication.QueuePlayerLoopUpdate does not seem to change anything. If it would I guess I should also see changes when moving objects etc. which should update the sceneview
just fyi this does work for me so it might be something else missing
is there like an ECS LineRenderer? https://docs.unity3d.com/Manual/class-LineRenderer.html
@graceful mason https://github.com/5argon/ECSLineRenderer here you go
yeah I cant seem to get git to work, it works if i just type git into cmd
butunity wont have it
ah - are you trying to import it as a package via package manager
yeah I should look for a tutorial, but I tried adding to to manifest.josn
added it to path but unity wont take it
maybe i need 32bit git
@graceful mason you can now add git repos through the pakage manager ui. Dont need to go through the manifest file. Pretty sure I am using 64bit git ๐ค
@amber flicker good to know. I am always getting a RotationSpeedSystem_ForEach has already been destroyed error although I check if its not null and enabled before accessing itRotationSpeedSystem_ForEach has already been destroyed ๐ค
O - I've seen that issue before @graceful mason I've honestly just asked someone to reinstall git 64 bit and made sure it was in the path (but it looks like it's on the path for you already)
well for me it just found git? Seems to be one of these things that either just work or are a pain in the ass if they dont
think i will do a dreaded reboot
you can also try cloning it as a submodule into your project
reboot of glory you have suceeded
@pulsar jay that sounds a little odd - does the editor world exist? Does [AlwaysExecute] on rot system make any difference?
the rotation system has both [ExecuteAlways]
[AlwaysUpdateSystem]
the world exists as the entities are there and are being rendered
the rotationsystem is also shown as running in the entity debugger
and it even updates timings when editor ui updates
@sudden comet Roslyn emits the capture of that variable in two different DisplayClasses (so updating one doesn't update the other once the Entities.ForEach happens). It should get fixed once we move to a method of codegen that no longer relies on DisplayClass manipulation.
but a breakpoint in the foreach lambda expression is not hit
ok it also doesnt hit the breakpoint in playmode
guess it may be connected to the code generation
funny thing is it hits the breakpoint during recompilation. Does it execute the original code before generating the new code? ๐ค
the OnUpdate method is actually called twice now during each editor frame.
Could it be that the withname and foreach filters somehow return an empty entity list?
Because it is only the lambda expression that does not get executed
sounds like a likely culprit
Just put a debug log into ForEach and it definitely gets executed a lot each frame
so the rotation system seems to run and update the rotation component. This is neither reflected in the inspector nor the scene view though
The later might be because the transform or some other system is not updating
@sudden comet yeah you can see it by yourself if you look at generated code in Postprocessed IL code window, I completely forgot about that window (as not using it often)
My built player crashes in some burst job, in editor nothing crashes. Anyone got any idea how I can pinpoint what is causing it? ๐ค
Or is it possible to build without burst?
Disable Burst compilation in Project Settings
Thanks, forgot to write I found it X)
this post looks amazing if only i was smart: https://0fps.net/2018/03/03/a-level-of-detail-method-for-blocky-voxels/
Hi all, I'm really having a trouble generating random numbers from within a JobComponentSystem. I've found various solutions but all processing on that thread seem to still produce the same values. Anyone got any ideas? Pseudo code I'm using now here:
I dont think you can create a random number in a job unless somethings changed recently
you can create an array of random numbers outside the job and then use them if that maybe helps
hmm, there's various places that pretty much mention it's a solved problem. There's other forum posts too
https://reeseschultz.com/random-number-generation-with-unity-dots/
How to idiomatically generate random numbers in Burst-compilable jobs with Unity DOTS.
I would think it would work, in that it assigns the random back to the initial array so the next number will be different but if I spawn 50 pawns, only 7 or so unique values are ever generated. Driving me nuts! If there's one thing that I didn't think I would get stuck on it's generating a random number ha
yeah that looks interesting, thanks for that
doesn't work for me though ๐ฆ
well, per thread it does. The gif even looks like it shows it working as I want it
Show full SystemBase setup with ForEach
As approach of preallocated array of random struct instances definitely work as expected.
I described this approach many times on forum https://forum.unity.com/threads/solved-gen-random-number-in-job-execute-causes-hang.779987/
Why you still using JobComponentSystem?
No real reason! I'd seen very little docs about SystemBase so was avoiding using it yet
Well not avoid this as it's recommended approach now. (Job)ComponentSystem will be removed. About your code, try to Debug.Log(nativeThreadIndex)
hard to keep on top of all the changes, will swap it now if it's just a straight swap
oh I know I've been miles behind several times 
so after swapping to SystemBase it's all running on the same thread... Confusion continues
ScheduleParallel for parallel scheduling with SystemBase ForEach
About your code, try to Debug.Log(nativeThreadIndex)
@halcyon blaze ^
yeah you have to do schedule and scheduleparallel for outside the main thread
Ah I see your problem
CellAreaHelper.RandomCellInArea(random
try to replace it to CellAreaHelper.RandomCellInArea( --> ref <-- random... and of course in method replace argument declaration to ref
Oh you legend, what a noob error
You passing your random by value to your static method, and at this point your .NextXXX inside this static method wouldn't change your random instance in system
Thanks a lot man.
Another quick one while I'm here... after swapping to SystemBase it's saying there's a dependency on Translation - what's the method to add that?
Everytime i tried to find stuff on SystemBase I struggled
Another quick one while I'm here... after swapping to SystemBase it's saying there's a dependency on Translation - what's the method to add that?
@halcyon blaze Didn't get what you mean
The system Assets.Scripts.Systems.MasterSchedulingSystem writes Unity.Transforms.Translation via MasterSchedulingSystem:<>c__DisplayClass_OnUpdate_LambdaJob0 but that type was not assigned to the Dependency property. To ensure correct behavior of other systems, the job or a dependency must be assigned to the Dependency property before returning from the OnUpdate method.
Can there only be a single value in dependency then?
Show your current system code
You can even remove all manual Dependency as SystemBase handle it for you automatically in current case. Just use ScheduleParallel() and not assign ForEach to any JobHandle
Only _ecbs.AddJobHandleForProducer(Dependency); as it not handled automatically, thus you should pass Dependency here
Ah nice that's worked perfectly
Thanks again! I'll try not to come bothering you again too soon ๐
When someone bothering me when I don't want that, I just completely ignore messages. Simple and effective strategy.
Will a NativeHashMap resize automatically if full when using Add (No concurrent version or writer)?
Yes. By doubling capacity strategy.
@storm ravine Perfect thanks
Out of curiosity how do you handle resizing NativeCollections from parallel jobs (The concurrent versions)
Is there any patterns or guidelines around for that, or its just something we shouldn't be doing
Native Collections aren't designed for frequent resizing
before scheduling you job calculate proper collection size and allocate as much memory as you goanna need
found that many of my systems need an EntityCommandBuffer
so here is my solution:
public abstract class SystemBaseEcb:SystemBase{
private EntityCommandBufferSystem barrier;
protected override void OnCreate(){
barrier = World.GetOrCreateSystem<EndSimulationEntityCommandBufferSystem>();
}
protected override void OnUpdate(){
OnUpdate(barrier.CreateCommandBuffer());
barrier.AddJobHandleForProducer( Dependency );
}
protected abstract void OnUpdate(EntityCommandBuffer ecb);
}```
so now my systems look like this:
public class Test : SystemBaseEcb{
protected override void OnUpdate( EntityCommandBuffer ecb ){
Entities.ForEach( ( Entity e ) => { ecb.AddComponent<Foo>(e); } ).Schedule();
}
}```
@dry dune have you checked the code gen for that?
it might help to have that aggressive inline thing on it
Benchmark and test the AggressiveInlining option. Use MethodImplOptions.AggressiveInlining.
note this is all guess work and i am 100% going to make similar
thanks for the idea ๐
I'm proud of my new crazy creation:
a generic extension method for EntityCommandBuffer that works inside jobs
to construct a complex tweener entity (with generic components and dozen of parameters) using fluent interface
ecb.Tween<MatColor>(entity).To( new float3( 0.2f, 0.4f, 1f ) ).Duration( 100 ).EaseOut( 0.2f ).Start();
Hey , a quistion : can unity export all gameobjects to entities at exporting and then It suddenly become 2 times faster than before?
Without bugs?
i guess
im planning on a custom kind of sub scenes
you can load all the gameobjects and convert them into a world. then serialzie out the world
ship that world with your game
pretty sure thats how subscenes work under the hood anyway
Hi guys,
Have a question about DOTS stack. As I understand It, it is really powerfull when your game have serveral thousand and more objects. Now my question is what are the benefit of using this programatic pattern when the game doesn't have that much entities ? Like in enterprise XR application ? (The question is not if we should use it now, more like in the future when DOTS stack will be fully ready for production)
@quaint niche Probably secondary things like battery life of the device and loading times
the performance will still help but in that case probably different ways
Yeah I read this, but It would be interresting to have some numbers, do you know any articles that put some numbers on those things ? (even if this is not DOTS from unity but any other Data Oriented programming) It would even be more interessting if the article focus on a game with few objects because there maybe it doesn't make much difference, I don't know
@ocean tundra Thanks for the answer by the way ๐
i think its far too early for numbers from anyone. maybe the unity team have some internal things, but so far it looks like they are pushing for more things on same hardware
Yes sure, but Unity is not the only program that use data oriented programming so even statistics from other technologies could give use a hint on what it could be. I'll look a bit to see if I found something on the internet
@sudden comet
Roslyn emits the capture of that variable in two different DisplayClasses (so updating one doesn't update the other once the Entities.ForEach happens). It should get fixed once we move to a method of codegen that no longer relies on DisplayClass manipulation.
@storm ravine Thanks again for what you did, the goal was more to be sure that it was a "bug" and have Unity to fix it ๐
Well it's not Unity Bug
It's Roslyn bug
They (Unity) wouldn't fix that exact issue. They just will move to another solution (from DisplayClass) which will fix that case by default
Out of curiosity how do you handle resizing NativeCollections from parallel jobs (The concurrent versions)
I think many of the collections that allow you to write are composed of small blocks so that more can be added/linked/used without needing to copy all existing data to a new space, as that would obviously cause problems with anything already in the process of writing/reading on another thread. maaaaaybe one of the lists uses locks instead.
UnsafeHashMap using buckets per thread and Interlock, but it not allocate anything when in concurrent mode, only reuse.
My general use case for unknown containers length is IJobParallelForDefer, and precalculated worse case (like for pathfinding I know I have max Width x Height amount of regions which will be processed, thus we allocate, for example, worse case hash map at OnCreate and just reuse that for iterations and clean in the first or latest job (clean up pretty simple - it just set Length to 0 and not free memory but override it when we reuse that, in other cases (like HashMap) it just reset buckets start indices to -1 etc.). In process of calculating we fill that hash maps, and using IJob in some places for remapping these maps keys to NativeLists which can be used for IJobParallelForDefer which allow us to process data batches effective, without unnecessary early out loops, or without processing noisy data, by only required amount which unknown at schedule time.
Of course it has own cost - in that case cost of preallocated container, but it become case specific which you should check and profile by yourself
Also own native containers for specific logic which allow growing per thread etc.
Hi guys.
Can somebody explain me why my CollisionJobSystems causes the given exception? Code and Exception is in the pile
https://www.codepile.net/pile/xvE0W1A7
{{ description }}
@vivid copper could you try
protected override JobHandle OnUpdate(JobHandle inputDeps)
{
var task = new PlayerCollisionJob
{
playerGroup = GetComponentDataFromEntity<PlayerTagComponent>(true)
};
var handle = task.Schedule(stepworld.Simulation, ref buildworld.PhysicsWorld, inputDeps);
//handle.Complete(); not sure if you want to force it to complete immediately
return handle;
}
the exception is gone but it doesnt trigger any collision but this seams to be another problem. thank you
might need to update that system after the buildphysicsworldsystem
hmm has anyone had a use for entityQuery.AddDependency(JobHandle)?
seems interesting how you can add another job dependency before the internal jobs kick off ๐ค
@safe lintel I was wrong it didn't change anything I disabled the system and have forgotten to reenable it. the exception still occures
@coarse turtle Where is that? I think it would be usefull with native collections
eg collectionX is setup in SystemA, SystemB reads CollecionX, but unless the dependency is setup jobs will throw me errors (maybe) or ill get lucky and it will run for a bit
This is a very specific question but does anyone here know about Voronoi diagrams? I would like to implement it with Jobs and Burst but don't really know how to, need them for biomes.
@odd cipher I've used them bit dont really understand the math underneath them
Same. that's the main problem
definitely not well enough to rewrite into burst
I've never had any performance issues creating them tho
maybe just use whatever oop based one you can find, then take the output and make it into entities or blob
i guess it depends on what your doing with it tho
I don't use Entities.
I'm trying to implement biomes into my world generation, I know two methods so far, using Heat and Moisture maps or a Voronoi diagram (Minecraft style).
Possibly.. it gets quite complicated
yup
Though if I don't care where a cold or hot biome gets placed I think just a Voronoi could work.
yea you can always add hot and cold based on a heat map later
Yeah. Kinda taking Minecraft for inspiration here. They don't have a heat map as far as I'm aware.
been awhile since i played but i think they do have some rules
so no snow gets next to a desert
Yeah I mean that can be done without a heat map
I just need to find out how to generate a Voronoi map.
http://paulbourke.net/papers/triangulate/
https://www.habrador.com/tutorials/math/13-voronoi/
https://en.wikipedia.org/wiki/Fortune's_algorithm
This is a tutorial on how to solve problems in Unity by using math such as Linear Algebra and C# code. You will learn how to find out if an enemy is infron or behind you, how to follow waypoints and learn when you have passed a waypoint, how to figure out if you are to the lef...
Hey guys, I'm getting some flickering when spawning in my units and buildings
The seem to start at 0,0,0 then jump to their translation position
I've Disabled the entities, and only reenable them when i 100% have set their translation, but they still seem to appear at 0,0,0 for 1 frame
its an ordering issue most likely, make sure your system that spawns stuff is updating before the transform group, or after the rendering
is [UpdateBefore(typeof(TransformSystemGroup))] enough to be before?
that should do it yeah
which would be the best built in buffer to use
im just testing with Entity manager but eventually i want to use a ECB
Even with entity manager it still flickers
hmm, odd, ive had this issue a few times now and that was the fix! i swear!
with ECB u could use the begin simulation group to make it spawn next frame.
are you updating the localToWorld directly or using Translation/Rotation
mmm nope, thats the way i was doing it too
going to try updating LocalToWorld
wtf
still flickers
๐คฆโโ๏ธ
Disable dosnt effect children or linked entity
oh no. how could i Disable all linked entities when using a ECB Instantiate
hemm, is there a way to use EntityArchetype with the entity created with IConvertGameObjectToEntity ?
ho, I found EntityManager.SetArchetype, nvm
weird, the less job workers i use, the faster my game ๐
at least in the editor, going from 1-11 workers is a 2ms difference, and it seems to scale in the sense that 5 workers is better than 11 but not as good as 1, not just a flat out more than 1 worker is worse equally
I think you should test in a build
yeah thats next
how many entities do you have?
this is a very low count
yea that will be it then, they have said that there is threading overhead even with the job system
ah editor crash just a moment, but anyway was testing menu options. I think in very small test level its less than 500 entities
so if you have low number of entities the scheduling cost is more then the perf benifits you could get with lots of entities updating on many threads
i wouldnt expect the overhead to scale though? i wouldve thought: run on mainthread sure faster than using jobs, but i get a gradual increase in overhead for every additional worker instead of a more or less flat fee
schedule or schedule parallel ?
its a mixture
i would think that schedule parallel is probably a bit dumb, doing something like entities count / worker threads
so that would increase scheduling cost with more workers
but at some point when you have tons of entities it becomes worth it
ScheduleParallel in ForEach works at Chunks level (as it IJobChunk), Chunk per thread.
Depends on what you doing parallel (fill NativeHashMap for example) it can have worth performance, because of locks (as it use Interlock under hood). Also Schedule overhead, as was mentioned above (and was mentioned by Unity many times), at low amount of entities bite performance benefit. With one big BUT - all depends what your job doing.
It can be 10 entities but processing - pretty heavy, thus you'll get parallelesation benefit
just building now but does 2ms sound kinda normal for scheduling overhead for 12 cores to you @storm ravine ?
in editor
well i suppose this is all down to project usage the more i think of it ๐
so dumb question
How you measured that it's exactly schedule takes 2ms? You wrapped it to profile markers? Or just looked at system timings? Which number you'll get when you disable jobs debugger, Burst safety checks and Leak detection to Off?
measured setting the JobsUtility.JobWorkerCount, all safety checks off
Is 2ms for all systems?
yeah pretty much mainly my simulationsystemgroup
Also important note (and this is one of reasons for batch count in IJobFor etc.) size of batch very important as if you have 100 items with batch size 1 per thread it will be slower than have 100 items with 20 items per thread (just abstract numbers for showing difference order). Thus it depends on your chunk layout (in case of ForEach) as it splits chunk per thread.
@storm ravine At what point in development did you start optimizing all your stuff.
I'm very early and dont want to waste time on it yet, but also it looks fun ๐
All these 2ms is very wide amount of reasons for performance difference. It depends on many many things - data layout, batch sizes, calculation cost per execute etc. etc. in different combinations it will give different timings.
do you mean IJobForEachEntity or IJobParallelFor when talking about batch?
@ocean tundra From architecture prototyping and preproduction. And through the whole development cycle. It's iterative. Added couple of mechanics, finalized them, polished, checked project-wide performance - optimize if performance dropped below the threshold or the total amount of performance drops from a couple of previous iterations dropped below the threshold.
do you mean IJobForEachEntity or IJobParallelFor when talking about batch?
@safe lintel IJobChunk, IJobFor, IJobParallelFor, IJobParallelForBatch and all parallel job types
As you can control batch sizes for some of them directly, for other - indirectly
ah just thought you were referring to directly controlled batch sizes
I referring to general potential performance issues with parallelization
Hmm seems like doing the SetSharedComponentFilterOnQuery call generates a compilation error despite the foreach lambda invoking Schedule ๐ค
yea I'm pretty sure
Well for me it not generates any errors
Hmm, let me see if I can generate it again in a new project
Ah my bad, I was in rider, sry, yeah in Unity I see error
Ah cool, I'll post it on the forums to see if someone at Unity can take a peek at the issue
I pointed them to it. You can fill bug report for that thus they will have ticket for that
Tbh it maybe expected
As it's not used anywhere by Unity and even not covered by tests
But stop
WithSharedComponentFilter
Why you not using this one?
hello, im try to freeze my character physic body with an job that work like this:
PhysicsVelocity.linear.xz=0;
Translation.value.xz=0;
but its lag my player some time. do u know an other way?
@ocean tundra From architecture prototyping and preproduction. And through the whole development cycle. It's iterative. Added couple of mechanics, finalized them, polished, checked project-wide performance - optimize if performance dropped below the threshold or the total amount of performance drops from a couple of previous iterations dropped below the threshold.
@storm ravine from personal experience , this is a very crucial & practical approach when performance is of prime importance. the "optimize at the end" blanket theory doesn't really leave much todo when all of your design and systems were never architectured with performance & scalability in mind. demands extensive rework of foundation modules leading to final hour chaos..
who can help me to freeze xz vectors on PhysicsVelocity
@mint iron wrong person
alright
what would be a good way to reference a texture2d asset from a component?
I cant do this because Texture2D isnt blittable
public struct IconComponent : IComponentData
{
public Texture2D value;
}
You can try managed IComponentData
public class IconComponent : IComponentData, IEquatable<IconComponent> {
public Texture2D Value;
public bool Equals(IconComponent other) { ... }
public override int GetHashCode() { ... }
}
@coarse turtle ty, I'll look into that
I think I'm being dumb about containers.
I'm refactoring a system that used to work with a DynamicBuffer on the player to which I would add lights that were within X rangesq, then every frame I would dump that dynamic buffer out to a NativeArray to set a computebuffer.
I'm rearranging things now to add new content, and I'm getting myself confused over how best to achieve this.
I have a set of entities with the light Data as IComponentData. I am thinking it may be best to do Entities.ForEach on these (feeding in the player position), and parallel writing out those which are in range to a NativeContainer, then after the job is complete copying the data (presumably via NativeArray) to the ComputeBuffer
So I thought maybe a NativeQueue.AsParallelWriter() might work, but I'm not sure about getting the data out after the job finishes in that case.
Maybe it's better to go back to running once on the main thread over an Array dumped out from the EntityQuery but it seems like that's not very efficient
do you need to change them in the process or are you just essentially concatinating the chunk arrays into a single one
for this one I'm just grabbing those within range and creating a new smaller array for that frame
did you flatten out the DynamicBuffer into seperate entities or its still on the lights
well I've currently ditched it (on a separate branch!) but it was a single dynamic buffer that sat on the player, and every frame I'd clear the data, iterate an array that I got using eq.ToComponentDataArrayAsync and add to the buffer within that job, then after completing the job, copy the dynamic buffer data out to an Array
which always felt a bit icky if I'm honest
yeah, because unless you're doing somethign else with it in ECS, its just being put there and then removed, could be outside entirely.
I tell a lie - in that version the lights weren't entities, apologies - they were simply data in a NativeList (because I need to delete them when they were picked up)
my bad
I remain confused about appropriate ways to iterate one entire set of entities for each of another set of entities, too, though perhaps that's unrelated to this query
the fastest way would be to have a query, iterate the chunks and effectively AddRange() with (memcpy/offset) the entire component data array for each chunk to make a big single set. Or keep the chunk arrays and use IJobForEach if the counts are big enough to justify it.
i dont know of a way without taking two passes
I'm sorry I don't follow. I have no idea about chunks!
I visualise this as a massive list of stuff, where each component is in range or not, and I want a smaller list with only those in range.
Apologies for not following ๐ฆ
just made my discord text like 300% somehow lol - ahh CTRL +/-
lol
Perhaps it's NativeList<> I'm really after. It just seemed like I could do this from the perspective of each light, rather than the perspective of the player
yeah i mean, you can loop through each light, and test it, store it off to a list.
for the two passes, i was talking about this sort of thing https://github.com/jeffvella/UnityEcsEvents.Example/blob/master/EventsExample/Assets/Game.Scripts/Systems/SimpleCollisionSystem.cs this seems to be the same as what you want, except instead of an event, you'd store it to a list when in range.
but trying to do this from the other direction: I am light, I am in range, add myself to some parrallel write collection... is that doable?
i presume u need a second set of data to test if in range
so you need to get that from somewhere first
the lights have their position in IComponentData (that's what I feed to the shader), and the player's position can be got from either a SingletonComponent get (not currently but I think I use it enough to do this), or just grabbing it async and combining the dependencies
ahh, i thought it was many to many, if its just lights in range of player that would be easier i think
yeah okay actually that many to many example will be really useful for something else, thanks
yeah this is one to many
or many-to-one (but not apparently yet!)
yeah id just getsingleton pass it in as local to ForEach on lights and call it a day ๐
yeah okay but it's the bit where I write the data in parallel from the Entities.ForEach(lights)
how many lights?
low hundreds
imo just use a list if you can preallocate the length that would be ideal
and do it from the player's perspective rather than parallel yeh?
i think from memory Queue is not stored directly as an array, so if you're just planning to memcpy it over to somewhere afterwards the ToNativeArray() is going to be expensive as it has to construct it. could be wrong there i dont have source in front of me.
yeah I read that ๐ฆ Okay well it will be simpler to implement that way anyway
Thanks yet again, @mint iron !
with hundreds i dont think its going to be worth the costs for fancyness, if you were talking 5k+ id say maybe.
yeah it definitely won't ever be that high as these lights are volumetric for my raymarching shader. I can handle a few tens of nearby ones easily, but hundreds starts to stretch it, hence the need to only get nearest ones each frame
if you use a list that is stored as a system field and re-used/cleared then it doesnt matter if it allocates within the job the first few times its used, it will settle.
yeah so keep it persistent, give it a reasonable Capacity and just let it deal with itself?
yeah exactly, only thing to watch is if you expanded to like a 100k, then went back to 100, youd be wasting memory
yeah that won't be an issue!
Cheers!!
mmm one last question... ๐
The data I need are split over 2 IComponentData (to make things cleaner for the shader down the line).
Should I generate 2 NativeArrays:
pickupEntityQuery.ToComponentDataArrayAsync<PickupPositionData>
pickupEntityQuery.ToComponentDataArrayAsync<PickupAnimationData>
for the job, or do this once to get the Entity array and then use GetComponentData<>(e) within the job?
NM I'm being a dumbass please ignore ^^
Is it possible to make a material property override for Texture Offsets and Texture Scales?
aka, these fields
if not, I guess I could technically just store these same values in a float4 and use them in my shader instead, probably
As I just updated to the latest version of ECS, I'm running into an issues using EntityCommandBuffers to create a new entity using Entities.ForEach. Does anyone have an example?
@prisma anchor lets see what you have, all i do is ECB.Instiante (spelling :P)
but I need to pass in the Jobindex right?
var deltaTime = Time.DeltaTime;
var entityComponentSystem = _entityCommandBufferSystem.CreateCommandBuffer().ToConcurrent();
Entities.ForEach((Entity entity, ref PowerUpCreateData createData, ref PowerUpBoardData boardData) => {
createData.TimeSincePowerUpCreated -= deltaTime;
if (createData.TimeSincePowerUpCreated <= 0) {
var powerUp = PowerUps[random.NextInt(0, PowerUps.Length)];
var x = boardData.boardSize.x * 0.5f - PowerUpHorizontalOffset;
var powerUpPosition = new float3(random.NextFloat(-x, x), random.NextFloat(0, createData.SpawnRange), 0f);
var powerUpInstance = entityComponentSystem.CreateEntity(
Ok, i see thanks, it doesn't need to be parallel
if its not schedule paraell you dont need concurrent
noted
Also, you have to create an entity from an archetype now? before you could pass in anoter entity
Quick question... hope someone can answer me fast... how many systems does unity ecs support ? Is there a limit ? Could i have 300 systems for example ? Pure ECS includes plenty of systems... for example a good dynamic spawn system in ecs takes about 5 systems to realize ( Recipes, Recipe, Condition, DefaultCondition e.g. )... so is there a limit ? Most of those systems would only run over a couple of entities per frame
Thats great to hear, thanks ! ^^
Is it true tag components have no chuck swap cost when added and removed?
Or is that a target goal of the Entities team?
adding components changes entity's archetype, i doubt there is no chunk swap cost
but i do hope that they create some kind of special usage for tag components so they wont trigger archetype change
actually they added that a while back
well, it still changes the archetype, but the chunks don't swap
the coming .enabled should help a lot with this
what would this new .enabled do?
but actually to that point, it could be worth doing what Joachim talked about - using an Enabled bool inside an ICD rather than adding/removing the tag - as it'll be easier to replace
@deft stump this is all we/I know https://forum.unity.com/threads/making-a-skill-system.894007/#post-5875804
taking a look...
on that note, I should hang around the forums more
Yea I think stuff like this is pretty significant - posted the link in here before and tweeted it too but that doesn't add much visibility ๐
oooh. so it's like enabling/disabling components in classic unity.
righto this does sound like a decent solution rather than adding/removing tags
thats a pretty big, and welcome change.
hoo, thats seems pretty big indeed
@leaden hatch here is my way to select icon texture:
Component contains only icon index
[Serializable]
[MaterialProperty("_Icon", MaterialPropertyFormat.Float)]
public struct MatIcon:IComponentData{
public float Value;
}```
and material shader uses a flipbook to display it
@dry dune tyvm very interesting
Is it possible to make a material property override for Texture Offsets and Tiling?
I'm trying to use a texture as a sprite sheet, basically, and this is how I tell the material to only show part of the texture
Unity supposedly automatically generates a shader property called "_WhateverYourTexturePropertyIsNamed_ST"
it's a float4
but making a MaterialProperty override for it (Like @dry dune just showed an example of) doesn't seem to work for me
[GenerateAuthoringComponent]
public struct MainTexOffsets : IComponentData
{
public float4 Value;
}
In my case, I am trying to work with the HDRP Unlit shader
yes Unlit is not supported yet
I don't understand what you mean. It's a shader just like any other shader.
if you mean there's no built-in material property override, then yes
nope this is dots way to tweak instanced material properties with component
but there is no built-in material property override for any shader's texture tiling/offset values
so you're telling me the HDRP unlit shader is not set up to be instanced?
Per-instance material params tweaking by dots component are not supported for unlit shaders
ok, so the lit shader should work if I write one for it then?
lit node in shader graph should work
there are some built-in material property overrides for unlit shaders, fyi
like the color
it's called HDRPMaterialPropertyUnlitColor
that might be the only one
I don't know what it is about the HDRP Lit shader, but I can't even get a texture to appear properly
and the HDRPMaterialPropertyBaseColor override doesn't seem to work on it for me
is there something special I have to do to get lights to work on entities?
when I use the HDRP Lit shader, all of my entites just appear as gray
I think I understand now what you might be trying to tell me @dry dune . You want me to go into ShaderGraph, and add my own custom node prior to Lit shader, and then feed it into the Lit shader's value
what I'm trying to do is skip that step and override the Lit shader's exposed property directly. It seems to work with the Unlit shader's color, not the the Lit one's. And I have no idea why.
both HDRPMaterialPropertyUnlitColor and HDRPMaterialPropertyBaseColor appear to be attempting to set the correct properties for their respective shaders
yeah seems to be something funky with lighting...turns out if I slide the Metallic value of the Lit shader up, the color changes do appear
anyway, sorry for all that, just thinking outloud.
new question is, how do I get lights to affect my Lit shader using entities?
also I feel like I should point out I am using the Hybrid Renderer V2 in Unity 2020, maybe that's caused some confusion
HDRP/Unlit is supported in Hybrid Renderer V2
is it alright if I ask for a code review on my movement system?
I'll put it all in one hate bin.
sure, we have many helpful people
alright... just a minute or two.
okay
I think I explained it well in hatebin
in context, I'm currently making a megaman battle network type of movement.
but I feel like my implementation of the movement is wrong somehow. feels way too hacky.
I'd like to get an opinion if this is fine or if I can still make this cleaner.
or if there's another method I can do without me looping through 18 panels XD.
tbh, i feel like its fine, 1 improvement could be making PanelData a buffer instead of a component and place it to entity
so instead of having 18 entities having 1 panel data, you could have 1 entity that holds all the panel datas
you could check DynamicBuffer in manual for more info, i am too lazy rn D:
and after that, you can implement IEquatable<T> interface in PanelData to get the panel data you are interested, thats another improvement you could make, but you need Buffer(Array) of PanelDatas first
@opaque ledge thanks.
I actually thought of that too.
but man, I thought it was the wrong approach too! it also felt hacky! XD
i can understand you feel like its hacky, but its not, each system you created is doing 1 job, and in the end it produces the result you want ๐
I got the same feeling back in the day, writing a 'whole' system just for single simple functionality, but thats ECS way actually ๐
dont forget to add proper UpdateAfter/Before attributes btw
dont forget to add proper UpdateAfter/Before attributes btw
do i have to because 1 system is writing and another system is reading?
yeah
otherwise it will be 1 frame delayed
if your movement system runs before your input reading system that means your movement 1 frame 'delayed', so its just better to manually arrange it
alright. any small optimization is good optimization ๐
i dont think it should be considered optimization, if you dont do it it will work 'wrong', but i guess not many people cares about 1 frame ๐
https://forum.unity.com/threads/entities-0-10-bug-future-of-addcomponentobject.879934/#post-5920799 Anyone have an idea what martinpa may mean by 'a documentation issue' in this reply?
I've no idea what that means
Ok thanks - wasn't sure if I was being particularly dense ๐
Hi I'm trying to change my ForEach to be readonly, as I am running into a warning. csharp var destroyHandle = Entities.ForEach((Entity entity, PaddleData paddle, ref Translation translation) => { entityBuffer.DestroyEntity(entity); }).Schedule(paddleHandle);
when I set change the second param to in Paddle paddle Unity crashes. Any ideas?
try disabling burst compilation @prisma anchor
in jobs > burst and unchecking the enable compilation
After some more googling, it seems that the issue is due to me scheduling the jobs incorrectly. I handle it tomorrow. Thanks @deft stump
can I ask for another code review?

i suck at reading other people's code, but i will try my best to help ๐
can I ask for another code review?
@deft stump NONoooooope
@storm ravine 
can't stop me boi!
Anyway here:
https://hatebin.com/acfwtqcjqn
here's context:
I'm currently making a megaman battle network type of movement.
As as @opaque ledge suggested, I should do a dynamic buffer instead of having 18 panels with their own IComponentData.
And so I did.
1 dynamic buffer with 18 elements.
But... I dunno if this is a fine solution or not. The movementOnIndex system is now slower than the previous solution.
@deft stump can you try to loop over the buffer with using buffer.AsNativeArray() instead of buffer itself
so something like, var panelDataArray = panelData.AsNativeArray(), then loop over the panelDataArray
also, if PanelData is a singleton (meaning that there is only 1 type of PanelData in the world) you can do GetSingletonEntity<PanelData> to get the entity that holds PanelData, so you can remove that EntityQuery
if there would be multiple PanelData as game is being developed, you could cache EntityQuery in OnStart method instead of creating it everytime on OnUpdate
EntityQuery panalDataEntityQuery;
void OnStart()
{
panelDataEntityQuery = GetEntityQuery(typeof(PanelDataBuffer));
}
void OnUpdate()
{
var panelManager = panelDataEntityQuery.ToEntityArray();
}
Question though. How do i skip the looping entirely?
I think that's also whats effin me up
like i said, implement IEquatable<PanelDataBuffer> in your PanelDataBuffer
or since your 'id' is int2 you can implement IEquatable<int2>
then you can do panelData.AsNativeArray().IndexOf(dataindex.index), if this returns 0 or bigger thats your index, otherwise your buffer dont have a PanelData with the index value you provided
What happens if I try to add a value to nativehashmap that's already in there
yo all! I have a weekly random question for you
do you think using ECB is faster than use the EM or it's just a matter of shifting the workload ?
specifically we are finding this operation extremely slow: _entityManager.SetSharedComponentData(entityView.uecsEntity, new UECSSveltoGroupID(egid.groupID));
@scarlet inlet setting shared comp data is very heavy due to having to find where to put the entity + having to do the move.
as far as i know entity command buffer tends to be faster
because it tries to batch operations together i believe
isn't it the same to use an entity component tag?
so for example if you do that SetShared from a for-each, and you have 3 entities you move on a chunk, it will try to batch the operation
lil bit more expensive
but only a small amount
would actually love to see whats the difference beetween the two
between shared component and entity component tag you mean?
or between EM and ECB?
because it tries to batch operations together i believe
@vagrant surge no if you not using batched api for ECB it will behave same as EM as underhood they using the same GetComponentDataWithTypeRW and then MemCpy. ECB will be faster only from 0.9+ entities releases, as they added BurstCompile support for playback chain and playback now call burst compiled function pointer, which will do job obviously faster than EM call without burst.
good news about the burst
It's old news as we on 0.11 package version already ๐
yeah I am sure 9 or 10
but I didn't remember that part
I guess I can create my EntityCommandBuffer and call Playback from mainthread whenever I wish
right?
[DisableAutoCreation]
public class SubmissionEntitiesSystemGroup : ComponentSystemGroup
{
public SubmissionEntitiesSystemGroup(SimpleEntitiesSubmissionScheduler submissionScheduler)
{
_submissionScheduler = submissionScheduler;
}
public EntityCommandBuffer commandBuffer => _entityCommandBuffer;
protected override void OnCreate()
{
_entityCommandBuffer = World.GetOrCreateSystem<EndSimulationEntityCommandBufferSystem>().CreateCommandBuffer();
}
protected override void OnUpdate()
{
base.OnUpdate();
_submissionScheduler.SubmitEntities();
_entityCommandBuffer.Playback(EntityManager);
}
readonly SimpleEntitiesSubmissionScheduler _submissionScheduler;
EntityCommandBuffer _entityCommandBuffer;
}
Yes you can. As Playback will call PlaybackInternal which in turn will call PlaybackChain, which in turn will call PlaybackChainChunk which is FunctionPointer
I'm pretty sure that the command buffer which you get from calling CreateCommandBuffer on a CommandBufferSystem can only be playedback once and is already played back by the CommandBufferSystem.
yeah
it's optional now apparently, but I get already the error
it's awkward, if I want the control over the playback I have to copy their pattern
with the m_PendingBuffers stuff
I guess I cannot have just one, because of the concurrency
I guess I can implement EntityCommandBufferSystem
this worked:
[DisableAutoCreation]
public class SubmissionEntitiesSystemGroup : ComponentSystemGroup
{
public SubmissionEntitiesSystemGroup(SimpleEntitiesSubmissionScheduler submissionScheduler)
{
_submissionScheduler = submissionScheduler;
}
protected override void OnCreate()
{
_ECBsystem = this.World.CreateSystem<SubmissionEntitiesCommandBufferSystem>();
base.OnCreate();
}
protected override void OnUpdate()
{
base.OnUpdate();
_submissionScheduler.SubmitEntities();
_ECBsystem.Update();
}
readonly SimpleEntitiesSubmissionScheduler _submissionScheduler;
SubmissionEntitiesCommandBufferSystem _ECBsystem;
}
[DisableAutoCreation]
public class SubmissionEntitiesCommandBufferSystem : EntityCommandBufferSystem
{ }
Yes ECB from ECBS will be played back at place where ECBS will be updated and if you playback that early it will throw error. You can just create EntityCommandBuffer from constructor and use that multiple times, as it has playbackPolicy argument which allow multiple playback
I need the control over the playback
I need the control over the playback
@scarlet inlet I don't get to which message this relates ๐
mine
is it possible to use ScheduleSingle with the foreach lambda?
there is no more ScheduleSingle, its renamed to Schedule
oh yeah, i am an idiot ๐
speaking of foreach lambdas, what do I have to do to get this component system working? I've tried using just ComponentSystem (instead of JobComponentSystem), using WIthoutBurt,Run,calling Schedule on the inner loop, etc., nothing will actually compile. Is nested foreach not supported? all it does is iterate one group of entities, then compare their distances to another group of entities.
https://hatebin.com/gvzencvffc
it also complains if I change the order of the parameters in the foreach which is annoying
Assets\Scripts\Systems\TargetingSystem.cs(15,5): error DC0002: Entities.ForEach Lambda expression invokes 'get_Entities' on a TargetingSystem which is a reference type. This is only allowed with .WithoutBurst() and .Run().
(changing it to use WithoutBurst or Run does not resolve it)
First of all - use SystemBase. Second - nested ForEach not supported.
Yeah I had started with SystemBase and just kept changing it to see if I could get it to work
Good to know like every tutorial out there is no longer valid oof
I assume the way to do it then is via calling GetEntityQuery and then only doing one ForEach loop that processes the query array
So I'm seeing the official messaging for Unity to use Hybrid Renderer v2 is to instantiate a Prefab and then their code will convert that to an entity.
wouldn't that have the same bottlenecks that instantiating GameObjects has?
Like if I want to create 100,000 entities, wouldn't instantiating Prefabs take absolutely forever, as opposed to creating the Entities manually?
I think the general workflow is to create a prefab entity
what is a prefab entity?
An entity with the prefab component
if you're using the conversion pipeline you can declare converted gameobjects as a prefab
I want to avoid GameObjects because I am attempting to spawn hundreds of thousands of entities
Well the idea is you're only using this 1 converted prefab that is an entity and you would use that to instantiate, because the converted prefab can be placed into a subscene or simply just instantiated once for conversion
I see. I think.
So you spawn one GameObject, it gets converted to an Entity, and then you start cloning it and making whatever changes you want then
Yea
Ok, I'll have to figure out how to do that, sounds smart.
conversion happening when you saving subscene not when you running the game
right now I'm only aware of how to create entities at runtime using the OnCreate method from JobComponentSystem because I'm a noob
fastest possible way to create lot's of entities is to use a batch version of Instantiate method to clone your prefab entity, and next to set initial params for those new entities using a job (foreeach parallel)
that sounds like a level 10 technique, and I'm still on level 1 myself
is there any good example project for just spawning entities?
thank you, thank you
So a question, i have bunch of entities that shares specific component called "ID" which is FixedString32, and it wont change during runtime, should i make it a blob asset or shared component data ?
In my use case, i am using IDs for UI, so i am not actually using that ID data for any ECS systems
best option is to replace id with integer
ECS internally doing exactly this to store types, each type gets it's int id that is blittable and can be used in component data
i dont want to do that tbh, i am not exactly great at tooling and designs so i rather have strings as ids so i can also use them when i want to hardcore some stuff
DOTS and strings aren't the best friends
I'm planning to put my UI/reference data into a Blob
99% of the data will be in components
Hi all, getting a really weird issue when incrementing a float inside a SystemBase on a single thread or multiple threads. As soon as it gets over ~ 1 it resets back to 0 and I'm certain the component isn't being added again
anyone got any ideas?
delay.TimeWaiting += deltaTime;
if (delay.TimeWaiting < delay.TotalTimeToWait)
return;
Literally all it's doing, but when logging the value never gets more than a few points over 1
you sure theres no other system setting the value?
Yeah the components created once in a system then that origin component is removed, then this system is the only other that does anything with the value
hard to help without full source code
One sec I'll give more context, wondered if there was any weird quirks anyone might know first
try to incapsulate the problem into the simpliest possible system
So a question, i have bunch of entities that shares specific component called "ID" which is FixedString32, and it wont change during runtime, should i make it a blob asset or shared component data ?
@opaque ledge Definitely - blob
https://hatebin.com/cdqpgajgrb
So inside System_StructureActionDelayed Delay.timeWaiting never increases above 1. It just resets back to 0 and keeps incrementing indefinitely
nothing else in my codebase touches that component
Simple and lightning fast image sharing. Upload clipboard images with Copy & Paste and image files with Drag & Drop
don't see any problem in your code
It's confusing the hell out of me ๐ฆ
make sure TotalTimeToWait value is correct
Stays at 3 the entire time when I logged that
you can disable burst and jobs, run you foreach on the main thread and to debug your code
yeah I managed to debug it
it just... randomly comes through as 0 again on it's next iteration
but it always resets when the value gets just over 1
public struct Timer : IComponentData{
public float Time;
public float MaxTime;
}
public class TestMyTimer : SystemBase{
protected override void OnCreate(){
var e = EntityManager.CreateEntity();
EntityManager.SetName( e, "Timer" );
EntityManager.AddComponentData( e, new Timer{MaxTime = 5} );
}
protected override void OnUpdate(){
var deltaTime = Time.DeltaTime;
Entities.ForEach( ( ref Timer t ) => {
t.Time += deltaTime;
if(t.Time<t.MaxTime) return;
Debug.Log( "BOOOM!: "+ t.Time );
t.Time = 0;
} ).WithoutBurst().Run();
}
}```
works for me
Yeah I know it must be something specific I'm doing, i'll take another look tomorrow. Cheers for the help
hemm does the scale of parents not affect childrens once they're turned into entities ? 
https://i.imgur.com/NVTqsM4.png the green outline is a collider (with the debug component)
the flickering zone is where my plane actually is
https://i.imgur.com/tJxFr0A.png I use the transform of "plane scale parent" to set the scale I want (and have my pivot point in a corner)
hoo ok nvm my changes to the child's transform are not applied in the entity for some reason
so with nested go where the root go has a IConvertGameObjectToEntity, you can't edit childrens as they're already converted ?
Hmm I'm pretty sure you can edit the children
I think you might want to use a GameObjectConversionSystem, at least that's what I did @zinc plinth
well do what with the conversion system ? ^^'
Ah just saw the message, well you would use a GameObjectConversionSystem to loop through each associated component
public class SomeConversion : GameObjectConversionSystem {
Entities.ForEach((SomeComponent c0) => {
// Grab its associated entity
var entity = GetPrimaryEntity(c0);
// If you want some children data
var comp = c0.GetComponentInChildren<AnotherType>();
// Get the child's associated entity
var child = GetPrimaryEntity(comp);
// Do some logic to add some type to the entity
DstEntityManager.AddComponentData(child, new IComponentData { });
});
}
Hey, I have System A and B. A has two Jobs. One should run before B and one after B. Is this possible or do I need to split A into two systems?
You can make a system run before another, but I don't think you can make a system "wrap" another one. Even if you could, I'm pretty sure that would be discouraged.
I guessed so
Just cleaner if you could schedule the clean up job for later directly in that system.
So your system does some stuff, and you wanna clean up for that after?
You could delay it until the next frame, so it'd be:
System A - Cleanup job
System A - Main job
System B
Depending, of course, on the details of what you're doing, but you might be able to do something like that
Update on .enabled and possible mega & tiny chunks: https://forum.unity.com/threads/new-enabled-disabled-state-filtering.902531/#post-5929685
you always post the hard questions ๐
Try disabling burst ^:d
and the oscar goes to....
is there a way to increase the Hybrid Renderer GPU instance data buffer?
I get this error:
System.IndexOutOfRangeException: Index {0} is out of range of '{1}' Length.
Thrown from job: Unity.Physics.Systems.ExportPhysicsWorld.ExportDynamicBodiesJob
This Exception was thrown from a job compiled with Burst, which has limited exception support. Turn off burst (Jobs -> Burst -> Enable Compilation) to inspect full exceptions & stacktraces.
The thing is, it seems to occur only if my animation system is executed at the right moment (before the system that actually spawns a bunch of physics entities; these show up but I get this error exactly once in the frame it happens)
I don't know what causes this error, and the stacktrace also just points into the physics system.
My animation system is reading a few blobassets and interpolates some Translation components (on the gun objects that spawn the physical projectiles)
It happens exactly after all 8 recoil animations on the barrel groups have been calculated once.
Maybe it's these systems, but that's not the physics system that throws the error.
Anyone who knows a good up to date example of spawning in massive amounts of blocks using multithreading?
I'm looking into the jobs, but they require me to already have the entities in place, but they are not even instantiated yet, want to have a way of doing that pre positioning them if possible.
Currently I'm spawning in the entities using just the main thread, but would be nice to spread out the load.
Or am I thinking about this in the wrong way, for perl noise I should probably just do the loop and leave the positioning as a job instead of placing the entire loop in a job...
@cursive cosmos Theres a way to copy all entities from a world, I believe that is meant to be very quick. So you could do your generation stuff in another world (maybe many worlds) and load it in when done and is needed
Dont know of any examples of this tho
I suspect my issue was that I instantiated physics entities inside SimulationSystemGroup, and it only became apparent after I ordered some systems around.
@cursive cosmos how many entities are you spawning? I always get a Hybrid Renderer GPU instance data buffer error at around 300,000 entities, though I think the number of Components your entities has might affect that.
after doing some googling, I did discover changing the value of kMaxGPUPersistentInstanceDataSize is the workaround for that
What I have a problem with is just the fact that I can't instantiate the entities inside a job, so I'm curious how I should be spawning these voxels.
I'm still very new to ECS myself, all I can say for certain is that there seems to be many different ways to spawn Entities
@cursive cosmos You can create entities inside a job, look at Entity Command Buffer
sweet, thank you!
@unborn totem @cursive cosmos @ocean tundra
This spawns a grid of 1 000 000 boxes for me in less than 2 seconds:
int perRow = 1000;
float step = 1.1f;
NativeArray<Entity> entities = new NativeArray<Entity>(perRow * perRow, Allocator.Temp);
EntityManager.Instantiate(myPrefabEntity, entities );
entities.Dispose();
Entities.WithAll<SomethingUnique>().ForEach( (int entityInQueryIndex, ref Translation t ) => {
t.Value.x = ( entityInQueryIndex % perRow ) * step;
t.Value.z = (int)( entityInQueryIndex / perRow ) * step;
} ).ScheduleParallel();
make sure to run this only ones ๐
you don't run into any Hybrid Renderer GPU data buffer errors when spawning 1,000,000 boxes?
I had to increase const int kMaxGPUPersistentInstanceDataSize = 1024 * 1024 * 64; // 64 MB to const int kMaxGPUPersistentInstanceDataSize = 1024 * 1024 * 1024 + (1024 * 1024 * 512); // 1.5 GB in order to spawn 2,000,000 quads
64MB -> 1.5 GB
nope, all fine for me
I do have 5 extra components per entity, ontop of whatever the prefab conversion adds
I have a hunch each component on X number of entities is what fills that up, depending on how much data the component stores
also my 2,000,000 quads seem to require 20GB of my RAM
@unborn totem wtf, how???
I'm not sure. Probably something I am overlooking.
are you doing something weird/special to RenderMesh?
this is wired, gpu memory should have only one box - this is nothing
no, but they aren't "just quads" in the sense that I am altering the Texture tiling/offset values to show specific sprites on a 4k texture that acts as my sprite sheet
but I would expect that texture to only exist in memory once
you have to use instanced materials
I am, as far as I know
yea by the sounds of it when you touch material your duplicating it
my gpu memory is free when i have 1M boxes
and i have different material properties and texture shifts
RAM
left part is before instantiation, right - after
opening up my project is taking a bit, but I'll show you what my material looks like
+100mb or so and i bet that huge part of this is entity debugger
I don't know what Unity thinks it is importing that's taking so long...
ok, here it is
bothing tiling and offset have the hybrid instanced checkbox checked
i forgot to do that for alpha clip threshhold, but I wasn't using it anyway
so that's my material
nothing out of the ordinary, right?
material looks ok
i have a bit more complex material
how are you using those values, touching RenderMesh.Material or those cool attribute rendering components?
this is how I'm spawning my entities, if that's what you mean
i hope you have this checked on material :)
@dry dune I do not have that checkbox
it is on material
seems possible
though the normal Unlit HDRP shader does
anyhow, this is how I'm spawning my entities for now, inside a for-loop in a Start() method. Nothing fancy.
var instance = entityManager.Instantiate(prefab);
entityManager.AddComponent<MainTexTiling>(instance);
entityManager.AddComponent<MainTexOffset>(instance);
entityManager.AddComponent<NonUniformScale>(instance);
entityManager.SetComponentData(instance, new Translation {Value = position});
entityManager.SetComponentData(instance, new Rotation {Value = rotation});
entityManager.SetComponentData(instance, new NonUniformScale {Value = scale});
entityManager.SetComponentData(instance, new MainTexTiling {Value = tiling});
entityManager.SetComponentData(instance, new MainTexOffset {Value = offset});```
@unborn totem I asume prefab has the RenderMesh on it?
how are you converting your prefab?
but... that would make prefab a gameobject?
as far as I know, entityManager.Instantiate turns a GameObject into an Entity
oh right, sorry, I am doing this var prefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(Prefab, settings);
or more specifically
var prefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(Prefab, settings);
var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;```
though I think my RAM issue might be more of a....parsing a gigantic JSON file needed to get position/size data in order to spawn my entities
there's a way to cache entities into a binary file after you spawn/place them isn't there?
thanks
I need to get a list of matrices from a monobehaviour for use in a SystemBase component system. But trying to call this (in OnCreate for example) crashes Unity when it tries to access Transform. So where is the proper place to grab this data? How can I easily transfer some matrices from a monobehaviour to the componentsystem?
If you enable safety checks, it shouldn't crash and give you a proper error at least. As for getting your timings right (assuming your system is running before Awake) - it should work fine if you add the Transform to your job. e.g. Entities.ForEach( in Transform t, ...) - if you need a specific Transform you can tag the gameobject. At least that's the way I'd recommend.
They were on already. I checked the log and it was a SIGSEGV fault when accessing Transform.get_position. I am just trying to pass a list of positions for a path to a system and having absolutely no luck. I just tried converting the monobehaviour to a component that has a list of positions but that doesn't work either so I'm not exactly sure how I'm supposed to do it at this point. Also tried just allocating a nativearray in OnCreate and filling it with the necessary data but then I can't even use it in the Entities.ForEach so...
And apparently a component can't contain a nativearray either and I can't use a managed array so how the hell do you store a list of positions in a component?
DynamicBuffers or something maybe?
Seems like a lot of convolution for something that should really just be like var list = path.Nodes in the OnCreate...
Is there a way to pass variables into a system and into a job? Tried using a constructor and setting the values, but jobs doesn't seem to like that a variable has no set value pre start.
So it sounds like you're having a pretty frustrating time like most of us did when getting started with dots. You are correct that DynamicBuffers are the right way to do an array associated with an entity (rather than NativeArray). I can hopefully reassure you that allocating a nativearray in OnCreate should work perfectly fine and any of the approaches you describe should work when you iron out some bugs. Did you also have the JobsDebugger enabled?
Ok, in that case you shouldn't get a crash to desktop so that sounds bad - latest packages I assume and 2019.3 or 2020? There are a few options - either you could go down the DynamicBuffer root (either entity or singleton), a persistent NativeArray somewhere (e.g. in a System which you reference), a BlobAssetReference (if your points don't move and are referenced by many entities but note if you're new to dots, these are a little fiddly) or possibly some other solution I'm not coming up with right now.
@cursive cosmos what kind of variables? You can do e.g. OnUpdate() { float varToPass = 5; Entities.ForEach(...) { Debug.Log(varToPass); } Worth checking out some of the examples in the pinned post if you haven't already.
@amber flicker I tried passing a x/y value into a job so it could create a grid of boxes, but it keeps complaining that "it's not assigned or the field is outside the local", does this mean I have to do something in the foreach to access private variables in the class?
you may just need to make local references to those variables before your lambda
so...I reasign them in the update? O.o
you create copies of the data in a local scope so the data is safe to work on in parallel and can be detected correctly by the code gen
This code: https://hatebin.com/spfsbgzacz
Results in this crash:
0x00007FF77F133D99 (Unity) Transform::GetPosition
0x00007FF77E5C65D5 (Unity) Transform_CUSTOM_get_position_Injected
0x000001E4C13795A9 (Mono JIT Code) (wrapper managed-to-native) UnityEngine.Transform:get_position_Injected (UnityEngine.Transform,UnityEngine.Vector3&)
0x000001E4C13793AB (Mono JIT Code) UnityEngine.Transform:get_position ()
0x000001E4C1378EDB (Mono JIT Code) [F:\Unity\td\Assets\Scripts\Game\NavPath.cs:42] NavPath:GetFloat3 ()
0x000001E4C1378A4B (Mono JIT Code) [F:\Unity\td\Assets\Scripts\Systems\PathfindingSystem.cs:18] PathfindingSystem:OnCreate () ```
@cursive cosmos yep. you reassign them in update
Ah ok so if you're iterating over any managed code (i.e. in your foreach) it will have to be main threaded - it should be using Run() rather than ScheduleParallel()
I don't know if that's the source of your crash
it is generally fine to access managed code in OnCreate
It isn't managed in the OnUpdate, it should be a NativeArray by then
But it crashes in OnCreate
trying to populate the nativearray
ah my bad.. I see
it's also 4am here and I can't sleep so I can't promise I'm not missing other obvious issues / stuff I should be communicating ๐ฌ
have you debug logged the navpath object in on create?
my guess is still that when the system is created, NavPath doesn't exist yet - though it shouldn't be crashing.. but that editor is a little old
Also, another question, is it stupid to put a big job like "print all these world blocks in a grid" in one job (Like, does it understand that the content should be async) or should you make the instantiating of the block a job and run the loop outside the system, starting a new instance of the system each itteration? (this sounds nasty)
I just stepped through with the debugger, it gets a reference to NavPath. I guess it could be getting a reference before the GameObject actually exists somehow, but how would I even check that? transform.childCount is returning > 0 so something is obviously there
public NativeArray<float3> GetFloat3()
{
var f = new float3[transform.childCount];
for (int i = 0; i < transform.childCount; i++)
{
var t = transform.GetChild(i);
f[i] = t.position.ToFloat(); //crashes here
}
return new NativeArray<float3>(f, Allocator.Persistent);
}
(ToFloat is just a helper function, new float3(x,y,z))
going to step through again, maybe t is null
i think mixing old unity and new in oncreate is probably a bit risky
try having a monobehavjour that gets the system instead, world.getexistingsystem
I don't fully understand sorry @cursive cosmos - running at reduced mental capacity but two thoughts 1) systems run over all data present - running a loop outside the system doesn't sound right and 2) Wherever possible you want to use the 'bulk' methods which is my terminology for e.g. Instantiate that takes a NativeArray or AddComponent that works by query - these are all much faster.
Similar to what Roycon says @golden elk - this could be a timing bug that may have been fixed in a later version of Unity. The more dots way of having this work is probably the approach you briefly tried where you write a custom MonoBehaviour that gets converted. e.g. adding a dynamicbuffer to the associated entity. Then your system will definitely run after the data exists.
Yeah I was trying to see if there was a super simple way to do it before trying dynamic buffers. Switching it around so the Monobehaviour gets the system in Awake and just sets the path that way doesn't result in a crash at least.
Transform was never null when debugging so I can only assume there was some internal reference somewhere that wasn't setup yet
yea, sounds like something like that
I'd hope that still doesn't exist with a recent version of the editor but it's possible
I'll have to try upgrading to 2020 at some point I suppose
Yea - the problem with the experimental stuff is you have to stay quite current. That said, a recent version likely still wouldn't work re the timing of OnCreate - just hopefully not crash.
right
If/when it comes time to work with DynamicBuffers, they sound more special then they are - they're actually really easy to use. The main thing to know about them is you can specify the default number of entries you expect to have - these are allocating with each entity that has that buffer and tightly packed in a chunk. If the buffer then exceeds that number, it will be moved to managed memory automatically.
yea super duper easy to use
i dont even specify a default size untill i get to optimization
np - good luck
It doesn't seem right using a system to do a job once, am I right in that?
added arc corners to the path and bumped up unit count to 1500. running at 10x speed ๐
https://i.imgur.com/ICLaahb.mp4
amazing
that's it for me tonight. thanks again for your help roycon and timboc.
anytime ๐
QQ all
can someone help me with ECS in unity?
And I would be glad if someone teachme
What syntax is relevant right now?
Entities. inject is very old and deprecated
inject still works? I thought it was completely removed already
idk
You can also check this as a reference: https://github.com/Unity-Technologies/EntityComponentSystemSamples
I thought it was removed too
you could also try https://www.youtube.com/watch?v=a9AUXNFBWt4
In this workshop style video we walk through an example project created by Unity Evangelist Mike Geig on how to script a Pong style game using Unity's Data Oriented Tech Stack (DOTS) including the Entity Component System (ECS). This video covers the latest syntax in Unity 2019...
It's just a 2 year old guide
should work
no, thats the most recent way of doing stuff
its void
if you can't do it, you have wrong entities version
^
@halcyon plume you can check out this playlist.
which is using the new SystemBase.
https://www.youtube.com/playlist?list=PL-05SQhI5rIY2MVt5s_EfvddNXS2GNAtA
update your entities package then
then you haven't latest entities
just SystemBase not ComponentSystemBase
also instead of saying you have latest, just tell the version you have
i just downloaded it
and what is the version of it ?
in 9 times out of 10, people who say they have latest version tend to have some ancient version for some reason
package manager can derp sometimes
package manager derps hard most of the time
or he could just use too old unity version that doesn't support the latest entities...
could be many things
yeah, people reference to stuff in a manual, but manual they link is 0.2 version while latest is 0.11 ๐
0.1.1
yeah that's really old.
new ecs versions are not supported by older editor version
which unity this is?
wait what unity version are you using?
2019.2.14f1
that's why
yeah, that's not good
go 2019.3 at least
i need to update it?
yes
how to do this?
if you want to use ECS, yes
go 2020.1 beta for even more futures
yes realy want
2020.1 is best for now if you do ECS
better hybrid rendering and more debugging support
how to update my unity?
use unity hub
oh i found
if he don't know how to update unity probably ecs going to be way to hard...
๐
yes but i like hard ways)
cuz its intresting)
so
2020 a or 2020b?
what do u recomend?
i would go for beta
well he DID mention he likes hard ways 
i had only one crash with alfa during last 10 days
well he DID mention he likes hard ways
@opaque ledge i said hard ways) non suicide)
going harder faster
better stronger
I have an old unsolved problem:
i have an entity with 2 components
one component - holds a ComponentType struct of the second component
second component - contains some data
at compile time i don't know the type of second component
at run time i can take it form first component
what i need is to write a system that can move that second component to different entity
any ideas?
@dry dune That sounds evil as
i think you can write system wich handle this two comonents and delete component in this entity and create 4 other
burst is AOT tho right ? not JIT, so all types needs to be known at compile type
in editor burst is JIT so it wont give you error, but in build you will get errors
how can you hold Type struct anyway in IComponentData ?
it is known for compiler, not for my system
isnt Type reference type tho ? how can you put it into IComponentData ?
ComponentType implements IComponentData
facepalm so its a custom struct, not actually a Type
not custom this is a struct form ecs package
alright
With DotsPhysics, is there any reason making change to PhysicsVelocity inside a collision event has no effect ?
I'm using ComponentDataFromEntity<PhysicsVelocity> to load & save the collided's speed, to make a bumper effect.
Using traces show that the speed value is correctly saved, but for some reason it does nothing on screen and the value is back to "normal" next frame.
Like, does the fact it's in a callback somehow make any changes in there get overwritten by the physics simulation before it can be applied or so some weird architecture like that ?
you might need to update your system in specific place, probably After StepPhysicsSystem and Before EndFramePhysicsSystem
not sure tho, maybe someone can help you better, or in forums
Using [UpdateAfter(typeof(StepPhysicsWorld))] raise a ton of errors, and using [UpdateBefore(typeof(EndFramePhysicsSystem))] change nothing.
Guess I will try the forums then.
where is entity pakage?
In "Advanced", did you check "Show Preview Packages" ?
if you're using the alpha they moved it to Project settings or Preferences I believe
Edit -> Project Settings
Find Package Manager in the window hierarchy
Check the Enable Preview Packages box
Click I understand
From some article about Unity 2020.2
restart your editor
Library\PackageCache\com.unity.2d.animation@4.2.4\Runtime\TransformAccessJob.cs(196,62): error CS1061: 'NativeHashMap<int, TransformAccessJob.TransformData>' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'NativeHashMap<int, TransformAccessJob.TransformData>' could be found (are you missing a using directive or an assembly reference?)
dont work
idk, maybe remove your Library folder and let Unity recreate it
is there a way to do Debug.log on burst mode ???
I don't think so? but as long as you're not debugging a burst-specific problem you could temporarily disable burst and log
latest version of Burst supports Debug.Log
check the Burst manual for more info
1.3.0
this package is broken
no its not, it works fine for me
what version?
Entities 0.11, Unity 2020.1.0b10
yes
wow its work
Collections as well
and now i have problems with components)
how to add IComponentData to prefab
cuz this is deprecated
I strongly suggest you should look at some tutorials
https://www.youtube.com/watch?v=lFl2SMfhvoA&list=PL-05SQhI5rIY2MVt5s_EfvddNXS2GNAtA&index=2&t=0s like this?
In this episode, we demo a very simple means of connecting keyboard input to generate player movement. Create Components and Systems to translate and rotate a spaceship in a top-down environment!
TimeStamps:
0:27 Starter Project
0:57 Packages
1:57 Creating the Spaceship SubS...
check out CodeMonkey's youtube channel, he has great tutorial videos there
idk i suppose so, i didnt check those
check out CodeMonkey's youtube channel, he has great tutorial videos there
@opaque ledge i like it) ty
i remember that he create objects through code
i find
just this attribute
You don't need Burst\Collections\Jobs installed manually as they will be installed automatically with entities package by their dependencies. You only need manually install Entities and HybridRenderer. Otherwise you will definitely stuck with updating progress, wrong dependencies etc. (especially in your case, when you have all problems above, it will happen 100%)
You don't need Burst\Collections\Jobs installed manually as they will be installed automatically with entities package by their dependencies. You only need manually install Entities and HybridRenderer. Otherwise you will definitely stuck with updating progress, wrong dependencies etc. (especially in your case, when you have all problems above, it will happen 100%)
@storm ravine Yes, thanks, I did it and it worked
And start from documentation in the first place as it describes all basic things required for understanding, better source is - read samples repo, read source code, read package tests code because they have exact implementations of things used by unity itself (especially tests and package source code), as what you trying to do is a bit mess and will more confuse you than help, of trying copy-paste things from everywhere without understanding basics of how it works at the initial level what is what etc.
Speaking of, I need to find the most up to date documentation, I keep seeing things in tutorials that are like deprecated or something, just plain out don't exist anymore. Makes it really hard for newbies in DOTS to learn about this x)
Having a hard time to just figure out how to do a job once and never again, seems overkill to use the SystemBase for just one job on update.
@cursive cosmos iirc, you can use Job.WithCode
What do you mean? All I do is with code. ๐
Check Entities Manual
and no, thats why SystemBase exists, to run a single job, or multiple jobs if they are dependend on each other
Does anyone know if you can tell a ComponentSystem to update after that the Animator has updated a transform? (with [UpdateAfter])
found the answer: [UpdateInGroup(typeof(PresentationSystemGroup))]
@opaque ledge So how do I limit the job so it only runs once in System base? I don't really want to use a bool for this if I can avoid it.
yeah, you either have to use a bool or tag component, tag component means a component that doesnt have any data in it
How to control a character through ECS,
There's lots of tutorials out there joker
@halcyon plume
https://www.youtube.com/watch?v=lFl2SMfhvoA&list=PL-05SQhI5rIY2MVt5s_EfvddNXS2GNAtA
This is probably the best one I can find.
In this episode, we demo a very simple means of connecting keyboard input to generate player movement. Create Components and Systems to translate and rotate a spaceship in a top-down environment!
TimeStamps:
0:27 Starter Project
0:57 Packages
1:57 Creating the Spaceship SubS...
ty
been thinking. has there been news that the VS tools for unity extension be updated for dots?
no i dont think so, there was this update that made VS emit error if you dont obey the ForEach restrictions/rules, but other than that nothing
Can someone tell me how to 3D objects to disable gravity in DOTS physics
upd: just found it
have some one cameraFolowSystem?
I donโt know how to do it, in a simple script I would do it easily, but in ecs I donโt know how to do it. I turned the camera into an entity. And then what? I issued a tag to the camera and the object I want to follow. What to do now?
Then make a ForEach for your camera to follow your target entity
something like
ForEach.WithAll<CameraTag>(ref Translation translation, ref Rotation rotation, in CameraData data)
{
translation.Value = SomeFunctionThatTakesEntityArgumentAndReturnsAPosition(GetComponent<Translation>(data.TargetEntity).Value);
rotation.Value = ARandomLookAtFunction(GetComponent<Rotation>(data.TargetEntity).Value)
}
your ForEach applies to EVERY entity that has Translation component
you have to add "CopyTransfromToGameobject" component in your camera object, so Unity will sync translations
is your Camera's convert mode set to "Convert and Inject" ?
alright, add that component, it should work
deprecated
not that
So, make an authoring component (Create->Ecs-AuthoringComponent) put that script to your camera's gameobject
in that authoring component's Convert method you add "CopyTransfromToGameobject" to entity, so something like dstManager.AddComponent<CopyTransfromToGameobject>(entity);
So I am trying to spawn a couple of voxels in a grid using IJobChunk right now, and I am curious about two things, how to get access to the ECB so I can get the entityManager and spawn the cubes and how I can make sure this only runs once.
Kinda want to give it a try to make a voxel world spawner but I seem to have a problem grasping what limitations these jobs have.
use ovverides
like this
And you can leave the OnUpdate() empty
and second answer
Learn how to Draw a Simple Sprite with Pure ECS in Unity 2019.
โ
Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=6eV9NR3Vb9U
Getting Started with ECS in Unity 2019
https://www.youtube.com/watch?v=ILfUuBLfzGI
If you have any questions post them ...
@opaque ledge so. what about my problem?
i literally answered ๐
@halcyon plume That is only using ECS, I'm using the job system and those does not explain how I can access the entityManager inside a job.
you cant
you cant
you can use ECB for creating/destroying entities, or remove/add components
@cursive cosmos https://docs.unity3d.com/Packages/com.unity.entities@0.11/manual/entity_command_buffer.html have you read this?
Not even the ECB?
yeah, I tried using the ECB, but I can't seem to get it into a job chunk in a proper way
well, i never used IJobChunk, but stuff should be the same
what seemed to be wrong ?
can you maybe share your code. so that we can see, why it is not working?
have never used IJobChunk before tbh. If you want your job iterating through certain set of entities. Why not put them in Native container and pass it to your job?
behause as far as I read it, you can only put chunk as input. maybe someone knows it better
I was just adviced to use this since I am trying to spawn a voxel world and that chunks would help with the speed.
Well, I'm creating the entities in the job, so the only thing I want passed in is just the type of entity.
http://prntscr.com/st5kth
Was trying to do something like this
ah ok, so basically you want to add certain components to the entities depending on the position for example right? Well I think my approach would be having those entities already stored as prefabs.
I have the entities stored as a prefab already, using the convert method.
just wondering how they should be inserted into the instantiate ๐
you should instantiate the prefab instead of the entity.
No...then it wont be an entity anymore.
EntityManager.Instantiate(yourEntityPrefab)
oh, but that entity is the entity prefab
I'm using the convert gameobject to entity method, so the prefab itself is not an entity but it gets converted to it at runtime

The problem the instantiate method has is that the Entity is not set, since this is a struct.
why are you doing ecb.EntityManager ? is that even available ๐
Please, I begging you, read https://docs.unity3d.com/Packages/com.unity.entities@0.11/manual/entity_command_buffer.html
you should be able to do ecb.Instantiate, no ?
oh wow thats system reference ๐
yeah, like Eizen said, follow that manual
also, imo ? ForEach already creates IJobChunk behind the scenes, just go for ForEach
But that manual only shows me using a foreach directly in the update ๐
And it doesen't matter ForEach or any Job (except Concurrent version for parallel)
yeah thats fair, do you know/remember how to schedule Jobs 'old way' ?
So my way forward should be doing a onetime job in the foreach and just stop it with a bool basically?
It's become not DOTS problem but general C# understanding here. Ok lets go through this. First - why you need IJobChunk here? How you understand it works? Which EQ used for IJC?
also, imo ? ForEach already creates IJobChunk behind the scenes, just go for ForEach
@opaque ledge In generates IJobChunk under hood but it call lambda per entity and not per chunk (method calling itself), Unity looking for per chunk iteration implementation for lambdas.
yeah thats way to go for Sugarspoon
I got adviced on this channel to use jobchunks for big one time spawns, that's it. I was actually using the foreach directly in the update previously, but it felt redundant to have it in an update method when I literally only run it once.
Who advised you that and how IJobChunk relates on spawns? Show him, we'll boooo him.
You have your grid - rows x columns
you want spawn something
I suppose - tiles on grid
Yes?
Cubes, yeah
you can always spawn from a Monobehaviour, with bursted job, you dont necessarily need to use a system for it i think
i mean you are not 'processing' any entities, you are just spawning/initalizing them, so imo MB would be better ๐คท
Thus you can flat you 2D grid to 1D
And you always can easily find XY from 1D index
There was Sark's Voxel World implementation, let me try to find you a link
currently it's more like a sheet with only two loops, ye
Thus you should just create IJobFor\IJobParallelFor
With length == rows * cols
In that job you'll use Concurrent entity command buffer
Oh...I'll take a look at that.
It's to early for him
one step at a time
okay what are you trying to do joker?
get target translation
Potential memory aliasing, and safety system prevents you from that
get target translation
for what?
he is trying to get camera to follow target entity

Noooooope 
