#archived-dots
1 messages · Page 63 of 1
@rotund token i`m trying to write a area of interest system for my networking using physics queries (overlapsphere)
relevancy?
i have an extremely efficient version that doesn't require physics if you want
can handle like 100k ghosts in like 1ms
i want
not relevancy, my game is topdown. Entities outside view are fully culled
What do you use? spatial hashing? brute force?
i use a spatial hashmap
that has been extremely optimized
it's in my core library and someone asked about it the other day
so i posted them a sample
that said if you are just a single camera view and everything has physic colliders then a simple overlap sphere will be fine for your use case
IJobEntityChunkBeginEnd
just allocate it a private field in OnChunkBegin
then clear per entity
Nicee thank you
i`m really new on jobs
public partial struct SerializeJob : IJobEntityChunkBeginEnd
{
[ReadOnly] public CollisionWorld world;
private NativeList<DistanceHit> distanceHits;
public unsafe void Execute(in WorldTransform transform, in NetworkedPeer peer)
{
distanceHits.Clear();
if (world.OverlapSphere(transform.Position, 5.0f, ref distanceHits, CollisionFilter.Default, QueryInteraction.Default))
{
Debug.Log("Hey");
}
}
public bool OnChunkBegin(in ArchetypeChunk chunk, int unfilteredChunkIndex, bool useEnabledMask, in v128 chunkEnabledMask)
{
distanceHits = new NativeList<DistanceHit>(Allocator.TempJob);
return true;
}
public void OnChunkEnd(in ArchetypeChunk chunk, int unfilteredChunkIndex, bool useEnabledMask, in v128 chunkEnabledMask, bool chunkWasExecuted)
{
distanceHits.Dispose();
}
}```
is this fine?
Thank you. It is working now
Humm, it is not
I will check it online, i think i can find the answer
Thank you for your time @rotund token
oh my bad
i forgot about that
yeah it's just a bad safety warning
put [NativeDisableContainerSafetyRestriction]
on it
since it's a container you aren't passing into the job it doesn't need to be safety checked
(ideally the safety system would ignore private fields - but it can't because people use constructors)
Nice, it works now
hmm, can't figure out any good way of doing this, tempted to just duplicate the method to each of the system's, but that just doesn't seem right...
oh sorry i missed this
it depends if you're using ISystem or SystemBase
this was something I bought up with Dani the other day actually
if you're using ISystem you can just have
public static void YourMethod(ref SystemState state)
and systemapi will work fine from ISystem
if you're using SystemBase though you're out of luck
oh fascinating, welp one of them is an ISystem, unfortunately the other is a SystemBase (due to the fact i can't find any way of getting the new input system to work with ISystem)
that is unfortunate, so should i just duplicate the method then?
is there anyway to call a method in an ISystem from a monobehaviour, as then i could probably get the input system to call stuff a monobehaviour that then calls the ISystem's methods?
kind of but highly not advised
ah unfortunate
could i use Object.FindObjectOfType<>() to get the input system monobehavior thing, and then just set actionEvents somehow to the ISystem's functions?
hmm ye it might be possible
surprisingly it actually works!
i dont think FindObjectOfType<>() can be used in a burst compiled function though... can it?
but then in the function i dont have access to the SystemState, hmm
can i store the SystemState in a component, or is that not advised?
action events can be created from scratch
new DefaultInputActions()
there is no need to keep it as singleton
true, for now i have it as a singleton anyway, although if ever i need multiple ill try that though, thanks
considering how it is a reference, i dont see any reason it would be bad? Am i missing something?
hmm there kind of are a lot of reasons to keep a single copy
disabling action maps
well, how many do you want to have in your world anyway?
I see no reason to have more than 1 holder
split screen or local coop
ideally you'd have separate worlds but unfortunately with only 1 hybrid renderer allowed it kind of makes split screen much harder and basically 1 world
ok that crashed visual studio's c sharp error thingy, odd
how do i store a reference on a component, as just doing public ref SystemState state aint working for some reason it is interpreting it as a method, weird
hmm, seems you can't store references in structs at all, should i use pointers?
use class
you can have a class inherit from IComponentData?
cool, thanks! And also is it a good idea to store the system state like this?
What system filter should I use for UI systems?
not sure how to ensure networking support (since I never used one)
Is it just me or is there a bug with ICleanupComponentData and netcode?
They work fine in server world but are not on the entities in the client world? The component doesnt exist on the entity even though they use the same prefab and bakers
(I disabled my clean up systems to remove them and it still doesnt work (They werent running in the first place i did check that as well))
Switching them to IComponentData makes them work fine
The work around i'm now using is adding a tag component and checking for the absence and then readding it for clients
Don't you add your cleanup components through system in the runtime world?
My understanding is that they should behave exactly like IComponentData but when an entity is destroyed you can query for just them and then do clean up logic (and then remove the component)
So it shouldnt matter if they are added via bakers
It works fine in my server world
Yeah, haven't tried it. I just know the documentations usage case https://docs.unity3d.com/Packages/com.unity.entities@1.0/manual/components-cleanup-cleanup.html.
I can imagine it could be some issue with baking being in a world where you now have a component that is not cleaned up if the entity is removed, but that's a wild guess x)
Well, CleanupComps, also clean up during baking sessions (as they are not serialized).
you can only add them in runtime
well somehow they magically work in my server world
I guess i'm just completely misunderstanding their use case
their use case - tag smth that needs to dispose of data
yeah but having to add the tag makes you do more steps
you have to build a destroy system
actually i really don't get the use case
My ideal version would be just like IComponentData store whatever you want in it but then allows for easy clean up
i need it to allow me to remove the entity form a specific area in a chunk system
e.g. entity is at (2,2) is destroyed, remove from that area chunk
let's say you have component with game object prefab
once you instantiate entity
your system instantiates game object from prefab and attaches to entity
ok, yeah i actually do get that case
but that seems like it has been pointlessly limited
reference to that GO will be stored on cleanup comp
so once you have a entity without prefab component but with cleanup
yup, i use it for sprite renderers in a different project
that means GO should be destroyed
there is no data that needs disposing that can be stored in subscene
yeah, but thats not what i want to use it for
think of it as being pre-setup in the baker
allowing for that wouldnt break the current logic
and would just enhance the use case
then you don't need it
except now i've got to build 3 new systems to accomplish the same thing
so yes, i would like to have it
ahhh, this is a lot more complicated
I wanted to instead make a destroy system by adding a DestroyTag, then i can do all the clean up via that.
Except that Netcode will just instantly destroy the entity client side when instead i want to control that
huh? why can't you do that
i need it client side
I've done that, I basically just put a delay timer onto it
with netcode using the ghost relevancy system?
not netcode, but it shouldn't be that difficult surely
sadly i think it is difficult
guess i'm going to make to go to my other option
which is ICleanupComponentData and then duplicate the stuff i need at runtime
yay double data
@rustic rain is there some way to delay creation/onstartrunning of a system until subscene data has loaded in?
RequireForUpdate?
Comparing this to IDisposable https://docs.unity3d.com/Packages/com.unity.entities@1.0/manual/components-managed-create.html is it even needed anymore? 🤔
require for update seems to not trigger OnStartRunning unless the required components are available on creation
🤷
yeah I've started to use requireforupdate for that , but tertle before did suggest to me a while ago to use a monobehaviour to create the systems you want in the order that you want
OnStartRunning runs right before Update if system was not updated previous group update
it's part of Update basically
yeah, a good point
and you can delay them all running at start pretty easily from that
i might have to do this, seems really frustrating
so it seems that, as mentioned above, if the components in RequireForUpdate do not exist on system creation, it doesn't fire OnStartRunning at all when those components are available later
unless i'm missing something here, going to try and confirm this
OnStartRunning will fire every time
Update happens but didn't happen previously
look at source of OnStartRunning and how it's called
it's literally
if (didn't update last frame) OnStartRunning();
mm yeah it could be because i'm passing QueryBuilder into RequireForUpdate, just trying to check this now
okay so when i use this, it never fires OnStartRunning:
when i just use the commented out line ( using the type of a single component ) it works fine
maybe i should test by just passing in an EntityQuery, like the old way
are you sure
your requirments are fullfilled for update at all?
sounds like your Update just never happens
Is a component showing up twice in the inspector something I should be worried about or is that just a UI bug?
both components definitely do exist i've confirmed that
make a log in Update
and be certain
or inspect system
and it's queires
in debugger
Occasionally when I pause the play mode, Scene Tags are shown to have an invalid value. Is that normal?
Okay so the problem, after searching the github samples, appears to be:
This doesn't work:
state.RequireForUpdate(SystemAPI.QueryBuilder().WithAll<PrefabHolderComponent>().WithAll<SpawnPoint>().Build());
did you check generated code?
But this does:
state.RequireForUpdate<PrefabBuffer_Weapon>();
state.RequireForUpdate<SpawnPoint>();
I think it might be because the QueryBuilder caches the query and possibly isn't being updated
whereas just passing in each type separately doesn't have that problem, and works as expected
@devout prairie I think the first one makes sure all entities with both prefabholder and spawn points
so I'd rather check
whereas the second one means any entity with just prefabBuffer OR spawn point will allow execution
the old method with SystemBase ofcourse was using GetEntityQuery(QueryDesc) but that's not an option in ISystem
ahhhh really
so how should that be written using QueryBuilder?
( or without )
Ahem
if those components exist on different entities
they don't share same query
just do separate Requires
state.RequireForUpdate(SystemAPI.QueryBuilder().WithAll<PrefabHolderComponent>().Build());
state.RequireForUpdate(SystemAPI.QueryBuilder().WithAll<SpawnPoint>().Build());
As far as I remember, you can add multiple to require for update
ah shit yeah that would make sense
yeah so because different entities, it would require different queries
it's obvious of course!
I am glad they defaulted to always running systems
in 0.17 they didn't and it caused me a lot of headaches
yeahh
well damn
i guess then it would be nice to have a way to write RequireForUpdate as a single line
but i can see the logic why what i was trying to do didn't work
Oh wait, you can just do this
state.RequireForUpdate(SystemAPI.QueryBuilder().WithAny<PrefabHolderComponent>().WithAny<SpawnPoint>().Build());
Change to WithAny
please no
I am not 100% sure, but check it and see if it works
the problem is i need both components to exist..
so not one or the other
Both exist for the system to run?
Ah yeah I see. Hmm
out of my depth, not sure @devout prairie
yeah no it's cool, you spotted the problem whereas i just didn't
doing this works, so it's fine either way: #archived-dots message
but yeah it would be nice to have a one-line approach to that
but looking through the github samples, it's obviously how they do it:
I think you can combine separate querys
I learned today about the RequireForUpdate<T>() so that is awesome
I thought I had to make a query every time
but yeah I guess that would be extra uneccesary code
I do like the samples, very clean and easy to read
Is there any way to get rid of this warning?
Diagnostic 'CS0282: There is no defined ordering between fields in multiple declarations of partial struct 'HitProcessingJob'.
The job struct has to be partial for code generation and I obviously need to add fields to it. So I see no way to avoid it.
Add a file called csc.rsp in Assets/ and add -nowarn:0282
So no way to avoid the problem itself? It can only be suppressed?
Don't think so, I think it's supposed to be suppressed by default so should be perfectly fine
Well, our sourcegen should emit #pragma disable warning CS0282 at the top of our partials (tmk)
Also, since when did my gold color turn sapphire - seems Unity Staff has blue color now? o.o
Maybe the 1.0 version does already? We are still on 0.51. Just wanted to make sure that its safe to supress this warning. But thats what I will do then. Thx @dense crypt
it seems they mess around with the roles quite a bit, i've noticed colors change a few times
i don't like it 😅 the gold color was cool
and I'm purple now 
I just deleted the library folder and now this problem is gone. I'm going to delete the library folder at the end of each day from now on. There is always something breaking :p
basic stupid question but is it not possible to use GetEntity inside a static method within a baker?
maybe if you pass in a reference to this ie the baker?
you got it thanks, that seems to work
as i have nativearray open. internal int m_Length; internal int m_MinIndex; internal int m_MaxIndex; why does it have min/maxIndex. makes little sense to me
only thing i can think of is that it's important for deferred arrays. i see no code references for it though. it's always set to 0 and length -1
Ahhh, is there a faster way to make it stop? Clear Entity Cache has no effect -> nuking library folder? Is there another way?
I'm thinking of going back to 0.51 for now. Such pain :p
i fixed this earlier by starting playmode with the subscene open.. can't remember if i also cleared cache during or before/after
I'm going to try that next time 🤞
Used for range checks on ijobfor and other parallel jobs
You should see an attribute on the top of native array related to it
ok, that makes sense. still, to have 2 ints for something potentially never used is odd.
guess there was no other way to make it work without a dozen job types
They are wrapped in unity collection checks
you just can't see it inspecting source because you're seeing the compiled dll
Is you try reference it in a build though it will cause an exception
OMG they finally tracked down my burst corruption 🥳
https://forum.unity.com/threads/burst-corruption.1370103/#post-8722500
Burst team must hate it when I report a bug, I've given them multiple really hard to track down issues
Is there a way to instantiate without removing prefab? Its not a big deal to add prefab back on to the new entity, but entities in the LinkedEntityGroup at instantiation time seems difficult?
you mean without removing Prefab tag?
Yeah
Well it wouldn't be odd if you could disable IEnableable on initialization, unless that is possible?
I thought that worked through bakers but can't you just use the ECB to disable it?
Sorry, I avoid the baking. Everything procedural from a database with empty scene.
Oh
entities in the LinkedEntityGroup at instantiation time seems difficult?
I can't use ECB I think because the issue of the child entities not being deferred yet?
there's a nice little feature that not many people know of that might help here
AddComponentForLinkedEntityGroup
ohhh
How did I miss that
but i'm not sure i've seen anyone use/mention this
but yeah you pass in a query mask and it'll run on all LEG objects after creation that match the mask (including root since it always adds itself to the LEG)
unfortunately they do not have a variation for IEnableable yet
Well that's really useful
but if you just want to add prefab back then this is how you can do it
I have yet to use an EntityQueryMask yet, so Ill have to see what thats about
entityquery.GetEntityQueryMask()
it's just a very fast way to determine if an entity matches a query
I'm just confused on why I would need that to run this. Is it a safety check thing?
i take it AddCompForLEG is optimal under the hood and not random access of those entities
I don't often pass queries into jobs maybe I am confused
you dont pass the query into the job
you pass the mask
Mm I don't see a use case yet in what I've done, so that's likely the confusion
imagine you have a entity and a bunch of linked entities you want to instantiate
and some have a component called SpawnTime
you don't know what in the hierarchy has this component
but you want to set it when you instantiate this entity
Ahhh so its a way to target with the query
yeah the query just determines what entities in the LEG get applied to
none is a valid option if nothing matches it
if you want it to be everything just pass in the universal query mask
I see, makes sense. My LEG is relatively small, so I didn't think of that circumstance but I could see it being useful
masks are also quite efficient, you will often see code like
return;
Its probably a better solution then a .Instantiate(WithInstatiationOptions
interesting, that's kind of perfect for something I want to do
where they could just use
return;```
Right, I was thinking along the lines of aspect for that kind of check but this is better than hard grouping with an aspect just for a check like that
1 gotcha with masks is the query
you don't really want to create this query from the system but instead you want to create it from the entity manager
so the query isn't added as a dependency into the system
i suddenly feel so much more motivated now that i know my burst corruption is fixed
Good point
I also have 1 other question... I have a system that is querying for an IEnabled component and state is set to require it. The system is running despite there being none Enabled. Other systems this has worked fine. Anything you can think of that would cause this?
systems use IsEmptyIgnoreFilter
to determine if it should run
so it ignores change/shared/IEnablable filters
you would need a sync point otherwise because a job that is currently running could change the enable state while the system is determining if it should run
I think that makes sense.. Ill have to try to check the other systems to see why its working there. Seems inconsistent but there must be something I am missing
Thanks again @rotund token you are the goat. You should have a donation link somewhere on your discord or unity profile. If I ever get to release and profit off this work Id have no problem sending you something. Best resource on Unity ECS there is
appreciate the kind words 
I concur
on another note whats the best way to freeze the physics or stop the physics on a bunch of entitys that have physicsbodys
could you add IEnableablecomponents to the physicsbodys
are you wanting to remove it from the simulation
or stop it being affected by the simulation
(but still queriable)
yeah at least temporarily
for it not to be effected but queryable basically
well no actually I want things to still interact with it
there's a PhysicsMassOverride component
so I guess I just want to freeze its position
/// Add this component to a dynamic body if it needs to sometimes switch to being kinematic. This
/// allows you to retain its dynamic mass properties on its <see cref="PhysicsMass"/> component,
/// but have the physics solver temporarily treat it as if it were kinematic. Kinematic bodies
/// will have infinite mass and inertia. They should also not be affected by gravity. Hence, if
/// IsKinematic is non-zero the value in an associated <see cref="PhysicsGravityFactor"/>
/// component is also ignored. If SetVelocityToZero is non-zero then the value in an associated <see cref="PhysicsVelocity"/>
/// component is also ignored.
/// </summary>
public struct PhysicsMassOverride : IComponentData
{
/// <summary> The is kinematic flag. </summary>
public byte IsKinematic;
/// <summary> The set velocity to zero flag. </summary>
public byte SetVelocityToZero;
}```
which lets you temporarily set something to kinematic or force it's velocity to 0
so it won't move
excellent, that's it, thanks a lot
if you're changing this frequently you can just put this on the entity at the start and just leave it at 0
and toggle it on/off as required
to avoid structural changes
good point, I will do that
You normally do this on OnStartRunning so Create is BurstCompile? Or is it burstable
it should be burstable - just use query build as normal but pass in EM
How UI works in multiplayer? Is it exists only on one World (kinda like singleton) or?
I need no indepth explanation, just general concept, I don't want networking
depends if you're talking just general multiplayer or like split screen
split screen just doesn't work well with entities unfortunately
in theory it should be amazing
but the hybrid renderer / brg doesn't support multiple versions
why not?
ah yes
you could just nicely have each split in a different world
BRG is annoying to use
also hybrid (gameobjects) become super funky
until there is render target
as cameras from each world would render
but normal entities just work beautifully with culling etc
so yeah it's a shame about entities graphics, it has so much potential for amazingly easy split screen
but it's not a super popular thing in games anymore
it's more about BRG I guess
however i wanted it for debugging
so i could run 2 clients in split screen
for debugging multiplayer games
instead of having to make a build etc
it didn't support it before BRG
well you can still do multiple UI 1 per world
it's just the renderer that would need to be handled differently
i think in a split screen game you'd have a separate world for presentation
yeah, I'm just figuring out concepts so I can do it correctly from the start
vs each local simulation
so you'd have each split screen local world with input, UI, etc
then copy what needs to render from both into a shared world and render that
that said, when i did this i stilly used 1 UI document
i just gave each world a root element in it
I hesitate not to use more UI Documents
considering they have a very nice feature - render order
i was told by a unity dev they only expect 1 UI document
and asked what my use case was when i was trying to use more than 1
(i wanted a module debug console)
basically if you have UI documents on top of each other
they wont block input into each other
so input would click both documents
it's a problem
yeah i havent tried since 2021
so click events should work same as 1 document
and another dev (but he was new) told me that multiple documents was the way 😅
so much confusion about
conceptually i kind of like the idea of 1 document
still, the fact that UI document scraps whole hierarchy as you disable it is frustrating and would require a workaround
then there is a problem to solve - order
Wait is there some integration of UI with entities now? I haven't touched my UI in probably a year or more, but I had created systems that link to each UI document to kind of be the middleman. Is there a simpler way?
nah, we're just doing own UI Toolkit implementations
basically same thing you do
Ok, probably something similar just with baking?
I decided to go against baking
A man after my own heart
because many UI things cannot be serialized
like localization tables
at least in a subscene
and it's still going to be managed data after all
(my baking works fine on this - i use a system/baking implementation)
so I decided to keep UI as game objects with all required references
Is there a way to write SystemAPI.Query with only tags? O.o
umm yeah something like that let me look itup
should probably work fi you return entity withall<T>
wondering how you did it
my biggest headache atm is tying best frontend practices
with Unity
public partial class UIDocumentSystem : SystemBase
{
private const string RootClassName = "root";
private readonly List<OrderedElement> elements = new();
private readonly VisualElement view = new();
private VisualElement root;
/// <summary> Adds a panel to the UI. </summary>
/// <param name="visualElement"> The panel to add. </param>
/// <param name="priority"> The draw priority. </param>
public void AddPanel(VisualElement visualElement, int priority = 0)
{
var e = new OrderedElement(visualElement, priority);
this.elements.Add(e);
this.elements.Sort();
var index = this.elements.IndexOf(e);
this.view.Insert(index, visualElement);
}
/// <summary> Removes a panel from the UI. </summary>
/// <param name="visualElement"> The panel to remove. </param>
public void RemovePanel(VisualElement visualElement)
{
var index = this.elements.IndexOf(new OrderedElement(visualElement, 0));
if (index < 0)
{
SystemAPI.GetSingleton<BLDebug>().Error($"Removing {visualElement} that isn't added.");
}
else
{
this.elements.RemoveAt(index);
this.view.Remove(visualElement);
}
}```
Can you elaborate what you mean? I need to start with SystemAPI.Query to add a WithEntityAccess / WithAll<T> no?
what's the purpose of Query for just Entity anyway?
you could just do Query operation
batched
^ this is a good point
Not sure what you mean. I query for tags that I don't need to read of in idiomatic foreach.
EntityManager.DestroyEntity(yourQuery);
or smth like this
SystemAPI.QueryBuilder().WithAll<Tag1, Tag2>().Build();
thats very different to SystemAPI.Query
what is your use case @mystic mountain
issue is suggesting you use the batch operations on em/ecb
Right now I'm just looking at RPC events.
Haha, nice one! I'm sure they love you 😄 was this bug only triggered with asynchronous compilation?
They didn't say what the cause was
I get it a lot but i haven't seen it reported much elsewhere
it was really demotivating me
you're such a good tester. 😄 if i get any errors it's mostly one that everyone gets ^^
oh yeah this reminds me
i started removing all Debug.LogX from my libraries
and moved them to a singleton component
that uses unity's logging package instead
so I can spam debug/verbose logs from my libraries but people using it won't see them
Stealing that
but why?
Shouldn't library users see that?
why would they want to see
"Packet decoded"
100 times a frame
no one wants to see a bunch of info/debug/verbose logs from a 3rd party package
also they can optionally turn it on if they want
unity log package has more log levels
verbose
debug
info
warning
error
fatal
by default i log anything warning or above to users, and the rest is hidden unless they turn it on via menu
this has also had a huge benefit of I can inject what world the log is coming from
that's cool!
docfx is pretty cool stuff 😄
Getting the following burst error when building my ecb.... i didn't think this was happening before or maybe i just missed it. (version pre15)
Error:
Burst error BC1016: The managed function
Unity.Entities.SystemState.get_World(Unity.Entities.SystemState* this) is not supported
My code:
EntityCommandBuffer ecb = SystemAPI.GetSingleton<BeginInitializationEntityCommandBufferSystem.Singleton>().CreateCommandBuffer(state.WorldUnmanaged);
Yeah it is an ISystem. doesn't give me a line number though so i thought it was that. only other reference to the World would be state.World.Time.DeltaTime
just use SystemAPI.Time
thanks
@rotund token could I trouble you for another question? Are EntityQueries burstable?
Getting another error on one of mine for using a managed array of ComponentTypes when I build an entityquery
I tried making it a native array but it didn't matter
GetEntityQuery()
yeah
yeah GetEntityQuery is not burstable it takes params EntityQuery[]
you should use the query builder
oh? Not sure I've used it before. I'll take a look
either use SystemAPI.QueryBuilder for convenience
or if doing it by hand
var query = new EntityQueryBuilder(Allocator.Temp).WithAll<Test>().Build(ref state)
I just had it done by hand. but definately better to know the SystemAPI way
Hey everyone. I've got a question. I have a bunch of game objects that use MonoBehaviours from the asset store. They are part of my game UI. How do I bridge them with entities? Can I bake monobehaviours into entities? And if not, how could I, for instance, fetch a bunch of entities to MonoBehaviour to show them in UI (or fetch monobehaviour to a system)?
is there a way to set the batch size for schedule parallel with IJobChunk?
a bit confused how to debug this, basically after a certain threshold my job performance just craters: before and after . basically just spawning characters and once it hits a certain number, it tanks immediately.
we have this issue randomly at work where some jobs suddenly take forever in editor
and a restart fixes it, never happens in a build
is this something similar?
or is this actually your job taking forever (looks more like it based off profiler on right)
if it is actually executing really slow, solution is to just profile the methods inside the job
is that ever where the entity count ramps up to a threshold and then takes forever or an either or situation regardless of entities? for me, its a charactercontroller job, mostly identical to the physics sample one(although I ported it since prior to 0.17 so not sure what the official one looks like now), basically spawning in entities to 100+ it gradually ramps up in perf and then bam one more entity(which is seemingly random per run) is the entity that broke the job's back and it the profiler looks like that
when profiling it, its the same performance hit proportionally to the entity count, its just more like one particular thread seems to hang up on the job
so like on 159 entities its fine first img, and the 160th will be the second img
yeah but what inside the job is taking that long
https://pastebin.com/7wsjy0XN thought mine was basically identical but it doesnt appear to be so, anyway cant check in a build because of https://forum.unity.com/threads/hdrp-build-failed-error-x4567-maximum-cbuffer-exceeded.543320/ now happening in urp. at least thats under review, thinking maybe should bug report this.
code gen is refusing, for some reason SystemAPI.GetBuffer<SomeBuffer>(SomeEntity); isnt allowed in a helper function on a component it seems... Are there any work arounds?
SystemAPI only works in Systems
oh...
Components are not meant to contain any logic, unless it's some helper
Think of components as simple data
like int or float
ah ok
i have 2 systems that need 1 function for very different reasons, do i just duplicate the function for each system or something else?
no clue what an extension is, but i'll look into that, thanks a ton!
but it won't be able to use systemapi
or get any other components
you need to pass them as ready parameters
ok cool!
ok, so then do you put these extension things on the component, or do you put them somewhere else?
hmm, im not certain an extension will work, as i need to use the system api in the function as far as i can tell: ```cs
[BurstCompile]
public bool IsSafe(int3 Pos, int MaxDangerLevel, ref SystemState state)
{
if (!Chunks.TryGetValue(GetChunkNum(Pos), out Entity ChunkEntity))
{
Debug.Log("chunk isnt real?");
return true;
}
if (ChunkEntity == Entity.Null)
{
Debug.Log("Couldn't get chunk entity, assuming safe!");
return true;
}
DynamicBuffer<EntityHerd> StuffInChunk = SystemAPI.GetBuffer<EntityHerd>(ChunkEntity);
for (int i = 0; i < StuffInChunk.Length; i++)
{
if (StuffInChunk[i].Danger > MaxDangerLevel && math.all(Pos.xz == (int2)SystemAPI.GetComponent<LocalTransform>(StuffInChunk[i].Block).Position.xz))
{
return false;
}
}
return true;
}
it can be part of component if this is specific to this component
no, such extensions is breaking pattern
components can't have such logic
and SystemAPI won't work
hmm, so i should just chuck that function on each ISystem that need it then?
sorry, what should i do instead?
you should keep it only as data
keep what as only data?
your component
anyway, what should i do with my function then, as it needs to be somewhere, and 2 systems definitely need it
sir, why can't you make your component so it can be used by both systems as is?
why do you need some extending logic to use that data?
because i can't memorise the code required to read my data
then make it so component doesn't need any code to be read
dont think that is really possible
plus i can hardly remember what i named the fields, and almost every time i have to go check how to get components by ref... my memory isnt the best
then you might as well scrap your component and start again if you want to do it properly
i have done that 3 times so far
I have rewritten 1 game 7 times while learning ECS 🤣
oh yikes
fully
welp i just can't think of any better way of storing what i need to, cause in need to store a bunch of entities and their positions, and unless i wanna check every entities position every time i move, then it seems right to split entities into chunk sized pieces, speeding up performance at the cost of complexity to use
if you would explain what you are trying to do
in the first place
people might suggest a proper approach
but don't explain what you already did, because that's just incompatible with ECS completely
simple 2d infinite world game, uses 2d simplex noise to decide where terrain is, uses 3 by 2 simplex noise for deciding the biomes and then fills whatever isnt terrain with stuff that belongs in that biome
explain again, but avoid implementations (noise)
just explain
what user need to experience
i dont know, i'm not good with putting this stuff in words, sorry...
imagine you're doing an ad for your game
and you are explaining the feature it got
you surely won't tell them "In this game you'll experience simplex noise 3 by 2", right? 🤣
i have no clue, i can send a screenshot of what it looks like though?
sure
so... what is it?
what is what?
this screenshot
top down view of all the biomes being generated, (in that screenshot terrain was hidden, but i can send another one showing terrain if you want me to)
x,y position of what?
i don't know what that means, but i hope so
or whatever you use
oh, i use ints as the smallest unit of moving, but divide the world into chunks for speed purposes when it comes to moving the player
ints as in position in one array?
nah i just use the default transform system that entities have
data wise each block on the map is one entity, each chunk is an entity that has a buffer component containing all the blocks(stored as entities) that belong to it, all these chunks are stored in a dictionary on a singleton component
the dictionary allows me to easily get the chunk entity from the chunk id (int2)
why not store it as just one big array
storing the chunks as an array, or storing the blocks as an array?
storing everything as an array
BlockOfData[]
where BlockOfData will contain properties like IsDangerous CanWalk and etc
or whatever you need
i dont quite understand, so do you mean that BlockOfData is an array of each block then?
I barely understand what you have either. Is it fully free or tiled or what?
It looked like tiles to me
i dont know what tiles are, everything's position has to be an int basically
so it is tile
if that is what tiles are, then i guess?
ah yes, except 2 of them
2 of them?
ye, one very large, and the other is very small
large one for chunks
small one for blocks, which belong to a chunk
you mean each square contains other squares?
ye basically
it's irrelevant then, just 2 tilemaps in a nutshell
sure
so datawise it's just an array
nope
if it's not you are doing smth wrong
it is a dictionary of chunks, which contain a buffer of blocks
so it is an array
the data this map represents is simple array
let's say this map only contains color of each tile
then it will be Color[]
yes i guess, but i dont have it saved as an array anywhere, never saw a need to, should i have it saved as an array somewhere?
now this map contains also a Walkable property for each tile
then it's some struct that contains both Color and Walkable boolean
and map is array of that struct
yes, and?
ye, but wouldn't that be super slow? The whole reason i used my dictionary of chunks approach was for performance, but i never tested just using an array...
no it won't
if you have 2 random access points
it's even slower
but considering you also access buffers just to access data...
what are random access points?
it's 100 times slower
it's when you access data not a fashion of for int = 0; int < maxValue; i++, but in a fashion of array[SomeRandomIndex]
oh fascinating
so looping through 1 array is faster than using 2 random access points?
looping through an array with thousands of structs in it is faster? I'll try it, but im doubtful
usually yes
that's why Entity random access is done through one huge dictionary
by entity index
which is what you do when you use GetBuffer
fascinating
ok ill change it up then and report back, currently i have 15 fps, i'll see if i gain any doing it using 1 giant array
should i use an array of entities each with a component, or instead should i use an array of structs, each one containing an entity?
how will i render then?
render what?
the blocks?
the way my screenshot is...
export what?
color map
what is a color map?
each tile has a color, right?
but this extremely slow
if all you need
is screenshot
you could render it in one quad
it'll be free
to render
ah no, screenshot is simplified, in the end it will have proper texturing... the solid colours are a placeholder
ah
then yeah, you can use entities I guess
but there's probably a better way
as in faster way
I think built in TileMap
is one of such ways
but I never used it
i didn't even know what a tile map was before you mentioned it, so ill look into it, but first ill try your giant array thing, as any performance over 15 fps would be nice
should i store them as a singleton buffer, or as a native array on a singleton component?
doesn't really matter, you can store it as either
ok thanks!
Btw how do we sort entities based on their properties ?
we don't sort entities 🤔
Hmmm... Well... And what if you need to process some entities before other ones ? Like based on their y position ? ^^ ( imagine a renderer )
then I'd make a job that will iterates entities and assigns them in order
So we basically query entities, copy them into another array, sort them, process that sorted array ?
But that will be much slower i guess :/
not usually, random memory access is usually the primary performance problem in DOTS if your doing things right
sorting data so its better suited to the cache can sometimes save you a ton of cycles
not really entities, but actual data to draw
it's going to be copied anyway
Hi everyone, is it possible to bake to a manually updated world? A world which hasn't been appended to the 'current playerloop'?
dreamingimlatios has a very extensive article in his repo surrounding sorting
no matter what, it will be expensive
best case is always to not be reliant on any sorting or just with small amounts of data.
also keep in mind. creating entities, the order is deterministic
so that can be taken advantage of
stupid question but I don't suppose anyone knows what I'm doing wrong with this foreach (var (physveloc) in SystemAPI.Query<RefRW<PhysicsVelocity>>().WithAll<TrainTag>())
it says type and identifier are both required 😕
Tuples can't be of length one. Ergo remove parentheses around physveloc and you're good to go
interesting, thanks
Does Deterministic means let say I spawn 8 entites 1 by 1 in order with playerId 1 to 8 then it will put in order with entity playerId 1 to 8 into chunk?
What would be the fastest way to create a graphics buffer from component data? I am trying to fetch data from several components and write them into the graphics buffer. I am currently doing this:
var enemyStats = new NativeList<EnemyStats>(Allocator.TempJob);
var compileEnemyStatsJobHandle = new CompileEnemyStatsJob()
{
EnemyStats = enemyStats
}.Schedule();
compileEnemyStatsJobHandle.Complete();
int enemyCount = enemyStats.Length;
if(this.buffer == null || enemyCount != this.bufferSize) Reallocate(enemyCount);
this.buffer.SetData(enemyStats.AsArray());
enemyStats.Dispose();
It works but it seems to be unoptimal with the Complete call etc.
@proud jackal Want to ask. Is that possible to load and instantiate entity prefab dynamically just like game object addressables without load subscene to load a bunch of entity prefabs? If cannot any plan to address this issue in future?
Afaik this is not possible at the moment. I am also waiting for this and currently have a custom solution which loads and converts prefabs at runtime. It has been teased several times that there will be a solution to pack converted prefabs and load them via "content managment" (the minimalist addressables replacement for asset bundles)
🤔 From documentation, it mentions that content management is for load and release unity engine objects and game object scene. I guess it's not for subscene and entity
Yeah documentation is lacking on that. I am pretty sure it is currently working for subscenes and it should work for prefabs in the future
Hi everyone is it possible to bake to a
sir, this is not possible without subscenes
everything regarding graphics registration is handled through subscenes
potentially you could roll your own solution to this
but it's going to be a bit complex
and slow
yes, as long as there are no structural changes, it'll stay this way. even ecb is deterministic when it comes to that
content management is already in 1.0.
you'll still have to bake in editor or build pipeline. there's no runtime baking nor is there any hint there ever will be
maybe something unofficial will come out to handle this
Yeah I know. I am only waiting for proper prefab handling. Runtime conversion of prefabs is just a workaround for this missing link
1.0.0-pre.15 Which means its still in preview... or its out now according to Unitys blog posts... or whataver. I have the feeling Unity is not so sure about that atm 🤷♂️
if you know how to handle graphics yourself, I have implemented a method that copies all component data from 1 entity to another.
Instead you can just use same code to serialize entity data
wdym proper prefab handling? that's already working fine. where do you have an issue?
they have an issue with subscenes 😅
There is no way to package, deliver and address prefabs
all of this can be done with subscenes
prefab in this case is just another entity but with prefab tag
Sure. I just need to rewrite everything that addressables already handle 🤷♂️
well, it really depends what exactly you miss from addressables
a subscene, either containing or referencing prefabs are your asset bundle. this will be handled as a GameObject and those can be built and delivered with content management
are there any samples of loading subscene dynamically btw?
i haven't found much more than this: https://docs.unity3d.com/Packages/com.unity.entities@1.0/manual/content-management.html it's pretty sparse
is there any way to do cache friendly networking area of interest system with dots? without random access?
and no wonder devs are afraid of subscenes looking at this page: https://docs.unity3d.com/Packages/com.unity.entities@1.0/manual/conversion-subscenes.html no loading/unloading examples. very meh docs right now
I have not tested this at all but I found this method to be interesting for this problem
One more question. Is that possible to load subscene without setup Subscene monobehavior game object at game object scene?
SceneSystem.LoadSceneAsync?
https://docs.unity3d.com/Packages/com.unity.entities@1.0/manual/scripting-loading-scenes.html
the subscene script itself does nothing except hold a reference to the subscene
so i'm reading a bit more into this, there is a whole pipeline setup here to do this stuff
that is managed via creating RequestEntityPrefabLoaded or PrefabAssetReference
does ref counting and everything for you
have a look at WeakAssetReferenceLoadingSystem
what are ComponentTypeHandles on ecs?
how you access entity data in a chunk for iteration
tertle is using ComponentLookup efficient?
If i need a nested loop for entities is using ComponentLookup the best way?
it's efficient for what it does
if you need random access of an entities component data then yeah it's the most efficient way
I see. is using random access of entities bad?
it's just always going to be faster to iterate a chunk,
but this is not always feasible
for a spatial hash system i think i will need this right?
or for physics queries
they return entities not the component i collided with
For collisions for example, you generally grab the lookup of the components you're checking for collisions between. Random access can't always be avoided after all.
using ComponentLookup ?
oh @rotund token my problem was to due with the placement of cc's, namely a bunch gathered up in close proximity must cause some recurring loop in the job. maybe this is a sign i should switch to rival
hmm it's that time of day, helper struct or static method
public readonly struct Flee
{
private readonly AgentFlee flee;
private readonly float3 position;
public Flee(RigidObject rigidObject, AgentFlee flee)
{
this.position = rigidObject.Position;
this.flee = flee;
}
public float3 GetTarget(in float3 fleePosition)
{
// Get the direction
var displacement = position - fleePosition;
// If the target is far way then don't flee
if (math.lengthsq(displacement) > this.flee.PanicDist * this.flee.PanicDist)
{
return this.position;
}
var direction = math.normalize(displacement);
var targetPosition = fleePosition + (direction * this.flee.PanicDist);
return targetPosition;
}
}```
public static class Flee
{
public static float3 GetTarget(in AgentFlee flee, in float3 position, in float3 fleePosition)
{
// Get the direction
var displacement = position - fleePosition;
// If the target is far way then don't flee
if (math.lengthsq(displacement) > flee.PanicDist * flee.PanicDist)
{
return position;
}
var direction = math.normalize(displacement);
var targetPosition = fleePosition + (direction * flee.PanicDist);
return targetPosition;
}
}```
i've gone forward and back on this like 3 times
benchmarking I can not see a difference so it's down to syntax and style
this is somewhat of a simpler example with only 1 method to avoid posting a giant code chunk
this is the type of thing that keeps me up at night
maybe it comes down to use
var linePath = new LinePath(pathArray);
var followPath = new FollowPath(rigidObject, agentMove);
var steering = new Steering(rigidObject, agentMove);
var targetPosition = followPath.GetTarget(linePath);
agentTarget.LinearVelocity = steering.Arrive(targetPosition);
agentTarget.FinalPosition = pathArray[^1].Position;```
```cs
var linePath = new LinePath(pathArray);
var targetPosition = FollowPath.GetTarget(position, linePath);
agentTarget.LinearVelocity = Steering.Arrive(agentMove, position, targetPosition);
agentTarget.FinalPosition = pathArray[^1].Position;```
do i prefer horizontal or vertical
hmmmmmm
personally I prefer the class
i think i agree in this small example
but i start questing it when i nest these helper structs inside helper structs
what if the static method ends up getting 5 params?
or i could just call the helper struct with 1 param
i've been a big proponent of helper structs over time, but that is more when state is involved
yeah, I don't know I still prefer the class, fewer lines of code and less setup
The thing that would make me choose helper struct is if I have a situation where I want to construct the helper only once with some data, and then perform multiple operations using that instance of the helper struct. Otherwise I think I'd choose static method
yeah the main issue i'm torn on here is, some of this movement logic will have multiple method calls while the above only have 1
so the multiple ones feel like they lean a lot more towards helper structs whereas the others feel like they should be a static class
but i like consistency, i don't want to do some 1 way and some the other way
this is the type of thing that haunts me for months
I guess if profiling says they're negligibly different in performance... it's an annoying problem.
I might prefer to go with the case where the majority feels best?
I get why that's a thing that could hang around for a long time though
I'd prefer the struct. Keeps the data in place, no searching for helpers.
sometimes you've just gotta make a choice and live with it
The whole thing is already written as structs from when i first wrote it like 2 years ago
I've just started re-visiting it atm to actually use it in my game and wanted to optimize some performance
(Doubled the follow path performance with minimal compromise!)
but my optimizations removed a bunch of methods and simplified stuff which led me to, should this even be a struct now thought
Imo it's ok to not just use one. I like the idea of struct use when state is involved over multiple calls and static when you just need one call. If you pick just one, then either way there will be weird cases imo.
But colours are different between structs/classes in my ide /twitches/
Haha
I guess those colours can inform you a little about how much state is likely to be involved...?
Hello, ADHD/autism traits. Relatable you are 😛
holy moly 3.6k line file in rival
Hmm, I'm having trouble with singletons and dependencies. I have one system that schedules a job to write to a NativeHashMap inside a singleton attached to the system. Then another system wants to read this singleton. Do I actually need to set up explicit dependencies between the systems?
ugh nvm, I forgot to pass state.Dependency to an IJob. I always forget to do this due to the automatic dependency passing with IJobEntity codegen.
So, this question might be a bit odd, but why is it that doing "new NativeArray(Allocator.Persistent)" in a job throws an error about how "Jobs can only create Temp memory", but creating a "new NativeList(Allocator.Persistent)" is just fine? Is there some sort of subtle issue with creating the native list? Is it just some sort of out-of-date aspect about the NativeArray?
Maybe I'm just confused about what the error message really means?
To put that another way, there are already ScheduleConstruct methods on some of the other native containers... so my understanding is that this is definitely possible and it just seems like this error is erroneous?
Mmmm, it looks like that throws from the DisposeSentinel object creation
do you have a callstack?
If you're asking me, it's just InvalidOperationException: Jobs can only create Temp memory Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle.CreateHandle (Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle& safety, Unity.Collections.Allocator allocator) (at <07b4fb2b5af74e479c2c24afaabbcaa4>:0) Unity.Collections.NativeArray`1[T].Allocate (System.Int32 length, Unity.Collections.Allocator allocator, Unity.Collections.NativeArray`1[T]& array) (at <07b4fb2b5af74e479c2c24afaabbcaa4>:0) Unity.Collections.NativeArray`1[T]..ctor (System.Int32 length, Unity.Collections.Allocator allocator, Unity.Collections.NativeArrayOptions options) (at <07b4fb2b5af74e479c2c24afaabbcaa4>:0)
Comes from the AtomicSafetyHandle
right
Seemed odd that it came from there, since it originates from that CreateHandle method but not the Create method that the other Native collections use
var newArray = new NativeArray<SimpleStruct>(1, Allocator.Persistent);
var newList = new NativeList<SimpleStruct>(1, Allocator.Persistent);
private struct SimpleStruct
{
private int Something;
}
What version of collections are you using?
(I didn't realize this was now seemingly supported by native list now, thought it was just a no go all around)
The type there is just some normal unmanaged struct
Yeah, the ScheduleConstruct stuff is kinda neat - I've been thinking about using it for performance, but haven't really done enough profiling to make sure it'd do anything
What version editor are you using?
2022.2.0b16.112.5806
mmm can you send me the source control sha1 from your editor log
I'm afraid that one's beyond me - do you have instructions?
something like
Built from '2022.2/dots/monorepo' branch; Version is '2022.2.0b10-dots (108970fe7f1b) revision 1083760'; Using compiler version '192829333'; Build Type 'Release'
And out of curiosity, do you not see this error message in AtomicSafetyHandle.CreateHandle?
Yes, except in my case Allocator.Persistent is also permissible
Oh, interesting
although it turns out there's a couple of similar looking functions so I want to make sure I'm not just barking up the wrong tree
Built from '2022.2/release' branch; Version is '2022.2.0b16 (3c3b3e6cd1d7) revision 3947326'; Using compiler version '192829333'; Build Type 'Release'
internal static void CreateHandle(out AtomicSafetyHandle safety, Allocator allocator)
{
safety = allocator == Allocator.Temp ? AtomicSafetyHandle.GetTempMemoryHandle() : AtomicSafetyHandle.Create();
if (!JobsUtility.IsExecutingJob)
return;
switch (allocator)
{
case Allocator.TempJob:
case Allocator.Persistent:
throw new InvalidOperationException("Jobs can only create Temp memory");
}
}
Mmmm okay
Is it possible to auto generate code based out of unity assets (e.g for each asset of a scriptable object type generate a component and system)?
Although I'm pretty sure this is coming from Rider's decompiler
Not sure I understand - what kind of code are you trying to generate?
I have an ability system which uses AttributeComponents<T>/AttributeModifierComponents<T> which are generated by creating SOs in the editor and assigning to authoring components. Then I have some systems that run over these components. Right now I'm generating it manually with a inspector button, but would be nice to learn code gen if I can do it with my use case x)
I think @solemn hollow does something similar to this for his ability/ai system stuff, probably guy to talk to
Unscientific benchmark of the IEnablable Overhead (no performance test, just eyeballing runtime)
100,000 entities, job with a bunch of work
0.02ms/thread
Very fast, minimal overhead
100% enabled
1.35 ms/thread
Nearly identical to running this without IEnablable
50% randomly with a component removed
0.65ms/thread
50% randomly disabled
0.71ms/thread```
comparing removing component vs disabled gives ~0.07ms overhead - better than I expected
Which version of the Unity Editor should I use for Dots right now? 2022.2.2f1? or still 2022.2.0b16? Jesus, it's still so hard to find any info on DOTS
.2f1 just came out today, last i looked there weren't even notes up for it yet -edit- yeah still not up
it was recommended to use .1f1 before today though
so yeah i'd probably just try .2f1 and see how it goes
What way to people generally like for 'resetting' a scene with entities?
i don't really reset scenes since i only have 1 scene
but for resetting worlds i just dispose and re-create it
So are all Systems still enabled?
sounds good
@rotund token what's component removed and disabled exactly?
removed i just removed a component from 50% of entities so it wouldn't run in that system
and disabled is just setting IEnablable component to false so 50% wouldn't run in that system
so i read that right that the remove test is a structural change?
the remove only removes them once
or was that not measured, just the sheer throughput
it's not constantly removing them
i purely wanted to see the overhead of checking the component is enabled or not
ok, cool. not too bad all things considered
What's the syntax to do this? 😛
World.Dispose() -edit- ok there's a little more than this, you need to remove it from player loop and a few other things. look at DefaultWorldInitialization.DomainUnloadOrPlayModeChangeShutdown for an example. mainly just call ScriptBehaviourUpdateOrder.RemoveWorldFromPlayerLoop and reset loop
Create world how you would normally create it
DefaultWorldInitialization.Initialize() for example
DomainUnloadOrPlayModeChangeShutdown is protected and CleanupWorldBeforeSceneLoadis private... how do you normally call that?
k. i'll have to do some reading. thanks for the starters
I'm getting an "Exception: Error: Invalid context argument index" when using the logging package, any idea what it means? Unity.Logging.Sinks.UnityDebugLogger.OnLogMessage (Unity.Logging.LogMessage& logEvent, Unity.Collections.FixedString512Bytes& outTemplate, Unity.Logging.LogMemoryManager& memoryManager) (at Library/PackageCache/com.unity.logging@0.51.1-preview.21/Runtime/TestSinks/UnityDebugLogSink.cs:50) Unity.Logging.Sinks.UnityDebugLogger.Unity.Logging.Sinks.ILogger.OnLogMessage (Unity.Logging.LogMessage& logEvent, Unity.Collections.FixedString512Bytes& outTemplate, Unity.Logging.LogMemoryManager& memoryManager) <0x283a8089950 + 0x0006a> in <ac3d567212b24eca84395dbe256527cf>:0 Unity.Logging.Sinks.SinkJob`1[TLogger].Execute () (at Library/PackageCache/com.unity.logging@0.51.1-preview.21/Runtime/Sinks/SinkSystemBase.cs:71) Unity.Jobs.IJobExtensions+JobStruct`1[T].Execute (T& data, System.IntPtr additionalPtr, System.IntPtr bufferRangePatchData, Unity.Jobs.LowLevel.Unsafe.JobRanges& ranges, System.Int32 jobIndex) (at <4a31731933e0419ca5a995305014ad37>:0)
what's the call to it
i've been using the package for a while and I haven't seen this issue
is the default unity Input burstable?
no
Something pretty simple 🤔
It works correctly for multiple logs and then it blows up lol
@rotund token I'm disposing and reinitializing my default world, but now I've lost my baked entities so my setup systems won't do their stuff
Do I need to be doing everything in a non-default world? or is there some easy fix here?
You'll need to reload your subscene in the new world
I was trying that with SceneManager but with no luck. Do I need to be using SceneSystem?
Walk you through it in like 30 min about to grab a haircut
If someone else hasn't
Hack way is just disable reenable all subscene game objects
But there are better approaches
KK. can chat later. I might be heading to bed now anyways
Native Crash Reporting
=================================================================
Got a UNKNOWN while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries
used by your application.``` Literally all the time randomly for me
whats the actual error/stack
at UnityEngine.Mesh:SetArrayForChannelImpl <0x000d5>
at UnityEngine.Mesh:SetSizedArrayForChannel <0x00132>
at UnityEngine.Mesh:SetArrayForChannel <0x00092>
at UnityEngine.Mesh:set_vertices <0x0002a>
at UnityEngine.TextCore.Text.MeshInfo:.ctor <0x00632>
at UnityEngine.TextCore.Text.TextGenerator:SetArraySizes <0x02702>
at UnityEngine.TextCore.Text.TextGenerator:Prepare <0x00202>
at UnityEngine.TextCore.Text.TextGenerator:GenerateText <0x00162>
at UnityEngine.TextCore.Text.TextHandle:Update <0x0009a>
at UnityEngine.UIElements.UITKTextHandle:Update <0x0033a>
at UnityEngine.UIElements.UIR.Implementation.UIRStylePainter:DrawText <0x0007a>
at UnityEngine.UIElements.MeshGenerationContextUtils:Text <0x0004c>
at UnityEngine.UIElements.TextElement:OnGenerateVisualContent <0x00042>
at UnityEngine.UIElements.VisualElement:InvokeGenerateVisualContent <0x000e7>
at UnityEngine.UIElements.UIR.Implementation.CommandGenerator:InvokeGenerateVisualContent <0x00042>
at UnityEngine.UIElements.UIR.Implementation.CommandGenerator:PaintElement <0x008c2>
at UnityEngine.UIElements.UIR.Implementation.RenderEvents:DepthFirstOnVisualsChanged <0x00442>``` Looks like UIToolkit
At least that one, I should look through previous logs and see if its always UIToolkit
havent seen that one
Hows enabling/disabling components realized btw ? How did they solve that issue ?
basically just a 128bit field per component in the chunk header
Ah i see and the query beneath basically just checks wether the component is enabled/disabled for the entity and skips it ?
foreach(entity in chunk)
if(!entity.Get<T>.Enabled) continue; // Skips the entity ?
Like this ? Sorry for the bad pseudocode 😄
Wont it cause branching ?
its a bit more efficient than that
it has some early outs for whole chunk disabled/enabled
hence the 0/100% case don't really change much
I hope so, otherwhise i would be pretty sad 😄
Ah so disabled/enabled components are now moved to special chunks basically ?
nope
even non-enablable component actually has this bit field in chunk header
just not used
Alright, i think im gonna look at the source later to understand this ^^
But is that implemented branchless ? I have seen many ECS were they simply skip the entity with an if condition which kinda ruins the performance and creates branches.
This is how IJobEntity code gens it
Hmmm i see... so it actually creates branches ( the if conditions ), however they are pretty efficient.
oh this only enteres if there are enable mask requied
if (!useEnabledMask)
{
for (int entityIndexInChunk = 0; entityIndexInChunk < chunkEntityCount; ++entityIndexInChunk)
{
ref var agentMotionArrayRef = ref InternalCompilerInterface.UnsafeGetRefToNativeArrayPtrElement<BovineLabs.Movement.Data.AgentMotion>(agentMotionArray, entityIndexInChunk);
ref var agentMoveArrayRef = ref InternalCompilerInterface.UnsafeGetRefToNativeArrayPtrElement<BovineLabs.Movement.Data.AgentMove>(agentMoveArray, entityIndexInChunk);
var __Unity_Transforms_TransformAspectTypeHandleArrayArray = __Unity_Transforms_TransformAspectTypeHandleArray[entityIndexInChunk];
var retrievedByIndexInpathBufferAccessor = pathBufferAccessor[entityIndexInChunk];
Execute(ref agentMotionArrayRef, in agentMoveArrayRef, in __Unity_Transforms_TransformAspectTypeHandleArrayArray, in retrievedByIndexInpathBufferAccessor);
matchingEntityCount++;
}
}
else
{```
the above is that else statement
Yep just saw that xD So its efficient, nevermind...
Thanks for the insight, would have taken hours to actually find the right code 😄
Code generation is awesome
Any idea why I getting this error? Is that unity editor or dots physics bug?
what situation do you like using FixedStepSimulationSystemGroup?
When I need smth to run exactly 50 times per second
It basically fulfills the same purpose as FixedUpdate from the mono world
(Pretty sure it runs 60fps by default)
But yeah, if you're doing physics stuff you should use it
So... how would I go about reloading my subscene in a new world? 😛
SceneSystem.UnloadSubScene
SceneSystem.LoadSubScene
Ah so it was using the SceneSystem...
I think the method is called SceneSystem.LoadSceneAsync and SceneSystem.UnloadScene
i don't know about whose bug it is, but i will say that we do have a todo item to improve the callstack here so you can at least tell which system is throwing the exception, because it's kind of embarrassing that you can't right now
🥳 Seems they've started working on support for change filters on netcode client
Been a good news week
maybe biased, but i thought it was pretty awesome when i did a game jam with it
You mean netcode?
i'm not on the netcode team, but i liked it so much that if i heard somebody was trying to make a networked game, i might suggest they use ecs just so they could use ecs netcode
Yes, it's great
I really like it
Make a lot of complicated topics like prediction very easy to work with
then I'll give it a shot
and I have another question, where can I find dots physics settings now?
I like it a lot more than monobehaviour based networking
What do you mean? Like gravity?
yeah, everything seems to be on components now
Yes, there's a PhysicsStepAuthoring component you can put on a subscene
will NoPhysics option still allow me to raycast stuff?
that's my plan also 😄
There's also an ECS specific character controller called Rival that you can look at if you like
thanks!
Is this the proper way to get an ECB?
var ecbSingleton = SystemAPI.GetSingleton<EndSimulationEntityCommandBufferSystem.Singleton>();
var ecb = ecbSingleton.CreateCommandBuffer(World.Unmanaged).AsParallelWriter();
Yes
In documentation I see this:
EntityCommandBufferSystem sys = this.World.GetExistingSystemManaged<FooECBSystem>();
EntityCommandBuffer ecb = sys.CreateCommandBuffer();
(in the old version, you don't in the new one)
^

Anything relating to getting systems is usually old, since that's not very straight forward for ISystem (and not really recommended anyways)
I see. Sadly documentation is also old 😄
yeah its going to take some getting used to with all these changes
Just get better at forgetting things 
oh yeah I'm there
anyone know why all of my subscenes broke?
Loading Entity Scene failed because the entity header file couldn't be resolved. This might be caused by a failed import of the entity scene. Please take a look at the SubScene MonoBehaviour that references this scene or at the asset import worker log in
Welcome to the club
all I see in the log is the import request nothing else
It happens every few reloads
oh
I'm assuming it will be fixed at some point, hopefully soon
You can usually fix it by reloading your scripts, then clearing the entity cache
If that doesn't work, restart the editor
i usually hit, clear entity cache, restart editor, clear entity cache
but yeah there are a few ways to fix it
thankfully it's a lot less common in pre vs exp though
it was nearly every recompile in exp
how would i get a singleton component from inside a monobehaviour?
create a query from EM
EntityManager.CreateQuery(....).GetSingleton
^
ahhhhaaaaa
thanks!
previously with managed SystemBase, i'd just grab the system with GetExistingSystem and get the public field i wanted
but after converting my SystemBase to ISystem, i'm storing the public field data to a singleton instead
Yep, that's the intended approach
Unless you like to live dangerously 
If it's more than 3 per day (8h of work) I deem it pretty unusable
Time to wait then 😅
every 3 hours is a lot better than every 5min
^
Sometimes if you're lucky you'll get the rare back-to-back
That's when you go make coffee
Also there's more pressing things still broken imo
every 3h is inside 3/day range 😄
but it's not more than 3 per day!
that's what I meant by in range 😄
mileage may vary*
yh sadly unity is still unity
for talking sake, is this an ok approach to creating said singleton and disposing of the hashmap data on destroy:
[BurstCompile]
public partial struct WorldSpaceDisplaySystem : ISystem
{
public struct WorldSpaceDisplayData : IComponentData
{
public NativeParallelHashMap<Entity, float3x2> HealthPositionDict;
}
[BurstCompile]
public void OnCreate(ref SystemState state)
{
state.EntityManager.CreateSingleton(
new WorldSpaceDisplayData()
{
HealthPositionDict = new NativeParallelHashMap<Entity, float3x2>(0, Allocator.Persistent),
});
}
[BurstCompile]
public void OnDestroy(ref SystemState state)
{
var stateData = GetSingletonRW<WorldSpaceDisplayData>().ValueRW;
stateData.HealthPositionDict.Dispose();
}
this is the first time i've tried this with a hashmap so i'm not even sure if this will work at all yet 😮
previously was just a field on a managed systembase
seems ok, you can change GetSingleton to TryGetSingleton in OnDestroy
I think the more "modern" way to do this would be to store the component on the system entity
should be fine
this gets a bit complicated
But it doesn't really matter
because queries don't return system entities by default
Yes, with queries
but systemapi singleton does (from memory)
RequireForUpdate is what always gets me with system components
this is the part i couldn't discern from the docs.. how do you create/access a system entity ( i thought what i was doing was the way to do that )
SystemAPI.SetComponent / GetComponent have overloads that take a SystemHandle
ah wait, yes i've seen this
Like @rotund token mentioned though, be careful as queries don't automatically match these components unless you specify EntityQueryOptions.IncludeSystems
is there any benefit to that over just CreateSingleton?
1 less entity really
There's no real performance benefit, it's just less boilerplate-y imo
kind of nice thematically
well i guess if i can avoid passing in a query options where not really needed then great, but i guess there might be cases where it could be useful to have that degree of separation
9/10 you're probs just going GetSingleton<MySystemComp> anyway right
Yes, unless you have multiple system entities that have the component
At which point GetSingleton will throw
I use singletons a ton is that bad 😕
no, unity made them very fast by not completing dependencies
in OOP kinda was