#archived-dots

1 messages Β· Page 88 of 1

gritty grail
#

let me try turning it off.

mystic mountain
#

Ye, stack tracing is super expensive X)

amber flicker
#

having a warning log every frame is also expensive πŸ˜…

gritty grail
#

I didn't even think about that xD

#

Thanks

safe lintel
#

for perf, disable jobsdebugger, enable burst without safety and disable stack tracing(but then occasionally check with those things so you dont do a ton a work and find you got tons of leaks happening under your nose)

gritty grail
#

Enable Compliation

#

but disable safety check

#

right?

mystic mountain
#

Anyone know if subscene gameobject need to be in a scene itself? Or I can store it on prefabs as well? Or maybe that isn't how you're supposed to use it?

safe lintel
#

my gut tells me it needs to be in the scene for now, not seen any uses of it in a prefab

#

but my own experience with them has been buggy and limited so i havent really done much with them

gritty grail
#

CastRay is cursed

#

πŸ‘€

#

I am now getting this error when CastRay is called.

safe lintel
#

ok you may also need to get the final handle for the collisionworld and pass it to your job

gritty grail
#

What do you mean by final handle?

#
public class TestJob : JobComponentSystem
{
    [BurstCompile]
    struct MoveJob : IJobForEach<PhysicsVelocity, Translation>
    {
        public float horizontal;
        public float vertical;
        public bool space;
        public CollisionWorld collisionWorld;
        public CollisionFilter filter;
        public void Execute(ref PhysicsVelocity velocity, ref Translation translation)
        {

            var rayInput = new RaycastInput();

            rayInput.Start = translation.Value;
            rayInput.End = translation.Value + 1.4f * new float3(0,-1,0);
            rayInput.Filter = filter;
            var hit = collisionWorld.CastRay(rayInput, out var castHit);
            if (space)
            {
                velocity.Linear = new float3(velocity.Linear.x, 6, velocity.Linear.z);
            }
            velocity.Linear = new float3(3 * horizontal, velocity.Linear.y, 3 * vertical);
            velocity.Angular = new float3(0,0,0);
        }
    }
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        var physicsWorldSystem = World.Active.GetExistingSystem<Unity.Physics.Systems.BuildPhysicsWorld>();
        var collisionWorld = physicsWorldSystem.PhysicsWorld.CollisionWorld;
        var job = new MoveJob{
            horizontal = Input.GetAxis("Horizontal"),
            vertical = Input.GetAxis("Vertical"),
            space = Input.GetKeyDown(KeyCode.Space),
            collisionWorld = collisionWorld,
            filter = new CollisionFilter {
                BelongsTo = ~0u,
                CollidesWith = (uint)(1 << 0),
            },
        };
        var handle = job.Schedule(this, inputDeps);
        handle.Complete();
        return handle;
    }
}```
#

This is what I have right now.

safe lintel
#

do something like
var handle = JobHandle.CombineDependencies(inputDeps, m_BuildPhysicsWorldSystem.FinalJobHandle);
and schedule your job with this handle

gritty grail
#

Do I need to update my code at all besides just adding that line?

safe lintel
#

when you schedule your job instead of inputDeps use handle or whatever you call CombineDepenencies

gritty grail
#

Okay, where do I get FinalJobHandle?

#

oh

#

from my physicsWorldSystem

#

so, like this?

#
        var newDeps = JobHandle.CombineDependencies(inputDeps, physicsWorldSystem.FinalJobHandle);
        var handle = job.Schedule(this, newDeps);
        handle.Complete();
        return handle;```
safe lintel
#

looks good

gritty grail
#

Well I am still getting the same error x.x

#

Maybe I should take this raycast out of the job entirely

safe lintel
#

ok just post the full thing again?

gritty grail
#
public class TestJob : JobComponentSystem
{
    [BurstCompile]
    struct MoveJob : IJobForEach<PhysicsVelocity, Translation>
    {
        public float horizontal;
        public float vertical;
        public bool space;
        public CollisionWorld collisionWorld;
        public CollisionFilter filter;
        public void Execute(ref PhysicsVelocity velocity, ref Translation translation)
        {

            var rayInput = new RaycastInput();

            rayInput.Start = translation.Value;
            rayInput.End = translation.Value + 1.4f * new float3(0,-1,0);
            rayInput.Filter = filter;
            bool hit = collisionWorld.CastRay(rayInput, out var castHit);
            if (space)
            {
                velocity.Linear = new float3(velocity.Linear.x, 6, velocity.Linear.z);
            }
            velocity.Linear = new float3(3 * horizontal, velocity.Linear.y, 3 * vertical);
            velocity.Angular = new float3(0,0,0);
        }
    }
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        var physicsWorldSystem = World.Active.GetExistingSystem<Unity.Physics.Systems.BuildPhysicsWorld>();
        var collisionWorld = physicsWorldSystem.PhysicsWorld.CollisionWorld;
        var job = new MoveJob{
            horizontal = Input.GetAxis("Horizontal"),
            vertical = Input.GetAxis("Vertical"),
            space = Input.GetKeyDown(KeyCode.Space),
            collisionWorld = collisionWorld,
            filter = new CollisionFilter {
                BelongsTo = ~0u,
                CollidesWith = (uint)(1 << 0),
            },
        };
        var newDeps = JobHandle.CombineDependencies(inputDeps, physicsWorldSystem.FinalJobHandle);
        var handle = job.Schedule(this, newDeps);
        handle.Complete();
        return handle;
    }
}```
safe lintel
#

i dont understand why thats not working 😩

gritty grail
#

same xD

#

I might just take it out of the Job for now and make it a separate component system

#

Until I stumble across a solution

#

Is there an advantage to doing handle = job.Schedule() and then completing the handle before returning it?

#

As opposed to just returning the job schedule?

#
        var handle = job.Schedule(this, inputDeps);
        handle.Complete();
        return handle;```
#

Doing this vs csharp return job.Schedule(this, inputDeps);

safe lintel
#

you could just return it as you schedule it

#

just a habit i have i guess

gritty grail
#

Oh okay

#

Just was curious

safe lintel
#

seriously though your problem is driving me nuts

gritty grail
#

Same, cause it makes me feel really icky knowing I could try to run the burst compiler on this

#

but having to settle for just a regular system makes me feel icky on the inside

#

😞

mystic mountain
#

You're still running your system before the Simulation right?

gritty grail
#

Uh, maybe

#

I'm not sure how to do your solution

mystic mountain
#

Did you.. try to change it? XD

gritty grail
#

Idk how XD

mystic mountain
#

[UpdateAfter(typeof())]

gritty grail
#

Do I put the attribute on the class?

mystic mountain
#

Yes, on top of the system

gritty grail
#

Still the same error

mystic mountain
#

Will you post your code again?

gritty grail
#
[UpdateAfter(typeof(Unity.Physics.Systems.EndFramePhysicsSystem))]
public class TestJob : JobComponentSystem
{
    [BurstCompile]
    struct MoveJob : IJobForEach<PhysicsVelocity, Translation>
    {
        public float horizontal;
        public float vertical;
        public bool space;
        public CollisionWorld collisionWorld;
        public CollisionFilter filter;
        public void Execute(ref PhysicsVelocity velocity, ref Translation translation)
        {

            var rayInput = new RaycastInput();

            rayInput.Start = translation.Value;
            rayInput.End = translation.Value + 1.4f * new float3(0,-1,0);
            rayInput.Filter = filter;
            bool hit = collisionWorld.CastRay(rayInput, out var castHit);
            if (space)
            {
                velocity.Linear = new float3(velocity.Linear.x, 6, velocity.Linear.z);
            }
            velocity.Linear = new float3(3 * horizontal, velocity.Linear.y, 3 * vertical);
            velocity.Angular = new float3(0,0,0);
        }
    }
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        var physicsWorldSystem = World.Active.GetExistingSystem<Unity.Physics.Systems.BuildPhysicsWorld>();
        var collisionWorld = physicsWorldSystem.PhysicsWorld.CollisionWorld;
        var job = new MoveJob{
            horizontal = Input.GetAxis("Horizontal"),
            vertical = Input.GetAxis("Vertical"),
            space = Input.GetKeyDown(KeyCode.Space),
            collisionWorld = collisionWorld,
            filter = new CollisionFilter {
                BelongsTo = ~0u,
                CollidesWith = (uint)(1 << 0),
            },
        };
        var newDeps = JobHandle.CombineDependencies(inputDeps, physicsWorldSystem.FinalJobHandle);
        var handle = job.Schedule(this, newDeps);
        handle.Complete();
        return handle;
    }
}```
mystic mountain
#

Another error?

gritty grail
#

This is the one I've been dealing with

#

After I changed the handle to handle.Complete();

#

And after I turned off and on whatever I was supposed to in the editor.

mystic mountain
#

Yeah ok. UpdateAfter wont work, so you can remove that...

#

Try UpdateBefore

gritty grail
#

Same error

#

If that gives any more context

mystic mountain
#

Do UpdateBefore and complete the handle before your job.

gritty grail
#

Complete my handle before my job?

mystic mountain
#

You can try completing the jobs already scheduled before. so InputDeps.Complete(); if this doesn't work, I would remove the code in your job, and see if it still gives same error. And if it does, this isn't your problem πŸ˜›

gritty grail
#

Well removing it fixes it

#

I already know that

#

If you're taking about removing raycast

mystic mountain
#

I'm not sure. But you can try only insert hysicsWorldSystem.PhysicsWorld into your job.

gritty grail
#

it doesn't like me creating a collisionworld in the code as well

#

So I am probably going to assume that I can't raycast in a job

#

So I'm trying to run the raycast in a componentsystem

mystic mountain
#

I can send you some code.

gritty grail
#

and then pass the boolean in a component on the player

#

Sure

mystic mountain
#

Don't have time to scale it down, but you have some reference of code that works πŸ˜›

#

Imagine you can find some example in the PhysicsSample sa well

safe lintel
#

mousepickbehaviour.cs

#

his code should work tho

gritty grail
#

Man, getting this raycast thing working is confusing

#

If my raycast comes into contact with my player at all, it doesn't work, even if the raycast shouldn't collide with the player

#

And even if I make it so that the raycast doesn't collide with the player, the boolean is finnicky

#

And only says true if you are on the ground and you move afterwards

#

So you can't jump up and down basically

safe lintel
#

hey diviel what unity version are you running?

#

for the raycasting

gritty grail
#

2019.3

safe lintel
#

b5?

gritty grail
#

b4

mystic mountain
#

@gritty grail solved your problem

gritty grail
#

What was the issue?

mystic mountain
#

use

        [ReadOnly]
        public PhysicsWorld physicsWorld;
gritty grail
#

Okay, that works

#

What is this error?

#

It happens from this

#
            bool hit =  physicsWorld.CollisionWorld.CastRay(rayInput);
            Debug.Log(hit);```
safe lintel
#

cant do debug.log stuff with the burstcompile attribute

gritty grail
#

Ohh

#

So for testing I have to remove BurstCompile?

#

Okay, now all of that works

#

I need to figure out why I'm getting inconsistent results with the raycast....

coarse turtle
#

if you want to debug, you can just untick the Enable Compilation button in toolbar -> Jobs -> Burst -> Enable Compilation (this is editor only), you'll still need to remove it when you make a build

gritty grail
#

Oh wait nvm I fixed it, planes just suck

zinc bone
#

Thanks for committing an entire channel to me

minor sapphire
#

Been away for a bit, baby born... Time deleted... Saw the havok release and pricing, got excited, has anyone done any benchmarks? I'd love to see a performance comparison...

