#archived-dots

1 messages ยท Page 147 of 1

pulsar jay
#

I see

#

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);

amber flicker
#

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.

pulsar jay
scenic oracle
#

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.

amber flicker
#

@pulsar jay what did you parse to .FromWorld in the end?

pulsar jay
#

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

amber flicker
#

Groovy ๐Ÿ‘

deft stump
#

@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)

pulsar jay
#

@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

scenic oracle
#

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.

pulsar jay
#

I see thats a problem. Are you using conversion Workflow or creating the entities from code?

scenic oracle
#

I'm using mostly the conversion Workflow.

amber flicker
#

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.

scenic oracle
#

I was just worried that there was some "official" way of doing this that I had missed.

amber flicker
#

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.

deft stump
#

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

pulsar jay
#

@amber flicker I would consider public GameObject fields the "official" (if not always best) way to do this with monobehaviours

scenic oracle
#

^

amber flicker
#

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?

pulsar jay
#

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?

amber flicker
#

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

pulsar jay
#

Thats nice. Sounds like it would just work!

storm ravine
#

It's for GenerateAuthoringComponent attribute

#

But anyway with custom IConvertGameObjectToEntity there is also no problems with this at all

scenic oracle
#

Oh yeah, GenerateAuthoringComponent does simply replace the Entity by a gameobject field.
Well damn, that make things way simpler.

pulsar jay
#

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

amber flicker
#

Yea you may need to update the world on Editor Update - ideally only when you need to

pulsar jay
#
        if(!Application.isPlaying && this.rotationSystem != null) UnityEditor.EditorApplication.update += () => this.rotationSystem.Update();
        #endif```` I tried that but it does not seem to change anything
storm ravine
#

@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.

amber flicker
#

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)

pulsar jay
#

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

amber flicker
#

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.

pulsar jay
#

Does EditorApplication.QueuePlayerLoopUpdate trigger EditorApplication.update? Or should it be the other way round?

graceful mason
#

my workflow... load mapdata from disk into buffer(1) --> populate Buffers(2,3,4) for verts, Tris, Uvs --> Populate Mesh Componenet

pulsar jay
#

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

graceful mason
#

Do I need to clean up the buiffers to save memory? There all just componenets DynamicBuffers on entitys

amber flicker
#

@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

pulsar jay
#

Ok sounds fine to me. Just wanted to make sure before I freeze my editor with an infinite loop ๐Ÿ˜…

amber flicker
#

Well done if you do all this without doing that at least once ๐Ÿ˜ฌ

graceful mason
#

I should learn to import someone elses github who has made one ๐Ÿ˜„

pulsar jay
#

@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

amber flicker
#

just fyi this does work for me so it might be something else missing

coarse turtle
graceful mason
#

yeah I cant seem to get git to work, it works if i just type git into cmd

#

butunity wont have it

coarse turtle
#

ah - are you trying to import it as a package via package manager

graceful mason
#

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

pulsar jay
#

@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 ๐Ÿค”

graceful mason
#

ah bad pic ๐Ÿ˜„

pulsar jay
#

@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 ๐Ÿค”

coarse turtle
#

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)

pulsar jay
#

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

graceful mason
#

think i will do a dreaded reboot

coarse turtle
#

you can also try cloning it as a submodule into your project

graceful mason
#

reboot of glory you have suceeded

amber flicker
#

@pulsar jay that sounds a little odd - does the editor world exist? Does [AlwaysExecute] on rot system make any difference?

pulsar jay
#

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

storm ravine
#

@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.

pulsar jay
#

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

coarse turtle
#

sounds like a likely culprit

pulsar jay
#

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

storm ravine
#

@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)

mystic mountain
#

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?

storm ravine
#

Disable Burst compilation in Project Settings

mystic mountain
#

Thanks, forgot to write I found it X)

graceful mason
halcyon blaze
#

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:

https://hatebin.com/dbvttkjoqu

pliant pike
#

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

halcyon blaze
#

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

pliant pike
#

yeah that looks interesting, thanks for that

halcyon blaze
#

doesn't work for me though ๐Ÿ˜ฆ

#

well, per thread it does. The gif even looks like it shows it working as I want it

storm ravine
#

Show full SystemBase setup with ForEach

#

As approach of preallocated array of random struct instances definitely work as expected.

halcyon blaze
storm ravine
halcyon blaze
#

Yeah I've seen your posts ๐Ÿ™‚

storm ravine
#

Why you still using JobComponentSystem?

halcyon blaze
#

No real reason! I'd seen very little docs about SystemBase so was avoiding using it yet

storm ravine
#

Well not avoid this as it's recommended approach now. (Job)ComponentSystem will be removed. About your code, try to Debug.Log(nativeThreadIndex)

halcyon blaze
#

hard to keep on top of all the changes, will swap it now if it's just a straight swap

