#archived-dots
1 messages Β· Page 285 of 1
hah that was exactly what i was hoping to hear π but how would you make sure it only ever triggers in first frame? those entities might move in chunks
man i have to say when you cache the handles for multiple components its quite some boilerplate
I am simply trying to change the scale of an entity with a spherical physics body. Anyone know how to do that?
I've tried
- Setting LocalToWorld
- Using Scale component
- Using NonUniformScale component
physics doesnt respect the transform system
you have to modify the collider blobasset directly
There
there's only one instance of a blobasset at a time, right?
So if I want many shapes with different sized I'd need to create many blobassets?
You check its been setup I.e. Seed ==0
hmm but that means im checking the whole chunk even if i only spawn one entity. i think i prefer the structural change here
You can check 10 million entities in 0.17ms - literally what I've been testing recently
And it's only entities in that chunk
You can run the whole thing in ISystem due to no command buffer so main thread is faster
i see. but you need to do the check for every component. while i need to only remove the Initialize tag once in any system. the other systems actually setting up the component can be ISystems
Unless you are doing archetype changes every frame I personally don't see benefits of using a tag.
My real issue with tag is sure it's fine for this one case, then you add another case, and another. Next thing you have 10 archetype changes due to initialisation
What do you mean check every component?
each of your systems beeing responsible for setting up one component need to check all components of that type in the chunk.
with one shared tag on an entity that is only there for one frame each system only needs to setup exactly that entity with the tag and its component. and i only have 1 structural change no matter how many systems do some setup
better yet. if i spawn alot i know that all newly spawned entities to setup are contained in seperate chunks that i can iterate over quickly
Yeah see that 1 shared component is already a deal breaker to me
I'm now coupling independent libraries together
yes thats my biggest hurdle with ecs atm anyways
id have that in some core library
And it still messes with systems setting up chunk components
I have to rebuild all the chunk components when the archetype changes
yes i always wondered about how to manage that efficiently. guess you need to avoid practically all changes with chunk components
one reason i dont use them yet. they dont feel complete yet.
how do you handle communication between two domains?
but then how do you not couple?
Seperate assemblies strictly prevent me from having circular dependencies
Entry piece of code I write, I write like it was for the asset store
yes i do that too (not for asset store but assemblies i mean). but still my effects need to know about the speed attribute which also is read by my AI etc
My actually ai is generic and standalone
yes but how do you get the speed or health data into the AI? i needed codegen to do that
It has no knowledge of a specific stat
That is purely setup in data
By a graph
If stat43 < x do y
The only thing that makes stat43 speed is some designer called it that
but somehow that stat43 variable needs to be written to from outside the AI right? eg. sloweffect or anything on which the AI should react. how to not couple this?
I could give you my Ai system right now
And you could use it
Without making a single file change in the assembly
dont cause mine runs great too π i just need an explaination on how to decouple those Domains completely
i just dont get how you get data from ECS into the stat43 or out for that matter without knowing where to read from
the designer somewhere has to explain that that stat43 in the AI is the same as the speed stat on the Unit or sth?
finally not on phone, can type easier
gone a bit off topic here
on the original idea, don't get more wrong using a tag component is fine for initialization. i was doing it until like a month ago.
my issue with shared initialization component is which system adds it?
or does all systems add it
if you have a standalone system adding it
well now when i write a unit test for any of these systems, i now have to initialization a second system
and then a 3rd for the ecbs
my single system is now no longer a nice little module that takes data, does work, spits out data
and that's basically what my goal is when writing any system. a nice little module
is it a requirement to make a good entities project? not at all
i've spoken a few times i enjoy trying to write idealistic software for myself
in reality this is often not feasible
yes makes sense. i do want those little contained systems too but i do see a benefit in "infrastructure" systems handling one simple thing once instead of many systems having to do that thing. purely a design choice i think. in testing id would always have that system run in any test i guess. (but my testing experience is very limited)
i'm a bit obsessive about architecture. i haven't written any code in 3 days but i've written 5 pages of ideas
on how to try get my condition triggers working really nicely
the ones for effects?
and i still haven't come up with a plan that i'm happy with
yeah
what type of conditions did you have in mind?
in my system i just got time and lifetime conditions. so stuff like trigger once every second. or trigger only once or trigger when destroyed.
on hit
on block
full health
low health
daytime
frozen
burning
stat == y
standing in lava
etc
the problem is, everything
these don't have to all be handled the same way, ones that are on the actor vs world etc would be handled different
so basically a buff on the character that returns damage on damage taken for example?
these are the conditions
any (multiple) condition can be paired with an effect
effect might be
increase stat
deal damage
heal self
chill
apply debuff
create another effect
etc
so if you have the on block condition implemented
you can now pair it with
heal self on block
chill enemies on block
create burning ground on block
etc
then you implement low health condition now you have
heal on low health
chill on low health
create burning ground on low health
the idea of this whole system is anytime an engineer implements a new condition or effect
designers have whole new set of combinations they can apply throughout the game
yeah we are back to poe π
since everything uses this system
(well to be fair this is based off for honor talk but i'm just more familiar with poe mechanics so i think about those for conditions/effects)
thats what i still need for my abilities (basically passive abilities are the same as your effect + condition id say). my effects dont trigger anything by themselves but are just something thats caused by abilities.
the one thing i'm trying to avoid is condition query events
as i might have significantly more conditions than events
so ideally i'd like events to modify conditions
(and well i'm trying to avoid what people call 'events' as well but it's still an event in game)
a whole lot of going in circles
is a condition a component on the effected entity?
no that's the thing
my effects are separate entities
we've run into a lot of problems at work putting too much on the actual actor entity
getting to the point where we have chunks with 3-5 entities max
so i'm trying to avoid this
yes but that also makes it hard to query a combination of effects
(also it makes things a lot faster to calculate when i can fit 500 entities in a chunk and have 0 structural changes ever)
i was thinking about splitting it the other way. having an extra entity per actor containing all effects
same with AI. but then again its more random access to read data from actor
i was going to make each effect share a chunk with other effects targeting same actor
but it's a huge memory waste so i ditched that early
really infeasible for any moderate scale
true. its a hard problem to solve with queries.
maybe having a hashmap containing all effects for every actor is ok
also my effects strongly rely on change filters to not explode
an idea i have come to and from multiple times
i think if i went this approach i'd just sit on a buffer instead
oh wait you said effect
not condition
nah that's not possible for the scale i'm trying atm
this system is basically an entire game
it eliminates like 50% of other systems a game would generally implement
i know that feel :S. My AI controlls playerinput. whole game is basically AI doing stuff and you watch
i'm falling a bit deep into OOP thinking atm
but i'm legit considering implementing like an unmanaged event
that conditions subscribe to >_>
:S
this is me in desperation
having ruled out everything sane
that said, the last time i went into insane with shared pointers
turned out amazing
man i wonder if that would be a case for that one article talking about some sets of components you can query in ecs systems
i do have some like, really solid ideas for this
but oddly enough i've ruled most of them out due to memory costs
though i probably shouldn't
damn im not finding the article :S
cant remember which ecs it was
there it is
i think that relations feature would be a great solution for this case
though i have no clue how it is implemented and thus could be really slow. it would be just such a nice way to be able to get all effects related to an entity by a query without having to maintain a buffer with references and using chunksize for it.
well im off to bed.
like a hashmap? π
i think you pile up too many type of effects into one and that makes it hard to think about
i'm only actually designing for ~3 cases atm
like daytime, frozen are static effects with a duration. on hit is a trigger
target, source, world
he just wanted to know what type of conditions i intend to support
just saying, i've those trigger types split from the rest that are defined by effects. all triggers are bascially just an integer mask
having world is a weird abstraction? isn't that just another source with an infinite duration. like walking into a cold cave or smth which would be triggered by a physics trigger or smth
i've found that making hashmaps for easier lookup is quite nice. the problem is with effect amount and processing and how that scales. like, I don't feel comfortable for a game having 1000s of different effects and special code. most have a very generic subset that's used over and over again
nah it's just things like
condition on this effect is it's night time, gain damage
most conditions are reactive like player takes damage or blocks damgae
but you can combine them
at night time + when you block damage, heal
(i support 8 conditions per effect simply due to bitmask, though i can't think of a use case for that many)
your night time example just seems like a set of effects that gets applied at different times. a night/day system could handle that
it could be a stat on a piece of gear
i see, yeah ok, then it's an effect with a time condition.
i've several conditions in place. there can be really annoying effect types, like, gain 5% crit for a certain spell
pretty much all the time I can squeeze them in the code. but that's what I was meaning previously, at some point you can have a LOT of checks. another way of handling this was having an array of flags (basically they define which checks are made) which are iterated and the flag is just used for a switch. that way I can reduce the conditional checking to a minium
at some point you can have a LOT of checks
yeah see that's what i'm trying to avoid
i don't want my conditions to check the state/events
i want the events to write true to the conditions
just been on the balcony thinking about your approach. really interesting because we come from different angles, yours is effects, mine is abilities and if you look at them from another angle they are quite the same
like an ability is a set of effects - just the execution phase is different
i hope we get a proper 2021 soon. usually today is their release day. fingers crossed. i've gone back to 2020.3
my 21 been stable as (now that i know the bugs to work around =D)
the build workaround made me tilt π
and those UIElements bugs in BuildConfig and Inspector
funny enough those UI bugs in build config were there in 0.17
i had really hoped they were fixed
what? I never had them. you mean where the sub menus didn't appear and filters weren't working?
yeah
i think it might have been only in 2022 or something and they backported the uielements updates
but i definitely had them a long time ago in 0.17
and i have a bug report open for it somewhere
i never noticed in 2020.3
22 worker threads is fun to look at
as my pc died on sunday, i'm still looking at the cause for the slowdown on having many entities. like my single schedule job just doubles in time. i just find this not acceptable.
oh its not in 2020.3
its only 2021
its the new versions of uitoolkit that breaks it
ah, and as your effects live as entities. this is where it differs to my abilities because creating short-lived entities has not been great
(would make so much easier though)
Solve the problem, indeed addressables does not copy the data to the proper external build directory.
I have to find the error files, windows search em in my Unity Project Windows Explorer, and copy the whole directory to...
A directory under my external build directory, specified by a path.
It's super weird, complicated and arcane... It could be fixed easily tho.
my entities are not short lived though (in general) which yeah is a big difference between our objectives
due to there being currently (as far as i know) no way to make entities interact with unity terrain, what would be the best tools to convert a unity terrain into a mesh?
unity terrain is just a height map right? Assuming there is a way to convert the height map into an image then i could just use blender!
apparently i just uninstalled my gpu, while trying to update my drivers, so if anyone replies i probably wont see it for a while
i haven't used unity terrain in a good 5+ years but you can just export it as a mesh right?
not without external tools
or an asset store plugin which costs 40 bucks
ooh ill try it, after i get my gpu and monitors not dying
ive already lost 1
and this 1 is now turning pink
good job windows
apparrently i cant plug my monitors into my usb ports, cause i uninstalled usb3 to dvi, somehow while updating my drivers
Hi guys. I haven't use dots for a while. And I'm starting a new city builder project which have hundreds units. Should I start with dots?
are you willing to learn the intricacies of dots before starting a project using it?
if so, yes
dots helps with having hundreds of entities running at the same time, it's not the only solution though
I leant the basics. I'm worry if the whole structure might change when Entities 1.0 releases.
if that happens, keep using whatever version you are comfortable with
Ok, thanks for the advise.π
np, i hope it goes well for you!
@viral sonnet what do you think for writing my global conditions
{
public bool Value;
bool IGlobalCondition.Value => this.Value;
}
public struct IsNightTimeCondition : ICondition
{
public byte Index;
byte ICondition.Index => this.Index;
}
[BurstCompile]
public struct NightTimeConditionSystem : ISystem
{
private GlobalConditionImpl<IsNightTimeCondition, IsNightTime> impl;
public void OnCreate(ref SystemState state)
{
this.impl.OnCreate(ref state);
state.EntityManager.CreateEntity(typeof(IsNightTime));
state.EntityManager.CreateEntity(typeof(IsNightTimeCondition), typeof(ConditionActive), typeof(ConditionAllActive));
}
public void OnDestroy(ref SystemState state)
{
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
this.impl.OnUpdate(ref state, default);
}
}```
simplifies to the above per condition
Obviously there is no job included above to write to the IsNightTime singleton. as long as this is adheres to strict change filtering rules it'll only trigger condition changes on night time changes OR if a new condition is created or destroyed (just for that chunk)
setting up the index is automatically handled by authoring (unique is not unique per condition and will vary depending on number of conditions on effect)
concept works
1 million conditions / entities overhead (every frame early out)
time to write 1 million events on night change
Not enzi but i like it. i dont fully understand how this byte Index works yet
oh my conditions are stored in a bit field of length 8 (1 byte)
{
public BitArray8 Value;
}```
each condition is given an index in this bit field
when bitfield == 255 (e.g. all conditions are true) then the effect triggers
for this specific case, bit 1-7 are always 1 and bit 0 is toggled since there's only 1 condition on this test effect
but yeah, no query, no Lookup, no ComponentFromEntity, no hashmaps just dependent on filters
i'm liking it. doesn't really solve my individual conditions problem i've been fretting about but i needed to get something done
ah i see. i was confused about "allConditions" somehow thought you have all possible conditions ever in there
with individual you mean something not global like nightime right?
something like low health on an entity
yes
i have 6 pages of designs for this now without something i like
i really want to do something like this that requires no lookups but i might be asking the impossible
You mean you actually write words in something other than code comments?
Pen and paper
that's even more hardcore π
This way I can throw them out instead if maintaining documentation when done
ah yes well played
It's mostly because I lie in bed when thinking and I can't justify the cost of a tablet just for note taking. But honestly just faster to just write notes on paper.
I miss my old 2 in 1 laptop
I'd use my tablet more if I weren't sitting on a couch haha. Maybe when I move π
Well it's a bloody Christmas miracle. My daughter is asleep early enough for me to have enough motivation left to open unity
cant you use the same pattern you use to write from effects to actors but in the other direction? if an IndividualCondition on an actor changes you write to some static memory block which the effect has a reference to and set the changefilter for the effect to recalculate the conditions of the effect.
Yes but it's a bit more complicated than that
I'd need memory blocks for every target * potential effect
And then each block would need to also now what effect chunks need to update
Every condition of a type in a chunk might be looking at a different entity
there is a good chance i will use SetComponent for this case
So i've been following your convo and understand the problem, just trying to follow how the solution you've written above works.. could you explain how that's laid out as if i was 12?
I like the bit field idea btw
So would there then be a conditions entity for every entity that requires conditions/effects?
so yes, i'm writing a basically entire game unified effect system
effects are basically
condition -> action
actions are broken in 5 categories atm
- modify stats
- enable/disable capabilities (put things on cooldown)
- add tags (stunned, invisible etc)
- remove modifiers (poison etc)
- create new effects
these can be applied to anything, equipment, skill trees, environment triggers, etc
and are intended to be extremely data driven
every time a new condition or action is implemented it can be used with all the existing ones added huge amounts of gameplay
now i have the whole effect workflow working amazing with cooldowns, durations, setting stats etc
but i'm working on now is trying to efficiently trigger the conditions
the above code is for triggering global conditions (time of day etc)
(each effect can have up to 8 conditions hence the bit array of 8 - though I think that amount will be highly unlikely and 90% of time i'd expect only 1 (or none) and rarely more than 2)
..just chewing on this over coffee, bear with me.. π
yeah that seems like it could apply to basically any aspect of cause/effect or events in a game
could potentially be a really efficient pipeline for anything that affects anything based on conditions right
yes, my objective is to basically use this for everything
so you're using change filtering to avoid having to query for these things
pretty much
if you're interested, it's inspired by this talk from a few years ago Data-Driven Dynamic Gameplay Effects on For Honor https://www.youtube.com/watch?v=JgSvuSaXs3E&list=LL
though my implementation would work nothing like theirs
yeah i think i actually watched a good portion of that
just curious for this line:
why do you not just go var value = globalCondition[0].Value;
i mean i guess in the case of multiple globalConditions ( atm only one ) you would be reinterpreting the whole array to bools, so i guess that would be simpler
this is actually unsafe because I could write anything in this component so yeah this is just a bug, thanks for spotting it
so say you have a million entities and 500 of them decide to fire the 'too hot' condition or something, how would they update the system
would they create a bunch of too hot entities and the system would read them in and parse them
or would they write to a fixed array of too hot bools or..
well yeah this is the problem i haven't solved yet how i want to do it
and i've been investigating for days on how i want to do it
Yeah
it's not /that/ hard to implement the problem is i'm testing this at
10,000,000 conditions/effects
It's a tough but interesting/important challenge
my assumption is that there will be a lot more conditions than actors
and these type of events (hot, on hit, etc) will not be that frequent
therefore the events should write to the conditions
instead of conditions reading the state
but i just haven't decided the best way i want to handle this yet
Yeah
i've already implemented 2 completely new patterns (at least i doubt anyone has ever used them before) while developing this
so i'm going a bit off the rails for this
Go for it imo
@rotund token nice solution, the only part I don't like about is that it's a system and job for every condition
public abstract partial class InteractionSystem<T> : SystemBase where T : InteractableBase
hmmm, I have such systems (that inherit)
I need to somehow create Dictionary of all systems that inherit from it and type T of that system
any idea how can I achieve that?
with reflection π
Scan the assemblies with reflection and grab all the systems that is a subclass of type T?
yeah, I got it, but now the other problem...
foreach (var interactableBase in fui.onFlyUpFinish)
{
var system = _interactionSystems[interactableBase.GetType()] as InteractionSystem<>;
}
oh god, I hate OOP
but I couldn't find any other way
basically
abstract InteractionSystem<T> has abstract Process();
and I need to call it based on interactableBase type
looks like this
I hope I don't have to use reflection to call it
after you have acquired the systems that match your needs you can mark them in some way, like RequiredForUpdate
Hello,
I don't want to interrupt the thread but I could use some feedback on something I'm currently stuck on.
I'm trying to implement a solution where
there is a simulation world which is updated slowly
It takes care of everything that is actually relevant to the game.
And the default world takes care of displaying everything in a pretty way.
To do this I would like to copy entities from the simulation world to the presentation world ever so often.
The only way I found to do this is using CopyEntitiesFrom() but the problem is,
that it doesn't replace the previously copied entities with the new copies.
So a ton of duplicates are created. What would be a good way to get rid of the duplicates and to preserve the new copies?
Could there even be a completely different solution to what I'm trying to achieve?
Btw moving the entities back and forth between the presentation world and the simulation world doesn't make sense in my case because that would prevent the presentation world to present the entities while the simulation world is calculating away at pathfinding etc.
Even though I can get those systems, I still have a problem of making sure they trigger. Best way is call that overriden method manually, but generics ruin it.
what's the point? why not just render entities from simulation?
why would you want to move huge data structures from 1 side of memory to another?
because I want sync points in the two worlds to be independent.
This way the simulation world can keep calculating expensive things without being forced to complete early by a presentation world sync point.
The presentation world isn't just responsible for rendering but also for interpolating between the different simulation world states.
but that still would be a huge sync point
when you move entities
cause you can't copy entities without making sure nothing is getting written to them
which would be
CompleteAllJobs();
yes but the simulation world entities would be copied over at a low rate, like every 100ms for instance
but why?
it sounds like you do a network game for 1 player lol
you will still have to run presentation every frame
or else nothing will be rendered
and your simulation world
will be limited to those same frames
and waiting until presentation from other world is finished
before next frame in Unity player even begins
yes but as I already said the advantage would be that the presentation world could have frequent sync points without disturbing the long-running jobs in the simulation world
but it's already like that
Simulation and Presentation groups are 2 different groups
which run one after another
it's like Update() and LateUpdate() afaik
so are system groups independent from each other regarding sync points?
simulation and presentation are
first runs simulation
only then presentation
after simulation is completely finished
Okay so if for instance the simulation system group just started a long-running job
and my custom system group, running right after the simulation system group, causes a sync point by creating a new entity.
Won't the simulation group jobs be forced to complete within this frame?
okay maybe the sync point takes effect on the frame after idk. My point is the system groups aren't independent from each other when it comes to sync points.
If presentation group has sync point it's also a sync point for the simulation group.
I think we talk about different sync point, hehe
I'm thinking about this one https://docs.unity3d.com/Packages/com.unity.entities@0.51/manual/sync_points.html
well yeah
and you shouldn't care about sync points in presentation
and after simulation
presentation is mostly managed anyway
so job stacking is impossible
What do you mean? π
yes
so best way to do it
in end of groups
at ECB
stack as many jobs as possible
and then run them all at once
utilizing as much threads as possible
after simulation is done, presentation comes in
and there is no job stacking there
all is run on main thread
because it uses managed code
sorry I still don't see how this could prevent presentation related systems from
causing simulation related systems to be forced to complete early and introduce lag into the gameplay experience but thanks for your help anyway π
they can't, because they simply not run until simulation is finished
finished with jobs or with single-threaded code?
it's all tied together
are you talking about procedural gen?
because there is already a streaming world. (utilized in the editor) what issue means is that you have a hard sync point when copying in the new rendermeshes
No we were talking about how to have system groups which don't block each other with sync points.
On the one hand systems responsible for long-running simulation jobs (pathfinding for instance)
and on the other hand systems responsible for interpolating between simulation results with pretty presentation.
My idea was to have two separate worlds for simulation and presentation but apparently the goal can also be achieved without separate worlds according to Issue.
In which case do sync points cause only some jobs to finish? Are there docs on this topic?
it's dependency related
whenever you force run job that has dependencies
all dependencies will have to be completed first
and so if dependencies have their own dependencies...
it'll practically run all previously scheduled jobs
and you want to do that as rare as possible
okay that makes sense. Do structural changes force all jobs to complete?
yeah
sir, you are overthinking imo about sync points and etc
all you want
is just group all your schedulable jobs and systems that cause sync point away from each other
so your scheduled jobs stack will be as big as possible before popping
this will result in juicy threads utilisation
Huh i just found out that removing a parent does not automatically remove the LocalToParent Component. Only completly destroying the parent does. why is that? does the localtoParent component do anything without a parent?
nah, it's just saved settings basically
hmm i only have a LocalToWorld matrix (which contains scale) and i want to rotate it. what to do? i cannot use transform, rotation and scale components.
mm, you can grab rotation from it, manipulate it how you want and write back to same fields
assuming it has no translation, rotation or scale
and it's not parented - that should work
yes that did work. but it has scale
and i cant get the scale out of the l2w matrix. since its somehow intermingled with rotation as i understand
there is no localToWorld.Scale
ah, that's just helper method
you can write your own
why do you care about scale for rotation anyway?
i just need to rotate the l2w matrix
scale matters for rotation only for children transforms
ah ok. then i just need a way to rotate an arbitrary localToWorld
well that doesnt help my understanding of it sadly.
im sure there is a simple math function i can use to rotate a 4x4 transform matrix by a quaternion. is there not?
yeah well found a thread that explains it. you need to pull out the scale before you can safely rotate the l2w... too much hassle. guess ill need to keep the scale component around and reconstruct the l2w from there.
You can multiply by other matrix
Create it from 000 pos, desired rotation delta and 111 scale
thanks! i think i found another way to handle my problem though.
Stupid question but i've never did this before:
How do i get a managed component from an entity
CompanionLink seems to be internal so i can't get that component to get a reference to the gameobject that it links to
If I understand the code correctly you can directly use EntityManager.GetComponentObject<T> on the entity (and with some luck unity injects all MonoBehaviours)
But I've never tried using the companion stuff
I don't even know how an entity ends up having a companion π€·
managed components are not on companionobjects. they are on the entities themselves. you can access them like regular components.
dont pin me down on the exact api but GetComponentObject<T> sounds about right.
if you want to query managed components you can actually just use entities.foreach
Entities.ForEach((MyManagedComponent m) => {}).WithoutBurst().Run();
otherwise as said, use GetComponentObject
CompanionObjects are for HybridComponents like spriterenderer or sth that has no pure conversion yet. those are real monobehaviours on hidden gameobjects
Ah! GetComponentObject seems to work
GetComponentData was complaining
just doing something hacky at the moment for debug purposes
basically, applying a TextMesh to my prefab
it renders, by the miracle of modern medicine, but was trying to access it to update it's text value
so, funky question: let's say i have an archetype of 128 bytes. it would need 2 cache lines to read the whole. and for simplicity, let's say this archetype only has 4 comps with a size each of 32. comp a, b, c, d. does the order in which i read these comps then matter?
what's confusing me is this. ecs lays out the data as SoA. so reading comp a actually reads comp A of entity 1/2. every comp access is actually a cache miss if you need only entity1 and are not SIMDing
so my conclusion is that the order doesn't matter anyway because every other comp read is a cache miss anyway
which makes it pretty bad (if you are not SIMDing) to have any comps smaller than 64 bytes
imma try il2cpp, im wondering what components do you need to add to the build asset to make it do it?
interesting, i just merged some comps and that made it substantially worse. job takes now ~3ms instead of 2.8ms. main comp increase from 16b to 36b. I don't get it. That's a pretty big increase
before I continue any thinking, entities is SoA, right?
i hate acronyms
ideally all components are loaded into cache so why would order matter
struct Entity{
float3 position
float3 velocity
int health
}
Entity[] myEntities
// SOA
struct Entities{
float3[] positions
float3[] velocities
int[] healthBars
}
Entities myEntities;``` good thing I've this reddit post still open. For some reason no Unity doc ever says what it is
structure of arrays and array of structs π
it confused me for the longest time but tbh, graphics where I don't know how it relates to the linear memory confuse me even more
but i don't get why either case would actually miss
take my cpu, 3900X
I have 64KB L1 per core, 512KB L2 per core (and 64MB shared in L3)
a chunk is 16KB
i can load, and ideally it does load, the entire chunk into the cache easily
hm, yeah, you are right. i'm probably mix it up with pre-fetching too
all nice in theory, then i make a test and it's not working out in practice
like why does it matter how i merge my struct
and it's about 20 something bytes
you've probably broken some simd operations
look at the difference burst has generated
(intel has even more per core cache, current gen is 80KB, 1.25MB and also 30MB shared)
i'm pretty certain none of the code has any simd but i'll check. it's the best reason i can think of
hm, good call. i'll check.
do you know if temp allocated memory in jobs end up in l1 cache of the core?
afaik it's allocated in global memory. would be nice. maybe stack alloc?
and yes, every merged data was used
i was pretty sure to begin with but i rechecked as the result is really confusing me.
and the simd part is too hard to find out right now. it's mostly scalar (the faster path)
just from my experience, smaller the components faster the job
as a general rule
and adding unnecessary data to a job is definitely noticeable for slowing down
what I can't say: how much one cycle of a job thread pushes the L1 cache, so how much pre-read data gets pushed out by other data. i'd have to count every stack alloc made. - what makes no sense nor reason to me is splitting or merging the same kind of data resulting in different timings. like, okay, i started a test that makes no sense in the context of cache lines or the L1 cache size. fine, but then to get slower. eh, that's just weird and i hope it's a simd thing i'm not seeing. i've to rewrite a lot for these tests so i think it's best if i start a focused one. - one other remark, with the size of L1 cache, it should matter very little how I micro optimize shuffling data around. pretty sure I don't exceed 16k per cycle. oh btw. 3900x has 32k, same as mine, I have a 5900x now
oh wait, 768k - per core, not thread, so yeah 64k
buuut π 32k data, 32k instruction
cpuz isn't lying ^^
Can you change the layer of an entity in runtime?
Having some trouble with conversion in NetCode, hoping someone can help.
I've got some GUI GameObjects which are regular UGUI buttons and such that I'd like to be part of a prefab that I can spawn in.
However because they are GameObjects, I don't want them converted, I just want them to spawn when the rest of the prefab does and be connected to the prefab with a managed component reference on the prefab root.
So the setup is pretty simple, I have my prefab referenced in a "Ghost Collection" prefab holder that'll get converted and I put on the game object part of the prefab a convert to entity stop thinking it would do that.
But it seems this "convert to entity stop" doesn't work for prefabs and the gameobjects get converted anyway.
Does anyone have experience with this kind of thing? How did you solve it?
This is the setup
hm I believe the plan (albeit not executed yet to my knowledge in master) is to kill build configs completely for 1.0. We agree the idea is useful, but we also don't have the people to make it work properly. Sorry.
would have thought build configs were the future of building projects and/or they would be more serious about expanding the team working on the future core of unity π₯²
Aren't build settings part of project settings?
But it seems this "convert to entity stop" doesn't work for prefabs and the gameobjects get converted anyway.
yes for some reason convert to entity stop doesn't work in subscenes
You can make your own script that destroys whole hierarchy of entities in conversion
That should achieve same result in the end
@rustic rain my assumption was that build settings override project settings (might have been a quirk here or there) but I guess itβs all going back to project settings in 1.0
How does one inject GameObjects from a prefab?
I guess I want the GameObject part of a GameObject prefab to spawn when I spawn an Entity prefab.
I sort of expected the GameObject part of the prefab to be serialized normally and just get instantiated by some built in system when the entity prefab was instantiated, I think this is supported with the addComponentObject method
subscenes don't really contain gameobjects once converted
imo the easiest (and probably best) way to implement this is to just setup a reference to the gameobject prefab and simple instantiate it when the entity is created
Its just pain cos you have to set up all the references from code instead of the editor
Yeesh I've fallen far lol, younger me would have never said that
not sure what you mean?
simply create a class IComponentData, with a GameObject field, let's call it SpawnGameObject
and query when the entity doesn't have a Gameobject but has the SpawnGameObject component
can re-use this for anything that needs a gameobject presentation
I'm just being a lil bitch XD
I've got this ShipManagedComponents which was going to have a bunch of references to the GameObjects in the GameObject prefab.
But instead, I can just set up all those references on the GameObject prefab and point to that with a single reference as you are describing
Thanks for talking it through tertle π
quick question, can I use Dots just for one part of my game. For example fish flocks. But everything else would be gameboject logic? or it is not recomended?
you can do that if you want to, that is what i did for the fluid in my fluid puzzle game!
You absolutely can and this is what Unity is expecting most people to do.
but is it worth it? That is question, as it is very small part of project, and I am scared it will effect build size and etc.
while I could use just particles in more stupid way.... tho Dots would make it more realistic my tenfold
No, its not worth it lol.
Unless you wanna learn how DOTS works and you are super keen.
There are a couple packages on the asset store for ECS flocks but they're not free
Yea I saw, there are some on github as well using ECS. Current asset I use uses shaders for fishes heavily, which comes to 22mb RAM usage. O wonder how much it would be in ECS style
ah yes, the problem I am also seeking solution for
I haven't really started to figure it
but I have this idea in mind:
- try to create managed component that will store prefab instances
- then cut those prefab instances from authoring components
- expect SubScene to serialize that GameObject reference
well yolo, lets go DOTS π
welcome to the dots world of chaos, we wish you luck!
i think you need to define what you mean by DOTS
thank you. Hey.. it cant be that bad......... right? .. right?
what you want to do can be done quite nicely with jobs/burst
without touching entities
and if it's only a small snippet of your app that is probably the approach i would take
depends, some parts are fun, others are nightmares, good luck!
oh yea, quite core question. it is possible to use entities and stuffs in WebGL riiiiight?>
from memory it's really not worth it
sometimes
from googling around it seems that some versions of dots work better or worse with it, and some unity versions work with dots and webgl better than others
oh yea... i totally forgot.... that Unity 2022 have problems with dots O.o
unlucky
well one more reason to only use burst and jobs
isnt jobs to use multithreading? while webgl is living in one main thread world?
ecs (entity component system) is also multithreaded btw
depend on the browser
so my knowledge were old O.o thank you for showing me this
no problem, wish you luck in getting stuff working!
i dont think my question was ever answered, so sorry but imma necrobump sorry lol
hmm
I assume during OnCreate cycle
not all systems are created yet
as in, literally instantiated as object
so annoying tbh
I want to make a mini helper system that would let me serailize certain fields in systems, but outside of systems themselves
so I'd just create a Mono<T> where T : system
and just write to fields of my choice
after they are created
all systems are created before OnCreate is called
wha
hence you should always use GetExistingSystem<T> not GetOrCreateSystem
unity considers GetOrCreateSystem a mistake
it never told me so
if you want to initialize something in a system before OnCreate use the constructor
just make sure you put [Preserve] on it to stop it stripping in builds
(btw this wasn't always the behaviour, but was changed a few years ago)
[0.9.0] - 2020-04-09
Changed
Systems are now constructed in two phases. First, ECS creates a new instance of all systems and invokes the constructor. Then, it invokes all OnCreate methods. This way, you can now use World.GetExistingSystem<OtherSystem>() from inside OnCreate().
on the constructor otherwise it will be stripped in builds
because it's created from reflection (activator)
so nothing references it
ah, I don't use constructors
yes i was just saying if you wanted to initialize something in a system before oncreate use the constructor
that's all
all right, looks like I made my project a bit faster
hmm
now how can I inject into before OnCreate phase
is it even possible?
looks like it is
Can use constructor like I just said π©
but I want to do that outside of systems
That said this sounds like you're going back to entities 0.0.11
Back when things were injected into systems
basically define fields as public or with [SerializeField] and then this field will get written value from some mono in scene, if it exists
Hello, I get an exception for this code. What am I doing wrong?
unprocessedEntitiesQuery = GetEntityQuery(ComponentType.ReadOnly<IsMirroredInPresentationalWorldTag>());
unprocessedEntitiesQuery.SetSharedComponentFilter(new WasProcessedByPresentation {Value = false}); // Throws exception```
InvalidOperationException: Trying to get iterator for ECS.Components.Tags.WasProcessedByPresentation but the required component type was not declared in the EntityQuery.
the error is pretty descriptive for this one
you're using WasProcessedByPresentation on your filter
but you haven't included it in your query
add it to the query
yes I just realized :p
thank you!
I should have told my rubber duck about the exception
Hello !
Is there a way to add an element to a DynamicBuffer using an ECB command ? I would like to be able to add an entity (wrapped into a IBufferElementData) to a DynamicBuffer after the ECB is playback. Currently I get an invalid reference to the entity when using Buffer.Add(entity) because it's a temporary index created from the ECB.
Addbufferelement
It is working with Parallel Writers ? I can't find it
Thank you very much !!
I'm not sure about my architecture, I didn't play with ECS for long time.
I'm trying to create as an exercice a simple Particle System with ECS.
So I have an Emitter entity that it responsible for spawning the particle entities. I would like to be able to track the spawned particles from the Emitter. Is it a good practice to store them in a DynamicBuffer even if the count of this buffer could be very huge (let say up to 100 000 element). Or should I find better architecture ?
I don't think storing them in a dynamic buffer is a good idea as i understand it they are slower than other approaches such as just creating a NativeArray as a member of a system..
Generally what you'd want to do with something like particles is each particle is an entity, and each particle entity has a Translation/LocalToWorld component which stores position..
You then use a SystemBase to loop over all of the particle entities and do whatever on them.
For more complex behavioural setups you maybe want to look at the unity Boids example, which to be fair is quite complex
Regards tracking which particles are spawned from that emitter, the approach would generally be apply a 'tag' component to each one which identifies it as a particle, so for example 'ParticleTag' and then loop over all entities that have this.
just create some component to keep track of them
@rustic rain Thank you very much for the answer ! What you describe is what I'm working on :
- One system that update the Emitters, responsible for spawning the entities and setup their components
- Based on components on the particles, different systems update the particles (Ex : If ColorOverSpeedComponent is on a particle, a dedicated system will query the speed and the color of the particle and update it.
This system looks nice because it's easily extensible.
For tracking the particles from an emitter, what I understand is that I have three choice :
- Using a hashmap as a System Member to associate each emitters with their entity (could be complicated to track the emitter deletion, etc...)
- Get rid of this tracking while it's a very specific usage
- Store the Emitter on the particle. Iterate over all particles and filter them to get all the particles that have been spawned from a specific emitter.
Am I right ?
or you can just give particle some component, for example Shared one
and then you can get a query of all entities that belong to that same shared component
and in case you need to remove all at once
it'll be simply through shared filter
I never use SharedComponent, I need to look at the documentation to see how it works, but it looks very promising, thanks !
I actually had my particles in a dynamic buffer prior to just refactoring them all out and as actual entities this past week(they werent entities in the buffer, just transform and color data)
what I can say is that a single particle emitter(my entity that contained a dynamic buffer of particles), would kind of kill the framerate with between 10-50k particles
but if I ran it with hundreds of emitters with small particle counts, I could easily get over 100k without issue
anyway I used project tiny's particle system as inspiration for it, all the code is in c# so its worth checking out whatever you decide to do
i think this is a good idea.. could have a shared component to group particles by emitter, and the shared component could hold an emitter index or the emitter entity
I actually reverted it to entities not for the particle count issues but because using DrawMeshInstancedIndirect meant I had to sort transparency myself, and I figured it was less work to just have entity particles than to research z sorting
so you have say three emitter entities, a million particles using three shared components to group them into three groups
it kinda seems like using a dynamic buffer would be slower, like if you are using purely data approach as you mentioned all your particles are just a position and a color it would make more sense to me just to have one or two giant arrays
or hashmap or whatever
dynamicbuffers are just slow in general
yeah, although with low particle counts(I guess what tiny expected) the relationship between the emitter entity and its buffer is a little more palatable than when you just have a really high quantity of particles
After looking at the documentation, this is exactly what I need
Thank you very much all for the answers
tbh it was perfectly fine for anything that I would have used the old shuriken for, though as entities you can kind of get closer to vfx graph
yeh it kinda makes sense for that many emitter with small particle counts really, before going to the stage of super optimization.. it's a shame vfx graph is such a goddamn pain to use, i've been using particle systems for years doing animation work and i find vfx graph to be a bit of a black box in terms of the order of nodes and operators and them not doing exactly what you'd expect etc etc
my experience is quite minimal with particle scripting so I usually figure its my own incompetence but I do wish they'd post the c++ source to a lot more of their subsystems on github, would love to glean more ideas on particle setup and the math behind some behaviours
btw @rotund token should we replace all GetOrCreateSystem<T> with GetExistingSystem then for caching systems in OnCreate? is GetOrCreateSystem slated for deprecation?
same, but as a start you could expand on something like this: https://learnopengl.com/In-Practice/2D-Game/Particles and slap physics rules/anim curves on the emitter
Learn OpenGL . com provides good and clear modern 3.3+ OpenGL tutorials with clear examples. A great resource to learn modern OpenGL aimed at beginners.
I have an unexpected excpetion when I run this code
var queryDesc = EntityManager.UniversalQuery.GetEntityQueryDesc();
queryDesc.None = new[] {ComponentType.Exclude<SimulationSystemEntityTag>()}; // This causes an exception...
query = GetEntityQuery(queryDesc); // ...here!
Is queryDesc.None broken?
First time I see em.UniversalQuery π
But I'd say it's the Exclude that messes up
Try that ? None = new ComponentType[] { ComponentType.ReadOnly<SimulationSystemEntityTag>() }
yep that worked π
what
UniversalQuery?
I want to know more about that
xD
hmmm
is that like, query for all entities?
yea
I wonder what would be application for that
I assume that's for excluding some components
i mainly use it to reset my world entirely
yeah, I guess it's one way
it does nuke WorldTime iirc so you'd need to recreate that if you ever do something like that π€
Is there a way to prevent an Entity field from being remapped during a call to Instantiate()?
I'd like each of my entities to have a component referencing the prefab they came from. But due to how instantiate works, any field containing an Entity reference in the local hierarchy will be remapped to the newly instantiated version of that entity. I'd rather not have to update this component on every newly instantiated entity.
Is there some kind of [DontRemap] attribute I'm missing? I looked through the remapping code and couldn't find anything like that.
Don't forget the physics component
hm, afaik only entity ids <= -1, so coming from ECB are remapped
From what I can gather, Instantiate keeps track of all the entities in the original prefab hierarchy when cloning them. Then it iterates all the entity fields and remaps any that reference the prefab hierarchy with the cloned entities.
from EntityRemapUtility.cs
public static Entity RemapEntityForPrefab(Entity* remapSrc, Entity* remapDst, int remappingCount, Entity source)
{
// When instantiating prefabs,
// internal references are remapped.
for (int i = 0; i != remappingCount; i++)
{
if (source == remapSrc[i])
return remapDst[i];
}
// And external references are kept.
return source;
}
Btw, I think this prefab remapping is generally a very useful feature. It allows you to have a prefab hierarchy with entities referencing other entities in the hierarchy. 99% of the time, you want all these remapped. I just wish there was a way to turn it off in the 1% of cases where you want to maintain the references to the prefab.
ah π€ sucks Burst doesn't exactly support unsafe function pointers yet
How so
internal static delegate* unmanaged[Cdecl]<uint, void> UnloadSoundHandler; It's more in regards to this syntax since I'm loading a native dll dynamically in the editor so I'm grabbing the function pointer and assigning it to delegate*
Burst doesn't recognize delegate* unmanaged[Cdecl]<> if you try to stick it into a bursted job π
Oh not what I thought you meant
Hmm I'm pretty sure I wrangled with something like this a while ago, but it was marshalling a managed method
I feel like I managed to get it to work somehow but I can't remember
o if there's a way that'd be nice to know since it'd be nice to keep writing jobs consistent while maintaining and adding more features to a library incrementally
but otherwise oh well, I don't really mind slapping compilation definitions onto jobs for editor stuff, I was more or less just hoping that it would work out of the box once I moved over to 2021 Β―_(γ)_/Β―
i can't remember it was a while ago
however there is a definitely a round about way of being able to call marshaled stuff
by writing a tiny little c++ library
o - i'll take another look at the forums - I feel like I remember seeing someone from Unity comment about it a while ago but can't really remember
take my little logger that I pass to native libraries to allow them to use the unity log
{
public static readonly SharedStatic<IntPtr> Ptr = SharedStatic<IntPtr>.GetOrCreate<RecastLogger>();
[RuntimeInitializeOnLoadMethod]
private static void Init()
{
Ptr.Data = Marshal.GetFunctionPointerForDelegate<DelegateLog>(DoLog);
}
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void DelegateLog(LogCategory category, string msg);
private enum LogCategory
{
Progress = 1,
Warning,
Error,
}
[MonoPInvokeCallback(typeof(DelegateLog))]
private static void DoLog(LogCategory category, string msg)
{
switch (category)
{
case LogCategory.Progress:
Debug.Log(msg);
break;
case LogCategory.Warning:
Debug.LogWarning(msg);
break;
case LogCategory.Error:
Debug.LogError(msg);
break;
}
}
}```
public static extern Context CreateContext(IntPtr log, bool state);```
I pass this to a library
if you simply made a little library that looked like
public static extern void SetMethod(IntPtr method);
[DllImport(DLL)]
public static extern void ExecuteMethod();```
you could set a method in the library, store it, then call ExecuteMethod from burst π
very round about
lol, yea i actually have something similar to that in my dll lol
Maybe i'll do that universally haha
Is it possible to change the layer of an entity at runtime? I want to display one on the UI for a moment to signify pickup.
I have it tween up, look attractive and dissapear, but it also shows in game too because the layer does not change to UI only.
This is valuable.
Did they fix that field? It used to not work
it's passed to the batch render group, not sure why it wouldn't work
Sorry, I think I'm thinking of the layerMask field which is the equivalent of Renderer.renderingLayerMask. Pretty sure this used to be broken. But I think it may have been fixed in a recent hybrid update based on some forum posts I found
I just tried it, certainly works
I use a non-entity identifier for this use case to grab the prefab from a collection.
This has the benefit of being serializable but has a few extra steps.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
The above code is in case someone wants to set a layer, code easily made thanks to tertle's great help again.
I have a whole pool of entities in my game with Disabled/Disabled Rendering tags
And I just clone em, and change stuff
Hey, I'll give more examples
https://pastebin.com/hQQijmMn This is the general premise of using Entities as Objectpools: https://pastebin.com/hQQijmMn
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
The code won't compile for anyone right off the bat since it uses some easily removed stuff.
But the premise of simply removing <disabled> and <disabledrendering> is awesome for all to use.
Assuming you don't mind 1 copy of prefabs floating in memory which is normally a non issue, this is awesome for object pooling.
Some fancy addressables moves and you can load and unload tho if that is an issue.
MY DOTS/ECS project I'm on now is like a symphony
I wish I could just show everyone how easy it is to use... But any time I try and make a new ECS/DOTS project, it just doesn't run, lolololol.
Have you looked at RenderMeshUtilitiy? It greatly simplifies use cases that need to set up a RenderMesh and related components
It looked simple enough to set 6 variables...
you could simplify this down to 3 lines
rm.layer = 3;
ecb.SetSharedComponent<RenderMesh>(e, rm);```
i dont wanna necrobump a necrobump, as such ill ask my question again, sorry lol, which components do you need on the build asset to make it do il2cpp as i wanna mess around with it?
also i don't really understand why you're using a ECB when you're using EntityManager right there
Are you sure that doesn't change e2's rendermesh?
render mesh is a struct
I did some freaky deeque things like that and it was setting the parents data
kk, pass by object
How does pooling like this compare to using prefab entities?
unity's advice is not to pool
yeah that was my understanding as well
Instantiating a prefab of an existing archetype is supposed to be very fast. Might actually be better than the structural change of removing Disabled and DisabledRendering tags from existing entities
When I say pool, it means just to clone an entity
Its the fastest way of instantiating
... that I know of
...the above line is for legal reasons I cannot speak of
..that indemnify me in case I do not know some black box inner workings of dots/ecs
..which I probably don't. therefore do not sue
ecb works good enough in most cases, on decent computers (one of my friends) you can istantiate 1000s of entities (all with rigid bodies aswell) per second and still get over 60 fps
I use ecb and ecbp depending on use
Your code appeared to be removing tags like Disabled, DisabledRenderering, and something called DOTS_OBJECT_POOLER from existing entities. But there is EntityManager.Instantiate() and EntityCommandBuffer.Instantiate() that are designed to create a new entity from an existing entity.
And there is a Prefab tag that works in a similar way to the Disabled tag. It is automatically filtered from all entity queries by default and these entities won't render. But Instantiate() will automatically remove this Prefab tag from the entity for you.
Yeah that's what I'm currently doing. I have a prefab system that builds up a NativeHashMap from this custom id to the prefab reference. It worked fine but I realized that several use cases would be simpler if I just stored the Entity reference directly.
That sounds cool. Well the main thing I'm trying to do is get all my systems working. I know I can do efficiency later if it all works now.
That's fair. I wasn't trying to argue the performance differences and haven't measured it myself. Just trying to point out another way that, in my opinion, feels a little more straightforward and ergonomic to use. Its also more consistent with gameobject workflows.
I haven't tried il2cpp recently but I saw quite a few forum posts since 0.51 came out talking about some new setting you have to change in the build settings: https://forum.unity.com/threads/il2cpp-dots-entities-arent-rendered.1303950/
ooh thanks so much!!!
such a bummer that chunks are 16k. i'd have a really good usage of sharedComp but it would also require to make a chunk much much smaller :/
kind of wish for a better implementation for sharedcomps. on one hand they are just a grouping mechanism
on one hand they are just a grouping mechanism
there is no other hand π
so now I'm going deep into DBs because when sharedComps are not sufficient. entities and DBs are the next best grouping mechanism π
@rotund token how do you handle cleanup of entities when transitioning scenes or states, e.g. going from in-game to the main menu?
i only have 1 scene
as for going back to main menu, i have a client (+server) world
and i just dispose of them
my current architecture is a bit weird actually
my menu/loading/etc is all part of client world
after disposing existing client world i just create anohter
i used to do that all in default world
but it annoyed me the state transitions across worlds
Ah ok, yes me too!
This is what I'll have to do
I'm attempting to write a script that turns All Entities on and Off: https://pastebin.com/UsYxk6VT
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I ran into a peculiar error where if I do not assign disabled to every entity in a .foreach, I get weird errors:
If you'll note in the paste.bin I arbitrarily don't run a ecb.addcomponent on every entity and it sends those errors. If I run it on every component it doesn't error out.
I should be able to do a workaround... But I wonder what's at play.
looks unrelated to the ecb
that just caused the issue to appear
seems you have bad dependencies somewhere (read error)
Here is my simple code:
public void LoadScene(Hash128 guid)
{
var system = World.GetOrCreateSystem<SceneSystem>();
var loadParameters = new SceneSystem.LoadParameters
{
AutoLoad = true
};
var entity = system.LoadSceneAsync(guid, loadParameters);
}
The guid parameter is pulled from a MonoBehaviour SubScene inspector field. It's property: subScene.SceneGUID. That is what is passed to the LoadScene method on Awake.
The LoadScene method is in a SystemBase.
When loading the game, the scene does load and I verified the name matches. But it doesn't become parented to World, and it's greyed out and doesn't open, always (closed). What am I missing here?
are you sure the entities aren't loaded?
No, I click on them and the inspector shows their component datum. But they entities do not appear in game view. There is only one cube in the sub scene. Also the sub scene that is referenced in the MB is a Prefab asset and not in scene when hitting play. Not sure if that matters or not.
i ask because these are actually open scenes for me and entities in world
just the inspector is broken
is your guid scene not in the World scene?
are you trying to open a subscene that's not actually a subscene
So I created an actual sub scene. Added a cube. Dragged the scene to prefabs assets, deleted the game object sub scene. Referenced the Prefab sub scene to MB that lead me to write my issue.
ah, put your subscene in the actual scene
Yeah I think thatβs the part Iβm having trouble with. Never done scene loading before in dots.
they can't be prefabs
the OnEnable method needs to execute on the subscene script
to setup before you can load it
{
GameObjectSceneUtility.RegisterSubScene(gameObject.scene, this);```
Ah. I see. Ok. Iβll run some more tests tomorrow. Thanks for the help.
But if they do, then they just get loaded automatically without me needing to mess with scene loading.
Ran into an odd bug today using netcode.
I had a ghost that was travelling along all fine at constant velocity but as soon as it reached around 2150 units along any axis from the origin it would snap to -2150 units on that axis and not move anymore.
Turned out that happened was the quantization I set was way too high and it was overflowing the float.
So if this bizarre situation happens to you, just make sure you use a lower quantization value or the unquantized variant.
how much did you quantize that to o_O
netcode requires quantization of floats for serialization
Hi !
Is there a simple way to initialize a PhysicsBody / PhysicsShape via code when instantiating an entity, I would like to be able to initialize it or not depending on a boolean value in a component ? I look at the PhysicsBody Authoring, but it looks like it add lots of components. Is there any helper function somewhere to do this ?
Thanks !
if worst comes to worst, you could have 2 different prefabs, one with physics, one without, although im certain there must be a better way than this
Thanks for the answer. It was my first intuition, but because I'm writing a simple Particle System, I need the shape to be configurable and not based on a prefab.
Thanks !
ah that makes sense, if every you do find an answer, post it here, as i would be fascinated to know. I wish you luck!
Thank you ! I let you know when i will work on it !
I've found a related page on the package documentation, see the "Creating bodies from scratch". There is no "automatic" way of setting up a body from code, but it looks not so complicated π https://docs.unity3d.com/Packages/com.unity.physics@0.51/manual/interacting_with_bodies.html
ooh cool!
Does EntityCommandBuffer support AddSharedComponent() in a burst job ? I get some strange errors that refer to it :
(0,0): Burst error BC1051: Invalid managed type found for the field `EqualFn` of the struct `Unity.Entities.FastEquality.TypeInfo`.: the type `System.Delegate` is a managed type and is not supported
where can i find -s WASM_MEM_MAX in unity
only if it's unmanaged afaik
but shared components are considered managed
from what I'v seen in manual
Thanks for the answer. I need to find a workaround to keep performance good... Thanks !
For this case I usually just keep special group that runs right before ECB
in which I do managed code, that causes sync points
In my case I instantiate Entities and add some Component and Shared Component (Physics Setup) to it in the same System. You think I would need to separate it in two system to keep burst for the larger part of the code ?
If whole purpose of system is to instantiate entities/add components and etc
you might want to just move it to non-bursted system
alltogether
you'll get rid of useless buffer/creation/filling/unpacking
and will be able to freely manipulate creation of your entities
Thanks, I will do it. But I have some performance Issue regarding instantiation. I need to investigate it. Thank you for the answer !
but it's all done on main thread anyway
the reason to use buffer - is to be able to "schedule" structural changes in bursted system
ECB itself is running on main thread
I try it using main thread, thanks !
Can you get a reference to a native array element without using a pointer?
in what scope?
local, since that's the only place where ref is valid
I didn't find any native array api that returns a ref struct
That's using pointers
but that gives you reference
Well yes, but I asked if it was possible without pointers
basically
why pointers are a problem in the first place?
It's not, but ref is generally safer, and I wanted to know if native array exposes any API that can do it
but it's literally that, kek
and in editor you'll have safe checks
Since when does unity have safety mechanisms for C# pointers
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
private static unsafe void CheckIndexInRange(int index, int length)
{
if (index < 0 || index > length)
throw new ArgumentException( $"Index {index} is out of range of length {length}" );
}
that part
When is that method called?
When you want it to xD
public static unsafe ref T GetAsRef<T>( this NativeArray<T> array, int index ) where T : struct
{
CheckIndexInRange( index, array.Length );
return ref UnsafeUtility.ArrayElementAsRef<T>( array.GetUnsafePtr( ), index );
}
it's not built in
...
So to answer my original question, no, there is no native functionality on NativeArray π
yep
I'm well aware of how to write it with pointers
If I were to access the struct from the automatically dereferenced pointer, I would need to store it as a ref struct though, right? Since otherwise it would copy it locally
e.g.
int* ptr = ...;
ref var p = ref ptr[someIndex];
why do smth fancy like this though
I wouldn't really call that fancy, it's just getting a reference to an element in an array
but you can do it without actually touching pointers yourself
ref UnsafeUtility.ArrayElementAsRef<T>( array.GetUnsafePtr( ), index );
this is all you need basically
Ah, didn't know that methods exists, cool
and that would act like a class
but I literally sent you it xD
Well that was when we were talking about if it was possible natively, so I saw unsafe and didn't continue reading π
my bad
Thanks for the pointers (hehe)
Will Burst optimize away property getters/setters so they are basically zero cost comparing to a field?
The CLR already inlines properties
Nice thanks.
How do you guys handle input? Do you read inputs per system, or do you have components that contain their respective values?
best to gather inputs up in a nice input struct
yeah and then you can use it as a SingletonComponent
hmm
I wonder if I can keep pointer reference
to singleton component
assuming it'll never change archetype
Is this the right way to execute some mainthread code after a scheduled job is complete?
it works but it's not really the intended way, you'd utilize the dependency chain and another job that calls Unpack... method
remember you can make managed jobs without burst
oh, other jobs can execute main thread stuff?
well I don't know what's in this method. there are some calls that unity complains about when not being called by mainthread so that's out the window but for everything else, it's possible
texture.Apply
the problem with LateUpdate is that it could be called a frame later (because the jobHandle.IsCompleted state is true a frame later) and make problems. if you are really concerned use .Run or jobHandle.Complete()
oh yes, that's why it's complaining about accessing deallocated stuff, i'll move it to update and let is handle .IsComplete, that should work
WithoutBurst and Run is 100% on mainthread so you can do all you want - the problem is that it has no dependency as input so it doesn't help in your case
yes, I'd use jobHandle.Complete too. it's the cleanest solution imo and maybe you can get around to burst compile the Unpack method/texture manipulation and then you can schedule both. I haven't used any Texture2D, someone else would need to answer how they use it and if it's possible to burst. (I don't think so as it's a managed class)
ugh nativearray deallocated error still
I don't understand these allocators so i'll revert back to .Run() and burst
Did you dispose your nativearray?
Are you scheduling your jobs in a MonoBehaviour?
yes mono, it's not ECS, I was disposing the nativearray in the main thread, in that method that's called after the job IsComplete
Im not sure that you can reliably use IsComplete tbh, might need to use handle.Complete() to force it finished at some point
ok, thanks
would I so: schedule from main thread, then wait a constant amount of time like 0.1 second then call complete then do the main thread work?
Several frames has likely passed in 0.1 seconds
If you don't dispose your nativearrays before then you will get the warnings
Call Complete() at the point in the frame when you need to use the data and dispose of things
@elfin spire might be able to schedule in update and then complete in lateupdate. this is kind of the pain point of why I personally dislike using jobs outside of ecs
maybe i should turn this into a compute shader.. all I'm trying to do here is update a 2000x2000 control texture (within a radius R of a bunch of coordinates do some simple math to set the pixel to the value 0,0.5 or 1) to show an influence map in the game around certain objects, what do you all think?
update frequency, about 0.1 second, can be less
think grass growing around wet areas and desert expanding around dry areas
eh for me easier just to do it as a job in update/lateupdate, more like if you start to schedule a lot of jobs from monobehaviours might need to think of strats for handling dependencies(which ecs basically does for you). think I was just fretting needlessly π
oh I get it
I always trip over allocator lifecycle
I used Ninja and coroutine, which was doing threading for me, no burst though
maybe split the texture data from the actual data and after you are done computing, generate/update the texture
you could do all that in a big 2000x2000 array
must be even possible to vectorize
if you split the load into quadrants you can even parellel it
2k is quite big though
for updating ever 0.1 sec you can use variable updaye group
that way you can change the update rate without much changes
how does this work? An EntityCommandBuffer can give us a DB with AddBuffer. Yet, the entity isn't even registered in a chunk and when the DB is inlined in the chunk, how does it know where to write the data to? or is it just a temporary buffer that gets copied to the chunk when the ECB gets applied?
yes addbuffer is just local memory inside the ecb
alright, thanks
I have quite the predicament, on one hand I want to use write handles, also to keep the safety system intact, on the other I want to bump the change version manually because I have conditional writes. Seems I need to write an Accessor that's not bumping the version. It would be great if we have a simple parameter for that.
well, easy enough to add to my lib
haha wrote something similar
turns out i didn't need it though
i wrote a lot of hacks for my current library
and i've managed to avoid using most of them
do you still use the temp memory and memcmp?
i just don't know how to get around that. for example, a buffer where spell ids are saved for cooldowns. not every spell has a cooldown, so how to exactly go about that for a memcmp?
my cooldown is a component and effects without a cooldown just don't have the component
oh you make zero compares. hm. is that a list or what are you using?
actually just spent all morning writing tests for all my states for activation
found 2 bugs
ah i see
oh so yeah im going to write up a little thing about my timer
{
remainings[i] = math.max(0, remainings[i] - this.DeltaTime);
}```
a timer like like this is hugely problematic with change filters right
because while remaining > 0 you need it to execute
so you can't just change filter it
so usually it just runs every frame
and i'm going for no operations executing when nothing triggers
i only solved this last night
glad you solved it π i have to ask though, why not use ticks?
if (batchInChunk.DidChange(this.RemainingHandle, this.SystemVersion))
{
var remainings = batchInChunk.GetNativeArray(this.RemainingHandle).Reinterpret<float>();
for (var i = 0; i < remainings.Length; i++)
{
remainings[i] = math.max(0, remainings[i] - this.DeltaTime);
}
}
// System 2
if (batchInChunk.DidChange(this.RemainingHandle, this.SystemVersion))
{
var remainings = batchInChunk.GetComponentDataPtrRO(ref this.RemainingHandle);
var length = UnsafeUtility.SizeOf<float>() * batchInChunk.Count;
if (UnsafeUtility.MemCmp(remainings, this.Zeros, length) != 0)
{
batchInChunk.SetChangeFilter(this.RemainingHandle);
}
}```
can you clarify ticks
simulation ticks. so you just save a start tick and end tick for timers
heh, that's a smart memcmp π
because
a) i don't want to be limited to fixed update
b) that still causes the system to update every frame which is what i'm trying to avoid
i will say the float subtraction was by far the slowest part of my whole loop
well, having float times is a huge pain in networking and general effects that tick with a certain interval
you could still have remaining ticks with an integer
so the memcmp still works
this is true but again i'm not sure i want to be restricted to a fixed update
it makes the library less universal
and i'm already testing this with more entities than anyone has probably ever used
what's this.Zeros? a matching nativeArray of zero values?
[NativeDisableUnsafePtrRestriction]
public void* Zeros;```
it's just a chunk of memory of 0s
since i'm in an ISystem i can't store native arrays
so literally just allocated a chunk of 16KB memory in the system
UnsafeUtility.MemClear(this.zeroes, maxSize);```
really nothing exciting
lol, what a workaround π what does Unity intend to use in ISystem? (now I know why my ISystem wasn't working with the nativecontainers)
native containers will work fine in 1.0
with the removal of dispose sentinel
they just currently don't so limited to unsafe containers
noice
anyway i can actually do this change filtering thing in the same system
i wrote a quick
public static unsafe void SetChangeFilter<T>(this ArchetypeChunk chunk, BufferTypeHandle<T> handle, uint version)
where i could specify the version specifically instead of using global
so i could just use global version + 1
but i decided i'd rather just a second system instead of another hack
i'm avoiding this extension
oh yeah there's another reason. server/client might tick at different rates and i'm actually quite a fan of using variable tick rates
reducing tick rate during heavy simulations
(though I would like the performance)
i did consider using quantized floats as ints but decided against it for now
not confident i can give up precision atm
as you are using read handles, this doesn't trip anything up?
i see
batchInChunk.SetChangeFilter(this.RemainingHandle);
i could just change that to batchInChunk.GetNativeArray(this.RemainingHandle);
and it'd do the same thing
yeah makes sense to just get the ro ptr. i can probably reduce some handles myself
i just thought calling SetChangeFilter was clearer what it was doing
yep, i also like thay approymuch better. more control over the change filtering is very welcome
but yeah a system checking a change filter will not trigger another change filter on itself hence the need for the second system (though as mentioned I could use the +1 hack above but decided against it)
hmm you indirectly notified me of a potential problem
SetChangeFilter should only be called on ComponentTypeHandle that are marked as write
time to throw in a check for that
i probably should also add that check π
i need to find out what's actually happening with refs. the difference between ref var input = ref inputs[i]; and var input = inputs[i]; one should put the pointers on the stack, the other the actual data, right?
hm, so I should really avoid refs for just reads. i saw some improvements for bigger structs. even down to anything > integer
main reason, no memcpy
(puts another test on his todo)
in theory putting the data on stack should be vastly superior
again it depends a lot on burst!
you could just end up loading the memory directly into simd registers
but no expert on this~
do entity and their rigidbodies obey regular time scale, or do they have a seperate one?
oh also how do i build with il2cpp, it appears i need some kind of tool installed?
thank you!
where is that?
i would assume that is in player settings, although where i cannot find
oh think i found it?
i notice you have incremental garbage destruction enabled, just curious is this better than the default usually
thanks!
That was the default when I created the project
oh, mine was default off
Switch to Android build...
but i wanna build it for windows?
Oh
any ideas how i would build it for windows?
Looking...
ok thanks so much!
Did you add the Windows Build Support (IL2CPP) module when you installed the version of Unity for this project?
that is a good question, i actually dont remember, i hope i did, let me check though brb
I hope not...because I'm running out of ideas... π
lol
it is installed
welp
Hum...
what editor are you using?
what do you mean, im using unity to edit my game, i guess?