dull copper
#

I'm still waiting for them to fix the licensing issue πŸ˜„

#

someone put LICENSE.MD at the root of the packge folder that is straight up noncommercial trial licensing text from regular Havok

#

it's not supposed to apply as is to the Havok Package but there it is so they gotta resolve it

#

but all in all, even if I like more robust Havok and the pricing is no issue, lack of source code access can be

mystic mountain
#

Is there any pricing on it yet?

dull copper
#

yes, it's free on Unity Personal and Unity Plus and will be 20 USD per seat/mo on Unity Pro

#

they will sell the sub on asset store apparently

#

never seen subs there before so that's new

#

I'm actually bit afraid that some other asset devs get greedy when they see this is offered as an option

#

I really really hate subs for nonimportant minor components

#

even that Havok sub can feel a lot if you don't really need it, but for people who know Havok and want it, it's really affordable now

#

it hasn't been in reach for licensing for most indie games before

#

of course it will not expose the whole Havok API either, just limited set of functionality that utilizes their solvers

#

what is cool is that testing it out is really simple if you are using Unity Physics package already, it's just a matter of toggling different physics backend from one script and possibly tweaking some edge cases manually

#

but for example, I tried just swapping the physics engine from their physics examples and things just worked like before

mystic mountain
#

Seeing the keynote, for high performance, is the goto- to write ForEach now? Or should we still write Jobs manually?

minor sapphire
#

I haven't seen the keynote yet. I'll have to check it when I get a moment

low tangle
#

I think its a convenience thing @mystic mountain

#

like auto jobs for the 99% in foreach

#

and when you need to get complex you still have to write proper jobs

#

we will see though

mystic mountain
#

Yeah I see.

low tangle
#

I'm thinking thats what it is

mystic mountain
#

Hope they release their new update soon :3

low tangle
#

god yes

#

I need it

mystic mountain
#
  • dots sample
low tangle
#

yes

#

some of the new hidden things need examples

#

or better documentation

#

autogen is meh

#

I get that from intelisense, wheres the 'why'

mystic mountain
#

Hum, aren't InitializationSystemGroup only supposed to run once?

amber flicker
#

think I've seen in the forums that it runs maybe once per world or something? so it happens twice because of the conversion world? think a google should reveal more

mystic mountain
#

Only thing I found was "(updated at the end of the Initialization phase of the player loop)".

amber flicker
#

then probably I'm wrong and thinking of something else - sorry I know that's not helpful πŸ˜…

mystic mountain
#

I would've thought the same as you , but looking of how my system behaves I'm not sure if I've somehow introduced a bug somewhere or it should always update like this...

mint iron
#

@mystic mountain InitializationSystemGroup is just a group that runs early, it still runs every frame.

slow epoch
#

Name is missleading af right now to be honest

mint iron
#

What really irritates me at the moment is the way they dynamically create the standard groups/systems so you can't easily make a group that runs between Init and Sync groups; or UpdateBefore/After the start/end CommandBuffer systems.

slow epoch
#

How do you manage to do Authoring for ISharedComponentData?

#

Haven't seen any examples about it

coarse turtle
#

In a MonoBehavior implementing IConvertGameObjectToEntity you just do dstManager.AddSharedComponentData(e, T) within the function call

#

pretty much the same as IComponentData

slow epoch
#

Oh for some reason i though you had to create all the entities that use the same data and then add to all of them that data

#

But i suppose you do that individually

analog beacon
#

I never used ECS, I believe DOTS is an improved version of ECS?

neon shore
#

DOTS is the whole stack with all features including ECS

#

DOTS is the Job system, the Netcode, ECS, etc.

analog beacon
#

thx

#

I will still have to learn how to use it, where to start?

neon shore
#

There are some tutorials on the unity learn site, it's still a bit rough for newbies though.

safe lintel
#

@analog beacon check out the pinned message here, ecs github samples in particular

gritty grail
#

I am going to make a tutorial soon

#

on how to do basic physics in Unity ECS

#

but now trying to recreate my project, putting a physics shape and convert to entity on a plane makes it disappear

#

and the entity debugger says it has no render mesh .-.

neon shore
#

By the way, does anyone know the best approach for static/singleton like objects in ECS. I'm thinking about having one Entity with components that hold the overall game data. But I don't know how to best access that component data from various component systems.
I haven't kept up to date with the ECS API in recent months.

gritty grail
#

Systems create references

#

to components when you query for them

neon shore
#

Well, yes, but it's not a component the system works on, it's one component it would take data from to work on other components or write data to with other components from a system

gritty grail
#

well i'm not exactly sure what you're trying to do πŸ‘€

neon shore
#

Basically I need to inject a reference to one component into various systems without that component being on any entities the system works on.

#

It's basically global data that needs to be accessed from systems.

gritty grail
#

well static variables don't work well in jobs

#

If you wanted to use those

#

But you could just create a class or persistent data

neon shore
#

Hence I decided to make it a component on an entity

#

You can't reference managed classes from jobs either

gritty grail
#

You can't just pass it when creating the job?

neon shore
#

nope

#

DOTS doesn't allow it.

gritty grail
#

Well I don't know if you can create a component without an entity and have the system recognize it

neon shore
#

Or do you mean the ComponentData?

#

Well, as I said, I did put it on an entity, which handles the global state, but I don't know how to inject it

#

if I put it on the job struct it's not a reference

#

and I therefore can't write to it.

#

I wonder would a NativeArray with just that component on it work?

gritty grail
#

Uh, maybe. How does something like Time.deltaTime work or Input.GetAxis?

neon shore
#

Those are read only things, I need to write to the data though.

#

With the above you basically just plug in primitive data to use, but I want the jobs to be able to modify the game data. Which should be thread safe since it would only be additions/subtractions

coarse turtle
#

Youll want to look at blobs as you can write into them and can allow you to put ptrs structs wrapping referenced types (I haven't tried running a blob through a job yet for write data)

neon shore
#

blob data is immutable

coarse turtle
#

you update via accessing the reference

#

there was an example in the discord here, but it's totally possible, just haven't tried it since I haven't had a need to do it (you might also be able use unsafe utility's memset πŸ€”)

gritty grail
#

I'm so confused xD, I started a new project, and tried to create an entity plane with physics shape

#

and it's disappearing

#

I go to my old project and do the same thing and it shows up

safe lintel
#

did you add the hybridrenderer package?

gritty grail
#

Thanks xD

#

Time to restart my tutorial

neon shore
#

Okay, I found a solution to my problem.

#

ComponentDataFromEntity works well in that case.

#

Not entirely sure if setting the ComponentData is entirely thread safe though because it's not a ref.

#

Well definitively not thread safe ^^

coarse turtle
#

Oh, you can do a EntityCommandBuffer to update the game entity data too

neon shore
#

Will that work with consecutive changes though?

#

As in, will they be accumulative, since I add something for each job

coarse turtle
#

Should be

neon shore
#

Doesn't the buffer only set the things at the end? or is that only for create operations?

coarse turtle
#

afaik they can run after all jobs have been completed, so towards the end

#

so meaning your next frame should have the data you set

neon shore
#

yes the wrong data

#

because the input that is incremented on is old on all of them

coarse turtle
#

i guess if you need the exact same frame accuracy πŸ€”

#

disabling the restriction on the ptr might be the way to go

neon shore
#

Well, I need the data to accumulate, if I pass in new data for something in the future it will always take the data from that point in time, not accumulative one after the other

#

What could also help would be a callback system for jobs, so I could collect the accumulative difference throughout the job and then pass that over once it's completed.

coarse turtle
#

hmm I guess queuing up your income might also work

#

e.g. in your job struct, pass in a parallelwriter queue

#

and in a job scheduled after that job struct, flush each income element from your queue and add it to your gameEntity

neon shore
#

Yeah, but then I have two jobs and two loops through all the entities.

#

At that point I can just use a local job variable and reuse that in a second job

coarse turtle
#

yea that's another option, I did the same in one of my systems too

#

with local system variable ptrs, and i just pass the ptr from job to job

radiant sentinel
#

Hello, is there any unity staff here?

neon shore
#

I'm still not happy with the Queue solution but for now it works.

pliant pike
#

basic question but what's the correct way to copy a nativearray to another nativearray

#
public NativeArray<float3> cachedwaypoints;
cachedwaypoints = EntityManager.World.GetExistingSystem<WayPointMoveSystem>().MoveWaypointslist.ToArray();```
#

like that code does not work, .Asarray works but .ToArray does not

#

I want a copy of the data because I'm getting an error where the data has been deallocated before its being used

neon shore
pliant pike
#

thanks, but I'm getting an error "object reference not set to an instance of an object"

safe lintel
#

well i dont think you can just turn a native array into a system

#

and second you need to initialize the system like new native array<float3>(allocator = allocator.tempjob)

#

oh missed the third part of that line but the initializing point still stands

pliant pike
#

well its a list from that system, but yeah I wasnt sure if I had to allocate it with a size

#

actually it doesn't seem as if I can allocate it without a size

low tangle
#

thenativearray.CopyTo .CopyFrom(NativeArray<T>)

#

I suggest not using built in List<T> and Dictionary<K,V> when you can

slow epoch
#

@neon shore you may want to check the SetSingleton methods that every system has

#

https://gametorrahod.com/ecs-singleton-data/ here's some info about it, don't know if this is what you need

Game Torrahod

You have these API to work with singleton data but how do they really works?

  • system.GetSingleton
  • system.SetSingleton(T data)
  • entityQuery.GetSingleton
  • entityQuery.SetSingleton(T data)

It's a singleton Entity
In the docs it says "singleton data", but actually you ...

mint iron
neon shell
#

so I just made a new project and plopped DOTS on it and made a subscene which has a simple prefab (parent empty, child capsule) , with 1 authoring component.
closing the subscene, I see 3 entities are created - numbered 1 2 4 , there's no 3.
in addition, the scene is rendering some ghost entities which exist nowhere and it is frustrating as heck :\ more are created every time i begin and stop playmode, did anyone else encounter this?

pliant pike
#

thanks everyone

#
public NativeArray<float3> cachedwaypoints;
 cachedwaypoints = new NativeArray<float3>(EntityManager.World.GetOrCreateSystem<WayPointMoveSystem>().MoveWaypointslist.Length, Allocator.Persistent);
        cachedwaypoints.CopyTo(EntityManager.World.GetOrCreateSystem<WayPointMoveSystem>().MoveWaypointslist.ToArray());```
#

the solution

#

I dont know why I wasted time doing that, I'm going to turn the list into a blobarray anyway, but at least I know for next time

tepid radish
#

Hi.
I would like to go with DOTS in my project.
I have lots of objects which need to be rendered and have physics on them.
So what resources would you recommend?
Or I just should start from Unity web page?

dull copper
#

@tepid radish start with official docs and DOTS sample repo, you can find links on the pinned message on this channel

#

most tutorials etc you find on the internet are totally outdated for DOTS

#

so official docs and samples are your best source

tepid radish
#

@dull copper Thank you. πŸ˜‰

mint iron
#

I'm having trouble figuring out NativeStream writing - anyone used this before? i can't find any documetnation.

The exception is ArgumentException: NativeStream.Writer must be passed by ref once it is in use but i have checked that my writer is being accessed by ref and every place i'm writing from the exact same instance/address. It seems like a misleading error message for something else going on. 😦

neon shore
#

For feedback on the proposed solutions, you can't have ref types in a job structs, so the singleton api can't be used. And the SharedStatic doesn't look threadsafe but I guess I can try it.

amber flicker
sonic holly
#