pliant pike
#

oh I know I've been miles behind several times leahYTHO

halcyon blaze
#

so after swapping to SystemBase it's all running on the same thread... Confusion continues

storm ravine
#

ScheduleParallel for parallel scheduling with SystemBase ForEach

#

About your code, try to Debug.Log(nativeThreadIndex)
@halcyon blaze ^

pliant pike
#

yeah you have to do schedule and scheduleparallel for outside the main thread

storm ravine
#

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

halcyon blaze
#

Oh you legend, what a noob error

storm ravine
#

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

halcyon blaze
#

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

storm ravine
#

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

halcyon blaze
#

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?

storm ravine
#

Show your current system code

halcyon blaze
storm ravine
#

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

halcyon blaze
#

Ah nice that's worked perfectly

#

Thanks again! I'll try not to come bothering you again too soon ๐Ÿ˜‰

storm ravine
#

When someone bothering me when I don't want that, I just completely ignore messages. Simple and effective strategy.

ocean tundra
#

Will a NativeHashMap resize automatically if full when using Add (No concurrent version or writer)?

storm ravine
#

Yes. By doubling capacity strategy.

ocean tundra
#

@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

dry dune
#

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

dry dune
#

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();
  }
}```
ocean tundra
#

@dry dune have you checked the code gen for that?

#

it might help to have that aggressive inline thing on it

#

note this is all guess work and i am 100% going to make similar

#

thanks for the idea ๐Ÿ™‚

dry dune
#

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();
native trail
#

Hey , a quistion : can unity export all gameobjects to entities at exporting and then It suddenly become 2 times faster than before?

ocean tundra
#

yup

#

its called SubScenes

native trail
#

Without bugs?

ocean tundra
#

but the docs suck atm

#

haha

native trail
#

Oh i see

#

Thanks, i guess we gotta wait if we dicided to use dots for a project

ocean tundra
#

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

quaint niche
#

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)

ocean tundra
#

@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

quaint niche
#

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 ๐Ÿ™‚

ocean tundra
#

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

quaint niche
#

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
#

@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 ๐Ÿ™‚

storm ravine
#

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

mint iron
#

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.

storm ravine
#

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.

vivid copper
safe lintel
#

@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; 
}
vivid copper
#

the exception is gone but it doesnt trigger any collision but this seams to be another problem. thank you

safe lintel
#

might need to update that system after the buildphysicsworldsystem

coarse turtle
#

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 ๐Ÿค”

vivid copper
#

@safe lintel I was wrong it didn't change anything I disabled the system and have forgotten to reenable it. the exception still occures

ocean tundra
#

@coarse turtle Where is that? I think it would be usefull with native collections

ocean tundra
#

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

odd cipher
#

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.

ocean tundra
#

@odd cipher I've used them bit dont really understand the math underneath them

odd cipher
#

Same. that's the main problem

ocean tundra
#

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

odd cipher
#

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).

ocean tundra
#

Procedural generation ๐Ÿ™‚ my favourite

#

i actually think you want all those maps

odd cipher
#

Possibly.. it gets quite complicated

ocean tundra
#

yup

odd cipher
#

Though if I don't care where a cold or hot biome gets placed I think just a Voronoi could work.

ocean tundra
#

yea you can always add hot and cold based on a heat map later

odd cipher
#

Yeah. Kinda taking Minecraft for inspiration here. They don't have a heat map as far as I'm aware.

ocean tundra
#

been awhile since i played but i think they do have some rules

#

so no snow gets next to a desert

odd cipher
#

Yeah I mean that can be done without a heat map

#

I just need to find out how to generate a Voronoi map.

mint iron
#

Fortune's algorithm is a sweep line algorithm for generating a Voronoi diagram from a set of points in a plane using O(n log n) time and O(n) space. It was originally published by Steven Fortune in 1986 in his paper "A sweepline algorithm for Voronoi diagrams."

ocean tundra
#

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

mint iron
#

its an ordering issue most likely, make sure your system that spawns stuff is updating before the transform group, or after the rendering

ocean tundra
#

is [UpdateBefore(typeof(TransformSystemGroup))] enough to be before?

mint iron
#

that should do it yeah

ocean tundra
#

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

mint iron
#

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.

ocean tundra
#

yup i tried that

#

does the hybrid renderer actually respect Disabled entities?

mint iron
#

are you updating the localToWorld directly or using Translation/Rotation

ocean tundra
#

Translation

#

should i caculate LocalToWorld too?

mint iron
#

mmm nope, thats the way i was doing it too

ocean tundra
#

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

zinc plinth
#

hemm, is there a way to use EntityArchetype with the entity created with IConvertGameObjectToEntity ?

#

ho, I found EntityManager.SetArchetype, nvm

safe lintel
#

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

ocean tundra
#

I think you should test in a build

safe lintel
#

yeah thats next

ocean tundra
#

how many entities do you have?

safe lintel
#

this is a very low count

ocean tundra
#

yea that will be it then, they have said that there is threading overhead even with the job system

safe lintel
#

ah editor crash just a moment, but anyway was testing menu options. I think in very small test level its less than 500 entities

ocean tundra
#

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

safe lintel
#

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

ocean tundra
#

schedule or schedule parallel ?

safe lintel
#

its a mixture

ocean tundra
#

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

storm ravine
#

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

safe lintel
#

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

storm ravine
#

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?

safe lintel
#

measured setting the JobsUtility.JobWorkerCount, all safety checks off

storm ravine
#

Is 2ms for all systems?

safe lintel
#

yeah pretty much mainly my simulationsystemgroup

storm ravine
#

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.

ocean tundra
#

@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 ๐Ÿ™‚

storm ravine
#

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.

safe lintel
#

do you mean IJobForEachEntity or IJobParallelFor when talking about batch?

storm ravine
#

@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.

ocean tundra
#

Oh dam

#

I should figure out some performance tests then ๐Ÿ™‚

storm ravine
#

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

safe lintel
#

ah just thought you were referring to directly controlled batch sizes

storm ravine
#

I referring to general potential performance issues with parallelization

coarse turtle
#

Hmm seems like doing the SetSharedComponentFilterOnQuery call generates a compilation error despite the foreach lambda invoking Schedule ๐Ÿค”

storm ravine
#

Nope

#

Are you sure you not missed dot?

coarse turtle
#

yea I'm pretty sure

storm ravine
#

Well for me it not generates any errors

coarse turtle
#

Hmm, let me see if I can generate it again in a new project

storm ravine
#

Ah my bad, I was in rider, sry, yeah in Unity I see error

coarse turtle
#

Ah cool, I'll post it on the forums to see if someone at Unity can take a peek at the issue

storm ravine
#

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?

coarse turtle
#

oh

#

most likely because I never saw it in the intellisense

radiant sentinel
#

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?

naive parrot
#

@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..

radiant sentinel
#

who can help me to freeze xz vectors on PhysicsVelocity

fleet hemlock
#

@mint iron wrong person

mint iron
#

alright

leaden hatch
#

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;
}
coarse turtle
#

You can try managed IComponentData

public class IconComponent : IComponentData, IEquatable<IconComponent> { 
  public Texture2D Value;

  public bool Equals(IconComponent other) { ... }
  public override int GetHashCode() { ... }
}
leaden hatch
#

@coarse turtle ty, I'll look into that

wary anchor
#

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

mint iron
#

do you need to change them in the process or are you just essentially concatinating the chunk arrays into a single one

wary anchor
#

for this one I'm just grabbing those within range and creating a new smaller array for that frame

mint iron
#

did you flatten out the DynamicBuffer into seperate entities or its still on the lights

wary anchor
#

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

mint iron
#

yeah, because unless you're doing somethign else with it in ECS, its just being put there and then removed, could be outside entirely.

wary anchor
#

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

mint iron
#

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

wary anchor
#

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 ๐Ÿ˜ฆ

mint iron
#

just made my discord text like 300% somehow lol - ahh CTRL +/-

wary anchor
#

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

mint iron
#

yeah i mean, you can loop through each light, and test it, store it off to a list.

wary anchor
#

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?

mint iron
#

i presume u need a second set of data to test if in range

#

so you need to get that from somewhere first

wary anchor
#

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

mint iron
#

ahh, i thought it was many to many, if its just lights in range of player that would be easier i think

wary anchor
#

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!)

mint iron
#

yeah id just getsingleton pass it in as local to ForEach on lights and call it a day ๐Ÿ˜›

wary anchor
#

yeah okay but it's the bit where I write the data in parallel from the Entities.ForEach(lights)

mint iron
#

how many lights?

wary anchor
#

low hundreds

mint iron
#

imo just use a list if you can preallocate the length that would be ideal

wary anchor
#

and do it from the player's perspective rather than parallel yeh?

mint iron
#

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.

wary anchor
#

yeah I read that ๐Ÿ˜ฆ Okay well it will be simpler to implement that way anyway

#

Thanks yet again, @mint iron !

mint iron
#

with hundreds i dont think its going to be worth the costs for fancyness, if you were talking 5k+ id say maybe.

wary anchor
#

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

mint iron
#

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.

wary anchor
#

yeah so keep it persistent, give it a reasonable Capacity and just let it deal with itself?

mint iron
#

yeah exactly, only thing to watch is if you expanded to like a 100k, then went back to 100, youd be wasting memory

wary anchor
#

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 ^^

unborn totem
#

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

prisma anchor
#

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?

ocean tundra
#

@prisma anchor lets see what you have, all i do is ECB.Instiante (spelling :P)

prisma anchor
#

but I need to pass in the Jobindex right?

ocean tundra
#

or ECB.CreateEntity

#

only if you are using concurrent and scheduleparaell

prisma anchor
#
            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(
ocean tundra
#

well you are using concurrent

#

is it Run, schedule or schedule paraell?

prisma anchor
#

Ok, i see thanks, it doesn't need to be parallel

ocean tundra
#

if its not schedule paraell you dont need concurrent

prisma anchor
#

noted

#

Also, you have to create an entity from an archetype now? before you could pass in anoter entity

ocean tundra
#

Use initinstate

#

(sorry spelling again, its early)

prisma anchor
#

Dur. I haven't done this stuff in months

#

Thanks again.

stone osprey
#

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

ocean tundra
#

@stone osprey no limit

#

but there is a bit of a system overhead atm

stone osprey
#

Thats great to hear, thanks ! ^^

ocean tundra
#

Is it true tag components have no chuck swap cost when added and removed?
Or is that a target goal of the Entities team?

opaque ledge
#

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

untold night
#

actually they added that a while back

#

well, it still changes the archetype, but the chunks don't swap

amber flicker
#

the coming .enabled should help a lot with this

ocean tundra
#

Thanks guys

#

Yea I'm looking forward to that too

deft stump
#

what would this new .enabled do?

amber flicker
#

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
#

taking a look...
on that note, I should hang around the forums more

amber flicker
#

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 ๐Ÿ˜…

deft stump
#

oooh. so it's like enabling/disabling components in classic unity.

#

righto this does sound like a decent solution rather than adding/removing tags

mint iron
#

thats a pretty big, and welcome change.

opaque ledge
#

hoo, thats seems pretty big indeed

dry dune
#

@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
leaden hatch
#

@dry dune tyvm very interesting

unborn totem
#

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

dry dune
#

yes Unlit is not supported yet

unborn totem
#

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

dry dune
#

nope this is dots way to tweak instanced material properties with component

unborn totem
#

but there is no built-in material property override for any shader's texture tiling/offset values

dry dune
unborn totem
#

so you're telling me the HDRP unlit shader is not set up to be instanced?

dry dune
#

Per-instance material params tweaking by dots component are not supported for unlit shaders

unborn totem
#

ok, so the lit shader should work if I write one for it then?

dry dune
#

lit node in shader graph should work

unborn totem
#

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

deft stump
#

god. it's so hard to get away from OOP mindset into DOD mindset

opaque ledge
#

yep

#

but remember that you dont have to do every single thing ECS way

deft stump
#

is it alright if I ask for a code review on my movement system?
I'll put it all in one hate bin.

opaque ledge
#

sure, we have many helpful people

deft stump
#

alright... just a minute or two.

deft stump
#

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.

opaque ledge
#

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

deft stump
#

@opaque ledge thanks.
I actually thought of that too.
but man, I thought it was the wrong approach too! it also felt hacky! XD

opaque ledge
#

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

deft stump
#

dont forget to add proper UpdateAfter/Before attributes btw
do i have to because 1 system is writing and another system is reading?

opaque ledge
#

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

deft stump
#

alright. any small optimization is good optimization ๐Ÿ‘Œ

opaque ledge
#

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 ๐Ÿ˜›

amber flicker
coarse turtle
#

I've no idea what that means

amber flicker
#

Ok thanks - wasn't sure if I was being particularly dense ๐Ÿ™‚

prisma anchor
#

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?

deft stump
#

try disabling burst compilation @prisma anchor
in jobs > burst and unchecking the enable compilation

prisma anchor
#

After some more googling, it seems that the issue is due to me scheduling the jobs incorrectly. I handle it tomorrow. Thanks @deft stump

deft stump
#

can I ask for another code review?

opaque ledge
#

Depends on your pay ๐Ÿ‘€

#

just put it, if someone wants to/can help, they will ๐Ÿ˜„

deft stump
opaque ledge
#

i suck at reading other people's code, but i will try my best to help ๐Ÿ˜„

storm ravine
#

can I ask for another code review?
@deft stump NOPLEASENO Noooooope PLEASENO

deft stump
#

@storm ravine entyLul
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. WOGGERS

opaque ledge
#

@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();
}

deft stump
#

Question though. How do i skip the looping entirely?
I think that's also whats effin me up

opaque ledge
#

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

dusk relic
#

What happens if I try to add a value to nativehashmap that's already in there

scarlet inlet
#

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));

vagrant surge
#

@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

scarlet inlet
#

isn't it the same to use an entity component tag?

vagrant surge
#

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

scarlet inlet
#

between shared component and entity component tag you mean?

#

or between EM and ECB?

vagrant surge
#

shared comp vs component tag

#

ECB should almost allways be faster than EM

storm ravine
#

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.

scarlet inlet
#

good news about the burst

storm ravine
#

It's old news as we on 0.11 package version already ๐Ÿ™‚

scarlet inlet
#

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;
    }
storm ravine
#

Yes you can. As Playback will call PlaybackInternal which in turn will call PlaybackChain, which in turn will call PlaybackChainChunk which is FunctionPointer

north bay
#

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.

scarlet inlet
#

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
    { }
storm ravine
#

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

scarlet inlet
#

I need the control over the playback

storm ravine
#

I need the control over the playback
@scarlet inlet I don't get to which message this relates ๐Ÿ™‚

scarlet inlet
#

mine

safe lintel
#

is it possible to use ScheduleSingle with the foreach lambda?

opaque ledge
#

there is no more ScheduleSingle, its renamed to Schedule

safe lintel
#

oh yeah, i am an idiot ๐Ÿ˜„

golden elk
#

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)

storm ravine
#

First of all - use SystemBase. Second - nested ForEach not supported.

golden elk
#

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

unborn totem
#

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?

coarse turtle
#

I think the general workflow is to create a prefab entity

unborn totem
#

what is a prefab entity?

coarse turtle
#

An entity with the prefab component

#

if you're using the conversion pipeline you can declare converted gameobjects as a prefab

unborn totem
#

I want to avoid GameObjects because I am attempting to spawn hundreds of thousands of entities

coarse turtle
#

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

unborn totem
#

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

coarse turtle
#

Yea

unborn totem
#

Ok, I'll have to figure out how to do that, sounds smart.

dry dune
#

conversion happening when you saving subscene not when you running the game

unborn totem
#

right now I'm only aware of how to create entities at runtime using the OnCreate method from JobComponentSystem because I'm a noob

dry dune
#

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)

unborn totem
#

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?

dry dune
unborn totem
#

thank you, thank you

opaque ledge
#

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

dry dune
#

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

opaque ledge
#

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

dry dune
#

DOTS and strings aren't the best friends

ocean tundra
#

I'm planning to put my UI/reference data into a Blob

#

99% of the data will be in components

halcyon blaze
#

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

ocean tundra
#

you sure theres no other system setting the value?

halcyon blaze
#

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

dry dune
#

hard to help without full source code

halcyon blaze
#

One sec I'll give more context, wondered if there was any weird quirks anyone might know first

dry dune
#

try to incapsulate the problem into the simpliest possible system

storm ravine
#

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

halcyon blaze
#

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

dry dune
#

don't see any problem in your code

halcyon blaze
#

It's confusing the hell out of me ๐Ÿ˜ฆ

dry dune
#

make sure TotalTimeToWait value is correct

halcyon blaze
#

Stays at 3 the entire time when I logged that

dry dune
#

you can disable burst and jobs, run you foreach on the main thread and to debug your code

halcyon blaze
#

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

dry dune
#
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
halcyon blaze
#

Yeah I know it must be something specific I'm doing, i'll take another look tomorrow. Cheers for the help

zinc plinth
#

hemm does the scale of parents not affect childrens once they're turned into entities ? Wat

#

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 ?

coarse turtle
#

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

zinc plinth
#

well do what with the conversion system ? ^^'

coarse turtle
#

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 { });
  });
}
sly moon
#

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?

tawdry tree
#

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.

sly moon
#

I guessed so

#

Just cleaner if you could schedule the clean up job for later directly in that system.

tawdry tree
#

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

sly moon
#

Ah that might actually be a good solution

#

Thank you!

amber flicker
scarlet inlet
#

Hello people

mint iron
#

you always post the hard questions ๐Ÿ˜„

mystic mountain
#

Try disabling burst ^:d

opaque ledge
#

and the oscar goes to....

unborn totem
#

is there a way to increase the Hybrid Renderer GPU instance data buffer?

warm panther
#

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.

cursive cosmos
#

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...

ocean tundra
#

@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

warm panther
#

I suspect my issue was that I instantiated physics entities inside SimulationSystemGroup, and it only became apparent after I ordered some systems around.

unborn totem
#

@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

cursive cosmos
#

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.

unborn totem
#

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

ocean tundra
#

@cursive cosmos You can create entities inside a job, look at Entity Command Buffer

cursive cosmos
#

will do!

#

@ocean tundra How do I get a hold of them, it's not with SystemBase?

cursive cosmos
#

sweet, thank you!

dry dune
#

@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 ๐Ÿ™‚

unborn totem
#

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

dry dune
#

nope, all fine for me

unborn totem
#

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

ocean tundra
#

@unborn totem wtf, how???

unborn totem
#

I'm not sure. Probably something I am overlooking.

ocean tundra
#

are you doing something weird/special to RenderMesh?

dry dune
#

this is wired, gpu memory should have only one box - this is nothing

unborn totem
#

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

dry dune
#

you have to use instanced materials

unborn totem
#

I am, as far as I know

ocean tundra
#

yea by the sounds of it when you touch material your duplicating it

dry dune
#

my gpu memory is free when i have 1M boxes

unborn totem
#

I am talking about normal RAM, not GPU memory

#

my GPU memory is much lower

dry dune
#

and i have different material properties and texture shifts

unborn totem
#

opening up my project is taking a bit, but I'll show you what my material looks like

dry dune
#

+100mb or so and i bet that huge part of this is entity debugger

unborn totem
#

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?

ocean tundra
#

material looks ok

dry dune
#

i have a bit more complex material

ocean tundra
#

how are you using those values, touching RenderMesh.Material or those cool attribute rendering components?

unborn totem
#

this is how I'm spawning my entities, if that's what you mean

dry dune
unborn totem
#

@dry dune I do not have that checkbox

dry dune
#

it is on material

unborn totem
#

it is not there

dry dune
#

so here we go

#

maybe Unlit node do not support that?

unborn totem
#

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});```
ocean tundra
#

