#archived-dots
1 messages Β· Page 88 of 1
Ye, stack tracing is super expensive X)
having a warning log every frame is also expensive π
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)
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?
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
ok you may also need to get the final handle for the collisionworld and pass it to your job
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.
do something like
var handle = JobHandle.CombineDependencies(inputDeps, m_BuildPhysicsWorldSystem.FinalJobHandle);
and schedule your job with this handle
Do I need to update my code at all besides just adding that line?
when you schedule your job instead of inputDeps use handle or whatever you call CombineDepenencies
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;```
looks good
Well I am still getting the same error x.x
Maybe I should take this raycast out of the job entirely
ok just post the full thing again?
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;
}
}```
i dont understand why thats not working π©
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);
seriously though your problem is driving me nuts
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
π
You're still running your system before the Simulation right?
Did you.. try to change it? XD
Idk how XD
[UpdateAfter(typeof())]
Do I put the attribute on the class?
Yes, on top of the system
Still the same error
Will you post your code again?
[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;
}
}```
Another error?
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.
Do UpdateBefore and complete the handle before your job.
Complete my handle before my job?
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 π
Well removing it fixes it
I already know that
If you're taking about removing raycast
I'm not sure. But you can try only insert hysicsWorldSystem.PhysicsWorld into your job.
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
I can send you some code.
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
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
2019.3
b5?
b4
@gritty grail solved your problem
What was the issue?
use
[ReadOnly]
public PhysicsWorld physicsWorld;
Okay, that works
What is this error?
It happens from this
bool hit = physicsWorld.CollisionWorld.CastRay(rayInput);
Debug.Log(hit);```
cant do debug.log stuff with the burstcompile attribute
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....
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
Oh wait nvm I fixed it, planes just suck
Thanks for committing an entire channel to me
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...
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
Is there any pricing on it yet?
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
Seeing the keynote, for high performance, is the goto- to write ForEach now? Or should we still write Jobs manually?
I haven't seen the keynote yet. I'll have to check it when I get a moment
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
Yeah I see.
I'm thinking thats what it is
Hope they release their new update soon :3
- dots sample
yes
some of the new hidden things need examples
or better documentation
autogen is meh
I get that from intelisense, wheres the 'why'
Hum, aren't InitializationSystemGroup only supposed to run once?
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
Only thing I found was "(updated at the end of the Initialization phase of the player loop)".
then probably I'm wrong and thinking of something else - sorry I know that's not helpful π
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...
@mystic mountain InitializationSystemGroup is just a group that runs early, it still runs every frame.
Name is missleading af right now to be honest
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.
How do you manage to do Authoring for ISharedComponentData?
Haven't seen any examples about it
In a MonoBehavior implementing IConvertGameObjectToEntity you just do dstManager.AddSharedComponentData(e, T) within the function call
pretty much the same as IComponentData
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
I never used ECS, I believe DOTS is an improved version of ECS?
DOTS is the whole stack with all features including ECS
DOTS is the Job system, the Netcode, ECS, etc.
There are some tutorials on the unity learn site, it's still a bit rough for newbies though.
@analog beacon check out the pinned message here, ecs github samples in particular
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 .-.
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.
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
well i'm not exactly sure what you're trying to do π
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.
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
Hence I decided to make it a component on an entity
You can't reference managed classes from jobs either
You can't just pass it when creating the job?
Well I don't know if you can create a component without an entity and have the system recognize it
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?
Uh, maybe. How does something like Time.deltaTime work or Input.GetAxis?
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
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)
blob data is immutable
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 π€)
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
did you add the hybridrenderer package?
Okay, I found a solution to my problem.
ComponentDataFromEntity works well in that case.
https://gist.github.com/Necromantic/390d21bef6fc2ba74dedebd87bf4a475 in case anyone cares. It's just a minimalistic example to check the functionality.
Not entirely sure if setting the ComponentData is entirely thread safe though because it's not a ref.
Well definitively not thread safe ^^
Oh, you can do a EntityCommandBuffer to update the game entity data too
Will that work with consecutive changes though?
As in, will they be accumulative, since I add something for each job
Should be
Doesn't the buffer only set the things at the end? or is that only for create operations?
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
i guess if you need the exact same frame accuracy π€
disabling the restriction on the ptr might be the way to go
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.
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
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
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
Hello, is there any unity staff here?
I'm still not happy with the Queue solution but for now it works.
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
https://docs.unity3d.com/ScriptReference/Unity.Collections.NativeArray_1.CopyTo.html You've got to allocate the second array of course.
thanks, but I'm getting an error "object reference not set to an instance of an object"
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
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
thenativearray.CopyTo .CopyFrom(NativeArray<T>)
I suggest not using built in List<T> and Dictionary<K,V> when you can
@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
@neon shore there is another option using SharedStatic but i have no idea how it performs because it seems to have a dictionary/type lookup in it behind the scenes. Might be convenient in some situations. https://gist.github.com/jeffvella/2036bc8d6d036d4416e743a94f9f16ea
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?
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
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?
@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
@dull copper Thank you. π
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. π¦
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.
@mint iron I haven't look at it much but just in case it helps - https://forum.unity.com/threads/nativestream-usage.753977/
are navmeshes supported in Dots?
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
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.. π€
If you need to create a navmesh from scratch that can be used on jobs you can use NavMeshQuery
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.
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.
It seems like the default world initialization/bootstrap is too slow for some reason
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
heh
on ECS department, Mozilla made a ECS for JS
Today we are introducing ECSY (Pronounced βeck-seeβ): a new -highly experimental- Entity Component System framework for Javascript. After working on many interactive graphics projects for the web in the last few years we were trying to identify the common issues when dev...
i know the guy who made it
some nifty demos https://ecsy.io/examples/
ECSY experimental entity component system framework for the web
o0o0o awesome
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 π
@simple cradle input component
something like PlayerInputComponent, that has stuff like moveX, moveY, bJump, etc
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");
}
}
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
but I'd still have to have my singleton Player player hanging around right?
why? not really
because I can't GetAxis without a player instance
ah
that's why I'm doing it like this
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")
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?
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"
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?
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
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;
}
});
another thing ive seen, but more with entitas, is to make input events into entities
I'd just turn the moveVector into a component
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
instead of putting PressedJump on the player?
yes
What's the benefit
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
Well, I'm not sure how event entities should look in Unity ECS π
I'm pretty new to this stuff and still learning.
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
so it runs the system once and deletes?
Without some code to look at this is kind of difficult to understand
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
there's a lot of generated scripts to look through π
not sure what I'm looking for exactly yet
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)
));
}
} ```
oh wait they're in features
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
so it's literally a system designed as an event subscriber pattern
yup
and the published events are entities
sounds slow, but isnt. Creating small entities with unity ECS is basically a push-back on an array
I mean it has to be more efficient in some capacity than polling every frame
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
and no matching functionality in Unity ECS?
you can do the same no issue
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 π
Why do you need reactive systems? Your systems donβt live alone all by themselves. What one system changes, may be of interest for another system.Β For example, if you build a strategy game you will most likely need to know where your units are in the game world. If your ga...
google-fu
this seems like what I need to study
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
so you're suggesting just poll inputs? π
@low tangle or am I interpreting that wrong
only if you are doing it on 100,000 + entities
if not, I should go for readability then?
yep!
Sounds neat, thanks!
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);
Well, is that not just polling
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
I'm finding it kinda hard to visualize that example
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
@simple cradle https://hatebin.com/pttbvbekqd
ah, line 178 is a typo
it should be a readwrite not a exclude
@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
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
DynamicBuffer in jobs, do I need to use IJobChunk?
@mystic mountain no
So how can I access in a IJobForEachWithEntity?
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
Ah, wow. I just thought it was some background nonsense xD
Since like IJobForEach_C/C/C is same as IJobForEach ?
you have to format it like this in the execute public void Execute(Entity currentbusiness, int index, DynamicBuffer<EmployeeEntitysArray> currentbuffer, ref EmployeeEntityInfo currenbusemployees)
Yeah : ) I got it working. But I just thought they were helpers for the regular IJobForEach()
yeah its pretty cryptic, i guess if you're needing that then you've reached boss mode ecs level.
How did you guys go about converting the camera to an Entity and still having a reference to it in code?
Which part are you having trouble with? Converting to entity? Or the reference?
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;```
few more DOTS videos from last Unite:
https://www.youtube.com/watch?v=VXuR8VVQzwQ
https://www.youtube.com/watch?v=mL4qrt-15TE
https://www.youtube.com/watch?v=iCnYm7kRC1g
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...
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...
For most Unity developers, the cutting-edge data-oriented approach introduced with the Entity Component System (ECS) is unfamiliar. While ECS clearly enables...
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
});
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
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.
Well I'm not sure exactly what the best method is, trying to figure that out :>
I want to convert my camera and put a tag on it
The conversion workflow has a method to add components during the process
Oh, well you can just add a ConvertToEntity but with the ConvertAndInject to your camera
I did that, but how do I add a tag?
Sounds like psuong has done that more than me, so I'll defer to them
You want another MonoBehaviour implementing IConvertToEntity which adds the tag to the entity, this would also be on the camera
Okay, I was thinking that maybe was the solution, I'll take over from here then, ty
np
hmm i have unity 2019.3.0b5 but my subscene are not converting to entities π€ like in https://www.youtube.com/watch?v=VXuR8VVQzwQ
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...
Working on updating my debug drawing utility so you can draw stuff from within a burst job.
@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
I have it
did you create the entity cache for that subscene?
Yes but im missing some part of UI also for normal gameobjects
like this convert to entity box
Do I need something to enable to work with entities?
oh you need to attach a ConvertToEntity script to your gameobject
that feature from the video is not yet released
oh :<
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.
@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
Is DOTs networking out yet?
@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
Can I make a game without any network code and have an expectation that it shouldn't be extremely hard to implement it later?
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
That's what I thought :/
Well it's going to be messy but I might just have to mess with what they have now.
is there any estimate timeframe for that 3rd person demo in DOTS (from unite keynote) ?
@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
cool yea, would be nice if it was around .3's release
that would be sweet
sooner would also be nice
yea, would be lovely to see how the network code works π
regular
how to pass input form new input system to some component?
create component that stores input? And some system which process that input?
@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
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?
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?
@tawdry tree i want to use new unity input system, which is not dots ready i guess
Hmm, that does make things trickier
Either way, in monobehaviours you can still do World.Current.GetEntityManager() or what it's called
and i want be ready for multiple players
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)?
one unit per player
the new input system works just fine in dots
just not in a job
a regular component system will work just fine
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.
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 π
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
but with this approach we are getting rid of of all its benefits? Like input map per player, events for specific actions?
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)
i will probably stick to mb for now
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);
}
}
command buffers are not bust compatible yet
comment out the tag for now
or dont remove the input
just set it to zero
i was just wandering what is faster removing or setting to 0. But when i remove it should system run faster in other updates?
setting is faster than structural changes like add/remove
setting yes, but most of the time if we remove it system updates will have less Input components to update
also be careful with adding-removing components
in some cases its more expensive than adding-removing entire entities
after all, add-remove component its a full delete, then swap, then create it again
yep
in a lot of cases for this kind of thing its better to spawn a new entity that points to its target
honestly this system seems kinda contrived atm
simple example that isn't really thought though yet
like what are you actually trying to solve
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
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
In work i stuck with Unity 2017.4 π and now Im starting my other after hours project - something like https://www.youtube.com/watch?v=qygwBZxLjLU so I wanted to see all the new Unity staff π
Here's what the critics are saying about Europe's fastest-selling Nintendo Switch game of 2019, The Legend of Zelda: Link's Awakening! Official Website: http...
I think ECS could fit here well
How to get entity that has Component with specific data in MB? Searching it some time with no luck :<
Run an entity query, then check manually inside the lambda?
Suboptimal perf-wise, but probably not a problem unless you have tons of em.
Regarding input and ECS, one of the recent Unite talks featured user inputs in ECS land:
https://www.youtube.com/watch?v=mL4qrt-15TE
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...
@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
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...
This is what Im doing but don't know how to get player entity in MB π
You can use the entity manager in a monobehavior
yes but how to find specific entity?
Give it a component with a certain value? With players you're going to have a limited amount of them, right?
I mean I don't know the api. In EntityManager i see only GetAllEntities. You mentioned about some Entity query?
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?
Unity 2019.3.0b5 and newest package
So basically latest then
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
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?
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?
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.
I did't found anything else to work and I totally know this is not the way π
Comments on methods would indeed be nice; it's one of the things I've been missing as well.
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
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.
Tried to restart unity?
No, good point
That worked, though it seems like I have some updating of systems to do...
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
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);
}```
π€
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
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.
you are using this in struct
i moved every function i wrote out of the Execute() and it seems to compile now
nailed it! thanks! β€
Has Unity said any reason why they are not doing anything related to Editor for ECS yet and focusing on all the conversion stuff?
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
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
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.
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
yeah what they showed and the ideas for the future makes a lot more sense than what exists currently
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
i always use tempjob for jobs
oh wait you want to allocate inside the job? hmm not sure if thats possible
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
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
Can I not move a camera by it's translation component?
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 π©
yeah*
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.
- InputSystem spawns bullets from list of cannons form ship entity
- 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?
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?
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
Ok , I found that I should use Chunk if I don't want to internally call "Complete" on all jobs dependent on my Singleton..
query.CalculateEntityCount() >= 1;
Singletons are inherently against the DOD approach
they arent really mutually exclusive, but it defeats the purpose of both to use them together
I have data for e.g. number of players in my game. How do you propose I increment/decrement this + do some logic?
arent you itereating over them in the game loop? To handle inputs, movements, animations, whatever
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)
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
Hum ok, so why I cant use singleton you say?
I misunderstood, nevermind π
@low tangle What does the jobHandle do in this context?
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
Hmm ok
And disposes itself after as well?
And it has readWrite definitions from Query I suppose.
[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
Cool, but since this is a singleton, it's maybe same or better with commandBuffer?
are you going to write onto the singleton component or just read from it?
write
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
I only iterate over one entity as well
oh
So should be fine.
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
Cool!
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
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?
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.
@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().
@mint iron store an string on entity and spawn en text mesh pro normally and link text from entity ?
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?
@amber flicker ok and no this doesn't make and warning
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.
ok, and how i can synchronize text with entity data ?
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.
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? 
@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).
@mint iron ok, thanks
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
@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.
@silver dragon thanks, so storing the Native Container type data with a public getter on a system is not an unreasonable way forward
What's unreasonable in dev? Depends on the use case π
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 π
Maybe we get some other possibilities later on, but for now this is the easiest way i found.
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.
@mint iron thank you!
but im not happy with it, doesnt feel good
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
Is DOTS the same as the Entity Component System?
yeh ECS is part of the whole Data oriented tech stack
Ok, just read the tutorial on ECS up at Unity's site. Sorry for butting in.
np π I'm procrastinating. Must get head down and crack through this refactoring. Thanks for the responses all!
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?
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.
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)
Hmh, yeah but the system will check for the query for each update, isn't there a cost to that?
you can set Enabled = false on the system.
That is too simple ._. :d
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
Do you run with 50~empty systems?
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 π
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.
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>());
yeah, I don't want to write to it π
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
ahh no, this isn't for data, this is literally just an event signal
Ok , but .. does ReadOnly do nothing on data or what? π
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
Ok, so you're saying this 5argon guy is writing bad code π
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)
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 π
I'm afraid it's above my pay grade to comment on that! π
@wary anchor Thanks anyway! : )
np, gl! I'm kinda doing something similar at the minute too, but lots of refactoring to do while I'm at it
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
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
there's an example floating around somewhere of scriptable objects conversion.
Think there was a post about asset blobs and SOs as well
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.
I'm just trying to figure out how exactly to use Blobs and SO's if you figure it out let me know
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
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.
it just seems really convoluted
I'm contemplating just how dirty I would feel if I made a system whose sole purpose was to store data.
I think I already did that 
I just don't know if I can bring myself to do it
π
@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#
thanks @coarse turtle hopefully they make it a bit more straightforward in the future
@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) : )
Far North Entertainment is working on a third-person zombie horde shooter using the Data-Oriented Technology Stack (DOTS), which has brought great performanc...
@mystic mountain thanks I'll take a look when I'm back online! I appreciate the effort, thank you!
has there been any word on RaycastCommand2D appearing?
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 : )
@dull copper yass
@dull copper dissapointment of a talk
they say absolutely nothing of how they make it work
its just a "intro to ECS" talk
@vagrant surge i have same problem . Every Unity talk about ECS is kind of introduction
What is ecs and some really base system exaple
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
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
i really liked the megacity culling one
Looking at the trend on Unity Youtube, soon we'll have "Create/Build <game_genre> with DOTS" for anything.
Project Tiny is our first implementation of the βpureβ DOTS runtime, targeting web and mobile. It lets you create games that load instantly and have a small ...
@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 π
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"
unless it's Acton or the Burst guy
putting roadmap talk as one was bit stretching it
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".
its retarded, honestly
Ye
one talk after another going with the ECS basics
Even those marked as advanced π
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
are all the packages and versions up to date?
Yes
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
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.
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?
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
@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
});
}
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!
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 π
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
I added new physics package to my project and their step physic system takes 4ms for allocating per update with empty project π
@karmic jewel here's some food for thought on unity physics package. https://gist.github.com/jeffvella/7bb400fa4c5a594783c08bf120066a52
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.
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
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
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.
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
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.
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
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.
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
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.
Anyone got any idea what this might be?
Found it, was a ToComponentDataArray job from wrong query.
A bit annoying that it froze my unity though x)
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?
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
Yeah ok, I simply early out atm. Just thought there might be some functionality built in : )
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.
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.
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 : )
@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?
@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"+
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
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
You kept the name it generated?
Hmm, you can send DM of code + printscreen of resource in folder if you want.
I won't bother you, if I can't fix this I shouldn't be involved in making games. Cheers!
I don't mind x) I might've made some mistake?
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
@wary anchor did you accidently remove the Initialize system? Or remove the UpdateInGroup initializeGroup ?
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
I'm a bit confused where you get the error π
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 π
Let's continue this in DM not to flood channel x) Oh did you solve it?
sure to the DMs, thanks
If anyone is interested; i have my debug drawing util updated to work from within burst jobs. https://github.com/jeffvella/UnityDebugDrawer - uses NativeStream and SharedStatic<T>
oof I am now scared of learning DOTS after I saw the code here...
That latest stuff is kinda not really dots don't let that put you off
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
@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 π
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.
Is there best usages for each systems job type or lets say everyone have same performance etc?
what do you mean exactly?
For example this system. Is written good or if I would use other job type/system i would be better?
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
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
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
oh great
This screen π
Is there a way to add or update component or I need always to check if entity have it
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?
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
So how would you guys go about accessing the player's translation in a job for something like an AI?
@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
ok, but you can't access singletons in jobs can you?
no, but you can access outside of the job, and give the job the location of the character when you schedule
@vagrant surge is workaroud for handling input from MB π
So
make a singleton
that has the reference to the player entity
and pass that entity into the job?
@vagrant surge if you have better solution Im open for it :D, didn't found other working solution
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
i feel this code is wrong but didn't found anything other
but thats overengineerinf for something like input
How to use DynamicBuffer to get all components from childs? Like from some entity which is player ship get all that ship Cannons components.
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
GetComponentDataFromEntity<Cannon>() get also from children?
it gets all component data with a Cannon type
but I need only cannons form one ship
and you can access it via an entity
to tag them to fire
so you have a ship with an archetype like: "Cannon, Child" right?
Ship:
Translation
Rotation
Player
MoveSpeed
RotationSpeed
Cannon:
Translation
Rotation
Cannon
Ship can have many cannons
On cannon sure there will be also child component
Oh, you can child the Cannon entities under the ship
- each cannon entity will have a
Parentcomponent storing the ship - each ship entity will have a
DynamicBufferofChildthat stores the entity withCannoncomponent
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)
i need to check if has component also?
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>
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?
I dont remember if ComponentDataFromEntity<T> accepts ISharedComponentData, but filtering with ISCDs can be a good idea, tags would also work
How do I incrementally add in a job?
I found that doing += doesn't seem to work in a job
I actually figured it out
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
well you cant do it in a multithreaded job that's all, you get weird incorrect results
I found that out the hard way
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.
why would it be bad with a single system as the data container?
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...
but you'd have to make sure the same with the static class
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
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.
@wary anchor You didn't like the settings solution? x)
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
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.
@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
Yeah, for strings you have to do some OnValidate and insert it into the data.
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?
For reference, this is what I'm using https://forum.unity.com/threads/code-and-template-for-singleton-scriptableobjects-to-ecs.756794/#post-5039336
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?
You can load it from Resource folder.
I wonder if there's a way to do something like your solution Jaws without needing a 3 systems for every SO
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/
(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)
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
@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.
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
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.
for SO stuff, there's also this project from @tertle but i havent had a chance to dig through it yet https://github.com/tertle/ecs-so
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 
haha yea, blobs are pretty convoluted atm
I just compensate for blob construction using the conversion workflow
Something I was messing around with to see if I can add Unity Components to a blob
https://github.com/InitialPrefabs/ReactiveDisposalSamples/blob/master/Assets/Sample/Scripts/Components/Unmanaged/SpriteRendererBlobProxy.cs
do archetypes need to be created in a monobehaviour? Or can I make them in a class of their own?
@amber flicker Thanks for link, I searched how to do that generic Singleton! Now I can simplify the scripts x)
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
the entitymanager you mean needs to be able to access the archetype?
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
ahhh right.. because.. ok gotcha