#archived-dots

1 messages Β· Page 93 of 1

rare umbra
#

Today is the day! (Wishful thinking)

onyx mist
#

I read the first part of that and got excited lol. I'll join you with wishing

coarse turtle
#

lol same here

stable fog
#

is today the day?

#

I got a question, I've asked it before but no one responded

#

I have a situation where I'm generating a few million raycast commands

#

its for analyzing a scenes structure

#

and i found that populating the NativeArray<RaycastCommand> too more time than actually executing the Raycasts

#

I'm executing the raycasts in a batch, and so its being executed in parallel

#

however, I'm populating the NativeArray sequentially in a loop

#

is it possible for me to populate that NativeArray in paralell, via jobs or something?

#

few million actually meaning about 200 million

#

ideally, though it will likely end up being less

safe lintel
#

yeah you can populate nativearrays in jobs

stable fog
#

noice

knotty radish
#

Hey everyone, I'm looking for some info that may or may not exist (I'm asking before making a thread and after searching).
Is there anything saying that we should reduce the number of components on the same entity ?
Also anything about the size of the component itself (let's say all the fields are always used by the system) ?
Thanks!

onyx mist
#

Iirc the recommended limit for the amount of component fields is 100 bytes. I've heard that It's better to have a lot of components with a few fields than one component with many fields

#

For your first question I'm not sure and also interested in an answer

knotty radish
#

Yeah heard about that too but didn't know about the 100 bytes

onyx mist
#

I do notice that when I have many components on an entity, chunk utilization goes way down

#

Might be me assigning correlation to the wrong thing tho

knotty radish
#

I will post a thread ~tonight and see if I can have some answers from the unity devs

onyx mist
#

Ok can you let me know when you do?

knotty radish
#

Sure!

merry oasis
#

is there any solution to lack of NativeArray<NativeArray<T>> / NativeList

plain cloak
#

you could flatten it for array case

merry oasis
#

nope, this is not for 2d array

#

i need a proper jagged array and it looks like implementing it myself is the only way which is really frustrating

plain cloak
#

would it be possible to use native multi hashmap instead, thats what i do

#

i also read somewhere about using entities with buffers like 2d array

#

i mean jagged*

merry oasis
#

i mean my use case is for managing sub-meshes for mesh generation

#

ill try multi hashmap, im not making very large meshes yet so performance will probably be fine 🀷

low tangle
#

It's fast, and yeah that's the tool I use for jagged arrays, works well with the matching job to visit values

onyx mist
#

is there a way i can extend the math.random class? i want to add a simple method but not sure where i can find it

#

basically a chance method

#

so if ( Chance(2) ) {}

merry oasis
#

ref extension method should work @onyx mist

#
    public static class RandomExtensions
    {
        public static int Chance(this ref Random rand, int inp)
        {
            
        }
    }
onyx mist
#

wouldnt extension methods not work in jobs because they are static?

merry oasis
#

no they are fine

onyx mist
#

NICE

merry oasis
#

you should just avoid accessing static data

onyx mist
#

oh so even normal static methods would work?

merry oasis
#

like everything in the Unity.Mathematics.math class is static right? but obviously those are all fine to use

onyx mist
#

ok thank you!!!

merry oasis
#

yes methods are totally fine, just make sure to not access any shared static data and you're all set

untold night
#

you can read static readonly data if it's burst compatiable, but such data will get backed into constants access by bursted functions

#

you can't write to static data, as others have pointed out

merry oasis
#

well static readonly struct fields are immutable by design, but its good to know that Burst/Jobs won't complain about them

onyx mist
#

"but such data will get backed into constants access by bursted functions" sorry could you elaborate on this?

#

im not sure what that means

fathom trout
#

@stable fog you can probably pass nativeslices of that array and populate in parallel

untold night
onyx mist
#

gotcha!

#

ty!

plain cloak
#

is there a way to disable transform conversion system?

prime cipher
#

While Rotation component allows to rotate and Translation component allows to move, which component should be used for scaling an entities appearance. Probably the rendered mesh needs to be scaled, as it sounds weird that the entity has a scale itself. But I can't find a property for RenderMesh that reflects a rendered scale. Sry, probably a dumb question.

slow epoch
#

LocalToWorld component has the scale

#

But i don't know how to modify the matrix to scale it

amber flicker
#

yea Scale or NonUniformScale (IComponentData's) are probably what you're looking for @prime cipher

languid stirrup
#

Is there any better way of creating an Entry point for coding in the DOTS world instead of a monobehaviour attached to an empty gameobject. I am trying a JobComponentSystem class with a EndSimulationEntityCommandBufferSystem var in it. Is there a better way?

prime cipher
#

@digital scarab @amber flicker THX, works like a charm.

#
[BurstCompile]
    [RequireComponentTag(typeof(SpaceObject))]
    struct OrbitingJob : IJobForEachWithEntity<Orbit, Translation>
    {
        public float DeltaTime;
        [ReadOnly] public ComponentDataFromEntity<Translation> Translations;

        public void Execute(Entity entity, int index, [ReadOnly] ref Orbit orbit, ref Translation translation)
        {
            Translation pivot = Translations[orbit.Focus];

            float3 dir = translation.Value - pivot.Value; // get point direction relative to pivot
            dir = Quaternion.Euler(0f, orbit.Speed * DeltaTime, 0f) * dir; // rotate it
            translation.Value = dir + pivot.Value; // calculate rotated point
        }
    }

    protected override JobHandle OnUpdate(JobHandle inputDependencies)
    {
        Debug.Log("SpaceObjectOrbitingSystem::OnUpdate()");

        var job = new OrbitingJob()
        {
            DeltaTime = Time.deltaTime,
            Translations = GetComponentDataFromEntity<Translation>(true)
        }.Schedule(this, inputDependencies);

        return job;
    }

shouldnt that work for the ComponentDataFromEntity? I get a weird exception: "InvalidOperationException: The writable NativeArray OrbitingJob.Iterator is the same NativeArray as OrbitingJob.Data.Translations, two NativeArrays may not be the same (aliasing)"

amber flicker
#

you can't have a CDFE take the same type (Translation) as the Job itself

#

you can remove Translation from the IJobForEach and use the entity passed into execute to get it from the CDFE instead

prime cipher
#

@amber flicker Oh I C, I thought it would be the combination of refs, so that Translation is different than Orbit+Translation

#

However, as I have the Entity also, I can simply get the Translation from the CDFE too

amber flicker
#

I think it's because there's nothing to stop you getting the same Translation (from the CDFE) as the one that would be passed as ref into the job so guaranteeing safety for writing is why that restriction exists I'd guess

prime cipher
#

Yes, but now I need to declare the CDFE to be writable 😦

amber flicker
#

yes

pliant pike
#

ironic I'm trying to do something similar to the example above but I need to iterate through all the CDFE in a for loop

#

I dont think I can do that though, I'm guessing I need to use an EntityQuery instead

amber flicker
#

Accessing components via CDFE is all rand access so it can be vastly better to iterate over a query if possible (which it should be)

glad grail
#

hi all, can anyone advise how to change which Material an entity is being rendered with? I can't seem to use RenderMesh in ForEach like I can with the Translation component...

pliant pike
#

for each entity I need to iterate over all other entities and check the distances between them so EQ converted to nativearray I guess would be best

amber flicker
#

@glad grail the reason you can't iterate over them is because every RenderMesh is a SharedComponentData which puts each entity with a different mesh into a separate chunk.

glad grail
#

oh so all entities instantiated from the same Prefab share the same SharedComponentData

amber flicker
#

@pliant pike not sure the best way to do that - you can't avoid rand access - nativearray method probably works as good as any - only thing that occurs to me is you may not want to calculate the distance from A to D as well as from D to A

#

@glad grail if the prefab has a RenderMesh, then basically yea, they'll all be entities with a SharedComponentData (RenderMesh) with the same value/hash - you can actually iterate over the entites, just not using foreach<RenderMesh>

glad grail
#

Thanks @amber flicker can you recommend a good way to change material (to show unit selected in RTS)? Or maybe show/hide a second child mesh?

amber flicker
#

I haven't done anything with materials and it's quite implementation specific but in case it helps point you in the right direction, you could e.g. add a 'Selected' tag to your unit and then do something like (psuedo code)myQuery = GetEntityQuery( ComponentType.ReadOnly<Selected>()); entityManager.SetSharedComponentData(myQuery, new RenderMesh(){ //your new values e.g. mesh = unitMesh, material = highlightMaterial .. }) This is a batch method. Otherwise you could iterate the query in a system and do e.g. var renderMesh = entityManager.GetSharedComponentData<RenderMesh>(entity); renderMesh.material = highlightMaterial; entityManager.SetSharedComponentData(entity, renderMesh); @glad grail

glad grail
#

that's really useful I'll look into that thanks @amber flicker

#

For the second snippet, is renderMesh an object? i.e. if I change it will it affect all entities using that RenderMesh, or will it assign a new one just to the selectected entity?

#

tbh the first approach looks like it will fit better anyway, just interested really.

amber flicker
#

so the first approach relies on you setting e.g. all the query results to have the same mesh (useful when you do want to change all in a bulk way but maybe not what you want a lot of the time). The second does assign to just one entity after getting the current values. You could mix them and e.g. get the RenderMesh from entity 1 then use a query to set the shared mesh for a bunch of entities at once. Not sure if that helps/makes sense.

glad grail
#

Yep that answers my question, SetSharedComponentData will assign a new data to just the one entity in the second code snippet.

civic bay
#

How can I change the scale of an Entity using the new ECS?

dry dune
#

EntityManager.SetComponentData(entity, new Scale(){Value=1.0f});

civic bay
#

I tried that but I just get this error: ArgumentException: A component with type:Scale has not been added to the entity.

#

@dry dune

amber flicker
#

I'm not a big fan of the way it works - there's two things that could be going on here - both visible via the entity debugger. I would guess your entity doesn't have a 'Scale' component. It likely either has a) no Scale component or b) a NonUniformScale component. If a) then add a Scale component. If b) change the NonUniformScale instead.

dry dune
#

then replace set with add

civic bay
#

I have this set up though

amber flicker
#

how does it look in the entity debugger?

civic bay
#

And then when I spawn the entity I call

                m_entityManager.SetComponentData(glitter, new Scale { Value = Random.Range(0.1f, 10.0f) });
safe lintel
#

are you trying to set the scale of a hybrid entity or a pure ecs entity?

#

because scale wont have any effect if you are using the old transform

amber flicker
#

also.. adding a Transform component? does that do anything useful?

civic bay
#

Yeah I believe hybrid @safe lintel

#

Also @amber flicker

#

Removed Transform

#

Didn't do anything, no

safe lintel
#

well if you continued using the transform, it would be most optimal to change scale via a ComponentSystem
like

            Entities.With(m_GlitterQuery).ForEach((Entity entity, Glitter glitter, Transform transform) =>
            {
                   transform.localScale = newScaleVariable;
            });       
civic bay
#

I got rid of the transform

#

So should I not be able to just add the NonUniformScale component?

#

Sorry, very new to this way of programming so it's confusing me haha

#

That's the entity debugger

safe lintel
civic bay
#

Thanks for the help @amber flicker @dry dune @safe lintel I got it sorted in the end. I used CompositeScale and setting the matrix manually. Probably not the best way to do it but it works haha

mystic mountain
#

We're moving to the end of the week, and still nothing :' (

tawdry tree
#

Such is development life, or at least the ones waiting on releases.
I'm they're all working as hard as is reasonable (possibly even more than that) to get it out as soon as they can.

safe lintel
#

hopefully friday's the day

onyx mist
#

Is it good practice to have a dynamic buffer on entities with a lot of fields in order to save on memory in the chunk? Only a single buffer so an entity wouldn't have more than one of these

#

Example: a bufferelement of personality with int fields like greed, kindness, pride, extroversion, etc

safe lintel
#

are you actually running out of memory on the chunk?

onyx mist
#

i currently have a lot of components on my entities so any reduction on that would be great

#

the ability to clump all the personality traits into one buffer that stores its mem on the heap sounds lovely

#

basically i wanna know if what i did for personality here is ok

#

and also if i can add more fields or if thats already too many

safe lintel
#

dont see any reason that there would be anything wrong with doing that, more curious how many components and fields in total you have?

onyx mist
#

ill send a pic in a sec

#

still trying to find ways to minimize the amount but a lot of it are tags

safe lintel
#

did you set the internal buffer size to something low? ive never personally tried it with zero

onyx mist
#

i didnt set the buffer size at all since i assumed it would make it so it would push all of it onto the heap

#

and i read buffers could be gigabytes in size if need be so hey why not lol

safe lintel
#

well my understanding is the internal size is whats stored in the chunk, and above that it goes to the heap

onyx mist
#

exactly

#

i dont want any of the buffers stored in the chunk ideally

safe lintel
#

oh right i get what you mean, wasnt sure if there was some hidden default if you dont happen to specify

onyx mist
#

hm im not sure πŸ€”

safe lintel
#

but all in all, id personally just store it as regular components until i ran into a problem, unless theres a particular reason you are trying to have the chunk store as many as possible?

#

if you are regularly iterating on them arent you giving up all the benefits of linear memory layout?

onyx mist
#

isnt that the ideal? all i know is i saw my chunk utilization go from 803 at the start of the project to 34 now and i got worried

safe lintel
#

premature optimization isnt ideal πŸ™‚

onyx mist
#

true

safe lintel
#

and it might not be an optimization at all in your case

onyx mist
#

yeah i think you're right! ill do more testing

#

in fact no you are right

#

thanks!

safe lintel
#

i dont know if theres a way to view cache usage, but the megacity project has a really high usage of chunks and i personally dont have any problems with it

onyx mist
#

i gotchu

languid stirrup
#

guys, I have been following the ECS unity tutorial on youtube. and it uses IJobProcessComponentData to filter which entities to work on. But i am trying it in code right now, and it doesnt seem to have IJobProcessComponentData anymore. Am i mistaken? if not, whats the best other subsitute for it? IJobParralelForFilter?

#

that tutorial video also mentions the [computejoboptimization] tag which my editor doesnt seem to recognize.

magic frigate
#

That is a very old tutorial

#

Changed to [BurstCompile]

solar spire
languid stirrup
#

ah, thnx @magic frigate and @solar spire

magic frigate
#

Jeez, even that video might be partially out of date in a matter of days

languid stirrup
#

oh wait, no.. I am not converting from gameobjects, I am making everything new from code

magic frigate
#

I think the title means more to convert the way the game is written rather than just the conversion workflow

languid stirrup
#

oh ok

solar spire
#

It's a whole playlist of all of the DOTS content from Unite Copenhagen

languid stirrup
#

gotcha, so weekend full for 43 minutes videos each :p

solar spire
#

Pretty much πŸ˜› I have all of them in my watch later list

languid stirrup
#

lol

solar spire
#
#
#

@dull copper your legacy will always be remembered o7

dull copper
#

for those wondering about this, the old pinned message couldn't fit all the info on single message anymore, so had to be repinned (with extra message to reserve more space)

solar ridge
#

@solar spire I saw that post and was like YES AN UPDATE! soarynHappy ... then was saddened to just see it is book keeping with having all the latest links available soarynSad why do you play with my heart so?

solar spire
#

If Discord allowed me to reorder pins or post messages larger than 2000 characters I wouldn't be here relishing in your pain

solar ridge
#

Loool

#

No worries

#

Im on standby development wise until they release the next update

solar spire
#

Everyone's waiting on that networking sample!

solar ridge
#

Networking will be fantastic! Though Im assuming they dont have a TCP handle at all

#

which in my case wont assist if they dont but wont be surprised if that is skipped over πŸ˜›

twin raven
#

I read Soaryns message "YES AN UPDATE" and got excited 😭

prime cipher
#

If I choose Convert and Inject Game Object with Convert To Entity, can I access the injected game object having the entity at hand?

worn stag
#

can we have fps sample release today pleaseπŸ₯Ί

frank knoll
#

Does anyone have ideas how to draw gizmos for component systems and entities without using monobehavior?

tawdry tree
#

In-editor you use mono for just about everything, so I'd assume you can't.
Though, all you'd need mono for would be the drawing itself; you could make some system basically output the exact inputs the gizmo drawing system uses. I suspect it might be easier to just have a mono class that reads entitycomponents and draws from that directly, though.

coarse turtle
#

@prime cipher yes you can

#

You can grab the component object via entity manager or using the query builder

low tangle
#

There's also some good stuff in EntityManager.Debug

#

Forgot the exact name

gusty comet
#

@frank knoll For that I use a Singleton, which allows to add Actions. The MonoB iterates over the Actions in OnDrawGizmos and invokes them. In my Systems I can then call the add method with anonymous body using the Gizmos.Draw* methods.

#

But yes at least for drawing you need the one MB to hook onto OnDrawGizmos

civic bay
#

I'm creating pure entities, not instantiating gameobjects and converting them

#

But how can I add Physics Body to it?

#

And Physics Shape Authoring

#

And to set values, i.e. dynamic and mass = 10

craggy orbit
civic bay
#

Ah brilliant, so I can add those components separately

#

like a normal component

#

and set the values that way?

craggy orbit
#

yep. exactly

civic bay
#

Thanks for your help πŸ™‚

craggy orbit
#

just to make sure we're on the same page, it's an ECS component, not monobehaviour

civic bay
#

Yeah, extending from IComponentData, right?

craggy orbit
#

yeah (im 90% sure)

#

might extend from something else but it is an ECS component

civic bay
#

Brilliant, cheers

languid stirrup
#

so, i have added a "toGenData" component to my entities and im just using it as a tag to generate some data for the entity. In the relevant JobComponentSystem I have a IJobForEachWithEntity<> job setup. At the end of this job's execute function I want to remove the toGenData component from this entity. I see i need a EntityCommandBuffer. and most examples i see, they are attaching it to a EndFrameBarrier. Is this appropriate/best way of doing it in my case?

#

mind you, this data only needs to be be generated the first time for every entity, even newer ones. hence using this tag

onyx mist
#

By endframebarrier do you mean like end[insert-system-group-here]barrier? Or postupdatecommands?

languid stirrup
onyx mist
#

Ahh I didn't know that was a thing. I usually just use the system group ECBs

languid stirrup
#

will that help me in my case?

#

and you mean the entitycomponentbuffers?

onyx mist
#

Yes

#

I have a similar system to yours with a "toBeUpdated" tag. I usually do that in the beginsim ECB and haven't had any issues so far with it

languid stirrup
#

are u using JobComponentSystem class with IJobForEachWithEntity job to perform logic on your entities?

onyx mist
#

Yes

#

Tho remember to take my words with a grain of salt since I didn't know about endframebarrier πŸ€” no idea how that differs from the group ECBs

languid stirrup
#

hmmmm, what do you mean groups's ECB's?

onyx mist
#

But as I said even iteration over tens of thousands of entities I haven't had an issue with my datagen tag

#

These ECBs

#

Keep in mind I'm abysmal at terminology

languid stirrup
#

oh.. i didnt know about these ECBS

onyx mist
#

Wish I was home so I could just show you the code for my system πŸ˜”

#

Ah

#

Looks like we learned something new about command buffers from each other

languid stirrup
#

please do when you do get home! lol, I could use all the insights i can get specially if you are doing simialr code

#

endframebuffer is supposedly the postupdate command buffer thingy for JobComponentSystems

#

as you dont get a postupdate command buffer for the JCS

onyx mist
#

Ah I assumed so since they sound like synonyms

#

That's interesting

languid stirrup
#

but in my Execute, i cant seem to get anything about of the EntityCommandBuffer 😦

onyx mist
#

Maybe the group ECBs are for more specific frame timings

#

Here's how I got my command buffer in a different system

languid stirrup
#

lol, I just check for group ECB in the code and wow... there are so many of them!!!!

#

how i paste code? cant seem to paste code here lol

onyx mist
#

Usually I just screencap it

craggy orbit
#

it's best to use 3 backticks (`) around block of code

#

you can put "cs" after the first set of 3 for basic syntax coloring

languid stirrup
#
EndInitializationEntityCommandBufferSystem endinti = new 
EndInitializationEntityCommandBufferSystem();
            EntityCommandBuffer ecb = endinti.CreateCommandBuffer();
            ecb.RemoveComponent<nodeToGenTag>(et);
#

ok thnx @craggy orbit but i think i got the cs part wrong hehe

raven badger
#

cs has to be on the same line as the 3 backticks I believe

#
bool test = true
languid stirrup
#

there you go, you are correct, the first line just needs to be the backticks and cs and the code starts from the next line

north bay
#

Is there a way to make sure that a job component system gets the job of another system as it's dependency?

tawdry tree
#

Why would you want to do that?
not to be rude or anything, but attempting to do so sounds like you might be doing a bad pattern

safe lintel
#

kinda have to do it for some of the physics system queries so its already a thing

#

if you search the physics code for FinalJobHandle you can see how they implemented it

north bay
#

I have a job which serializes the messages of a connection and another one who send the messages.

#

I can probably just put them into one system and schedule them with the other one as a dependency.

gusty comet
#

Depends how you want to separate your code. You can also have two systems and use the UpdateBefore or UpdateAfter class attributes.

dusty scarab
#

Is the update here?

dull copper
#

no

dull copper
#

I'm super curious if they finally fixed the unity physics timestepping

#

because they did use it on the upcoming shooter sample

#

and they definitely can't make networked shooter's physics dependent on rendering speed

mystic mountain
#

@dull copper what do you mean fix physics tinestepping? Are you talking about dots physics?

#

The net sample uses simulation and render loop already.

dull copper
#

dots physics yes

#

I think they use simulation group for it but it's ran on each update

mystic mountain
dull copper
#

I'm getting nightmares of this if endif stuff here πŸ˜„

#

there has to be cleaner way to do this

fair condor
#

Anyone know how to get the length / byte array from a BlobBuilder or BlobAssetReference<t>?

I want to store it manually, outside of any subscene, and manually create a BlobAssetReference from its bytes:
BlobAssetReference<BlobData>.Create(bytes);

The data is in there, and the unsafe ptr is exposed, but not its length: "BlobAssetReference.m_data.header->Length" that is internal.

#
[FieldOffset(8)]
public int Length;

I could just grab it manually I guess

fair condor
#

Current solution:

public unsafe static class BlobAssetExtensions
{
    public static Type BlobAssetHeaderType = typeof(BlobAssetReference<>).Assembly.GetType("Unity.Entities.BlobAssetHeader");
    public static FieldInfo LengthFieldInfo = BlobAssetHeaderType.GetField("Length");
    public static int LengthFieldOffset = LengthFieldInfo.GetCustomAttribute<FieldOffsetAttribute>().Value;
    public static int SizeOfHeader = Marshal.SizeOf(BlobAssetHeaderType);

    public static int GetLength<T>(this BlobAssetReference<T> reference)
        where T : struct
    {
        var ptr = IntPtr.Add(new IntPtr(reference.GetUnsafePtr()), -SizeOfHeader + LengthFieldOffset);
        return *(int*)ptr;
    }

    public static byte[] ToManagedByteArray<T>(this BlobAssetReference<T> reference)
        where T : struct
    {
        var ptr = new IntPtr(reference.GetUnsafePtr());
        var length = reference.GetLength();
        var managedArray = new byte[length];
        Marshal.Copy(ptr, managedArray, 0, length);
        return managedArray;
    }
}
plain cloak
#

is there anyway to disable transform components getting added to entities?

safe lintel
#

you can make a conversion system to handle it after the fact, its a little clumsy but it works

stuck hatch
#

Hello, what can I do if my system is not visible in entity debugger?

safe lintel
#

@plain cloak

    [UpdateAfter(typeof(LegacyBoxColliderConversionSystem))]
    [UpdateAfter(typeof(LegacyCapsuleColliderConversionSystem))]
    [UpdateAfter(typeof(LegacySphereColliderConversionSystem))]
    [UpdateAfter(typeof(LegacyMeshColliderConversionSystem))]
    [UpdateAfter(typeof(PhysicsShapeConversionSystem))]
    [UpdateAfter(typeof(LegacyRigidbodyConversionSystem))]
    public class PhysicsAdditionalConversionSystem : GameObjectConversionSystem
    {
        protected override void OnUpdate()
        {
                Entities.ForEach((RemoveVelocity removeVelocity) =>
                {
                    var entity = GetPrimaryEntity(removeVelocity.gameObject);
                    DstEntityManager.RemoveComponent<PhysicsVelocity>(entity);
                }
            );
        }
    }

RemoveVelocity is just an empty monobehaviour. someone mentioned a better way which was I think to set the entity to an archetype but I never tried it personally

#

@stuck hatch does your system not have entities to process? it wont show up if so

stuck hatch
#

I have disabled one and an entity query which includes disabled

#

I also use World CreateSystem and I see the debugger runs into OnCreate but no OnUpdate

plain cloak
#

@safe lintel i see, it would have been better if i could just disable it but i guess this works too. thanks

stuck hatch
#

if I use GetEntityQuery in a system, is it correct that this defines a scope for the system?

safe lintel
#

i think its also tied to whatever job that system also schedules

stuck hatch
#

For some reason EntityQueryOptions.IncludeDisabled does not work, I tried with entityMgr.SetEnabled(entity, false) and entityMgr.AddComponentData(entity, new Disabled()); not both together, the query could not find the entity, now I am using EntityQueryOptions.IncludePrefab, with Prefab Component, that works

rare umbra
#

hey guys, I posted this the other day but I'm still not able to figure out what's up.

I have 2 systems:

Vendor Transaction - Finds transactions, deducts currency from wallet component for the transaction then adds a Dead Entity component
Dead Entity Cleanup - Finds Dead Entity component entities and deletes them

When I run the code with 2 entities that have transaction components I get the following happen in sequence:
Add dead entity component to entity 1
Add dead entity component to entity 2
Add dead entity component to entity 1
Add dead entity component to entity 2
Delete entity 1
Delete entity 2

#

followed by exception: DeadComponent has already been added to the entity

#

wondering if anyone can help me? Sounds like the the request to add the component via a buffer is happening twice before the actual buffer runs, perhaps?

plain cloak
#

you should exclude DeadComponent from your PurchaseQuery

#

or

#

run the dead entity cleanup some time after end simulation barrier

#

@rare umbra the problem is when vendor transaction runs you add the entity at end simulation barrier and dead entity system misses the query for the current frame. When next frame comes dead entity system queues destroy command for end simulation barrier again so vendor transaction runs again since vendor transaction component is still there. And you get 2 destroy requests for the same entity which causes the error

#

another solution is not using command buffer for destroying the entities and doing in at initialization system group or something using EntityManager batched operations. This should also be more efficient

rare umbra
#

@plain cloak

you should exclude DeadComponent from your PurchaseQuery

I’ll probably do this, sounds pretty straightforward, thanks!

Or run the dead entity cleanup some time after end simulation barrier

Not sure how to do this tbh but I would like to know for the future. I tried having each of those systems run barriers in different steps but didn’t have much luck. Any particular examples you’d recommend trying?

tawdry tree
#

[UpdateAfter(EndSimulationBarrier)] Or something like that.
In this case, it sounds like you want to put it on the system that does dead entity cleanup

rare umbra
#

I’ll try that too, thanks! Won’t be in front of my PC until tonight but will let you know how it goes

#

I’ll try both but I’d rather the second fix because the frame delay is unwanted

plain cloak
#

@rare umbra i had the same problem before and what i do is, I run DestroyDeadEntity system at InitializationSystemGroup and I use entityManager instead of command buffers. You could also use EndInitializationCommandBufferSystem aswell though.

rare umbra
#

I think I tried to use entityManager but the compiler didn’t like it. Like it wasn’t in scope or something

#

Does entityManager need to be passed into the job?

safe lintel
#

you can only use entitymanager on the mainthread

#

but unlike the commandbuffers, you can pass in nativearrays or queries to create or destroy entities

rare umbra
#

I’m finding that systems are a little hard to fathom if you’re not that familiar with threading / jobs

mystic mountain
#

I have this "maybe" problem that I have a NativeMap of an ID to entity. This entity will undergo some loading of data, and can be requested to be created by multiple entities same frame, hence I want to add it to the map to be able to check if it's created in a single threaded way. So.. to the problem is that using buffers to delay will not give me the final entityID when used, so I can't add it directly to the map, is there a way to manually remap this to the correct one at the same sync point?

onyx mist
#

I'd love to know this too. Deferred entities are killing my brain cells

mystic mountain
#

Hmm, I think my specific problem can be solved by simply adding a tag to the created entity to add itself to the map funny enough.

onyx mist
#

Yup that's the workaround I ended up going with in mine

onyx mist
#

is there no way to add a dynamic buffer to a deferred entity like how i want to do so here

#

usually id have it so a separate job runs on the children that makes them add themselves onto the parent but this is a special case where doing that would result in a lot more work

safe lintel
#

is childrenBuffer meant to be a buffer on the child entity from the command buffer?

#

oh wait never mind read the code again πŸ˜›

mystic mountain
#

Don't know a way to do that no

safe lintel
#

ok so I think to get around this you need to make another entity that acts as an event, with a component that stores the child you are creating and the entity with the buffer you want to add the child to.

#

and then another job or system that processes that event entity

onyx mist
#

oh wow i never considered using an event entity

#

thanks baron!

safe lintel
#

time for bed, i hope to wake up to a plethora of new dots packages! πŸ˜‰

mystic mountain
#

I don't see how much different an event entity would make over leaving a Component (to add itself) on child though.

stiff skiff
#

The component will cause 2+ Archetype changes. The event entity will only cause 1.

mystic mountain
#

So how is 1 entity creation and destruction vs 1 additional archetype change?

#

I don't see where the event creates an archetype change though, since you add to existing buffer. Similarly component on entity to add itself would already exist in archetype, only a set required, so only 1 archetype change on removal, which can be done on query.

golden heron
#

anyone got experience using unity.physics?

#

im trying to figure out the best procedure for creating complex compound collider bodies that can have their colliders changed.

amber flicker
slow epoch
#

Wow what

#

How is hd more important than universal since universal is more needed

#

I suppose they need to improve hdrp to "sell better" unity

civic bay
#

I have a GameObject that I convert into an entity, it has a Physics Shape and Body script attached and I added a NonUniformScale to it when I instantiate the entity, but how can I change the size of the Physics Shape? It's too big for the now scaled down entity

amber flicker
#

Afaik physics colliders can’t scale at runtime

golden heron
#

@amber flicker you know the best way to create physics bodies at runtime?

amber flicker
#

sorry, not actually done anything with Unity.Physics yet - just remember reading some related forum posts

golden heron
#

Hehe same, is all kinda contradictory tho

amber flicker
#

still v early days.. I'm an early adopter but I think I'll still be avoiding it for the foreseeable..

dull copper
#

I totally agree with Unity on focusing first to HDRP on Hybrid Renderer

#

actually wrote a post on that thread too now

#

I mean, I'd agree if they did it first for URP as well

#

but it does make a lot of sense trying to tackle it first for one system rather than trying to solve everything at once

#

this is what they do with DOTS anyway already, build systems iteratively

#

and they are slowly getting dots ecosystem expanded

amber flicker
#

just feels a little contradictory to all the talk of perf by default, dots on mobile - megacity on mob etc... like, I get it. They have finite resource. Still.. 'starting to look mid next year' means another year before use. I'm also quite anxious about how divergent hdrp & urp are and when built-in will suffer from not being developed.. but that's a more tangential concern.

dull copper
#

well

#

right now

#

if you pick latest versions

#

hybrid renderer doesn't work with anything properly

#

so wanting it to work with everything is bit of a stretch

#

I mean, people can want things, but there are realities to face here

#

they also have their reasons for doing it hdrp first vs urp first, but we wouldn't know it

#

in past they used to do lwrp support first simply because it was simpler to play around with

amber flicker
#

As for me, I'm just disappointed that a) the RPs are fundamentally very divergent (not talking full support, just basics working), b) it will consequently take a long time before anyone can use dots on mobile and c) this is the first we're hearing of it.... but disapointment != disagreeing with their decision

slow epoch
#

I feel like the current state of Unity is really confusing and frustrating for a lot of devs since they see all of those videos talking about DOTS being the future and all the cool things you can do with it but they end up in a in-between state of not being able of using old stuff because it doesn't work with DOTS but DOTS not working because most of it is not ready yet

dull copper
#

yeah I guess they could be more transparent on the future predictions

slow epoch
#

And you end up throwing away DOTS, having to implement a lot of basic stuff by yourself or just wait nonexistent release dates for your issue to get fixed

dull copper
#

if you follow up the dev more closely, it's pretty clear most of the DOTS ecosystem will not be complete in few years

slow epoch
#

Yeah but that's not what they say in all the talks they do

dull copper
#

even then, people expected to have fully functional ECS editor by now

#

they do say these things are going to previews when they promo them, so it's not like they lie to users

slow epoch
#

Well URP or LWRP is out of preview right now isn't?

dull copper
#

LWRP is out of preview, URP isn't released yet officially

#

it's kinda weird setup

#

URP is technically out when 2019.3 releases

slow epoch
#

Also ECS is gonna be out of preview technically in 2020.1 but since Physics for example is a different thing, we don't know if that's gonna be out of preview as well

#

Yeah but URP and LWRP is the same

#

Or i'm missing something

dull copper
#

a lot has changed

#

like URP now has dedicated post processing

#

of course the core of it is still the same

#

but there are big changes still

slow epoch
#

Well that's what i mean about confusing then

dull copper
#

Entities "core" is out of preview first

#

it's not same with the whole DOTS ecosystem

#

you should totally expect dots packages still be in preview or experimental state when the entities package releases

#

I wouldn't even expect hybrid renderer to be production ready with hdrp by then

#

more like at the summer earliest

#

also would totally expect them to slip from the last roadmap estimates :p

slow epoch
#

Yeah but my main concern is how they prioritize the different packages and the decisions they make, i mean is not wrong to make the decisions they are making since a lot of stuff is still in a very early version but, as i said, they show it to us as "look at this shiny new thing we have that you can use" and people go ahead and try to make real games with something that's not ready yet

#

The problem comes from devs for being missinformed but i feel like unity could express better the fact that all of this is still an early version a lot of can change

#

And if you want to make stuff with it you should expect redoing the same thing multiple times because the API has changed or the workflow has been modified

amber flicker
#

I mean.. we're all battling with similar things so I hear what you're saying @slow epoch however honestly I think most devs dabbling in this stuff do know it's preview and what that can mean. I think @dull copper may feel that a lot of us are impatient about it all despite that - which I'd agree with. DOTS is clearly a huge undertaking. I also agree that it's pretty confusing right now. Even if you're very up to date with the state of everything in Unity (which is hard), choosing what technologies to use right now is actually very hard. Do I start a new mobile project using URP? Gotta think pretty darn hard I'd say. I guess we can all agree that the direction they're going is quite promising overall but the next few years are likely to be pretty tricky to navigate.

civic bay
#

It's crazy how different DOTS is, I feel so dumb asking for help for what sound like extremely basic things, such as how to change the scale of an entity. It's so alien to me. I feel like a beginner all over again

#

Speaking of, how can I set the parent of an entity to a GameObject in the scene so when I move it, the entities move with it? Is that even possible?

hollow scroll
#

@civic bay there is the Parent component (if your gameobject already have a child and converttoentity component this parent component is added automatically), but it's basically a parent component with the Entity ID set to the parent

civic bay
#

Whenever I add the Parent component my entities just don't even show anymore

#

Even though the entity debugger they're spawning in

#

Nevermind they're under the map

hollow scroll
#

if you are creating a prefab with ConvertToEntity you don't need to add the parent component

#

manually adding that is only necessary if you are parenting during runtime

trail burrow
#

Using any of the new stuff (ecs, burst, srp, etc) for a game that actually needs a launch date and be economically viable is a huge mistake atm

hollow scroll
#

doing that here πŸ˜›

dull copper
#

I don't feel like SRPs present as big of a risk

#

going all in with DOTS however...

trail burrow
#

All my tests of urp/hdrp have ended in "oh so this is still broken, ah well"

#

Every single time

civic bay
#

@hollow scroll I'm basically spawning in a bunch of entities from the sky, and when they hit the floor I remove the physics components frmo it so they don't keep updating

#

But I need to parent them to the floor, because the floor moves

#

So I need the entities to move with the floor

hollow scroll
#

@civic bay ah ok.. so adding parent component in that case is ok

civic bay
#

Am I going about it the right way by adding the parent upon Instantiating the entity, but set the parent after I remove the physics components?

#

Or adding the component and setting it actually

#

At that time

#

Because it doesn't have a parent while it's falling

hollow scroll
#

@civic bay you can add the parent component when you remove the the phsycis component that it's when you mention that needs to be parent to the ground

dull copper
#

in my experience, if we count hybrid issues out, main things causing people pain with SRPs are just feats that are missing or don't have 3rd party asset to implement something, sure there are still tons of bugs but it's not like the built-in renderer didn't have those too

civic bay
#

But how can I get a reference to the Floor Entity in that ComponentSystem?

dull copper
#

hdrp is more all around package tho, you shouldn't miss that many feats with it

trail burrow
#

@dull copper no, just stuff being broken, crashing, etc.

#

i would not say either urp or hdrp are production ready from my tests, its very easy to brake both of them

hollow scroll
#

@civic bay you can have another query in the jobsystem that gets the ground entities, and then get the entity from that query in a job or however you prefer, and use that for the job that adds the parent component to the entities touching the ground

dull copper
#

if talking about individual feats, I feel like shader graph itself is most fragile thing

#

then srp batcher comes next

trail burrow
#

and thats not even counting platform specific issues i have not even bothered trying to examine, if it doesn't work flawlessly on windows, then im not even gonna attempt to run it on switch/ps4/xbox/android/ios

dull copper
#

most things breaking for me has usually been either one

civic bay
#

@hollow scroll Thank you for your help, much appreciated πŸ™‚

trail burrow
#

@dull copper i mean unity is betting everything on dots, we'll see if it pays of in 2022 πŸ˜„

dull copper
#

or 2025

#

because if they say it's ready in 2022, we all know it will not

trail burrow
#

lol

dull copper
#

but it's still good to have targets

trail burrow
#

getting jaded? πŸ˜„

dull copper
#

because with 2025 target they'd just slip further away

#

I mean, anyone who's followed Unity's scheduling and estimates know it's true.. but they usually get there eventually

#

I don't think they planned ECS core to take this long either

trail burrow
#

my main... woudn't call it worry.. but issue/concern with all this is that the old system (GO/MB) basically seems abandoned internally at Unity, but anyone that wants to build a real game today still has to use it... but they don't seem to be updating anything relating to that anymore at all.... is this gonna go on for 2-3 years now?

dull copper
#

anyway, this is why I'm not pissed at all at Unity for not shipping production ready packages next year for all dots feats

#

because it's just not realistic at all

#

well, technically the old system has been there for what, 14 years?

#

like, it's still going to keep working

#

they updated mono, c# and made incremental GC

#

those were the biggest wins for it

#

I don't really see point on trying to implement new stuff for the old setup at this point at all

#

would rather see them putting those resources on dots

#

obviously they will not let the old monobehaviors completely break either before they get dots done

trail burrow
#

Yeah but you are not trying to build a game and ship? There's tons of shit that just issues going on get fixed it seems, because dots.

dull copper
#

I am but not focusing with dots with it

#

like, there's no realistic hope on getting hybrid rendering done in time for me

#

and frankly, I don't even care about that before you get rest of the dots systems fully functional, maybe for some upcoming projects then...

languid stirrup
#

anyone know what does this NativeFixedLengthAttribute class do?

#

Nvm. Got it to work. But still doesn’t make it blittable lol

civic bay
#

Is there a way to get the entity ref from ConvertToEntity.ConvertAndInjectOriginal(gameObject);

hollow scroll
civic bay
#

Jesus christ, after 3 days of trying to understand ECS, it finally clicked

#

It's like trying to ride an inverse bike

onyx mist
#

Congrats!

safe lintel
#

and soon the old way will feel like the inverse bike πŸ™‚

slow epoch
#

"soon"

main glen
#

anyone started a multiplayer project with dots around ?

dull copper
#

most are probably waiting for the new packages still πŸ˜„

hollow sorrel
#

waiting for the bike update

left oak
#

i'm just like, trying to make awssdk play nice with dots 😩

safe lintel
#

its enough of a struggle just doing singleplayer πŸ˜„

mystic mountain
#

@main glen yes

winter veldt
#

hey all

#

question: is there a specific build recommended to play with a stable(ish) release of DOTS? i know when it was ecs it seemed to break every update.

deft niche
#

0.1.1 version of entities package with 2019.2.12f1 is as stable as it can be.

winter veldt
#

so sticking to 2019.2? i did install the latest 2020 beta and had menu's and items and stuff i hadn't seen before. is there anywhere with actual documentation you can follow? every tut or article i find on the net seems to be from some obscure build.

deft niche
#

2020 is not really stable.. its in alpha. 2019.3 is also in beta. 2019.2 is the latest stable version

#

Should probably wait for the new package to come out if you are just getting started

#

The APIs and workflow is going to change with the new update so its going to mess you up again with the old tutorials! πŸ˜„

winter veldt
#

that's exactly what's been going on. i figured with the supposed stable release set for what? 2020.1 release? they would at least have solidified their workflow somewhat

deft niche
#

Thats a tentative date. nothing is set in stone yet.

#

enjoy the preview packages for now πŸ™‚

winter veldt
#

yeah just assuming they'd have an idea what the finishline is looking like when they mention it. but no bother. I was looking at the DOTS-training-samples and giving them a shot, but if i have no real place to start... I don't know enough about ECS to try to blindly work it out

golden heron
#

@amber flicker @slow epoch the ecs systems are useable on mobile now. There are a few aspects which require some imagination, but even if you just have gameobject puppets following your entities around, it improves calculation speeds.

#

I .... actually dont need a renderer on my main ecs systems tho hehe

winter veldt
#

@golden heron what do you use ecs for? ai stuff? that's the type of thing i'm interested in

golden heron
#

Well, first ill show an old video.

#

This is messy, from literally my first few weeks in unity.

#

Each of those white dots is a solar system. That will be simulated on a central server, whilst players receive data and react in their own small spaces.

amber flicker
#

@golden heron sure, there are lots of things dots can be useful for... just a shame if it doesn't cover rendering. Also unsure if dots animation package will require hybrid renderer? Animators are sometimes the bottleneck for me and would like to be able to use the dots version.

golden heron
#

Yeah, everything would be better in dots hehe

#

But, im finding that people have... kinda missed another aspect of how to use ecs.

winter veldt
#

yesssss! that's the stuff i like to see! backend simulations are where my mind jumps with ecs.

golden heron
#

All the consideration of huge numbers of entities catches attention, when people could be instead creating a smaller number of complex multiple entity objects to make the game with.

winter veldt
#

i've always been interested in trying to do world sim in the background while just rendering what's going on in the player's area... stopping the "the world is frozen, unless the player is interacting with it" most games have

golden heron
#

Yeah, my game is intended to be a realtime universe simulation which is always ticking over irrelevant of players.

#

It'll respond to players, if trade economy is affected for example, but generally most of the systems will be in a data only mode, updating less frequently with minimal information, whilst the physics and collisions will only be considered in player systems.

#

There is another aspect of large number of entity management people forget - if you update every entity per frame, you hit your limit real quick, but if you only update your entities every other frame, and stagger them, you can almost double your ftotal entity scope.

#

Now, imagine the scope of a game which updates its background entities once every 5 seconds?

winter veldt
#

yes! are you finding it plausible to handle that much data? can you essentially do limitless number of entities just by increasing that delay?

golden heron
#

Well no, there is still the limit between memory available and a little overhead for the staggering, but you definitely can achieve a similar increase in useage numbers as you get from pooling in standard unity

#

I found i could run a million entities at about 25fps on my old dual core 2.2ghz - old one too, core 2 duo i think

untold night
#

Cross-post from the forums:

Hydrogen.Entities update:
After some work and life induced delays, I have made some samples and scene setups outside of the testing environments. These samples are based on the various requests people made and each has it's own readme file that goes over the different parts of the samples:

https://github.com/periodyctom/Hydrogen.Entities/releases/tag/0.2.0-preview.3

Also bug fixes and some optimizations/minor enhancements.

#

feedback appreciated

golden heron
#

@untold night have you used unity.physics much?

untold night
#

Part of my push for getting this done was to play with Physics more

winter veldt
#

nice. that's still a lot. i was assuming i'd have to generalize things from individual units to say overall faction status when out of a specific range of the player... but sounds like it could be an increasingly large radius if i lower the update ticks

golden heron
#

Hehe well im having trouble getting an adaptable physics body working, i need to add/remove colliders or recalculate compound colliders at runtime and it doesnt seem easy atm.

#

@winter veldt mind if i send a dm? I just finished a mk1 design you might appreciate.

untold night
#

I believe they're working on an API for altering colliders at runtime but I don't know what the timeframe for that is

golden heron
#

Well i guess its rebuilding afresh for now then hehe

untold night
#

with the latest DOTS packages you can at least rebuild in a burst job

golden heron
#

fortunately it can be a change which happens instantly

winter veldt
#

@golden heron for sure!

golden heron
#

@untold night could you outline what kinda helpers are in your "Hydrogen" api?

untold night
#

There's a lot in the documentation and now in the samples, but heres a quick run-down:

  • A pipeline for Converting ScriptableObjects to DOTS Blob Assets, running on the back of the Game Object Conversion pipeline
  • A pipeline for loading Singleton ECS data components from files or scenes, originally for converting config data to make it usable in jobs/component systems.
  • A pipeline built on top of the other two that helps you convert ScriptableObject singleton data (as there's quite a few people who use the SO as a manager/singleton pattern) and migrating that data to ECS. Which handles a lot of the memory management and boilerplate for you.
  • full test coverage of the above.
prime cipher
#

If I created a subscene, how would I be able to instantiate it in a script? Using it as a template for creating lots of similar entities, editable as a subscene.

untold night
#
golden heron
#

Nice, thanks dude

#

have you explored multiple worlds?

hollow sorrel
#

#nasa

untold night
#

I've not messed with multiple worlds since the earlier dots days. This currently works with the default live world and conversion world stuff.

deft niche
#

anyone has any idea on the latest update on entities package ?

rare umbra
#

dumb question - how do I get the entity from a component? My job is using NativeArray<PurchaseRequestComponent> but because I want to add a component to the same entity I need to grab the entity reference

#
        {
            for (int i = 0; i < PurchaseRequests.Length; i++)
            {
                var purchaseRequest = PurchaseRequests[i];

               //Need to reference the entity that purchaseRequest is attached to ```
untold night
#

is this an IJob?

rare umbra
#

yup

untold night
#

how are you passing the component data to the Job in the first place? Are you using EntityManager or System Queries?

#

or are you operating with Chunks on the System level then passing to IJobs?

rare umbra
#
        {
         All = new ComponentType[] { typeof(PurchaseRequestComponent),}
        });```
#

Not sure if this is the best way, just the way I'm currently doing it

untold night
#

why aren't you using IJobForeachWithEntity<...> which probably fits your problem better.

Although you can get a copy of the entity array out of a query

rare umbra
#

I'm using it in another system, not sure why I'm not here

#

lemme convert it over

#

Would it have any impact on the other data I'm trying to grab?

        public ComponentDataFromEntity<VendorOfferComponent> VendorOfferComponents;```
untold night
#

Probably not, as long as you're not writing the same entities you're reading from concurrently with another job.

if you really need to do it in an IJob for some reason, you can use ToEntityArray:

https://docs.unity3d.com/Packages/com.unity.entities@0.0/api/Unity.Entities.EntityQuery.html?q=EntityQuery#Unity_Entities_EntityQuery_ToEntityArray_Allocator_JobHandle__

Which has both a main thread version and a version that collects the entities from the query on a thread you can then pass as a dependency to your job.

rare umbra
#

bah, can't seem to fathom what I'm missing in the OnUpdate having switched over to IJobForEachWithEntity

untold night
#

can you show your job signature and Execute function?

rare umbra
#

sure, 2 secs

#

InvalidOperationException: VendorTransactionJob.Data.WalletComponents is not declared [ReadOnly] in a IJobParallelFor job. The container does not support parallel writing. Please use a more suitable container type.

untold night
#

you declare two of the job, assign the fields of one of them, then launch a blank one

#

you also need to add [ReadOnly] before the ref PurchaseRequestComponent purchaseRequest

So it should look like this:

public void Execute(Entity entity, int jobIndex, [ReadOnly] ref PurchaseRequestComponent purchaseRequest)

rare umbra
#

so I tried to assign the fields to the second job (first one is legacy) but couldn't find the correct syntax for the assignations within the new VendorTransaction declaration

untold night
#

as an additional optimization/change, you can schedule the Job by passing the PurchaseQuery as the parameter to the schedule instead of the system this, it will then use a hotpath to operate on the query data

#

make sure you're using the [ReadOnly] attribute from Unity.Collections and not the one from one of the System namespaces

#

did that help?

rare umbra
#

2 secs

untold night
#

I see what the problem is

WalletComponents needs to have the attribute [DisableParalellForRestriction] assuming no other threads can access it at the same time, since you're writing to it.

You can also mark VenderOfferComponents as [ReadOnly] as well

#

you don't need to mark CommandBuffer.Concurrent as [WriteOnly] either

rare umbra
#

I can only use
[NativeDisableParallelForRestriction]
Is that the one? the other one is throwing a compile error

#

well that works now, yay

#

can I get rid of the PurchaseQuery now that the component type is specified in the IJobForEachWithEntity?

untold night
#

you can if you don't need the query for any other filtering, such as excluding components or the any/none fields.

What will happen is the query will get created in the background the first time you schedule the job with the system and will then use the cached Query when you schedule it every time after

rare umbra
#

cool thanks!

#

seems to be working nicely

#

thanks for the help @untold night

orchid yoke
#

Is it possible to access entities in a JobComponentSystem, im trying to loop through a set before starting the job but cant seem to access the entities in the OnUpdate? I tried creating a new EntityQueryBuilder but that caused a null reference.

#
        new EntityQueryBuilder().WithAll<Comp>().ForEach((Entity entity, ref Comp comp) => {
            data.Add(comp.Value);
        });
hollow sorrel
#

i dunno about the entityquery way but you can use IJobForEachWithEntity instead of IJobForEach and pass in Entity as first param to the Execute

orchid yoke
#

I got the Job the way I want it, I just want to populate a readonly list prior to the job executing.

prime cipher
#

What would be the way to create shaders for a material used in RenderMesh component? From the default URP shaders, some work, some show just a flat pink. I created a simple shader (basically only color to albedo on master node) in shader graph, which results also in flat pink

orchid yoke
#

Figured it out, IJobComponent has GetEntityQuery so when I used that it worked better!

craggy orbit
#

@prime cipher i recently found out that PBR materials don't work with DOTS yet. you have to use Unlit shaders for now.

prime cipher
#

@craggy orbit yes, creating an unlit shader graph asset works. Thx. So no lit shaders, no particles -> no real effects in DOTS 😦

craggy orbit
#

yeah. definitely a bummer. but we're anticipating the next DOTS release sometime this month, or so i've heard. that might bring support

magic frigate
#

Is .2 coming with the DOTS fps sample? I forget

mystic mountain
#

Ugh, why is InitializationGroup not bound on same loop as Simulation x)

stiff skiff
#

Same loop?

mystic mountain
#

Yeah. It's run 1:1 with PresentationGroup.

remote coyote
#

That's good to know

dull copper
#

@magic frigate you mean the 0.2 entities or 2019.2?

#

all in all, would expect next packages to launch along with the fps sample as they've only given estimate for the fps sample and it relies on all these packages

#

and it'll be 2019.3 compatible

civic bay
#

Is it possible to instantiate an entity inside a Job?

trail burrow
#

only indirectly

#

via entity command buffer

civic bay
#

@trail burrow How can I go about that?

mystic mountain
#

@civic bay Create a commandBuffer from a CommandBufferSystem which acts as a barrier/sync point at different points in your gameloop. The usual way is to use this system as a private varaible in your system, note the system and not the commandBuffer - it needs to be created each "frame" it's used. Use in in the system "as" you would use EntityManager. If using paralell jobs, you want to use EntityCommandBuffer.Concurrent, simply .ToConcurrent(), on your buffer when passed into Job. After you've scheduled your job you have to add a dependency of the job to the commandBufferSystem (so it knows it is completed) do calling AddJobHandleForProducer.

slow epoch
#

At which point in the gameloop are all the jobs completed?

#

At certain points like CommandBuffers, at the end of the frame?

mystic mountain
#
Executing the commands in an EntityCommandBuffer invokes the corresponding functions of the EntityManager. Any structural change, such as adding or removing entities, adding or removing components from entities, or changing shared component values, creates a sync-point in your application. At a sync point, all Jobs accessing entity components must complete before new Jobs can start. Such sync points make it difficult for the Job scheduler to fully utilize available computing power. To avoid sync points, you should use as few entity command buffer systems as possible.
safe lintel
#

@slow epoch a job finishes when it completes its work or if you call .Complete();, theres not a hard set time compared to barriers

mystic mountain
#

But if you have a Destro/Create/AddComponent/RemoveComponent in your barrier all jobs will complete?

slow epoch
#

Then a job can end up completed 2 o 3 frames after scheduling it if nobody told it to be completed?

safe lintel
#

you know thats a good question

slow epoch
#

Or whatever times it takes

#

I'm talking here in ECS

#

If you use JobComponentSystem

mystic mountain
#

And if it doesn't require a Complete if it only uses SetComponent, then how does it know the dependency between jobs using that component so it have to wait for them to complete until it can set component.. hmmpf.

slow epoch
#

I though there was some kind of point where all jobs were completed because certain jobs that don't have any kind of dependencies but can take a huge amount of time don't have a determined end point

safe lintel
#

maybe the commandbuffer is skipped a frame if the job takes a particularly long amount of time? this would be good to test out

mystic mountain
#

I would imagine there is a Complete at the start/end of each gameloop to start next for the JobComponentSystem jobs.

safe lintel
#

i think multiframe jobs should be supported, i do recall reading that there were issues a long time ago regarding them(leak issues) but this was back during times of using Inject to get queries so assuming thats not the case now

slow epoch
#

Would it be at the end or the start of each frame/gameloop?

mystic mountain
#

Yeah, I don't know. At some point the main thread is used for jobs as well? I've no idea where that is either πŸ˜›

slow epoch
#

I'm curious about the approach to this since i've stumbled with similar problems in the past working with only jobs

#

Not having a clear idea if they need to be completed at the end or at the beginning of the frame

#

Well, it's more like "what is the best" but i suppose as always it depends

calm dock
mystic mountain
#

I usually don't think about it, since data/entities that are dependent on each-other will sort itself out.

calm dock
#

Can ECS can save me from that latence ?

#

When NavMeshAgent

#

try to go to other side

#

They have path one by one

#

I want them all react fast like at start of video

slow epoch
#

That's because the pathfinding is async

#

You can use CalculatePath so it's calculated in the same frame

calm dock
#

same mate

slow epoch
#

CalculatePath + setting the resulting path is the same?

#

Right now there are not a lot of options for pathfinding with ecs besides NavMeshQueries which are incomplete at the moment

#

Unity said pathfinding will come for the next year

calm dock
#

I think you are right...

#

Do you think using simple job can make it faster ?

slow epoch
#

You can't use the current NavMesh inside jobs

#

Also you can change NavMesh.pathfindingIterationsPerFrame to your needs

#

I think is maxed at 500

safe lintel
#

minor correction in that they said they would start work on navigation next year, who knows when a useable package will be released

calm dock
#

Ty @slow epoch I will try

mystic mountain
#

If I have multiple GetEntityQuery calls in my OnCreate of JobComponentSystem, what decides if the System runs it's update or not? Do the queries && , || or always update when multiple?

trail burrow
#

|| afaik

mystic mountain
#

Hmm, so I'll have to manually check IsEmptyIgnoreFilter or is it better to let the systems setup "empty"?

#

that looks like &&

#

Oh, so it doesn't add to the m_RequiredEntityQueries

#

Ok, but still use GetEntityQuery to create them I guess?

safe lintel
#

how do jobs complete in relation to command buffers? if a job takes x frames to finish, I assume it can potentially skip the barrier x times too?

trail burrow
#

@safe lintel the barrier will call .Complete() on the job handle afaik

mystic mountain
#

It calls Complete on all handles you've added to the AddJobHandleForProducer at least.

hollow sorrel
#

i think jobs from componentsystems will always be completed next frame, only jobs that are started outside ecs can run multiple frames

worldly pulsar
#

@safe lintel depends on how you .Complete() the job. If you added its handle to the return value of a JobComponentSystem.Update() the job will be Completed by the next sync point (either barrier or mainthread ComponentSystem, or EntityManager operation).
If you want to have a job run over multiple frames you have to manage its handle on your own so it finishes when you Complete() it manually, barriers have nothing to say in this case (but the safety system will kick in if you do something icky)

mystic mountain
#

@worldly pulsar Do you know where the handle is passed to the Barrier then from the JobComponentSystem?

#
    public abstract class JobComponentSystem : ComponentSystemBase
    {
        JobHandle m_PreviousFrameDependency;

        JobHandle BeforeOnUpdate()
        {
            BeforeUpdateVersioning();

            // We need to wait on all previous frame dependencies, otherwise it is possible that we create infinitely long dependency chains
            // without anyone ever waiting on it
            m_PreviousFrameDependency.Complete();

            return GetDependency();
        }

interesting...

#

So basically each system loops around it's dependency to be completed next frame.

hollow sorrel
#

oh? does that mean that if your jobcomponentsystem runs late in the frame, it'll complete() late in the next frame as well?
thought it might complete all running jobs at the start of a frame somewhere

mystic mountain
#

I don't fully get it though, shouldn't all systems be dependent on previous barrier since it can change the structure etc?

worldly pulsar
#

@mystic mountain pretty sure this is just a failsafe, there is a "complete all JobComponentSystem handles" method somewhere, but I don't remember where

#

for EntityManager operations this would be EntityManager.CompleteAllJobs() (which is called from BeforeStructuralChange() )

mystic mountain
#

But what is the point of AddJobHandleForProducer, if we still need to complete all jobs?
(edit) nvm, ofc we need to know we got all buffers..

#

But then again, we could still complete all..

worldly pulsar
#

I'm a bit rusty on this part of the code, but if I remember correctly the CompleteAllJobs() only completes jobs returned from JobComponentSystem.Update(), so if you schedule something and don't return it from Update() (like, you have a job writing to an ECB and you want that ECB to complete at some specific barrier) you need to AddJobHandleForProducer

#

I need to read what exactly happens to the handle returned from Update(), it was always a bit magical for me to be honest

mystic mountain
#

The only thing I can find is that it does this after it's update with the handle

        unsafe void AddDependencyInternal(JobHandle dependency)
        {
            m_PreviousFrameDependency = m_SafetyManager->AddDependency(m_JobDependencyForReadingSystems.Ptr, m_JobDependencyForReadingSystems.Length, m_JobDependencyForWritingSystems.Ptr, m_JobDependencyForWritingSystems.Length, dependency);
        }
worldly pulsar
#

and that AddDependency inserts the jobhandle into all the related type Read/WriteFences. EntityManager.CompleteAllJobs (which is called by the EntityCommandBuffer.Playback()) goes through all Read/WriteFences and completes them

rare umbra
#

Any news on the release @digital scarab ?

stiff skiff
#

My safe bet now is 13th of december >_< The 2018.3 release date from last year

onyx mist
#

no

#

I veto this idea

raven badger
#

Seconded

onyx mist
#

how do i set the component of a value within an icomp within an icomp? ala
commandBuffer.SetComponent(index, baby2, new Parents { Mother = entity });
https://puu.sh/EGARd/bb6af459ee.png

#

i get this error upon attempting this

#

managed to get around it by doing this!

#

not sure if its optimal but hey

#

ok new question regarding the same "Family" compdata. While parents is a compdata, the others are buffers. How do I access these internal buffers? https://puu.sh/EGBdV/a6358d1c04.png Using this creates an error on the first line.
ArgumentException: A component with type:Children [B] has not been added to the entity.

#

all relevant entities definitely have the family component

#

[NativeDisableParallelForRestriction] public BufferFromEntity<Children> childrenBuffer;

#

and heres the declaration

onyx mist
#

thought i could be slick with this...

languid stirrup
#

so If Entity A and Entity B. and I have A.neighboutEntity = B. Now does my system have 2 entities or a total of 3 entities?

onyx mist
#

if a.[x] is an entity variable than you'd be passing around a reference so the system would be 2 entities

languid stirrup
#

awesome! thnx πŸ™‚

onyx mist
#

np!

hollow jolt
hollow sorrel
#

jobs are multithreaded and can use burstcompile

#

= zoomyfast

hollow jolt
#

is there a benefit for using a job for a single entity ? Like for example there will only be one player that will have one component, system and entity ?

#

@hollow sorrel

magic frigate
#

I guess in that case the issue would be the job overhead vs potential burst savings?

hollow jolt
#

well yes, i wonder were to draw the line

#

like what if i have 10 unique entities

#

would they benefit using the job system ?

#

or rather should i just keep those 10 unique "things" in a classical Mono-Behaviour way ?

magic frigate
#

I have no informed opinion but my best guess is that it depends if they have a nontrivial performance cost or not

hollow jolt
#

@magic frigate how do you organize your scripts ? I was going for something like this.
PlayerFolder:

  • Player_Spawner.cs -- ( entityManager init and set data )
  • Player_Data.cs -- ( ECS : Component )
  • Player_System.cs -- ( ECS : Job Execute )
magic frigate
#

I've mainly been reading sample stuff and trying to learn. Haven't made anything substantial enough to merit organization yet

hollow sorrel
#

@hollow jolt yea there is a cost to scheduling a job, but no idea how much
docs state use non-job systems when The amount of work the system performs is less than the small overhead of creating and scheduling a Job.
but that doesn't give any numbers

rule of thumb i've been following is if something is so insignificant it barely even shows up on profiler (like 0.05ms), i'd put it in a regular componentsystem
simple systems with one entity usually fall under that

summer latch
prime cipher
#

What would be the best practice, if I need to run the same system for different combinations of components, inject the EntityQuery as parameter for the job or create a wrapper system per combo? This is needed, as the same system calculation needs to be parametrized per combo additionally

summer latch
#
  1. create separate systems. 2. create separate jobs that chain @prime cipher
remote coyote
#

Nice nambiar!

#

thanks for sharing

hollow sorrel
#

i feel like i'm i'm missing something

#

can someone tell me why this is causing 136 bytes of GC.Alloc (with leak detection turned off)? deep profile isn't helping either

https://hatebin.com/htimrqdcqd

#

oh and Player here is just an empty component

#

maybe it's normal and i just didn't notice it before, but other systems don't seem to have this

mint iron
languid stirrup
#

Guys. What’s the best way to have a linear fixed length array in an entity. Don’t want a ishared one. Cuz this array might be changing every frame. Also this array will be unique to every entity. I think dynamic buffeted array. But mine will be fixed size so still use dynamic buffer or something better is available?

hollow sorrel
#

ah, putting the float2 in the lambda reduces it to 112 bytes

#

hmm

trail burrow
#

you can stick an public UnsafeArray* MyArray; in a component

#

yes they are done in a C-style API, take it or leave it πŸ˜„

languid stirrup
#

But but it’s unsafe! It says I need unsafe switch to compile it. What are the implications of this unsafe? I will have about 10k if these entities with about 800 array size.

trail burrow
#

implications of unsafe is nothing really

languid stirrup
#

Of int btw.

hollow sorrel
#

@mint iron do you know if there's a way to get rid of the lambda altogether? seems entityquerybuilder isn't usable in regular componentsystems

languid stirrup
#

Really? Will I still get detailed stacktraces for debugging?

hollow sorrel
#

and passing a method to ForEach doesn't seem to work

trail burrow
#

@languid stirrup lol yes

#

i mean if you try to de-reference a null pointer

#

your game will crash ofc

#

especially in burst

#

but yeah if you dont wanna use dynamic buffer

#

u dont have a choice

#

atm

mystic mountain
#

You can also just use unsafe context and fixed array in components e.g.

unsafe struct MyData : IComponentData
{
    public fixed int data[100];
}
languid stirrup
#

Hmmm. Either the whole entity will be disposed. But the array won’t be reassigned it anything. It wil always be accessed via its elements. And burst is cool with unsafe stuff? Does it burst still boost speeds? @trail burrow

trail burrow
#

@mystic mountain the runtime tends to buck and choke quite hard when putting really really large structs on the stack

#

it's the one reason i tend to not use it

#

@languid stirrup the array needs to be free:ed manually

#

yes burst supports unsafe stuff

languid stirrup
#

I don’t have a prob with dynamic buffered if they are fast and burst friendly.

trail burrow
#

@mystic mountain you can for example make mono corrupt the stack if you push enough stuff on the stack

#

making all kinds of fun stuff happen πŸ˜„

mystic mountain
#

I've been there x)

languid stirrup
#

So @trail burrow buffer array good too? I want a suggestion of what is faster with burst. If it’s buffered array I’ll gladly use them.

trail burrow
#

what's a buffered array?

#

you mean dynamic buffer?

languid stirrup
#

Dynamic buffet array. Yes

trail burrow
#

use whatever you want, i have never benchmarked any of them against each other

#

if you need absolute speed just do a public int* MyArray; and public int MyArrayLength; and allocate the memory by hand

#

and burst can work with that yes

languid stirrup
#

Oh. Hmm ok. I might benchmark them then.

#

Yea but pointers are unsafe again. Lol. Thnx for the discussion @trail burrow

trail burrow
#

yes it's 'unsafe', it's completely fine

languid stirrup
#

I will bench and see

trail burrow
#

all of the ECS uses unsafe code internally

languid stirrup
#

Lol ofc. Without pointers u can’t have any proper software :p

mint iron
#

@hollow sorrel modern c# versions should be compiling a lambda that doesn't have external references to a straight method call, they're not as nasty as they used to be. That said, Unity is doing a whole lot of stuff behind the scenes there - https://hatebin.com/akgdzsiujs. You could consider converting your code into a job.

hollow sorrel
#

yea but docs say it's better to put things in ComponentSystem if it's smaller than scheduling job overhead

#

which i imagine would be the case for a 1-entity with just assigning a value

#

also kinda weird if gc alloc in non-job systems is by design

mint iron
#

i vaguely recall i read an official post about in on the forums a while back that they were aware of it and intended to get rid of it before the final version.

#

i've been away for a few weeks, have they released the new entities version from Copenhagen? cause they were supposed to be changing Entities.ForEach to be compiled as a job behind the scenes.

#

also, the ToEntityArray() inside ForEach is already running a job πŸ˜„

coarse turtle
#

Hmm I've no idea if they did

hollow sorrel
#

whaaat

coarse turtle
#

Been gone for a week too

hollow sorrel
#

also no new releases no

#

at this point i wouldn't be surprised if new version is released with 2019.3 stable release

slow epoch
#

This topic made me think, how do you translate an Attribute to an authoring class?

#

How do you compile that?

hollow sorrel
#

@mint iron ComponentSystems run jobs too? dunno why they mentioned using it to avoid job overhead then

mint iron
#

@hollow sorrel one option is to decompose the process used inside ToEntityArray() to have an early out when runnign the job is not nessesary, and copy the data to a persistent array rather than using temp storage. (this is older code that i think needs to be updated but shows the basic idea: https://hatebin.com/mwevdqczdp)

hollow sorrel
coarse turtle
#

Oo I've been wondering about creating a template that can do that

manic elbow
#

any good ECS physics tutorials? I sorted navigation fine (for space game), but rather have actual physics for collision detection then my crazy math that I try to optimize more and more

languid stirrup
#

So wait. For smaller tasks like shifting elements of an array or simple logic on an entity is better to be implemented in ComponentSystem and only stuff on larger array of an entity should be implemented in IJobComponentSystem?

hollow sorrel
#

i caved and turned it into a jobsystem btw, seems no more garbage now

mint iron
#

my interpretation of what they've been suggesting is to start out with Entities.ForEach and focus on getting your game to work; because ForEach mirrors IJobForEach it should be relatively easy to convert to jobs for performance later.

hollow sorrel
#

also went from 0.05ms to 0.03ms which implies it's better even for small stuff but dunno how much of that is editor overhead and profiler accuraccy

onyx mist
#

@trail burrow do those unsafe collections have an option to be stored on the heap like dynamic buffers do? My buffers can get really big and I don't want the stack to explode or anything

trail burrow
#

@onyx mist they are all stored on the heap

#

they work like the regular .NET collections

onyx mist
#

Oh wow that's great!

trail burrow
#

except, only deal with structs/pointers/native mem etc. ofc

onyx mist
#

And they show up in the debugger?

trail burrow
#

debugger?

onyx mist
#

The entity debugger

trail burrow
#

no i doubt they do that

onyx mist
#

Ah oki

glad grail
#

hi, I have a component which has a unique identifier. Something like struct Foo { int uid; } which I use to link DOTS with another system.
Is there a quick way of finding an entity which has a specific uid in the Foo component?

Currently I have this:

protected override void OnUpdate() {
    Entities.WithAllReadOnly<Selectable>().ForEach((Entity e, ref Foo f) => {
        if (f.uid == targetUid) {
            // do stuff

Seems like there might be a better way?

#

Maybe I should keep an external dictionary of uid->Entity ?

left oak
#

if you're finding them one at a time, a nativehashmap would do, @glad grail

pliant pike
#

what's the best way to compare a float3 to another float3 in a job?

worldly pulsar
#

f1.Equals(f2) or math.all(f1 == f2). Burst should produce the same code for both.

pliant pike
#

thanks @worldly pulsar finding this stuff in the docs is kind of difficult

worldly pulsar
#

at this point source code is better than docs tbh

pliant pike
#

yeah except I'm no good at reading the source code

languid stirrup
#

@worldly pulsar what about float3 == float3 ?

#

Or do I have to do math.all?

pliant pike
#

yeah that does not work, well it doesn't work in a if, it returns a bool3

languid stirrup
#

Oh.......

#

That somehow makes sense

dusty scarab
#

Quick question. I understood the CodeMonkey tutorials on ECS. Can someone give me a basic idea of a project I should try and develop using ECS?

tawdry tree
#

Counterquestion: Do you want to develop a project in ECS?

#

If so, I'd suggest something mechanically simple, like tower defense or simpler. Most arcade games (asteroids and such) would fit, too

dusty scarab
#

Yes! I'm trying to familiarise myself with this, so i assume learning it on a basic poject would be the best way to go

safe lintel
#

could recreate a demo unity project, so its less about coming up with new ideas and more about translating work to using ecs+jobs

worldly pulsar
tawdry tree
#

Then my suggestion above is what I'd go for. Aside from that, you should try to make a hello world (hello cube/cubes) project if you haven't

languid stirrup
#

Any Pure ECS handling mesh manipulation examples Apart from boids example?

dusty scarab
#

okay thanks! I did the hello world thing initially. I'll have a look at the training samples and try some

languid stirrup
#

Also search for Unity ECS sample and you’ll get a link to git repo of projects and it’s docs

dusty scarab
#

Currently breaking down the ESC Physics sample

rare umbra
#

Doh can’t find the Unite 2019 talk that has the new less boilerplate stuff. Is it β€˜converting scene data to DOTS’?

safe lintel
#

do you mean what was shown in the keynote?

rare umbra
#

Ah yes I think it was in the keynote yes

magic frigate
rare umbra
#

Thanks!

winter veldt
#

hey guys, quick question.. is there a way to pass LocalToWorld back to a GameObject?

coarse turtle
#

The transformsystemgroup should have systems which copy the LocalToWorld or (TRS) matrix back to the hybridized gameObjects

#

as long as the gameObjects are converted the entities should be set up properly to sync entity data to transform gameobject data

left oak
#

I think you want CopyTransformToGameObject

coarse turtle
#

yep that was the system πŸ‘

winter veldt
#

copytransformtogameobject seems to be obsolete, it auto-adds GameObjectEntity script, which uses Transform instead of LocalToWorld, and transform no longer exists

safe lintel
#

you need to use the actual component with conversion instead of the proxy component

mystic mountain
#

I had a dream last night that 2019.3 was released with new updates on all dots packages... 😒

untold night
#

I dreamed about driving a submersible.

That dream sounds better

silver dragon
#

multiplayer repo got an update... nothing really new, just CONTRIBUTING.md, but maybe it begins πŸ˜‰

#

btw. first commit from joeante...

slow epoch
#

At this point they are teasing us

hollow sorrel
#

it's a sign

#

time to invest in unity stock

#

i know this isn't a meme channel but it's hard to resist

flat talon
#

as stoked as I am about DOTS and the road ahead, I think it will take some time to get all current devs onboard that train πŸ™‚

#

quite a lot of devs are not too happy about the focus on dots. So hard to say what will happen to stock πŸ˜‰ and they haven't gone public yet have they?

craggy finch
#

I need help

flat talon
#

can you be more specific? πŸ˜„

craggy finch
#

umm

flat talon
#

@mystic mountain Hereapplesy? πŸ˜„ (j/k)

mystic mountain
#

#solved

flat talon
#

What have people been using to pass on a collection of native arrays to a job? I got a case where I want to run a parallel job that each processes a native array of floats. My current plan is to copy all the arrays into one big array and have a native array of structs with offset+length data in them.. but it just feels so.. unnecessary? (and no nativearray<nativearray<float>> doesnt work)

#

With that I can use NativeDisableParallelForRestriction to allow writing at the same time into the same array since I guarantee the jobs wont alias.

mystic mountain
#

Maybe the unsafecollections fholm posted yesterday solves your problems?

flat talon
#

ohh I must have missed that

#

I know Unity is adding some unsafe collections too

languid stirrup
#

@flat talon also, try using WriteOnly tag on your output array, that way burst will not have a problem multiple threads writing to the same array

flat talon
#

unfortunately in this case I need read/write :/ since I'm adding to existing values in the array

languid stirrup
#

and do other threads need to read from this array?

flat talon
#

I guess I can have a separate input and output though

hollow sorrel
languid stirrup
#

if not... then i suggest breaking the arrays into input array and output array

flat talon
#

they do need to read and write, but not in the same sections.. ie one job doesnt need to read the output of another thread. So it makes sense to have two arrays for input and output

#

each job has its own section in the array that others wont touch.

I was just wondering if this is the only way to do this? Currently I need to do a bunch of copies from multiple native arrays to combine them, and after the job the same to split the big array into smaller ones. Seems.. not great πŸ™‚

languid stirrup
#

there are always better ways of doing things, thats why we ask others hehhe

#

are all your float array same size?

civic bay
#

Is it possible to use GameObjectConversionUtility.ConvertGameObjectHierarchy(prefab, World.Active)); with EntityManager.CreateEntity();

languid stirrup
#

@flat talon also another thing that makes it faster, when allocating memory to output nativearray pass it the the option of NativeOption.UninializeMemory

civic bay
#

Like I convert the prefab on Start() but I need to create thousands of these entities

languid stirrup
#

that way, allocation doesnt require time

civic bay
#

If I use Instantiate it seems to take a performance hit?

#

But the prefab has the physics shape / body set up on it

#

So I need to convert it

languid stirrup
#

well... once you have converted to Entity, then using instantiate defeats the prupose of ECS

flat talon
#

unfortunately not all are the same size no :/

languid stirrup
#

@civic bay you will need to add new compoents to your ocnverted object, using ECS components

civic bay
#

But ConvertGameObjectHierarchy only converts the prefab to an entity one time

#

How do I make thousands of them?

languid stirrup
#

and never instantiate, cuz instantiate cannot benefit from ECS

#

for loop πŸ˜„

#

best to be done in a Job i think

flat talon
#

you can use a conversion system. There is also a way to "mass instantiate" with an array iirc

civic bay
#

Yeah I tried to set up a job haha, didn't work well

languid stirrup
#

and yea, there is a way to mass entitize a prefab in an array, i dont rem what syntax tho

civic bay
#

But is using EntityManager.Instantiate not ECS?

#

Surely I shouldn't be converting 1000's of GameObjects to Entities?

hollow sorrel
#

i think you should convert once and then you can mass instantiate a bunch of copies of that entity with a nativearray method in entitymanager

languid stirrup
flat talon
#

If you do the conversion inside of a subscene, the conversion is just run once and the result is saved in the subscene

languid stirrup
#

yea, you only convert from a prefab ONCE, then just make an archetype of it and create an array of those entities

civic bay
#

How do you create an archetype out of it though?

flat talon
#

use the GetPrimaryEntity method thing.. whats it called again

mystic mountain
#

That's what he did? I think you're confusing him with mixing archetype and prefab entity x)

civic bay
#

So I convert the prefab on Start()

#

And then on Update I spawn 10000 entities by using EntityManager.Instantiate(ConvertedPrefabEntity)

flat talon
#

why not use a conversion system or the interface?

civic bay
#

How so?

flat talon
civic bay
#

Yeah I did but he uses instantiate too?

flat talon
#

he's using the Convert() function and conversion systems, not start/update

mystic mountain
civic bay
#

That's what I'm doing though, doesn't he remove the Convert script later on?

mystic mountain
#

Would it even matter where the conversion is called from? Doing it with some ConversionSystem to add it to your Component or in Create of System, wouldn't the result be same in the end?

flat talon
#

the Convert method (from the interface) is useful when converting GO->entity one object at a time. In the case you want to do 1/n->1/n a system is generally more useful.

Btw regarding prefabs, the conversion basically creates an entity that is used as a template to create further entities of that prefab. And as above there's a way to create a ton of entities at once.

Or am I missing where you are stuck?

#

@mystic mountain afaik the result is different if you use a subscene.. I dont think it would save the conversion result there if you just use start

mystic mountain
#

So instantiating a prefab from a subscene lives in the subscene as well then?

flat talon
#

Also in the Convert interface you should declare references to prefab objects, perhaps you are missing that step?

#

@mystic mountain if you do it as part of the conversion flow, then yes the resulting entity is saved in the subscene asset

#

This confused me a while ago, since I expected the conversion to run every time you start the game

mystic mountain
#

But if I have a spawner in my subscene that references a prefab. Will the spawned entities belong to the subscene in runtime?

flat talon
#

if the spawner isnt using the conversion flow to instantiate the prefabs then no

#

however the original (converted) prefab entity will πŸ™‚

civic bay
#

So my set up is:

Prefab Spawner -> On Start() ConvertGameObject(prefabToConvert)
prefabToConvert -> is a gameobject that has PhysicsBodyAuthoring and PhysicsShapeAuthoring scripts on it

#

PrefabSpawner -> Update() -> m_entityManager.Instantiate(ConvertedPrefab)

#

Is this not correct?

#

I don't need to have the Convert to Entity script if I do it manually, right?

#

The Prefab Spawner is just a gameobject in my scene

flat talon
#

I would use the Convert method in the Prefab Spawner, rest sounds fine

civic bay
#

and the prefabToConvert is just in my project view

#

But how do I get a reference to the Entity via PrefabSpawner

#

If the Prefab converts itself

flat talon
#

you could store it in an entity singleton for example

civic bay
#

But the GameObject doesn't exist in the scene

flat talon
#

some people use static fields

civic bay
#

It's just in the project folder

flat talon
#

yeah that is fine, an entity is still created that is the "template"

civic bay
#

But the prefab won't be created?

#

if it doesn't exist in the scene

flat talon
#

not as a GO no

civic bay
#

So if I make a prefab and put the Convert script on

#

It will convert to an entity regardless if it exists in the scene?

flat talon
#

uh no, then nothing will trigger the Convert script.. hence why that is on the PrefabSpawner GO? or is that not in the scene?

civic bay
#

That's what I mean though

#

PrefabSpawner GO is on the scene

#

Which just has a ref to the prefab in the folder

flat talon
#

yes that is all fine

civic bay
#

So do I still call ConvertGameObjectHierarchy?

flat talon
#

ah

#

no

civic bay
#

Just put the Convert script on the entity prefab?

#

And it'll somehow convert it and instantiate it as an entity?

flat talon
#

conversionSystem.GetPrimaryEntity(prefab)

civic bay
#

ooooh

flat talon
#

ok here is what you do

civic bay
#

You mean to extend from IConvert thingy

#

And override Convert

flat talon
#

Implement IConvertGameObjectToEntity and IDeclareReferencedPrefabs on the PrefabSpawner monobehavior

#

yes

#

in the Convert() method (from the interface) you use:
conversionSystem.GetPrimaryEntity(prefabFieldFromYourBehavior)

#

Then in DeclareReferencedPrefabs() you declare the reference to a prefab, so it can track it correctly

#

one sec, see if I can find an example for you

civic bay
#

Thanks

flat talon
#

btw even though the prefab doesnt exist in your scene, you are still referencing it (from a folder) in your script as a GameObject type yeah?

#

ie the field

civic bay
#

Yeah

flat talon
#

perfect

languid stirrup
#

anyone know how do i give a fixed lenght for dynamic buffers in the IComponent struct? or do i give it a fixed length somewhere when i initalize it?

#

the entity contains this ICompoentData btw with the dynamic buffer

flat talon
civic bay
#

Thank you

flat talon
#

@languid stirrup I've never used a dynamic buffer inside an IComponent, is that even supported?

languid stirrup
#

IComponentData* and i guess so, i think lol, lemme see

flat talon
#

@languid stirrup Normally a dynamic buffer is added directly to the entity (like a component), but that ofc means you can only have one of each type of buffer on entity

civic bay
#

Awesome, thanks for your help. Will have a look at them both now

#

Sorry if I seem dull, I thought I got the hang of ECS, turned out I hadn't

flat talon
#

np and good luck! Also the upcoming 0.2 release will make some of this a bit easier πŸ™‚

#

no worries, Im still getting the hang of it and the damn thing keeps changing constantly!

civic bay
#

Haha, all the best buddy! πŸ™‚

craggy finch
hollow sorrel
#

weren't you told not to crosspost, your question has nothing to do with DOTS

languid stirrup
#

@flat talon oohhh. Yea I need one type of array. Cool. I’ll try that.

flat talon
#

you can even read buffers from other entities in a similar way you read components, getting it as an array you pass to the job

civic bay
#

Hey @flat talon quick question

#

I set up the component system like in that forum and I got it spawning in my prefabs

#

Should OnUpdate on my SpawnSystem : ComponentSystem be called every frame?

#

At the minute it only spawns 1 prefab, I can make a for loop to spawn 100, but I want it to keep spawning forever

flat talon
#

depends on your needs? keep in mind that if you want to spawn more than 1 in a frame, instead of a loop there's a way to do that all in one call and you get back an array of entity IDs you can use to set position on etc

civic bay
#

Yeah I wanna do the 2nd option I think

flat talon
#

someone posted that command here above earlier

civic bay
#

How can I set up the component system to always update?

#

Just to see how this looks first

flat talon
#

var entities = new NativeArray<Entity>(spawner.count, Allocator.Temp);
EntityManager.Instantiate(spawner.prefab, entities);

civic bay
#

but if I put 1000 in there, won't it just spawn 1000 straight away?

flat talon
#

it will update if there are entities in the query

#

yes it will

#

hence I asked if you need to spawn more than 1 in the same frame πŸ˜‰

civic bay
#

ahh

#

OKay so what I'm doing is making a pourer

#

like salt

#

So I need like 5 per frame

#

Like every update, spawn 5 entities

#

If I have

EntityManager.Instantiate(spawner.prefab, entities);```
Won't that just spawn 5 and then stop?
slow epoch
#

As far as i know, OnUpdate should be called every frame unless you modify the query from the system

#

In which case it'll only be executed when there are entities matching the query

civic bay
#

That's what I was thinking, but it seems to stop after I do it

#

Don't have any queries

slow epoch
#

Is the system active in the Entity Debugger?

civic bay
#

This is just for instantiating stuff

#

I think it works now

slow epoch
#

What was the issue?

flat talon
#

How are you defining your system, do you even have a query set?

#

btw.. since you are doing a "pourer", I've fiddled with similar system when I was doing a particle emitter. It can get a bit.. interesting where you want a consistent flow/sec but the delta time can differ πŸ™‚ so you need to figure out how many to spawn on every update/tick based on how many are left to spawn in that time slot so to speak

plain cloak
#

does [WriteOnly] have any benefit? or is it the same as no attribute?

flat talon
#

afaik it does help the system figure out potential memory aliasing, so it can allow multiple threads writing to the same array at once

plain cloak
#

i see, thanks

civic bay
#

@slow epoch I was doing the component system inside the spawner GO

#

I split everything up

flat talon
#

can you post your system? Are you setting up a query in OnCreate() or using a foreach query to run it?

civic bay
#
public class ParticleSpawnSystem : ComponentSystem
{
    int spawncount = 1000;
    int spawned = 0;

    protected override void OnUpdate()
    {
        if (EntityPrefabSingleton.Instance.Entities.Count > 0 && spawned < spawncount)
        {
            int amtToSpawn = 5;
            Entity entity = EntityPrefabSingleton.Instance.Entities[UnityEngine.Random.Range(0, EntityPrefabSingleton.Instance.Entities.Count)];
            NativeArray<Entity> entities = new NativeArray<Entity>(amtToSpawn, Allocator.Temp);

            EntityManager.Instantiate(entity, entities);

            for (int i = 0; i < entities.Length; i++)
            {
                EntityManager.AddComponent(entities[i], typeof(ParticleTag));
                EntityManager.AddComponent(entities[i], typeof(PhysicsStatus));
                EntityManager.AddComponent(entities[i], typeof(LocalToWorld));
                EntityManager.AddComponent(entities[i], typeof(RenderMesh));

                float3 spawnPositon = new float3(0, 10, 0);
                EntityManager.SetComponentData(entities[i], new Translation { Value = spawnPositon });

                EntityManager.SetComponentData(entities[i], new Rotation { Value = Quaternion.Euler(UnityEngine.Random.Range(0.0f, 360.0f), UnityEngine.Random.Range(0.0f, 360.0f), UnityEngine.Random.Range(0.0f, 360.0f)) });
                spawned++;
            }

            entities.Dispose();
        }
    }
}
#

@flat talon

flat talon
#

that is a component system with no entity query, so not surprising it doesnt call Update every frame πŸ™‚

civic bay
#

It is called every frame πŸ˜›

flat talon
#

then Im confused, and I thought you said somewhere above it wasnt?

#

anyways, you got things working then? πŸ™‚

civic bay
#

Oh yeah it wasn't working because I got lazy and put everything was inside my MonoBehavior script that converted the prefabs

#

So because I had the Convert to Entity script on, it was destroying the GO and the Glitter Spawn would only run once before it was destroyed

#

But now I've split it out into separated .cs files, it's working now haha

flat talon
#

generally a component system is supposed to process a set of components, and not be "open ended" like that one. For example you could create it to query for Spawner entities in your world, and for each one you would spawn new entities

civic bay
#

Well when I convert my prefabs, I do dstManager.AddComponentData(entity, new ParticleTag)

#

So should I have an Entity Query in my component system (the spawner) that just contains Particle Tag?

flat talon
#

that is the particle, the system you pasted here is really the spawning logic.. so it would query for and process each emitter/spawner

#

The ParticleTag is on the entities you are spawning "from the emitter"

civic bay
#

Ah so I should add a component to my spawner entity?

#

Or did I read that wrong

flat talon
#

What is the spawner entity at the moment?

#

I assume you are tracking that in EntityPrefabSingleton.Instance.Entities.Count ?

#

By having a component on it and making the system respond to a query for that component, you can remove the usage of "EntityPrefabSingleton.Instance.Entities.Count"

civic bay
#

No, that's just a singleton to keep a reference to the converted prefabs to entities

flat talon
#

ah ok

civic bay
#

I have 3 particle prefabs that I emit from this spawner

flat talon
#

So your "prefab spawner" is just a gameobject holding a reference to the prefab, but is never converted into an entity?

civic bay
#

The spawner has the Convert to Entity script on it, but set to Inject GameObject

flat talon
#

If you change that into what I suggested above, then you can support multiple spawners at once

civic bay
#

Only need 1

flat talon
#

ok then place a component (with relevant info like spawnrate) on the spawner entity, or a tag if you dont need any data

civic bay
#

And then on the spawn system, add that tag to the entity query?

flat talon
#

yes

civic bay
#

Brilliant, I'll do that now

flat talon
#

it would result in about the same as what you have now, but with a bit more flexibility. But can be more easily extended, ie support more than 1 and you can have data on it like spawnrate and even keep what prefab to spawn on that component instead of the singleton

civic bay
#

Ahh i understand it now!

#

Thank you so much for this btw

flat talon
#

np

winter veldt
#

alright, still not sure how to pass localtoworld back to transform. all copytransformtogameobject gets me is a Transform component attached instead of localtoworld, which i can't find anywhere

flat talon
#

I think it depends on whether the object being converted has a parent or not? I think I remember reading that somewhere

winter veldt
#

no parent, just trying to have a go move around so i can attach a camera to it

flat talon
#

oh you're writing data from entities back to GOs? I think Joa recently commented on that on the forums, that the conversion workflow wasnt really meant for that

#

I believe they are even going to remove some of the old stuff there to support that

winter veldt
#

i see. well i'm just at a loss of how to set up a camera in pure ecs then. i was hoping to not have to write my own thing.

flat talon
#

I've seen ECS code manipulating the camera

#

I believe it was on the main thread though, not in a job

#

lets see what 0.2 will offer, their plan is to be able to convert all object types into entities

winter veldt
#

oh if i don't make it a job i can just edit GO's directly? i.. didn't think that was supposed to happen.

slow epoch
#

There wasn't back in the old days something like IJobTransform?

flat talon
#

actually yeah

#

Jobs can use TransformAccessArray