are navmeshes supported in Dots?

slow epoch
#

Yeah but is not really a good implementation yet since you need to do a lot of work to get a path right now

#

But i think someone already did something so it could be easier to use

sonic holly
#

well, i was thinking of gradually integrating parts of the dots code into my game, one would be to replace the current spawning of bullets and enemies

#

the bullets would be easy but the enemies use navmeshes to navigate and have their respective behaviours so im not sure now

#

maybe i should just use it for the bullets.. πŸ€”

slow epoch
#

If you need to create a navmesh from scratch that can be used on jobs you can use NavMeshQuery

lapis yoke
#

Hmm, i'm having trouble implementing an FPS counter in the DOTS Physics Sample. No matter what the actual framerate is, Time.deltaTime is always 0,01666667, resulting in a perfect 60 fps. I imagine it has something to do with the physics being coupled to the framerate right now, but is there something else i can use to measure the actual fps? (It doesn't need to be super accurate, just a good indication)

#

Going back to the good old DateTime seems to work ok.

slate breach
#

I'm getting this error and I can't find out why: "Loading GameObjectEntity in Playmode but there is no active world." I made a new subscene and when I press play and this error comes up. Does anyone know where this is coming from?

#

If I load the game with the sub scene disabled there's no error and if I enable it after the game is started up it works fine.

slate breach
#

It seems like the default world initialization/bootstrap is too slow for some reason

vagrant surge
#

Tiny is such a total clusterfuck @dull copper

#

so now they remove 2d support

#

and focus on crappy 3d for mobile-web

#

well not remove, but kinda shift focus

dull copper
#

heh

vagrant surge
#

on ECS department, Mozilla made a ECS for JS

#

i know the guy who made it

mint iron
#

o0o0o awesome

simple cradle
#

So I was able to get rewired working alongside ECS by making a singleton monobehavior containing my rewired player and just getting the input in the update() which the systems can then reference

#

idk if it's a good way of doing it but it works πŸ˜„

vagrant surge
#

@simple cradle input component

#

something like PlayerInputComponent, that has stuff like moveX, moveY, bJump, etc

simple cradle
#

the problem is rewired input is all handled through an object

#
public class RewiredInput : Singleton<RewiredInput>
{
    protected RewiredInput() {}

    public Player player = ReInput.players.GetPlayer(0);
    public float3 moveVector;

    void Update()
    {
        moveVector.x = player.GetAxis("Move Horizontal");
        moveVector.y = player.GetAxis("Move Vertical");
    }
}
vagrant surge
#

well, that movevector is what you would have in the PlayerInputComponent

#

you would have a non-burst ECS system that just reads from rewired input

#

and sets player input comp variables

simple cradle
#

but I'd still have to have my singleton Player player hanging around right?

vagrant surge
#

why? not really

simple cradle
#

because I can't GetAxis without a player instance

vagrant surge
#

ah

simple cradle
#

that's why I'm doing it like this

vagrant surge
#

then yes

#

the way ive allways done it in my own projects, is that i have an InputSystem, that does the typical stuff like

#

PlayerInputcomponent cmp
cmp.bJump = pressed("spacebar")

simple cradle
#

and I only need to run the update loop once per update rather than once per entity

#

so I don't think I'm losing much performance right?

vagrant surge
#

no

#

main thing is to copy it into a component

#

so then you can do the proper jobs-burst stuff

#

as its now on the "ecs world"

simple cradle
#

ah I see, that's the important part πŸ˜„

#

so I'd have a non burst input component to grab the input data

#

then use that in burst components

#

yeah?

vagrant surge
#

yeah, you have a non-burst system

#

that just accesses that rewired stuff and writes into PlayerInputComponent

#

and then the other burstable systems can read the player input component

simple cradle
#
        Entities.ForEach((ref Translation translation, ref MoveSpeedComponent moveSpeedComponent ) =>
        {
            if ( RewiredInput.Instance.moveVector.x != 0.0f || RewiredInput.Instance.moveVector.y != 0.0f )
            {
                translation.Value += RewiredInput.Instance.moveVector * moveSpeedComponent.moveSpeed * Time.deltaTime;
            }
        });
vagrant surge
#

another thing ive seen, but more with entitas, is to make input events into entities

simple cradle
#

I'd just turn the moveVector into a component

vagrant surge
#

yes

#

another pattern is to create event entities

#

for example, lets say jump

#

you have a system

#

and if you pressed spacebar

#

you create a NEW entity

#

that has component "PressedJump"

#

and thats it

simple cradle
#

instead of putting PressedJump on the player?

vagrant surge
#

yes

simple cradle
#

What's the benefit

vagrant surge
#

you dont need to iterate the player, and the event can be on someone

#

you can have PressedJump have a entityID target

#

and then you have a system that iterates PressedJump

#

its also how the new DOTS networking works

#

server to client calls work by creating a new entity that has the event data

simple cradle
#

Well, I'm not sure how event entities should look in Unity ECS πŸ˜„

#

I'm pretty new to this stuff and still learning.

vagrant surge
#

you just use the ecs world as an event bus. Create entity, and the event type/payloadis done on components

#

then the system that handles the event deletes the entity

simple cradle
#

so it runs the system once and deletes?

vagrant surge
#

yes

#

the Entitas demo projects do that

#

all the time

simple cradle
#

Without some code to look at this is kind of difficult to understand

vagrant surge
#

llook at the Entitas demo projects

#

like that match1 game

#

they have a couple videos showing stuff

#

and generally do their input through creating event entities

simple cradle
#

there's a lot of generated scripts to look through πŸ˜„

#

not sure what I'm looking for exactly yet

vagrant surge
#

here is what you need

#
    {
        var input = _contexts.input.isBurstMode
            ? Input.GetMouseButton(0)
            : Input.GetMouseButtonDown(0);

        if (input)
        {
            var mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            var e = _contexts.input.CreateEntity();
            e.AddInput(new Vector2Int(
                (int)Math.Round(mouseWorldPos.x),
                (int)Math.Round(mouseWorldPos.y)
            ));
        }
    } ```
simple cradle
#

oh wait they're in features

vagrant surge
#

he creates a new entity with Input component

#

that has a vec2

#

for the mouse click coordinates

#
    {
        var inputEntity = entities.SingleEntity();
        var input = inputEntity.input;

        var e = _contexts.game.GetPieceWithPosition(input.value);
        if (e != null && e.isInteractive)
        {
            e.isDestroyed = true;
        }
    }```
#

the system syntax is a lot different

#

but the TLDR there is that it just iterates entities with Input component

#

and then grabs the board piece at that position and sets isDestroyed to true

#

other systems then actually destroy the board piece and make things scroll and stuff

simple cradle
#

so it's literally a system designed as an event subscriber pattern

vagrant surge
#

yup

simple cradle
#

and the published events are entities

vagrant surge
#

sounds slow, but isnt. Creating small entities with unity ECS is basically a push-back on an array

simple cradle
#

I mean it has to be more efficient in some capacity than polling every frame

vagrant surge
#

yup

#

thats the idea

#

Entitas takes it to a extreme

#

as in entitas, you can configure systems to only run when stuff has changed

#

so this case, of the input system, will do 0 every frame

#

until there is a newly created event entity

simple cradle
#

and no matching functionality in Unity ECS?

vagrant surge
#

you can do the same no issue

simple cradle
#

you can configure a system to not run under conditions?

#

I don't know all of the things I can do with Unity systems yet πŸ˜„

#

google-fu

#

this seems like what I need to study

low tangle
#

if you want to do work when there is changes you can use a changed filter on a query

#

but its not ever often I need to do that

#

you mostly want work work with querys and addition/subtractions on the query types

#

when changing becomes too expensive you do something non intuitive at first

#

you ditch the changes to structure (for that one collection of high performance entities that cant change) and simplely put bool flags on it for events and query every frame if(bool) in the job loop

#

changing components on a entity is good up to say 20k on desktop a frame (depending on all other things being light or reasonable) but switching to polling can work upwards to a million or more

#

changing the archetype is good for readability and debugging

simple cradle
#

so you're suggesting just poll inputs? πŸ˜„

#

@low tangle or am I interpreting that wrong

low tangle
#

only if you are doing it on 100,000 + entities

simple cradle
#

if not, I should go for readability then?

low tangle
#

yep!

simple cradle
#

Sounds neat, thanks!

low tangle
#

if its input for a player controller I suggest doing it a bit different

#

attach the input data onto a player, process all inputs, and always start with zeroing the input.

#

something like this:

//all {input}
foreach entity in query
input = default
input.mousex = Input.GetAxis("Mouse X")

//different system
//all {input, player}
player.magic(input.mousex);
simple cradle
#

Well, is that not just polling

low tangle
#

it is, but only on the query of inputs

#

polling for a event system is very slightly different

#

think of a component that has 12 bools in it for various UI events on a button

#

so that way your 'button' never has to change to 'button, click' 'button, clicked, onmouseleave'

#

instead you just have a button with 12 bools for each random ui state in it

#

and you loop over all buttons all the time, and branch on all 12

simple cradle
#

I'm finding it kinda hard to visualize that example

low tangle
#

alright

#

writing a example up

vagrant surge
#

one very important thing to take seriously on unity ECS vs Entitas is that unity is faster at doing queries, its memory is fully contiguous, but on the other hand, adding-removing components is very expensive

#

while on entitas adding-removing components is very very fast, so its recomended that you use entities for state almost every time

#

btw, very expensive in relation XD

#

unity DOTS is still much faster at adding components than monobehavior is

low tangle
#

ah, line 178 is a typo

#

it should be a readwrite not a exclude

slow epoch
#

@vagrant surge how different is the performance on adding-removing components in ecs vs entitas?

#

And i suppose with that you don't mean creating and destroying entities

onyx mist
#

What is a good alternative to coroutines that scales with timescale and can work with the job system?

#

Some preliminary googling led me to async but it doesn't seem to scale with timescale, tho I guess I can work around that if no other options are available πŸ€”

#

I usually use coroutines in a loop so anything that can run well there would be rad

mystic mountain
#

DynamicBuffer in jobs, do I need to use IJobChunk?

pliant pike
#

@mystic mountain no

mystic mountain
#

So how can I access in a IJobForEachWithEntity?

pliant pike
#

you have to use a specific format ijobforeachwithentity_EB or something like that

#

yeah I'm using IJobForEachWithEntity_EBC in my project which is an entity a buffer and a component

#

they are here in the changelogs

mystic mountain
#

Ah, wow. I just thought it was some background nonsense xD

#

Since like IJobForEach_C/C/C is same as IJobForEach ?

pliant pike
#

you have to format it like this in the execute public void Execute(Entity currentbusiness, int index, DynamicBuffer<EmployeeEntitysArray> currentbuffer, ref EmployeeEntityInfo currenbusemployees)

mystic mountain
#

Yeah : ) I got it working. But I just thought they were helpers for the regular IJobForEach()

mint iron
#

yeah its pretty cryptic, i guess if you're needing that then you've reached boss mode ecs level.

gritty grail
#

How did you guys go about converting the camera to an Entity and still having a reference to it in code?

tawdry tree
#

Which part are you having trouble with? Converting to entity? Or the reference?

gritty grail
#

Well kinda both? I put the Convert to Entity on the camera as inject

#

So maybe just the reference?

#

I hold the gameobject reference in this