@unborn totem I asume prefab has the RenderMesh on it?

unborn totem
#

it does, yes

#

if by RenderMesh you mean a MeshRenderer

#

as well as a MeshFilter

ocean tundra
#

how are you converting your prefab?

unborn totem
#

var instance = entityManager.Instantiate(prefab);

#

letting DOTS do it for me

ocean tundra
#

but... that would make prefab a gameobject?

unborn totem
#

as far as I know, entityManager.Instantiate turns a GameObject into an Entity

ocean tundra
#

try converting it first to be safe

#

ConversionUtilty

unborn totem
#

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?

ocean tundra
#

oh that kinda makes more sense

#

@unborn totem look at world serialization

unborn totem
#

thanks

golden elk
#

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?

amber flicker
#

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.

golden elk
#

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...

cursive cosmos
#

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.

amber flicker
#

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?

golden elk
#

Yes it's enabled

#

I turned Burst off completely and it still crashes out so ๐Ÿคท

amber flicker
#

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.

cursive cosmos
#

@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?

amber flicker
#

you may just need to make local references to those variables before your lambda

cursive cosmos
#

so...I reasign them in the update? O.o

amber flicker
#

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

golden elk
#

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 () ```
deft stump
#

@cursive cosmos yep. you reassign them in update

golden elk
#

Can you not access anything managed in OnCreate?

#

On 2019.3.4f1

amber flicker
#

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

golden elk
#

It isn't managed in the OnUpdate, it should be a NativeArray by then

#

But it crashes in OnCreate

#

trying to populate the nativearray

amber flicker
#

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 ๐Ÿ˜ฌ

ocean tundra
#

have you debug logged the navpath object in on create?

amber flicker
#

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

cursive cosmos
#

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)

golden elk
#

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

ocean tundra
#

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

amber flicker
#

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.

golden elk
#

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

amber flicker
#

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

golden elk
#

I'll have to try upgrading to 2020 at some point I suppose

amber flicker
#

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.

golden elk
#

right

amber flicker
#

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.

ocean tundra
#

yea super duper easy to use

#

i dont even specify a default size untill i get to optimization

golden elk
#

yeah I'll take a look at them

#

thanks for your help

amber flicker
#

np - good luck

golden elk
#

progress anyway, just gotta make the turning better

cursive cosmos
#

It doesn't seem right using a system to do a job once, am I right in that?

golden elk
ocean tundra
#

amazing

golden elk
#

that's it for me tonight. thanks again for your help roycon and timboc.

ocean tundra
#

anytime ๐Ÿ™‚

halcyon plume
#

QQ all

#

can someone help me with ECS in unity?

#

And I would be glad if someone teachme

#

What syntax is relevant right now?

hollow scroll
#

Entities. inject is very old and deprecated

halcyon plume
#

so foreach now is better?

#

but it dont work

#

Does anyone have fresh guides on ECS

dull copper
#

inject still works? I thought it was completely removed already

halcyon plume
#

idk

hollow scroll
#

I thought it was removed too

dull copper
halcyon plume
#

It's just a 2 year old guide

dull copper
#

but it's bit outdated by now

#

probably among most recent tutorials tho

halcyon plume
#

this is deprecated?

#

cuz i cant do this

dull copper
#

should work

halcyon plume
opaque ledge
#

no, thats the most recent way of doing stuff

halcyon plume
#

its void

dull copper
#

if you can't do it, you have wrong entities version

halcyon plume
#

i have last version

opaque ledge
#

thats ComponentSystem

#

use SystemBase

dull copper
#

^

deft stump
halcyon plume
#

i havent systembase

opaque ledge
#

update your entities package then

dull copper
#

then you haven't latest entities

hollow scroll
#

just SystemBase not ComponentSystemBase

dull copper
#

also instead of saying you have latest, just tell the version you have

halcyon plume
#

i just downloaded it

opaque ledge
#

and what is the version of it ?

dull copper
#

in 9 times out of 10, people who say they have latest version tend to have some ancient version for some reason

opaque ledge
#

package manager can derp sometimes

deft stump
#

package manager derps hard most of the time

dull copper
#

or he could just use too old unity version that doesn't support the latest entities...

halcyon plume
dull copper
#

could be many things

opaque ledge
#

yeah, people reference to stuff in a manual, but manual they link is 0.2 version while latest is 0.11 ๐Ÿ˜„

halcyon plume
#

0.1.1

deft stump
#

yeah that's really old.

opaque ledge
#

wow, thats old

#

like 2 years old i think

dry dune
#

new ecs versions are not supported by older editor version

dull copper
#

which unity this is?

deft stump
#

wait what unity version are you using?

halcyon plume
#

2019.2.14f1

deft stump
#

that's why

dull copper
#

yeah, that's not good

opaque ledge
#

go 2019.3 at least

halcyon plume
#

i need to update it?

deft stump
#

yes

halcyon plume
#

how to do this?

dull copper
#

if you want to use ECS, yes

opaque ledge
#

go 2020.1 beta for even more futures

halcyon plume
#

yes realy want

dull copper
#

2020.1 is best for now if you do ECS

#

better hybrid rendering and more debugging support

halcyon plume
#

how to update my unity?

dull copper
#

use unity hub

halcyon plume
#

oh i found

dry dune
#

if he don't know how to update unity probably ecs going to be way to hard...

opaque ledge
#

๐Ÿ˜„

halcyon plume
#

yes but i like hard ways)

#

cuz its intresting)

#

so

#

what do u recomend?

opaque ledge
#

i would go for beta

deft stump
#

^

#

or you can be even crazier and go for alpha

opaque ledge
#

well he DID mention he likes hard ways UnityChanExcited

dry dune
#

i had only one crash with alfa during last 10 days

halcyon plume
#

well he DID mention he likes hard ways UnityChanExcited
@opaque ledge i said hard ways) non suicide)

pseudo pollen
#

going harder faster

halcyon plume
#

better stronger

dry dune
#

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?

ocean tundra
#

@dry dune That sounds evil as

halcyon plume
#

i think you can write system wich handle this two comonents and delete component in this entity and create 4 other

opaque ledge
#

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 ?

dry dune
#

it is known for compiler, not for my system

opaque ledge
#

isnt Type reference type tho ? how can you put it into IComponentData ?

dry dune
#

ComponentType implements IComponentData

opaque ledge
#

facepalm so its a custom struct, not actually a Type

dry dune
#

not custom this is a struct form ecs package

opaque ledge
#

alright

scenic oracle
#

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 ?

opaque ledge
#

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

scenic oracle
#

Using [UpdateAfter(typeof(StepPhysicsWorld))] raise a ton of errors, and using [UpdateBefore(typeof(EndFramePhysicsSystem))] change nothing.
Guess I will try the forums then.

undone torrent
#

how can i get editor world ?

#

i mean using World. ....

halcyon plume
scenic oracle
#

In "Advanced", did you check "Show Preview Packages" ?

halcyon plume
#

no

#

there show deps and reset to defaults

amber flicker
#

if you're using the alpha they moved it to Project settings or Preferences I believe

scenic oracle
#

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

halcyon plume
#

ty

#

hmmm

#

what to do?

#

@scenic oracle

opaque ledge
#

restart your editor

halcyon plume
#

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

opaque ledge
#

idk, maybe remove your Library folder and let Unity recreate it

undone torrent
#

is there a way to do Debug.log on burst mode ???

tawdry tree
#

I don't think so? but as long as you're not debugging a burst-specific problem you could temporarily disable burst and log

opaque ledge
#

latest version of Burst supports Debug.Log

#

check the Burst manual for more info

#

1.3.0

halcyon plume
opaque ledge
#

no its not, it works fine for me

halcyon plume
#

what version?

opaque ledge
#

Entities 0.11, Unity 2020.1.0b10

halcyon plume
#

sooo

#

i need enities. hybrid render and jobs?

#

and burst

deft stump
#

yes

halcyon plume
#

wow its work

opaque ledge
#

Collections as well

halcyon plume
#

and now i have problems with components)

#

how to add IComponentData to prefab

#

cuz this is deprecated

opaque ledge
#

I strongly suggest you should look at some tutorials

halcyon plume
opaque ledge
#

check out CodeMonkey's youtube channel, he has great tutorial videos there

#

idk i suppose so, i didnt check those

halcyon plume
#

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

storm ravine
#

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%)

halcyon plume
#

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

storm ravine
#

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.

cursive cosmos
#

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.

deft stump
#

@cursive cosmos iirc, you can use Job.WithCode

cursive cosmos
#

What do you mean? All I do is with code. ๐Ÿ˜„

opaque ledge
#

Check Entities Manual

#

and no, thats why SystemBase exists, to run a single job, or multiple jobs if they are dependend on each other

gusty saffron
#

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))]

cursive cosmos
#

@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.

opaque ledge
#

yeah, you either have to use a bool or tag component, tag component means a component that doesnt have any data in it

halcyon plume
#

How to control a character through ECS,

deft stump
#

There's lots of tutorials out there joker

halcyon plume
#

i dont see) sry

#

can u send link?

cursive cosmos
#

@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...

โ–ถ Play video
halcyon plume
#

ty

deft stump
#

been thinking. has there been news that the VS tools for unity extension be updated for dots?

opaque ledge
#

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

halcyon plume
#

Can someone tell me how to 3D objects to disable gravity in DOTS physics
upd: just found it

halcyon plume
#

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?

opaque ledge
#

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)
}
halcyon plume
#

dont work)

opaque ledge
#

your ForEach applies to EVERY entity that has Translation component

halcyon plume
#

even now dont work

opaque ledge
#

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" ?

halcyon plume
opaque ledge
#

alright, add that component, it should work

halcyon plume
opaque ledge
#

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);

cursive cosmos
#

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.

halcyon plume
#

use ovverides

#

like this

#

And you can leave the OnUpdate() empty

#

and second answer

#

@opaque ledge so. what about my problem?

opaque ledge
#

i literally answered ๐Ÿ˜„

cursive cosmos
#

@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.

opaque ledge
#

you cant

deft stump
#

you cant

opaque ledge
#

you can use ECB for creating/destroying entities, or remove/add components

humble falcon
cursive cosmos
#

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

opaque ledge
#

well, i never used IJobChunk, but stuff should be the same

#

what seemed to be wrong ?

humble falcon
#

can you maybe share your code. so that we can see, why it is not working?

cursive cosmos
#

Might have figured it out, just a sec

#

can job structs handle entities as input?

humble falcon
#

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

cursive cosmos
#

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.

halcyon plume
#

@opaque ledge no

cursive cosmos
humble falcon
#

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.

cursive cosmos
#

I have the entities stored as a prefab already, using the convert method.

#

just wondering how they should be inserted into the instantiate ๐Ÿ™‚

humble falcon
#

you should instantiate the prefab instead of the entity.

cursive cosmos
#

No...then it wont be an entity anymore.

humble falcon
#

EntityManager.Instantiate(yourEntityPrefab)

cursive cosmos
#

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

storm ravine
cursive cosmos
#

The problem the instantiate method has is that the Entity is not set, since this is a struct.

opaque ledge
#

why are you doing ecb.EntityManager ? is that even available ๐Ÿ˜„

opaque ledge
#

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

cursive cosmos
#

But that manual only shows me using a foreach directly in the update ๐Ÿ˜„

storm ravine
#

And it doesen't matter ForEach or any Job (except Concurrent version for parallel)

opaque ledge
#

yeah thats fair, do you know/remember how to schedule Jobs 'old way' ?

cursive cosmos
#

So my way forward should be doing a onetime job in the foreach and just stop it with a bool basically?

storm ravine
#

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.

opaque ledge
#

yeah thats way to go for Sugarspoon

cursive cosmos
#

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.

storm ravine
#

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?

cursive cosmos
#

Cubes, yeah

opaque ledge
#

you can always spawn from a Monobehaviour, with bursted job, you dont necessarily need to use a system for it i think

storm ravine
#

Ok, let's go to second step

#

You have rectangular grid

opaque ledge
#

i mean you are not 'processing' any entities, you are just spawning/initalizing them, so imo MB would be better ๐Ÿคท

storm ravine
#

Thus you can flat you 2D grid to 1D

#

And you always can easily find XY from 1D index

opaque ledge
#

There was Sark's Voxel World implementation, let me try to find you a link

cursive cosmos
#

currently it's more like a sheet with only two loops, ye

storm ravine
#

Thus you should just create IJobFor\IJobParallelFor

#

With length == rows * cols

#

In that job you'll use Concurrent entity command buffer

opaque ledge
cursive cosmos
#

Oh...I'll take a look at that.

storm ravine
#

It's to early for him

opaque ledge
#

one step at a time

halcyon plume
#

can u now help me?

#

cuz Unity said that i cant use GetComponent in ForEach

opaque ledge
#

that looks fine

#

you can

#

you already do

halcyon plume
#

bottom

deft stump
#

okay what are you trying to do joker?

halcyon plume
#

get target translation

storm ravine
#

Potential memory aliasing, and safety system prevents you from that

deft stump
#

get target translation
for what?

opaque ledge
#

he is trying to get camera to follow target entity