#
[SerializeField] private GameObject playerCamera;```
dull copper
#

We're pulling back the veil on the Data-Oriented Technology Stack (DOTS). Users have described DOTS as a black box in the Editor, referring to the process un...

β–Ά Play video

Get a high-level overview of the Entity Component System (ECS) and turn-based game loops, and see a proof of concept built using ECS. The session covers some...

β–Ά Play video

For most Unity developers, the cutting-edge data-oriented approach introduced with the Entity Component System (ECS) is unfamiliar. While ECS clearly enables...

β–Ά Play video
tawdry tree
#

Well, you can't use the gameobject as the reference after converting it. However, you can get a reference to an entity.

Entity EntityRef;

entities.WithAll<Camera>.ForEach(entity=>{
  /* Save reference to entity here
  Maybe do  a sanity check to only get one, too, or add tags if you have multiple cameras. 'MainTag', 'SecondaryTag', etc.  */
EntityRef= entity
});
coarse turtle
#

If you convert a camera, that should be part of the archetype, so you can do Entities.WithAll<Camera>().ForEach((Camera c) => {});. I think the EntityQueryBuilder only supports up to 1 "UnityComponent" so you can't do multiple "UnityComponents" within the function args

tawdry tree
#

They probably want the entity reference, given how they used the gameobject in mono world. Unless they do some camera effects.
Then again, if the goal is to move the camera or something, they might as well do a normal ECS query each update, instead of caching it.

gritty grail
#

Well I'm not sure exactly what the best method is, trying to figure that out :>

tawdry tree
#

What are you trying to achieve?

#

Or: Why do you do the refererence in monobehavior?

gritty grail
#

I want to convert my camera and put a tag on it

tawdry tree
#

The conversion workflow has a method to add components during the process

coarse turtle
#

Oh, well you can just add a ConvertToEntity but with the ConvertAndInject to your camera

gritty grail
#

I did that, but how do I add a tag?

tawdry tree
#

Sounds like psuong has done that more than me, so I'll defer to them

coarse turtle
#

You want another MonoBehaviour implementing IConvertToEntity which adds the tag to the entity, this would also be on the camera

gritty grail
#

Okay, I was thinking that maybe was the solution, I'll take over from here then, ty

coarse turtle
#

np

compact hound
mint iron
#

Working on updating my debug drawing utility so you can draw stuff from within a burst job.

dull copper
#

@compact hound you may need hybrid renderer package, not 100% sure... I mean you technically need hybrid to be able to convert meshes etc to entity side but there are conversion tools that work without hybrid as well

#

it's been months since I last tried subscene conversion

compact hound
#

I have it

safe lintel
#

did you create the entity cache for that subscene?

compact hound
#

Yes but im missing some part of UI also for normal gameobjects

#

Do I need something to enable to work with entities?

safe lintel
#

oh you need to attach a ConvertToEntity script to your gameobject

#

that feature from the video is not yet released

compact hound
#

oh :<

safe lintel
#

yeah i was just gonna say itching to get my hands on that new live conversion feature

#

btw does anyone know how to create an entity within an authoring component that works in a Subscene? Not the entity that IConvertToEntity automatically creates but if you wanted to make another one within that same script just doing dstManager.CreateEntity(); wont have any effect in a subscene, only a non subscene usage. I did submit that as a bug(they havent gotten back to me yet) but kinda wondering if there was another way.

vagrant surge
#

@slow epoch about 10x to 20-30x slower in unity ECS vs entitas

#

more if your entity has a lot of componentes

#

i have that metric from my own implementation of a C++ ECS following the same memory model as unity ECS

#

best ii could is to get at about 10x the cost of adding-removing in Entt, which is like Entitas but C++ and faster

#

btw it still means like millions of adds a frame at 60 fps, so dont worry that much

gritty grail
#

Is DOTs networking out yet?

dull copper
#

@gritty grail kinda, but it's super early

#

that repo hasn't been updated since July tho

#

so would expect update once the new fps project gets released at least

gritty grail
#

Can I make a game without any network code and have an expectation that it shouldn't be extremely hard to implement it later?

dull copper
#

no

#

that's like the worst idea when making a multiplayer game

#

well, technically you can do all kinds of silly things, including that

#

but it's going to be a rocky road if you haven't prepared everything to play ball with your networking solution from day one

gritty grail
#

That's what I thought :/

#

Well it's going to be messy but I might just have to mess with what they have now.

fathom trout
#

is there any estimate timeframe for that 3rd person demo in DOTS (from unite keynote) ?

dull copper
#

@fathom trout should be out in few weeks now if their plans hold (they rarely do tho)

#

like, usually estimates drift

#

I'd assume they want the shooter sample to release somewhat at the same timeframe with 2019.3 release which is supposedly happening at the end of this month

fathom trout
#

cool yea, would be nice if it was around .3's release

low tangle
#

that would be sweet

safe lintel
#

sooner would also be nice

coarse turtle
#

yea, would be lovely to see how the network code works πŸ™‚

gritty grail
#

Can you move a camera with a job?

#

Or do I have to use a regular componentsystem?

low tangle
#

regular

compact hound
#

how to pass input form new input system to some component?

#

create component that stores input? And some system which process that input?

mint iron
#

@compact hound yep, create an entity, add some input components then have a system that updates the component values. @low tangle posted an example yesterday you might be interested in: https://hatebin.com/pttbvbekqd

compact hound
#

Ok so I have simple example.
I want to rotate player object so I have:

  • RotationSpeed component which stores rotation per second value
  • RotationSystem which modify Rotation based on RotationSpeed
    And I have some structural questions
  • where I should store max rotation per second value? In RotationSpeed or in some Player component?
  • How in MonoBehaviour store reference to player entity and adds to it input components?
tawdry tree
#

You should probably not do the last part in monobehavior, instead making a PlayerInputSystem or something like that.
Do the player control one 'thing' or multiple?

compact hound
#

@tawdry tree i want to use new unity input system, which is not dots ready i guess

tawdry tree
#

Hmm, that does make things trickier

#

Either way, in monobehaviours you can still do World.Current.GetEntityManager() or what it's called

compact hound
#

and i want be ready for multiple players

tawdry tree
#

And then do the usual entity stuff on it

#

Multiple players? Then you need a playercomponent with a PlayerNum value, probably.
But does each player control one thing? One character/unit/whatever? Or can they potentially control multiple units (like in most strategy games)?

compact hound
#

one unit per player

low tangle
#

the new input system works just fine in dots

#

just not in a job

#

a regular component system will work just fine

tawdry tree
#

Then you could simple give them PlayerComponent:

struct PlayerComponent :IComponent {
  public int PlayerNum;
}

And where you handle your input, you grab the entity manager on start and update the RotationSpeedComponent using the input in update

//Pseudo-code
class PlayerInput : MonoBehaviour {
  private EntityManager _entitymanager;

  void Start(){
    _entitymanager = World.Current.GetEntityManager();
  }

  void Update(){
    var players = Entities.HasPlayerComponent;
    foreach (possible playerNum){
       //Do inputs 
    }
  }
}
#

Though by the sound of what June says, this could instead be a system. Some general idea would apply, though.

low tangle
#

yep exactly

#

do that, but in a regular ComponentSystem

tawdry tree
#

Another way to handle it could be to give player entites some InputComponent with the relevant values. That would have other benefits such as easily scaling to work with certain online multiplayer methods, and you could take control away from the player, for example for cinematic stuff.
I gotta go now, but it sounds like June can help you with further questions πŸ™‚

compact hound
#

@tawdry tree thanks

#

@low tangle have you any usage of it in component system?

low tangle
#

I haven't personally no

#

I did see some people discussing it on the forms

#

one sec

#

this is a pretty good post from the guy working on the new input system

compact hound
#

but with this approach we are getting rid of of all its benefits? Like input map per player, events for specific actions?

low tangle
#

yep

#

ecs is a polling approach and you will have to create the event layer yourself (or just hook it in a monobehavuiour and inject entities)

compact hound
#

i will probably stick to mb for now

compact hound
#

Why Im getting this?
error: Accessing the type AICaptain.RotationInput is not supported by burst

public struct RotationInput : IComponentData
{
        public float Rotation;
}

[BurstCompile]
private struct ProcessRotationInputJob : IJobForEachWithEntity<RotationInput, RotationSpeed>
{
    public EntityCommandBuffer.Concurrent CommandBuffer;

    public void Execute(Entity entity, int index, [ReadOnly] ref RotationInput rotationInput, ref RotationSpeed rotationSpeed)
    {
        rotationSpeed.RadiansPerSecond = rotationInput.Rotation * rotationSpeed.MaxRadiansPerSecond;
       CommandBuffer.RemoveComponent<RotationInput>(index, entity);
    }
}
low tangle
#

command buffers are not bust compatible yet

#

comment out the tag for now

#

or dont remove the input

#

just set it to zero

compact hound
#

i was just wandering what is faster removing or setting to 0. But when i remove it should system run faster in other updates?

low tangle
#

setting is faster than structural changes like add/remove

compact hound
#

setting yes, but most of the time if we remove it system updates will have less Input components to update

low tangle
#

how many of these components do you expect to have?

#

< 1000 is pointless

vagrant surge
#

also be careful with adding-removing components

#

in some cases its more expensive than adding-removing entire entities

low tangle
#

yep

#

shouldnt discourage it though

vagrant surge
#

after all, add-remove component its a full delete, then swap, then create it again

low tangle
#

yep

vagrant surge
#

in a lot of cases for this kind of thing its better to spawn a new entity that points to its target

low tangle
#

honestly this system seems kinda contrived atm

#

simple example that isn't really thought though yet

#

like what are you actually trying to solve

vagrant surge
#

for a rotation input, you probably only have like 1

#

so just leave the component there and set to zero or to whatever if you press the joystick

compact hound
#

i see

#

would you still use commandbuffer for it?

vagrant surge
#

im waiting for Tiny or just normal ECS to be a bit more developed to try to make some pure ECS stuff. i normally just do C++ stuff with different ECS libs

#

one is similar to Entitas model, another one i created myself and its similar to how unity works

compact hound
#

I think ECS could fit here well

compact hound
#

How to get entity that has Component with specific data in MB? Searching it some time with no luck :<

tawdry tree
#

Run an entity query, then check manually inside the lambda?
Suboptimal perf-wise, but probably not a problem unless you have tons of em.

compact hound
#

@tawdry tree I was on this talk πŸ™‚ The problem is that I want to use new Input System which is not dots ready yet so I want to pass input from MB for now

tawdry tree
#

You could make the monobehavior create an entity, or set values on an entity, an have some other system 'read' those and use that to set the value on the relevant entities. A bit roundabout, but...

compact hound
#

This is what Im doing but don't know how to get player entity in MB πŸ˜‚

tawdry tree
#

You can use the entity manager in a monobehavior

compact hound
#

yes but how to find specific entity?

tawdry tree
#

Give it a component with a certain value? With players you're going to have a limited amount of them, right?

compact hound
#

I mean I don't know the api. In EntityManager i see only GetAllEntities. You mentioned about some Entity query?

tawdry tree
#

I might not be talking about features which currently exist (in an easily accessible way), since I haven't worked with the latest versions of ECS, informing myself instead from talks and the documentation

#

Let me boot up unity and see if I can't find out before i have to go for dinner

#

I've been meaning to update my project and check out the latest APIs anyway

#

Speaking of which, what Unity version and Entities package do you use?

compact hound
#

Unity 2019.3.0b5 and newest package

tawdry tree
#

So basically latest then

tawdry tree
#

That's one way to do entity queries, at least

#

Don't intellisense help you if you write entityManager. (and wait a moment?)
Looking through that kinda stuff can be illuminating

compact hound
#

Ok so I have query with Player component. But how to get entity that have specific id in that Player component

#

i can do var players = query.ToComponentDataArray<Player>(Allocator.Temp); and iterate but then i will lost entity reference?

tawdry tree
#

I'm going to eat dinner now, but there should be other methods on query, check what intellisense says, or you'll have to wait for someone else.

#

Do you really need the entity reference, though?

compact hound
#

I have hard time with api discovery (i think is better word for it) Comments on methods would be nice πŸ™‚ .
I want to store player entity reference for creating input data components for specific player.

compact hound
tawdry tree
#

Comments on methods would indeed be nice; it's one of the things I've been missing as well.

gusty comet
#

Figured out a puzzling problem I was having...evidently TempJob wasn't enough. Needed to use Persistent despite the NativeArrays only being used in two jobs (written in job 1, then read & deallocated at the end of job 2)

#

That was a really confusing problem (indicies mismatching showing me bad data in certain scenarios, out of memory exceptions other scenarios) started to look like a race condition, other times it looked like it was just ignoring my conditionals which would have skipped certain entities

#

least I know what that bug looks like now

tawdry tree
#

Unexpected exception System.IO.FileNotFoundException: Could not load file or assembly 'Smash, Version=0.3.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies.
File name: 'Smash
While compiling job: System.Void Unity.Entities.JobChunkExtensions/JobChunk_Process`1<Unity.Entities.GatherEntitiesJob>::Execute

Bugger. Anyone seen this error before?
Further info, I just updated all my project's packages. No compile-time errors, but get that one if I try to run.

compact hound
#

Tried to restart unity?

tawdry tree
#

No, good point

#

That worked, though it seems like I have some updating of systems to do...

gusty comet
#

That's another good bit of info - if something like an OutOfMemory exception occurs due to a bug in my code and I find & fix the bug, further problems can arise which normally wouldn't have if I had just restarted the editor after fixing my code

sonic oyster
#

Hey!

#

I have a small question regarding job system.

#

I created a void inside Execute()

#

will passing ref NativeArray<bool> NA_test with arguments make the void return the changed values to original NativeArray<bool>?

#

i.e.:


public void Execute()
{
    void MyMacroFunction(ref NativeArray<bool> NA_test)
    {
        NA.test[0] = true;
    }
    
    MyMacroFunction(ref MyNativeArray);
}```
#

πŸ€”

compact hound
#

it is easy to find out πŸ˜„ Personally i don't see reason to do that. I think it should work. Also this void method can be outside Execute I guess.

#

Your NativeArray is in job whole scope so you shouldn't even need to pass it

sonic oyster
#

You say? Im gonna try that then

#

Nope.

#

Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead.

compact hound
#

you are using this in struct

sonic oyster
#

i moved every function i wrote out of the Execute() and it seems to compile now

sonic oyster
#

nailed it! thanks! ❀

slow epoch
#

Has Unity said any reason why they are not doing anything related to Editor for ECS yet and focusing on all the conversion stuff?

safe lintel
#

maybe its just too big a task to do a pure ecs experience for the editor? sounds like parts of it etc still require gameobjects (joachim used the phrase "companion gameobjects") so for the near future conversion is the name of the game

slow epoch
#

I suppose is not as easy as making a new editor window that has an entity hierarchy

#

But i somehow feel like ECS should be part of a different engine knowing how different is from what Unity is

safe lintel
#

yeah but then it might take eons before having something useable. might as well reuse stuff in hybrid mode that would take too long to make pure versions of and have something where you can get most of the benefits from. making a new engine from scratch, might as well spin up another company and product if you do that.

low tangle
#

this post and the others in the thread make it seems like, obviously they've been working on prototypes of unity systems but its proving too difficult to just switch everything over

#

so hybrid is the road towards what they want to make

#

which tbh once conversion is cleaned up, it will literally be what the editor layer would look like on top of a entity stack. this next version is running entity conversion all the time

#

like the one that comes to mind, is a hierarchy tree, doesn't exist fully and when it does, its only a runtime structure for updating the matrices

#

so you cant just display the entity hierarchy like you can with monobehaviours

#

so you have to create a intermediary tree structure for editing and manipulating it

#

which just brings you back to a gameobject scene setup

#

so in a way they already have a good stack of that half of the pipeline, they just need to focus on the conversion (which they now have put a ton of effort into) which bridges over to ecs where its done and legacy without. then just slowly bring the rest of the systems over and nothing too painful ever happens to us users

#

after seeing this unite It all started making sense

safe lintel
#

yeah what they showed and the ideas for the future makes a lot more sense than what exists currently

fathom trout
#

has anyone allocated NativeList (or any native container) within an IJobParallelFor, using Allocator.Temp ??

#

I have a IJobParallelFor which for each index, needs to do a bit of recursion (to a max depth) and skip certain elements that it already moved through.

#

so in Execute I allocate a NativeList then pass it to a function (the recursive function), it adds processed indices to the list and each recursion checks if the index it processed is already there (and if so continues)

#

then the native list is disposed right after the function is called

#

it seems to work but I might also be seeing weird behaviour from it

safe lintel
#

i always use tempjob for jobs

#

oh wait you want to allocate inside the job? hmm not sure if thats possible

low tangle
#

thats what Temp is for

#

if it isn't complaining you are probally okay

#

have you thought about using a fixed size array instead?

#

thats usually what I do in gpu programing - same applies here

fathom trout
#

yea the fixed size could work, i just tried an alt version where i send a large TempJob array into the job (each index gets X amount of indices of the array) and it exhibited the same behaviour, so i think it is something else & not related to doing the in-job temp allocation

gritty grail
#

Can I not move a camera by it's translation component?

safe lintel
#

well yes if you have a CopyTransformToGameObject component on the camera entity

#

theres also a CopyTransformFromGameObject if you want a gameobject to drive a translation/rotation component value

#

or is it localtoworld

#

cant remember, its late 😩

gritty grail
#

oh okay

#

thanks

#

So I can move a camera in a job

#

good to know

safe lintel
#

yeah*

gritty grail
#

whoops

#

thanks though xD

compact hound
#

Case:
Ship with front cannon and rear 3 cannons on both sides

What guys you think would be best approach in ECS? I would make cannon an entity with position, rotation and canno. On ship entity store references to cannons during conversion from GO?

And how to tell them to shoot?
Input -> Makes input entity
InputSystem -> process input entities. And now I see few options.

  1. InputSystem spawns bullets from list of cannons form ship entity
  2. InputSystem tells Ship to shoot, then some ShipSystem process it. But this can be further divided. I can have later some tower which also have some cannon that can shoot. I think would be best to avoid entites like "ship", "tank", "tower" but then where to store list of cannons :D
    I really struggling with ECS thinking. 😬

Maybe any1 have good article/book how to design things in ECS with good examples?

mystic mountain
#

How can I use singletons in Jobs?

#

E.g. I want to change value in ForEach job, do I get Entity and Component from a Query to fill up job and update with a command buffer?

low tangle
#

query.ToComponentArray<T>(out jobhandle)
stuff that handle into the inputs of your job
sanity check before the job schedules that the array is 1 (or more)
then just access slot 0

mystic mountain
#

Ok , I found that I should use Chunk if I don't want to internally call "Complete" on all jobs dependent on my Singleton..

low tangle
#

query.CalculateEntityCount() >= 1;

wispy walrus
#

Singletons are inherently against the DOD approach

#

they arent really mutually exclusive, but it defeats the purpose of both to use them together

mystic mountain
#

I have data for e.g. number of players in my game. How do you propose I increment/decrement this + do some logic?

wispy walrus
#

arent you itereating over them in the game loop? To handle inputs, movements, animations, whatever

mystic mountain
#

This is the game server, who is asked by the master server if there are any spots open for new players to join (request are in a dynamicBuffer)

wispy walrus
#

oh so you are talking about the layer above DOTS, seems like I misunderstood. Then again you couldnt use signletons with entities either way since they are structs so my comment didnt make much sense, sorry bout that

mystic mountain
#

Hum ok, so why I cant use singleton you say?

wispy walrus
#

I misunderstood, nevermind πŸ™‚

mystic mountain
#

@low tangle What does the jobHandle do in this context?

low tangle
#

schedules the work to find the chunk, copy the data to the native array

#

does that all in a job and makes it right before you run your job

#

doing just a little bit more work on other threads :)

#

this works good for other types of jobs as well

#

like say, grab all n players into a array, for this job to have access to

mystic mountain
#

Hmm ok

#

And disposes itself after as well?

#

And it has readWrite definitions from Query I suppose.

low tangle
#

[DisposeOnJobCompletition] on the array, in the last job that uses that array (you can chain it though other jobs)

#

doesn't have to be readWrite, since its a copy

#

but if you want to apply it back, you can do that too

#

theres a nice command to bulk apply back a native array of component types to a query

#

but you would have to do that on job completion which can be a pain

mystic mountain
#

Cool, but since this is a singleton, it's maybe same or better with commandBuffer?

low tangle
#

are you going to write onto the singleton component or just read from it?

mystic mountain
#

write

low tangle
#

tricky with a paralel for

#

if you do it as a single job and not go wide, then its fine to just write and increment

#

but if you want to use all cores, you cant write to a single value

mystic mountain
#

I only iterate over one entity as well

low tangle
#

oh

mystic mountain
#

So should be fine.

low tangle
#

alright

#

.ScheduleSingle() then and if it complains on the array, you are safe to put a [NativeDisableParalelForRestriction] on it

#

since you only ever do one write on it

#

1:1

mystic mountain
#

Cool!

safe lintel
#

anyone catch the thread with joachim's answers regarding lights and lightmaps? https://forum.unity.com/threads/authoring-lights-and-static-content-with-lightmaps.755534/#post-5035073

seems like the companion object [system] is different from that light pooling system in the hybrid renderer, wonder how it works

wary anchor
#

Hi all. Question about singleton components vs any other system for storing global/game-state type data at runtime.

I currently have some public NativeArray data (very infrequently recalculated) on a system which other systems occasionally need to access. This works fine but feels a bit wrong somehow. But much worse than that, I also have some global static stuff that I really want to get rid of as it was only ever a temporary "where can I chuck this stuff I need everywhere" thing. What's the current thinking on things like game settings and calculated data that many systems need access to within DOTS?

neon kraken
#

Hello,
I want use ECS for spawn my elements buts i don't know how i can span an text. I use prefab and i have try use TextMeshPro and 3D text and both not work :(

My question : How i can show text from an entity ?
Thanks.

mint iron
#

@neon kraken you can store text with an entity by adding a NativeString64/NativeString512 field in a component. It can be converted to a managed string later using .ToString().

neon kraken
#

@mint iron store an string on entity and spawn en text mesh pro normally and link text from entity ?

amber flicker
#

In case @neon kraken you're unaware (there's no reason you would know unless you'd be in DOTS a long time) - the only components supported by the conversion workflow currently are pretty much MeshRenderers and some physics stuff. When you try and convert a prefab with components that aren't supported am I right in thinking there are still no warnings or similar?

neon kraken
#

@amber flicker ok and no this doesn't make and warning

amber flicker
#

I might post something on the forums - anyone else here think at least a warning would be sensible?

#

Ah thinking about it, I remember at Unite they showed an inspector window that shows what the conversion will look like afterward. Doubt it will show things it hasn't converted though. Which I kind of understand but it's a bit rough for anyone new to it.

neon kraken
#

ok, and how i can synchronize text with entity data ?

amber flicker
#

So if it's the data then as @mint iron started mentioning, there are NativeString variants. For the display, you'll still need to use a monobehaviour. In my opinion, probably only worth separating this out if you have a lot of strings & string manipulation and you can work with capped string sizes.

neon shell
#

So, I just recently imported Unity Physics for use with DOTS, and I noticed the 'enter playmode' time increased by over 10 times (total of about 12 seconds per attempt to play), removing Unity Physics package restored that time to the much faster one, is anyone else experiencing this? NepThink

mint iron
#

@neon kraken not sure exactly what your trying to do but here's an example:

Imagine you have some enemies, and they have been converted into entity prefab so they can be instantiated from the ECS side. They have a component on them with their name stored as a NativeString64.

You might have a UI element that shows the enemy name when they are shot. The text is still the normal monobehavior textmeshpro canvas stuff. So you just need to get the name out of the enemy and then updated in the UI.

You could have a system, inventively called NameUpdateSystem which 1) finds the entity of the correct enemy, 2) reads the name from the component on the enemy 3) updates the text somehow (a longer explanation if you get to that point).

neon kraken
#

@mint iron ok, thanks

wary anchor
#

what are you guys doing for storing things like game settings? scriptable objects read into singleton components?

#

I'm not sure how to structure things best and I'm looking at a big refactor rn

silver dragon
#

@wary anchor I store game settings in singleton components. Other runtime data, e.g. for my chunk system is stored in its own system which only holds data. All other systems read/write the data there. The chunk data mainly consists of Dicts, NativeQueues and NativeLists. They can't be handled in a component.

wary anchor
#

@silver dragon thanks, so storing the Native Container type data with a public getter on a system is not an unreasonable way forward

silver dragon
#

What's unreasonable in dev? Depends on the use case πŸ˜›

wary anchor
#

kinda makes it easier to visualise, although it does feel a bit like mixing data and function

#

I dunno man, some of my code is definitely unreasonable by any metric πŸ˜„

silver dragon
#

Maybe we get some other possibilities later on, but for now this is the easiest way i found.

mint iron
#

i'm using prefabs and when they get instantiated (either from addressables or being in the scene by default) the conversion loads them into DataComponents. In some cases it was creating a lot of duplication to request the data from many systems, so i ended up making helper systems that expose public methods.

wary anchor
#

@mint iron thank you!

mint iron
#

but im not happy with it, doesnt feel good

wary anchor
#

It almost feels like they should have not tried to bridge the gap between OOP and DOP and just made a totally fresh start on a DOTS editor, most of the issues I've had have derived in one way or another from the hacky way that we have to generate data or systems, or interact with them, or visualise them, etc. But we are where we are. I'm kinda glad to tried to go "pure" ECS rather than anything hybrid at this point tbh

upbeat eagle
#

Is DOTS the same as the Entity Component System?

wary anchor
#

yeh ECS is part of the whole Data oriented tech stack

upbeat eagle
#

Ok, just read the tutorial on ECS up at Unity's site. Sorry for butting in.

wary anchor
#

np πŸ™‚ I'm procrastinating. Must get head down and crack through this refactoring. Thanks for the responses all!

mystic mountain
#

A bit in relation to what @wary anchor asked before, is there any benefit from using SingletonComponent compared to NativeArray of data for singleton patterns?

low tangle
#

Just preference

#

Could make your job simpler but that's about it

mystic mountain
#

Another question x) Is there any system, or system group that is only run once? On like initialization?

#

When prototyping I currently have a lot of data in "setting assets" ie. scriptableObjects that are used as singletons. Now I want to expand it by adding a systems that when used in editor, writes to component at start of simulation loop, and reads in end of simulation loop. And outside of that creates the data on initialization.

#

I might create a system that destroys itself in the update(?). And use before and after Begin/EndSImulationEntityCommandBufferSystem.

wary anchor
#

June showed me a way to do one-time jobs a while back. It works like this: you create an entity with an empty Component as an event trigger on it. For the system, you use this component to construct a query, and Require that component to be present for update to occur (then when it's not present, you'll find the system is not run in the debugger). A rough outline of how the system is set up is here: https://hatebin.com/owgacmvdhy

#

It means you can also kick it off again at a later time if you wish just by creating that Event (which itself is literally just an empty IComponentData struct)

mystic mountain
#

Hmh, yeah but the system will check for the query for each update, isn't there a cost to that?

mint iron
#

you can set Enabled = false on the system.

mystic mountain
#

That is too simple ._. :d

wary anchor
#

well my raymarching/ECS system runs at 1000 fps for 33005 atoms and custom physics, so if there is a cost, I don't think it's very much

mystic mountain
#

Do you run with 50~empty systems?

wary anchor
#

only a handful so far but I'm currently doing a few more during this refactor

#

Check the debugger though, the system is "not run" - the extent of the overhead I'm not sure about, but try it and see πŸ™‚

mint iron
#

yeah its pretty cheap to check simple queries, since Archetype already has a count of items within its chunks. I haven't seen perf tests on how it scales with complex queries though.

mystic mountain
#

Yeah, so maybe not too much overhead then. : )

#

@wary anchor Is there any reason for having ReadOnly on entity creation?
World.Active.EntityManager.CreateEntity(ComponentType.ReadOnly<AtomGridUpdateEvent>());

wary anchor
#

yeah, I don't want to write to it πŸ™‚

mystic mountain
#

Hm, so this will give error? I'm asking because in https://gametorrahod.com/ecs-singleton-data/ he/she wrote

    em.CreateEntity(ComponentType.ReadOnly<SingletonData>());

    s1.SetSingleton(new SingletonData { singletonInt = 555 });

Which doesn't make much sense for me then :S

wary anchor
#

ahh no, this isn't for data, this is literally just an event signal

mystic mountain
#

Ok , but .. does ReadOnly do nothing on data or what? πŸ˜›

wary anchor
#

well you can specify you want something to be readonly or readwrite, as this doesn't even contain any data, and I have no intention of writing any, it might as well be readonly

mystic mountain
#

Ok, so you're saying this 5argon guy is writing bad code 😎

wary anchor
#

wait? what I'm not suggesting anything of the sort

#

you linked to a singleton entity page, I'm not talking about that

#

I showed an example of how you set a system to run once (or on demand)

mystic mountain
#

Yeah yeah, I understand.

#

I just figured you might know if the code provided in the singleton post should work or not since you used same syntax, and you explained it so that it shouldn't work πŸ˜›

wary anchor
#

I'm afraid it's above my pay grade to comment on that! πŸ˜›

mystic mountain
#

@wary anchor Thanks anyway! : )

wary anchor
#

np, gl! I'm kinda doing something similar at the minute too, but lots of refactoring to do while I'm at it

mint iron
#

im gonna have to redo my singleton stuff soon, because its annoying af when you try to load a new scene to test something, and you have a bunch of systems that blow up because they're using singletons that don't exist.

#

i could put HasSingleton everywhere an bail on the updates but thats going to bloat out my systems

wary anchor
#

I'm looking at whether Addressables + scriptable objects is a reasonable way forward but it looks too complicated at first glance

#

SOs seem the natural solution

#

but I'm not sure of the most sensible way to get their data into a usable form within ECS

mint iron
#

there's an example floating around somewhere of scriptable objects conversion.

mystic mountain
#

Think there was a post about asset blobs and SOs as well

mint iron
#

Addressables has a learning curve, but i like the idea of being able to update the configuration remotely, and the attached conversion scripts do run whenever you instantiate an addressables prefab. In theory if your systems are waiting for stuff to exist before they run, it should work well with the async nature of addressable loading.

pliant pike
#

I'm just trying to figure out how exactly to use Blobs and SO's if you figure it out let me know

mystic mountain
pliant pike
#

yeah thanks, its still kind of confusing, blobassetreference only seems to work in a class for instance I'm not familiar with some of the keywords, its difficult when I'm just blindly copying code

#
public static BlobAssetReference<WaypointBlobs> ConstructBlobdata()
    {
        var builder = new BlobBuilder((Allocator.Temp));

        ref var root = ref builder.ConstructRoot<WaypointBlobs>();

        var nodearray = builder.Allocate(ref root.Waypoints, 3);

        nodearray[0] = new float3(0, 0, 0);
        nodearray[1] = new float3(100, 100, 100);
        nodearray[2] = new float3(200, 200, 200);

        return builder.CreateBlobAssetReference<WaypointBlobs>(Allocator.Persistent);
    }```
#

is that all I need? I cant find the blobdata or figure out how to reference it

mystic mountain
#

How to solve order of your systems when you can use Being/EndSimulationEntityCommandBufferSystem ? Prefix your systems with AAA / ZZZ xD

#

@pliant pike I never used it myself, so can't tell.

pliant pike
#

it just seems really convoluted

wary anchor
#

I'm contemplating just how dirty I would feel if I made a system whose sole purpose was to store data.

pliant pike
#

I think I already did that leahS

wary anchor
#

I just don't know if I can bring myself to do it

mint iron
#

πŸ˜„

coarse turtle
#

@pliant pike you should dispose your builder before you get out of scope of the ConstructBlobData() function call

#

plus a lot of the style is doing everything by reference, it honestly looks a lot cleaner in c++ than in c#

pliant pike
#

thanks @coarse turtle hopefully they make it a bit more straightforward in the future

mystic mountain
#

@wary anchor @mint iron Gonna give you a treat πŸ˜‰ I have now scriptable objects that contains Data and is updated into the world.

Templates systems and base ScriptableObject
https://pastebin.com/muHxMwYP

ScriptTemplate for reduced copy pasta
https://pastebin.com/XXdtRfyH

Realdeal : )
https://pastebin.com/Rri0qH2w

So simply create right click and create the setting. Create the settingSOAsset by assetmenu in a resource folder , press enter to use default name (required) : )

dull copper
wary anchor
#

@mystic mountain thanks I'll take a look when I'm back online! I appreciate the effort, thank you!

true star
#

has there been any word on RaycastCommand2D appearing?

mystic mountain
#

I might add that it will most likely not behave as expected if you have multiple worlds and change values in one of the worlds, then you simply have to remove those Insert/Extract systems : )

vagrant surge
#

@dull copper yass

vagrant surge
#

@dull copper dissapointment of a talk

#

they say absolutely nothing of how they make it work

#

its just a "intro to ECS" talk

compact hound
#

@vagrant surge i have same problem . Every Unity talk about ECS is kind of introduction

#

What is ecs and some really base system exaple

vagrant surge
#

yeah man its getting real old

#

the only videos unity related about ECS about a higher level architecture

#

is the videos from Entitas

#

but Entitas isnt the same model as unity ecs

#

then you also have some of the videos by Mike Acton himself about stuff like Megacity

#

which is crazy advanced

wary anchor
#

Mike Acton's boids walkthrough is very good - at least after about 5 runs through with pen and paper for me. I eventually got what was going on. I'm sure sharper minds would do it much quicker than me. But do watch that, several times, with the code in front of you and stepping through each phase to work out exactly what data goes where. I found it really helped me understand how to use ECS in my own project

vagrant surge
#

i really liked the megacity culling one

neon shore
#

Looking at the trend on Unity Youtube, soon we'll have "Create/Build <game_genre> with DOTS" for anything.

dull copper
#

@vagrant surge at least half of the unite sessions are intros, they are not really meant to give much info if you've already used the thing

#

tbh, I dunno if they could fill that many sessions if everything was in depth πŸ˜„

vagrant surge
#

man, literally every ECS talk is about just the basics

#

they could talk about using it in practise

#

not just "yeah you can do parallel for very fast"

dull copper
#

unless it's Acton or the Burst guy

#

putting roadmap talk as one was bit stretching it

neon shore
#

The biggest problem is probably that they have to start from scratch and explain the basics of ECS in every talk again. The first 10+ minutes of every talk are basically "Why DOTS/ECS".

vagrant surge
#

its retarded, honestly

compact hound
#

Ye

vagrant surge
#

one talk after another going with the ECS basics

compact hound
#

Even those marked as advanced πŸ˜‚

frosty holly
#

I have some PURE ecs code that I am trying to add to an existing project and nothing is rendering. I was wondering if anyone might be able to help. The code renders when in a standard project

I'm using
Unity 2019.12f1 or 2019.2.4f1 (With latest packages)
Burst 1.1.2
DOTS Linux Platform 0.1.3
DOTS Platforms 0.1.3
DOTS Windows Platform 0.1.3
Entities 0.1.1
Hybrid renderer 0.1.1
Jobs 0.1.1
Lightweight RP 5.7.2
Memory profiler 0.1.0
Shader graph 5.7.2

using System.Collections;
using System.Collections.Generic;
using Unity.Entities;
using Unity.Transforms;
using Unity.Collections;
using Unity.Rendering;
using UnityEngine;

public class DotsManager : MonoBehaviour
{
    [SerializeField] Mesh myMesh;
    [SerializeField] Material myMaterial;

    private void Start()
    {
        EntityManager entityManager = World.Active.EntityManager;

        NativeArray<Entity> entities = new NativeArray<Entity>(1, Allocator.Temp);

        EntityArchetype cubeArchetype = entityManager.CreateArchetype(
                typeof(RenderMesh),
                typeof(LocalToWorld),
                typeof(Translation)
            );

        entityManager.CreateEntity(cubeArchetype, entities);

        for (int i = 0; i < entities.Length; i++)
        {
            Entity cubeEntity = entities[i];

            // Setting rendering.
            entityManager.SetSharedComponentData(cubeEntity, new RenderMesh
            {
                mesh = myMesh,
                material = myMaterial
            });
        }
    }
}
#

The code works in another project and I am a bit stumped as to why

pliant pike
#

are all the packages and versions up to date?

frosty holly
#

Yes

frosty holly
#

Even systems don't seem to work. Seems to be totally broke somewhere

#

Works in an empty project. I bet there is just one checkbox or something somewhere

safe lintel
#

theres more to an entity than just those components for rendering

#

add converttoentity on a cube and double check the components that get added to it.

karmic jewel
#

Hopefully someone can point me in the right direction. I come from a very heavy OOP background and so far, really jive well with ECS, and I've found its how I've been wanting to program all along if that makes any sense.

So, I'm trying to make a handful of turrets aim at where the players mouse cursor has raycast into the scene and contacted a plane. I have a Player component, and a Tracker component (the Player component is essentially a tag, since AI controlled turrets will operate differently) and the Tracker component is a float3, essentially the point in space we are wanting to aim at.

My stumbling block is, how to raycast from the camera, into the world (so basically grab the rotation and position of the camera) and store that somewhere that each of the players turrets can access to get the position that was hit, and add it into their tracker component (to be used later by a system that actually manages rotating the turret appropriately to hit that point).

Traditionally, I would have used something like Zenject, DI in a reference to the main camera, so each turret could cast for itself (somewhat wasteful, since all the players turrets are aiming at the same spot). I feel like I'm missing a critical piece of understanding that will bridge that gap for me.

I guess a simple version of my question is, how to make many entities use the same camera for raycasting purposes? Or, is there a more appropriate ECS way that I'm failing to think of?

frosty holly
#

Finally found it. UniRX seems to be causing it. Have no idea why yet though

EDIT: Use the latest version of UniRX and it works

coarse turtle
#

@karmic jewel so if you think about it from a data aspect, assuming we have 1 camera, we can likely grab camera data from a query and likely perform a raycast and use tht collision pt for the turrets

So as just as a crude example that runs on a main thread (ofc you can likely try to parallelize this by writing the collision pt to a component data and run the turret logic on a job, also I'm assuming you're not using the Physics package):

// In on update of a component system, let's assume that 
// camQuery = GetEntityQuery(ComponentType.ReadOnly<Camera>());
var cam = EntityManager.GetComponentObject(camQuery.GetSingletonEntity());

// Do some stuff with our camera like grab a world position via a raycast
var ray = cam.ScreenPointToRay(your_mouse_position);

if (Physics.Raycast(ray, out var hitInfo)) {
  // Get your collision point from the hitInfo
  var collisionPt = hitInfo.point;
  
  // Iterate through your turrets and do some custom logic
  Entities.WithAny<Turret>().ForEach((ref Turret turret) => {
    // you can access your collisionPt in this lambda expression
  });
}
karmic jewel
#

Interesting. I had just started looking at the EntityQuery. Also on further review of the examples, it seems I had a misconception about the needed simplicity in the component systems.

I did plan on trying the new Unity DOTS physics, but i may work on just getting a version up period before getting too crazy. Thanks a ton @coarse turtle , I think this can get me on the right track!

coarse turtle
#

Np

#

Quite a few ppl on this channel have used the physics package more extensively; I'm mainly in the 2d space atm so I haven't quite used it πŸ˜…

karmic jewel
#

I've just been eager to get myself out of the rut I'm in! ECS seems like a pretty big shift so hopefully it can get some creative thinking going

compact hound
#

I added new physics package to my project and their step physic system takes 4ms for allocating per update with empty project πŸ˜„

mint iron
remote coyote
#

Did Acton do any talks this Unite, or do they save him for the Unite in the US?

#

I was at least glad to get a confirmation that they have "some" LODing on Netcode snapshots in the next version.

remote coyote
#

Also for some lower level stuff, do look at their github. They released some cool DOTS projects around Unite.

#

But I agree that their talks have been too shallow for the most part.

#

Hopefully they'll go more in-depth at GDC when Entities package has reached 1.0

gusty comet
#

This is sort a theme with Unity though, most (if not all) of their talks are high level that gloss over the details

#

I guess that is a consequence of being a generalist engine and not making any games at the side

#

I like the mike acton talks, he really goes in depth, but then again

#

it isn't really a practical talk for a game dev

#

its cool, just not what I expected I guess

remote coyote
#

I actually think its more about the fact that they want to make DOTS approachable for more than just the advanced user, but DOTS is a pretty advanced topic, so its hard.

gusty comet
#

that is also true

#

but what I'm talking about isn't just for dots

#

pretty much all of their talks are like that, addressables, xsrp etc

remote coyote
#

But I completely agree. They have talked about what ECS is, what cache is, SIMD, etc... hopefully when it gets to 1.0 they start focusing more on actual use. Another point might be that they don't want to have deep dives on code APIs that will be deprecated in a year. When they're out of preview that will no longer be the case.

#

True, they seem to target the wrong audience for a lot of this.

#

The developers who are interested in the advanced topics like addressables and DOTS right now, are the developers who want the advanced content, that knows what it is already and have probably tried it themselves, but just needs more examples and more deep dives.

#

I've spent a lot of time understanding the DOTS Netcode preview from late June, and they've barely talked about it or done any docs on it. I'm super hyped for the next version.

#

But had hoped for more deep diving into using it, from Unite. Just barely skimming the surface.

#

I saw some things that I really liked though, so its more about just getting access, for me, now.

gusty comet
#

I hope they don't leave networking alone like they did with unet, or with current navmeshes

#

I was hoping for an update on the fps sample project, perhaps making it use new dots features etc

mint iron
#

a lot of the samples have been disappointing in that regard, where they're skipping over the complexity by just using managed components and no burst jobs, essentially just using systems update as a monobheavior.

gusty comet
#

unity needs a fully fledged sample project that is kept updated with every release rather than one of projects that work on specific versions and then get forgotten imho

#

I though fps sample was just that, it would get updated with new features etc

remote coyote
#

I doubt they'll update FPS Sample to DOTS. That would surprise me at least. It shows "a way" to use the new network stack with a more hybrid gameobject oriented approach, suited for production right now.

#

Their new TPS demo will be their advanced DOTS sample, that show DOTS Netcode, DOTS Animation, Live Link, etc.

mystic mountain
#

Found it, was a ToComponentDataArray job from wrong query.

#

A bit annoying that it froze my unity though x)

mystic mountain
#

Is there a way to tell a job not to run if DynamicBuffers are empty?

#

And a bit more abstract question, what determines if you use DynamicBuffer vs entities with tag?

remote coyote
#

I use a tag for that

#

or rather, a tag when buffer has elements

#

you can also do hasComponent on the buffer element to check if the buffer is allocated for the entity

#

I do not thing dyn buffer has any way of telling whether it has elements without getting the buffer, and then you're already processing the entity.

#

so a tag was the only workaround I managed to come up with, and its fairly clean, as long as you remember to add/remove it properly

#

adds another element of adding bugs if not careful of course

mystic mountain
#

Yeah ok, I simply early out atm. Just thought there might be some functionality built in : )

remote coyote
#

would be nice to have some built in functionality for this

#

its easy to forget to add or remove the tag, and thus get hard to find bugs going. But I very carefully unit test most of my code, so I retain a bit of confidence when approaching it like this.

mint iron
#

for the second question, you could in many cases break out a DynamicBuffer into components on entities. What you gain is being able to use queries on them, and reference them each independently (Entity) rather than through a parent association. What you lose is the ability to have them immediately and easily available from the parent's context and to iterate them locally/fast in a job. I guess you could prefetch them and pass an array of them into the job to get a similar thing going or you're stuck with xFromEntity.

#

But i think you already know all that, i guess its just what best suits how you need to access it.

#

Also DynamicBuffers you can add/remove without creating sync points which is nice.

mystic mountain
#

Hmm right. So I'm thinking if there are X many that it will be faster to parallelize it would be better to use entities.

#

Ah, good point.

#

Another thing is that they are not independent of the "parent" entitiy, so if it is removed they won't be removed as well if using entities.

#

Which is a double edged sword, sometimes you might want that : )

wary anchor
#

@mystic mountain I couldn't get your singleton settings stuff to work, lots of errors about not having scripting define symbols at the beginning of lines and so on.
It seems like a very complicated solution, I'm really after something quite simple that I can understand more easily. How are singleton components typically created? In a master singleton component system or like you have with their own systems?

mystic mountain
#

@wary anchor Could you show me your errors? It might just be that you don't have the NetCode. Where you just change where it says "ClientAndServerInitializationSystemGroup" and similar to "InitializationSystemGroup"+

wary anchor
#

that was one of the errors about the group, but hang on I see the problem with the other one. scratch that user error. I already removed them as I couldn't get it to work before

#

I'll try again

wary anchor
#

okay getting closer, but getting a null ref exception about the newly created settings object in a resources folder - it is in a resources folder, so not sure why it's not being picked up

mystic mountain
#

You kept the name it generated?

wary anchor
#

restart unity?

#

yeah

#

sorry about this, being totally thick today for some reason

mystic mountain
#

Hmm, you can send DM of code + printscreen of resource in folder if you want.

wary anchor
#

I won't bother you, if I can't fix this I shouldn't be involved in making games. Cheers!

mystic mountain
#

I don't mind x) I might've made some mistake?

wary anchor
#

no it'll be me, don't worry I'll work it out. Better to learn this way anyway πŸ˜‰

#

it's trying to get data before it's set any data

#

yeah okay I don't understand what that's about. In your AAAInsert system you're getting the data, but you're not setting it until the ZZZ system, so there's a null ref exception @mystic mountain

#

but it may be because I failed to rename things properly, best just check ahem

mystic mountain
#

@wary anchor did you accidently remove the Initialize system? Or remove the UpdateInGroup initializeGroup ?

wary anchor
#

mm nope they're all still there

#

the Iinitialize

#

oops

#

the InitializeSingletonSystem also has a call to GetData() and this is the error that's thrown first

#

as none has been set yet

mystic mountain
#

I'm a bit confused where you get the error πŸ˜›

wary anchor
#

I broke this down to find the part that was giving the NRE and it's the GetData() line:

[UpdateInGroup(typeof(InitializationSystemGroup))]
public abstract class InitializeSingletonSystem<C, S> : ComponentSystem where C : struct, IComponentData where S : SingletonComponentSettings, new()
{
    protected override void OnUpdate()
    {
        var newEnt = PostUpdateCommands.CreateEntity();
        var set = SingletonComponentSettings.GetSetting<S>(typeof(S).ToString());
        C newComponent = (C)set.GetData();
        PostUpdateCommands.AddComponent(newEnt, newComponent);

        this.Enabled = false;
    }
}```
#

had to rename Settings as that was already taken πŸ˜‰

mystic mountain
#

Let's continue this in DM not to flood channel x) Oh did you solve it?

wary anchor
#

sure to the DMs, thanks

mint iron
analog beacon
#

oof I am now scared of learning DOTS after I saw the code here...

wary anchor
#

That latest stuff is kinda not really dots don't let that put you off

remote coyote
#

Just start with entities foreach on ComponentSystem, they'll soon release a job variant. It gets you into the DOTS way of flow without the overhead of learning jobs and burst limitations at the same time

safe lintel
#

@analog beacon imo its like trying to scale a small wall at the start, but once you get the terminology under your belt it gets much easier

#

if you have questions, this is the right place to ask πŸ™‚

tawdry tree
#

The terminology is crucial, I would even say.
That, together with the hardest step, which is wrapping your head around the core concept and principles of ECS, and you're like 80% there.

compact hound
#

Is there best usages for each systems job type or lets say everyone have same performance etc?

safe lintel
#

what do you mean exactly?

compact hound
safe lintel
#

thats fine, you can use other job types when you run into issues ijobforeach doesnt solve(like needing more than 6ish components or wanting to access the chunks explicity) but that setup is definitely the right way to go if it suits your work

compact hound
#

I was told that is better to not remove tags like MoveInput here, just to clear it but in this example just with one MoveInput and RotationInput system takes 0.09ms in update

#

Is not better to remove it and stop system from update?

#

Or is there any other way to stop system form update

vagrant surge
#

dont worry about that. You can look at some boolean for enable/disable somewhere, global, or you can just wait

#

unity devs have said multiple times that they have a system coming that will fully disable systems that wont iterate entities

compact hound
#

oh great

#

Is there a way to add or update component or I need always to check if entity have it

gusty comet
#

If you separate up your IComponentData into many small IComponentDatas, does the order in which you AddComponentData(entity, data) when you do IConvertGameObjectToEntity.Convert() matter for memory layout?
For example, if I had a component with a float and 3 separate byte-holding components - if they were in the same component I'd normally put the float first then the 3 byte fields. But if they're in separate components entirely, that shouldn't matter then right?

vagrant surge
#

you generally want to do a bunch of add component at once

#

i think its possible to add many comps to 1 entity at once, that wins hard

#

and yeah, the byte stuff is as you say

gritty grail
#

So how would you guys go about accessing the player's translation in a job for something like an AI?

vagrant surge
#

@compact hound raw "has" is odd to see. Usually you are checking the has in the system query

#

in your case, something like 2 systems, one that looks for "entities with RotationInput", and another one that looks for entities that DONT have rotation input

#

@gritty grail store it in a global or singleton

gritty grail
#

ok, but you can't access singletons in jobs can you?

vagrant surge
#

no, but you can access outside of the job, and give the job the location of the character when you schedule

compact hound
#

@vagrant surge is workaroud for handling input from MB πŸ˜„

gritty grail
#

So

#

make a singleton

#

that has the reference to the player entity

#

and pass that entity into the job?

vagrant surge
#

pass its location

#

as a float3

compact hound
vagrant surge
#

oh i see

#

in your case then you are alright, no proble

#

tho in your case you can give the input to a job, and then the job does the whole query thing

compact hound
#

i feel this code is wrong but didn't found anything other

vagrant surge
#

but thats overengineerinf for something like input

compact hound
#

How to use DynamicBuffer to get all components from childs? Like from some entity which is player ship get all that ship Cannons components.

coarse turtle
#

uh, a DynamicBuffer just stores elements, but you can make a query that has the Cannon component and use query.ToComponentData<Cannons>(Allocator); or you can use GetComponentDataFromEntity<Cannon>() in a component system

compact hound
#

GetComponentDataFromEntity<Cannon>() get also from children?

coarse turtle
#

it gets all component data with a Cannon type

compact hound
#

but I need only cannons form one ship

coarse turtle
#

and you can access it via an entity

compact hound
#

to tag them to fire

coarse turtle
#

so you have a ship with an archetype like: "Cannon, Child" right?

compact hound
#

Ship:
Translation
Rotation
Player
MoveSpeed
RotationSpeed

Cannon:
Translation
Rotation
Cannon

Ship can have many cannons

#

On cannon sure there will be also child component

coarse turtle
#

Oh, you can child the Cannon entities under the ship

  • each cannon entity will have a Parent component storing the ship
  • each ship entity will have a DynamicBuffer of Child that stores the entity with Cannon component
#

To access the cannons from the ship, grab the DynamicBuffer<Child> and you can grab the component data via GetComponentDataFromEntity<Cannon>()[entity] or EntityManager.GetComponentData<Cannon>(entity)

compact hound
#

i need to check if has component also?

coarse turtle
#

yea, ComponentDataFromEntity<T> has a helper function Exists so you can check if the enity has said compnoent data, for EntityManager you can use HasComponent<T>

compact hound
#

ok thanks, one more think if ship have few types(groups) of cannons like rear, front. Where would be the best to store that information? As value in Cannon component or by different tags? Then how to get only cannons with specific type?
Maybe CannonType should be ISharedComponent then I could filter query?

coarse turtle
#

I dont remember if ComponentDataFromEntity<T> accepts ISharedComponentData, but filtering with ISCDs can be a good idea, tags would also work

compact hound
#

ok thanks

#

i go sleep now πŸ˜„

gritty grail
#

How do I incrementally add in a job?

#

I found that doing += doesn't seem to work in a job

gritty grail
#

I actually figured it out

slow epoch
#

Okay now i'm concerned. I don't know if it's true but if it's, why you can't use += in a job

pliant pike
#

well you cant do it in a multithreaded job that's all, you get weird incorrect results

#

I found that out the hard way

wary anchor
#

I'm still really struggling with setting up settings and calculated data decently in a pure DOTS project. I can't find any clean way to get real SingletonComponents working with all the data from the various sources: such as SOs with typical int/float/string/ etc data types, or data calculated at startup including compute buffers and other collections. I can see how to do it with a system as a data container, but that's horrible for interdependency and will be a nightmare to maintain as the project grows.

pliant pike
#

why would it be bad with a single system as the data container?

wary anchor
#

It means I have one system which I have to keep up to date with references to GameScaleSettings, ComputeBuffer reference, string data for download/level loading, a hodgepodge of different things. Might as well just make a static class to dump all of that in instead, then at least I don't need to keep getting the system everywhere...

pliant pike
#

but you'd have to make sure the same with the static class

wary anchor
#

yes, which is why I don't want a static class either. It seems like singleton components are designed for this, but actually implementing them in any usable way seems difficult

amber flicker
#

I sometimes like to start with the syntax I'd like to be using and go from there? Perhaps Settings.Multiplayer.MaxPlayers or whatever - where perhaps Multiplayer : ScriptableObject and Settings handles hooking up to that SO. Or whatever you prefer really.

mystic mountain
#

@wary anchor You didn't like the settings solution? x)

pliant pike
#

yeah I'm kind of confused with them to be honest, making sure you only have one entity can be difficult and GetSingleton doesn't work as a check so you end up with a compile error if no entity exists

mint iron
#

i'm at the same dilemma. If you put it in a system, you have to initialize it everywhere in OnCreate by stashing a local reference to the system. If you put it in on singleton entities then you're making a bunch of GetSingleton calls scattered all over the place. If you store it in some other static helper then you have a dependency there. Its like which is the best of the bad options.

wary anchor
#

@mystic mountain sorry, not really. I can't use it with eg strings in the inspector (as the IComponentData can take NativeString64 but this isn't exposed), and it's not clear how I can write data to store there on recalculation. I appreciate the effort, though, so thank you

mystic mountain
#

Yeah, for strings you have to do some OnValidate and insert it into the data.

wary anchor
#

Sounds like I'm not the only one struggling with this. I can't find a lot of helpful information from Unity about it, anyone else?

mystic mountain
mint iron
#

I'm assuming that at some point they would have scriptable objects auto converted. As an aside can you instantiate a SO directly somehow with addressables or would you need a gameObject prefab with SO's linked within it, then have that converted?

mystic mountain
#

You can load it from Resource folder.

mint iron
#

I wonder if there's a way to do something like your solution Jaws without needing a 3 systems for every SO

amber flicker
#

For a resources-type approach for SO's but without string messiness, you can do something like this: https://baraujo.net/unity3d-making-singletons-from-scriptableobjects-automatically/

code//aleat

(Para a versΓ£o em portuguΓͺs, clique aqui
[https://baraujo.net/blog/unity3d-criando-singletons-de-scriptableobjects-automaticamente/]
)

Howdy! Just wanted to share a small class that I'm using to make my life easier
on Unity3D [http://unity3d.com/]: a singleton
[https://en....

#

(Sorry if I'm talking cross-purposes - I'm not all that clear on what the main issue is)

wary anchor
#

central storage and access of global data. OOP-type singletons are definitely not the same as singleton components as described by eg the overwatch GDC talks

mystic mountain
#

@mint iron You only need the first one, the other two are for updating the SettingSO in editor and let it update into ECS directly.

pliant pike
#

i just remembered something they said in one of the Unite talks recently, I cant remember exactly, but the state of a world in ECS is just the sum of the all the components, what is stored in all the components

#

to save a state you would just need to store all the components data at that time

#

I don't know if its relevant but it made me think, maybe dont use singletons unless you really need to and store the data close to where its needed

mint iron
#

That sounds closer to the right answer.

#

i guess the things that are important to me are: 1) being able to find it easily and see the current values in EntityDebugger 2) less boiler plate code that bloats everything making it harder to read. 3) easy conversion from whatever authoring state it arrives from into ECS world.

pliant pike
#

yeah Systems are a bit of a black box in the entity debugger, and less boilerplate would be much appreciated, Blobdata's are like a labyrinth leahYTHO

coarse turtle
#

haha yea, blobs are pretty convoluted atm

#

I just compensate for blob construction using the conversion workflow

dreamy spear
#

do archetypes need to be created in a monobehaviour? Or can I make them in a class of their own?

mystic mountain
#

@amber flicker Thanks for link, I searched how to do that generic Singleton! Now I can simplify the scripts x)

coarse turtle
#

archetypes dont need to be created in MonoBehaviours, you can create them elsewhere as long as you have access to the EntityManager of some said world @dreamy spear

dreamy spear
#

the entitymanager you mean needs to be able to access the archetype?

wary anchor
#
var entityManager = World.Active.EntityManager;

        var atomArchetype = entityManager.CreateArchetype(
            typeof(Translation)
}

as long as you can access the entityManager, you can use its CreateArchetype method

dreamy spear
#

ahhh right.. because.. ok gotcha