#archived-dots

1 messages · Page 63 of 1

late mural
#

i have a function that tells me if any given position is safe, but i have 2 systems that need to use it for completely different reasons, so would i store this as a helper method on the component where i store the chunks? And if so how would i deal with the fact im using SystemAPI.GetComponent in the function?

thorn trout
#

@rotund token i`m trying to write a area of interest system for my networking using physics queries (overlapsphere)

rotund token
#

relevancy?

#

i have an extremely efficient version that doesn't require physics if you want

#

can handle like 100k ghosts in like 1ms

thorn trout
#

i want

#

not relevancy, my game is topdown. Entities outside view are fully culled

#

What do you use? spatial hashing? brute force?

rotund token
#

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

thorn trout
#

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?

rotund token
#

you also need to inherit from IJobEntity

#

^ also

thorn trout
#

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

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)

thorn trout
#

Nice, it works now

late mural
rotund token
#

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

late mural
#

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)

rotund token
#

yeep

#

and that was my problem as well

late mural
#

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?

rotund token
#

kind of but highly not advised

late mural
#

ah unfortunate

late mural
#

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?

late mural
#

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?

rustic rain
#

new DefaultInputActions()

#

there is no need to keep it as singleton

late mural
#

true, for now i have it as a singleton anyway, although if ever i need multiple ill try that though, thanks

late mural
rotund token
#

disabling action maps

rustic rain
#

well, how many do you want to have in your world anyway?

#

I see no reason to have more than 1 holder

rotund token
#

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

late mural
#

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

late mural
late mural
rustic rain
#

yes

#

this is managed component

late mural
#

cool, thanks! And also is it a good idea to store the system state like this?

rustic rain
#

What system filter should I use for UI systems?

#

not sure how to ensure networking support (since I never used one)

hybrid jay
#

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

mystic mountain
#

Don't you add your cleanup components through system in the runtime world?

hybrid jay
#

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

mystic mountain
proud jackal
#

Well, CleanupComps, also clean up during baking sessions (as they are not serialized).

rustic rain
hybrid jay
#

well somehow they magically work in my server world

#

I guess i'm just completely misunderstanding their use case

rustic rain
#

their use case - tag smth that needs to dispose of data

hybrid jay
#

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

rustic rain
#

once you instantiate entity

#

your system instantiates game object from prefab and attaches to entity

hybrid jay
#

ok, yeah i actually do get that case

#

but that seems like it has been pointlessly limited

rustic rain
#

reference to that GO will be stored on cleanup comp

#

so once you have a entity without prefab component but with cleanup

hybrid jay
#

yup, i use it for sprite renderers in a different project

rustic rain
#

that means GO should be destroyed

rustic rain
hybrid jay
#

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

rustic rain
hybrid jay
#

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

pliant pike
#

huh? why can't you do that

hybrid jay
#

i need it client side

pliant pike
#

I've done that, I basically just put a delay timer onto it

hybrid jay
#

with netcode using the ghost relevancy system?

pliant pike
#

not netcode, but it shouldn't be that difficult surely

hybrid jay
#

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

devout prairie
#

@rustic rain is there some way to delay creation/onstartrunning of a system until subscene data has loaded in?

devout prairie
#

🤷

pliant pike
#

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

rustic rain
#

it's part of Update basically

pliant pike
#

and you can delay them all running at start pretty easily from that

devout prairie
rustic rain
#

Why RequireForUpdate is not an option?

#

seems like easiest solution

devout prairie
#

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

rustic rain
#

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();

devout prairie
#

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

rustic rain
#

are you sure

#

your requirments are fullfilled for update at all?

#

sounds like your Update just never happens

muted star
#

Is a component showing up twice in the inspector something I should be worried about or is that just a UI bug?

devout prairie
rustic rain
#

and be certain

#

or inspect system

#

and it's queires

#

in debugger

muted star
#

Occasionally when I pause the play mode, Scene Tags are shown to have an invalid value. Is that normal?

devout prairie
#

This doesn't work:

state.RequireForUpdate(SystemAPI.QueryBuilder().WithAll<PrefabHolderComponent>().WithAll<SpawnPoint>().Build());
rustic rain
#

did you check generated code?

devout prairie
#

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

rustic rain
#

sir, assuming you inlined it

#

there is a possibility

#

codegen broke

worn valley
#

@devout prairie I think the first one makes sure all entities with both prefabholder and spawn points

rustic rain
#

so I'd rather check

worn valley
#

whereas the second one means any entity with just prefabBuffer OR spawn point will allow execution

devout prairie
#

the old method with SystemBase ofcourse was using GetEntityQuery(QueryDesc) but that's not an option in ISystem

devout prairie
#

so how should that be written using QueryBuilder?

#

( or without )

rustic rain
#

Ahem

#

if those components exist on different entities

#

they don't share same query

#

just do separate Requires

worn valley
#

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

devout prairie
#

yeah so because different entities, it would require different queries

#

it's obvious of course!

worn valley
#

I am glad they defaulted to always running systems

#

in 0.17 they didn't and it caused me a lot of headaches

devout prairie
#

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

worn valley
#

Oh wait, you can just do this

#

state.RequireForUpdate(SystemAPI.QueryBuilder().WithAny<PrefabHolderComponent>().WithAny<SpawnPoint>().Build());

#

Change to WithAny

rustic rain
#

please no

worn valley
#

I am not 100% sure, but check it and see if it works

rustic rain
#

that would be disgusting

#

creating 3rd query for no reason

devout prairie
#

so not one or the other

worn valley
#

Both exist for the system to run?

#

Ah yeah I see. Hmm

#

out of my depth, not sure @devout prairie

devout prairie
#

yeah no it's cool, you spotted the problem whereas i just didn't

#

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:

pliant pike
#

I think you can combine separate querys

worn valley
#

I learned today about the RequireForUpdate<T>() so that is awesome

#

I thought I had to make a query every time

pliant pike
#

but yeah I guess that would be extra uneccesary code

worn valley
#

I do like the samples, very clean and easy to read

pulsar jay
#

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.

dense crypt
pulsar jay
dense crypt
#

Don't think so, I think it's supposed to be suppressed by default so should be perfectly fine

proud jackal
#

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

pulsar jay
devout prairie
viral sonnet
#

i don't like it 😅 the gold color was cool

pliant pike
#

and I'm purple now leahSAD

muted star
#

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

pliant pike
#

basic stupid question but is it not possible to use GetEntity inside a static method within a baker?

devout prairie
pliant pike
#

you got it thanks, that seems to work

viral sonnet
#

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

muted star
#

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

devout prairie
muted star
rotund token
#

You should see an attribute on the top of native array related to it

viral sonnet
#

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

rotund token
#

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

rotund token
#

Burst team must hate it when I report a bug, I've given them multiple really hard to track down issues

winter depot
#

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?

rotund token
#

you mean without removing Prefab tag?

winter depot
#

Yeah

rotund token
#

That seems like an odd request

#

But I doubt there is

winter depot
#

Well it wouldn't be odd if you could disable IEnableable on initialization, unless that is possible?

rotund token
#

I thought that worked through bakers but can't you just use the ECB to disable it?

winter depot
#

Sorry, I avoid the baking. Everything procedural from a database with empty scene.

rotund token
#

Oh

entities in the LinkedEntityGroup at instantiation time seems difficult?

winter depot
#

I can't use ECB I think because the issue of the child entities not being deferred yet?

rotund token
#

there's a nice little feature that not many people know of that might help here

#

AddComponentForLinkedEntityGroup

winter depot
#

ohhh

rotund token
#

this was my like #1 cool feature when 1.0 released

winter depot
#

How did I miss that

rotund token
#

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

winter depot
#

Well that's really useful

rotund token
#

but if you just want to add prefab back then this is how you can do it

winter depot
#

I have yet to use an EntityQueryMask yet, so Ill have to see what thats about

rotund token
#

entityquery.GetEntityQueryMask()

#

it's just a very fast way to determine if an entity matches a query

winter depot
#

I'm just confused on why I would need that to run this. Is it a safety check thing?

devout prairie
#

i take it AddCompForLEG is optimal under the hood and not random access of those entities

winter depot
#

I don't often pass queries into jobs maybe I am confused

rotund token
#

you pass the mask

winter depot
#

Mm I don't see a use case yet in what I've done, so that's likely the confusion

rotund token
#

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

winter depot
#

Ahhh so its a way to target with the query

rotund token
#

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

winter depot
#

I see, makes sense. My LEG is relatively small, so I didn't think of that circumstance but I could see it being useful

rotund token
#

masks are also quite efficient, you will often see code like

    return;
winter depot
#

Its probably a better solution then a .Instantiate(WithInstatiationOptions

pliant pike
#

interesting, that's kind of perfect for something I want to do

rotund token
#

where they could just use

    return;```
winter depot
#

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

rotund token
#

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

winter depot
#

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?

rotund token
#

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

winter depot
#

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

rotund token
#

appreciate the kind words UnityChanSalute

pliant pike
#

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

rotund token
#

are you wanting to remove it from the simulation

#

or stop it being affected by the simulation

#

(but still queriable)

pliant pike
#

yeah at least temporarily

#

for it not to be effected but queryable basically

#

well no actually I want things to still interact with it

rotund token
#

there's a PhysicsMassOverride component

pliant pike
#

so I guess I just want to freeze its position

rotund token
#
    /// 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

pliant pike
#

excellent, that's it, thanks a lot

rotund token
#

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

pliant pike
#

good point, I will do that

winter depot
rotund token
#

it should be burstable - just use query build as normal but pass in EM

rustic rain
#

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

rotund token
#

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

rotund token
#

so you can only render from 1 world

#

otherwise it would be super easy to implement

rustic rain
#

ah yes

rotund token
#

you could just nicely have each split in a different world

rustic rain
#

BRG is annoying to use

rotund token
#

also hybrid (gameobjects) become super funky

rustic rain
#

until there is render target

rotund token
#

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

rustic rain
#

it's more about BRG I guess

rotund token
#

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

rotund token
rustic rain
#

so

#

with current workflow

#

it's 1 UI per PC

#

might as well be static

rotund token
#

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

rustic rain
#

yeah, I'm just figuring out concepts so I can do it correctly from the start

rotund token
#

vs each local simulation

rustic rain
#

btw turns out Community MVVM Toolkit works with Unity

#

including codegen

rotund token
#

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

rustic rain
#

I hesitate not to use more UI Documents

#

considering they have a very nice feature - render order

rotund token
#

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

rustic rain
#

shouldn't be that way now

#

They will share single hierarchy

rotund token
#

yeah i havent tried since 2021

rustic rain
#

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

rotund token
#

conceptually i kind of like the idea of 1 document

rustic rain
#

still, the fact that UI document scraps whole hierarchy as you disable it is frustrating and would require a workaround

rustic rain
rotund token
#

and my workflow on it is good now so i dont really want to swap

#

i have that solved

rustic rain
#

so you just rebuild hierarchy as you add screens to root?

#

as in, reorder them?

winter depot
#

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?

rustic rain
#

basically same thing you do

winter depot
#

Ok, probably something similar just with baking?

rustic rain
#

I decided to go against baking

winter depot
#

A man after my own heart

rustic rain
#

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

rotund token
#

(my baking works fine on this - i use a system/baking implementation)

rustic rain
#

so I decided to keep UI as game objects with all required references

mystic mountain
#

Is there a way to write SystemAPI.Query with only tags? O.o

rotund token
rustic rain
#

no need

#

I totally understand how it can be done, just

rotund token
rustic rain
#

wondering how you did it

#

my biggest headache atm is tying best frontend practices

#

with Unity

rotund token
#
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);
        }
    }```
mystic mountain
#

Can you elaborate what you mean? I need to start with SystemAPI.Query to add a WithEntityAccess / WithAll<T> no?

rotund token
#

oh i guess you can't

#

just looked at api

rustic rain
#

what's the purpose of Query for just Entity anyway?

#

you could just do Query operation

#

batched

rotund token
#

^ this is a good point

mystic mountain
rustic rain
#

or smth like this

winter depot
#

SystemAPI.QueryBuilder().WithAll<Tag1, Tag2>().Build();

rotund token
#

thats very different to SystemAPI.Query

#

what is your use case @mystic mountain

#

issue is suggesting you use the batch operations on em/ecb

mystic mountain
#

Right now I'm just looking at RPC events.

viral sonnet
rotund token
#

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

viral sonnet
#

you're such a good tester. 😄 if i get any errors it's mostly one that everyone gets ^^

rotund token
#

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

winter depot
#

Stealing that

rustic rain
#

Shouldn't library users see that?

rotund token
#

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

viral sonnet
#

that's cool!

viral sonnet
#

docfx is pretty cool stuff 😄

tribal pollen
#

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);

rotund token
#

hmm looks fine

#

sure it's on that line?

#

ISystem right

tribal pollen
#

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

rotund token
#

yeah you are getting World

#

that's your issue

tribal pollen
#

AHH fk right its nto unmanaged

#

😅

rotund token
#

just use SystemAPI.Time

tribal pollen
#

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

rotund token
#

yes

#

are you doing something like

tribal pollen
#

I tried making it a native array but it didn't matter

rotund token
#

GetEntityQuery()

tribal pollen
#

yeah

rotund token
#

yeah GetEntityQuery is not burstable it takes params EntityQuery[]

#

you should use the query builder

tribal pollen
#

oh? Not sure I've used it before. I'll take a look

rotund token
#

either use SystemAPI.QueryBuilder for convenience

#

or if doing it by hand
var query = new EntityQueryBuilder(Allocator.Temp).WithAll<Test>().Build(ref state)

tribal pollen
#

I just had it done by hand. but definately better to know the SystemAPI way

stiff mesa
#

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)?

safe lintel
#

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.

rotund token
#

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

safe lintel
#

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

rotund token
#

yeah but what inside the job is taking that long

safe lintel
late mural
#

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?

rustic rain
late mural
rustic rain
#

Components are not meant to contain any logic, unless it's some helper

#

Think of components as simple data

#

like int or float

late mural
#

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?

rustic rain
#

just make extension

#

static

#

void Kek(this DataType lul)

late mural
#

no clue what an extension is, but i'll look into that, thanks a ton!

rustic rain
#

but it won't be able to use systemapi

#

or get any other components

#

you need to pass them as ready parameters

late mural
#

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;
}
rustic rain
rustic rain
#

components can't have such logic

#

and SystemAPI won't work

late mural
#

hmm, so i should just chuck that function on each ISystem that need it then?

rustic rain
#

no

#

what you are trying to do is OOP

#

you are trying to objectify your component

late mural
#

sorry, what should i do instead?

rustic rain
#

you should keep it only as data

late mural
#

keep what as only data?

rustic rain
#

your component

late mural
#

anyway, what should i do with my function then, as it needs to be somewhere, and 2 systems definitely need it

rustic rain
#

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?

late mural
#

because i can't memorise the code required to read my data

rustic rain
#

then make it so component doesn't need any code to be read

late mural
#

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

rustic rain
#

then you might as well scrap your component and start again if you want to do it properly

late mural
#

i have done that 3 times so far

rustic rain
#

I have rewritten 1 game 7 times while learning ECS 🤣

late mural
#

oh yikes

rustic rain
#

fully

late mural
#

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

rustic rain
#

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

late mural
#

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

rustic rain
#

explain again, but avoid implementations (noise)

#

just explain

#

what user need to experience

late mural
#

i dont know, i'm not good with putting this stuff in words, sorry...

rustic rain
#

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? 🤣

late mural
#

i have no clue, i can send a screenshot of what it looks like though?

rustic rain
#

sure

late mural
#

it only has like 5 biomes currently, but i'll add more eventually

rustic rain
#

so... what is it?

late mural
#

what is what?

rustic rain
#

this screenshot

late mural
#

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)

rustic rain
#

ok, so

#

by the time you need to access data

#

you know x,y position on this map?

late mural
#

x,y position of what?

rustic rain
#

of point on this map

#

or tile

late mural
#

i don't know what that means, but i hope so

rustic rain
#

or whatever you use

late mural
#

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

rustic rain
#

ints as in position in one array?

late mural
#

nah i just use the default transform system that entities have

rustic rain
#

anyway

#

what does this map represent

#

data wise?

late mural
#

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)

rustic rain
#

why not store it as just one big array

late mural
#

storing the chunks as an array, or storing the blocks as an array?

rustic rain
#

storing everything as an array

#

BlockOfData[]

#

where BlockOfData will contain properties like IsDangerous CanWalk and etc

#

or whatever you need

late mural
#

i dont quite understand, so do you mean that BlockOfData is an array of each block then?

rustic rain
#

I barely understand what you have either. Is it fully free or tiled or what?

#

It looked like tiles to me

late mural
#

i dont know what tiles are, everything's position has to be an int basically

rustic rain
#

so it is tile

late mural
#

if that is what tiles are, then i guess?

rustic rain
#

is that it?

late mural
#

ah yes, except 2 of them

rustic rain
#

2 of them?

late mural
#

ye, one very large, and the other is very small

#

large one for chunks

#

small one for blocks, which belong to a chunk

rustic rain
#

you mean each square contains other squares?

late mural
#

ye basically

rustic rain
#

it's irrelevant then, just 2 tilemaps in a nutshell

late mural
#

sure

rustic rain
#

so datawise it's just an array

late mural
#

nope

rustic rain
#

if it's not you are doing smth wrong

late mural
#

it is a dictionary of chunks, which contain a buffer of blocks

rustic rain
#

so it is an array

late mural
#

no?

#

am i missing something?

rustic rain
#

the data this map represents is simple array

#

let's say this map only contains color of each tile

#

then it will be Color[]

late mural
#

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?

rustic rain
#

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

late mural
#

yes, and?

rustic rain
#

so if it's just an array

#

then all you need to access data from it

#

is index

late mural
#

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...

rustic rain
#

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...

late mural
#

what are random access points?

rustic rain
#

it's 100 times slower

rustic rain
late mural
#

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

rustic rain
#

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

late mural
#

fascinating

rustic rain
#

but anyway

#

that probably is not all

late mural
#

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

rustic rain
#

just keep it the way

#

so you don't need to share logic between systems

late mural
#

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?

rustic rain
#

no

#

for things like this

#

don't use entities

#

just use big arrays

late mural
#

how will i render then?

rustic rain
#

render what?

late mural
#

the blocks?

rustic rain
#

hm

#

what exactly are blocks?

#

is it 3d or literally the way your screenshot is?

late mural
#

the way my screenshot is...

rustic rain
#

you could just export it to texture

#

and draw it as one quad

late mural
#

export what?

rustic rain
#

color map

late mural
#

what is a color map?

rustic rain
#

each tile has a color, right?

late mural
#

no?

#

each entity has a material though, as it is all done using prefabs

rustic rain
#

but this extremely slow

#

if all you need

#

is screenshot

#

you could render it in one quad

#

it'll be free

#

to render

late mural
#

ah no, screenshot is simplified, in the end it will have proper texturing... the solid colours are a placeholder

rustic rain
#

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

late mural
#

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?

rustic rain
late mural
#

ok thanks!

stone osprey
#

Btw how do we sort entities based on their properties ?

rustic rain
stone osprey
#

Hmmm... Well... And what if you need to process some entities before other ones ? Like based on their y position ? ^^ ( imagine a renderer )

rustic rain
#

then I'd make a job that will iterates entities and assigns them in order

stone osprey
#

So we basically query entities, copy them into another array, sort them, process that sorted array ?

But that will be much slower i guess :/

pliant pike
#

sorting data so its better suited to the cache can sometimes save you a ton of cycles

rustic rain
#

it's going to be copied anyway

muted star
#

Hi everyone, is it possible to bake to a manually updated world? A world which hasn't been appended to the 'current playerloop'?

viral sonnet
#

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

pliant pike
#

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 😕

proud jackal
#

Tuples can't be of length one. Ergo remove parentheses around physveloc and you're good to go

brave field
pulsar jay
#

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.

brave field
#

@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?

pulsar jay
brave field
pulsar jay
muted star
#

Hi everyone is it possible to bake to a

rustic rain
#

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

viral sonnet
viral sonnet
#

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

pulsar jay
pulsar jay
rustic rain
viral sonnet
rustic rain
#

they have an issue with subscenes 😅

pulsar jay
rustic rain
#

all of this can be done with subscenes

#

prefab in this case is just another entity but with prefab tag

pulsar jay
#

Sure. I just need to rewrite everything that addressables already handle 🤷‍♂️

rustic rain
#

well, it really depends what exactly you miss from addressables

viral sonnet
#

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

rustic rain
#

are there any samples of loading subscene dynamically btw?

viral sonnet
thorn trout
viral sonnet
rustic rain
#

docs are also outdated

#

on next page

brave field
rotund token
#

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

thorn trout
#

what are ComponentTypeHandles on ecs?

rotund token
#

how you access entity data in a chunk for iteration

thorn trout
#

If i need a nested loop for entities is using ComponentLookup the best way?

rotund token
#

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

thorn trout
#

I see. is using random access of entities bad?

rotund token
#

it's just always going to be faster to iterate a chunk,
but this is not always feasible

thorn trout
#

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

hushed lichen
#

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.

safe lintel
#

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

rotund token
#

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

pliant pike
#

personally I prefer the class

rotund token
#

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

pliant pike
#

yeah, I don't know I still prefer the class, fewer lines of code and less setup

signal phoenix
#

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

rotund token
#

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

hushed lichen
#

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

viral sonnet
#

I'd prefer the struct. Keeps the data in place, no searching for helpers.

pliant pike
#

sometimes you've just gotta make a choice and live with it

rotund token
#

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

minor sapphire
#

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.

rotund token
#

But colours are different between structs/classes in my ide /twitches/

minor sapphire
#

Haha

#

I guess those colours can inform you a little about how much state is likely to be involved...?

hushed lichen
safe lintel
#

holy moly 3.6k line file in rival

whole gyro
#

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.

urban ore
#

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?

balmy thistle
#

Mmmm, it looks like that throws from the DisposeSentinel object creation

#

do you have a callstack?

urban ore
#

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

balmy thistle
#

right

urban ore
#

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

balmy thistle
#

It's inconsistent for sure

#

How are you initializing the NativeList ?

urban ore
#
var newArray = new NativeArray<SimpleStruct>(1, Allocator.Persistent);
var newList = new NativeList<SimpleStruct>(1, Allocator.Persistent);

private struct SimpleStruct
{
    private int Something;
}
balmy thistle
#

What version of collections are you using?

urban ore
#

2.1.0-pre.2

#

Should've started with that, sorry

rotund token
#

(I didn't realize this was now seemingly supported by native list now, thought it was just a no go all around)

urban ore
#

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

balmy thistle
urban ore
#

2022.2.0b16.112.5806

balmy thistle
#

mmm can you send me the source control sha1 from your editor log

urban ore
#

I'm afraid that one's beyond me - do you have instructions?

balmy thistle
#

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'

urban ore
#

And out of curiosity, do you not see this error message in AtomicSafetyHandle.CreateHandle?

balmy thistle
#

Yes, except in my case Allocator.Persistent is also permissible

urban ore
#

Oh, interesting

balmy thistle
#

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

urban ore
#

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");
      }
    }
balmy thistle
#

Mmmm okay

mystic mountain
#

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)?

urban ore
#

Although I'm pretty sure this is coming from Rider's decompiler

balmy thistle
#

No, that looks right

#

thanks

urban ore
mystic mountain
# urban ore 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)

rotund token
#

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
dense oriole
#

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

rotund token
#

.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

tribal pollen
#

What way to people generally like for 'resetting' a scene with entities?

rotund token
#

i don't really reset scenes since i only have 1 scene

#

but for resetting worlds i just dispose and re-create it

tribal pollen
#

So are all Systems still enabled?

rotund token
#

disposing the world will destroy all systems

#

and re-create them

tribal pollen
#

sounds good

viral sonnet
#

@rotund token what's component removed and disabled exactly?

rotund token
#

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

viral sonnet
#

so i read that right that the remove test is a structural change?

rotund token
#

the remove only removes them once

viral sonnet
#

or was that not measured, just the sheer throughput

rotund token
#

it's not constantly removing them

#

i purely wanted to see the overhead of checking the component is enabled or not

viral sonnet
#

ok, cool. not too bad all things considered

tribal pollen
rotund token
#

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

tribal pollen
#

DomainUnloadOrPlayModeChangeShutdown is protected and CleanupWorldBeforeSceneLoadis private... how do you normally call that?

rotund token
#

im not saying you call it

#

i'm just saying look at how to dispose a world properly

tribal pollen
#

k. i'll have to do some reading. thanks for the starters

orchid ginkgo
#

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)

rotund token
#

what's the call to it

#

i've been using the package for a while and I haven't seen this issue

tawdry mulch
#

is the default unity Input burstable?

rotund token
#

no

orchid ginkgo
#

It works correctly for multiple logs and then it blows up lol

rotund token
#

hmm

#

i never use that

#

i always use $"{path} was not found"

#

in burst

tribal pollen
#

@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?

rotund token
#

You'll need to reload your subscene in the new world

tribal pollen
#

I was trying that with SceneManager but with no luck. Do I need to be using SceneSystem?

rotund token
#

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

tribal pollen
#

KK. can chat later. I might be heading to bed now anyways

winter depot
#
    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
rotund token
#

whats the actual error/stack

winter depot
#
      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

rotund token
#

havent seen that one

stone osprey
rotund token
#

basically just a 128bit field per component in the chunk header

stone osprey
#

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 ?

rotund token
#

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

stone osprey
#

I hope so, otherwhise i would be pretty sad 😄
Ah so disabled/enabled components are now moved to special chunks basically ?

rotund token
#

even non-enablable component actually has this bit field in chunk header

#

just not used

stone osprey
#

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.

rotund token
stone osprey
#

Hmmm i see... so it actually creates branches ( the if conditions ), however they are pretty efficient.

rotund token
#

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

stone osprey
#

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

rustic rain
#

it is indeed

#

but it's really sad how badly it's integrated with Unity

brave field
#

Any idea why I getting this error? Is that unity editor or dots physics bug?

tribal pollen
#

what situation do you like using FixedStepSimulationSystemGroup?

rustic rain
misty wedge
#

It basically fulfills the same purpose as FixedUpdate from the mono world

rotund token
tribal pollen
#

So... how would I go about reloading my subscene in a new world? 😛

rustic rain
tribal pollen
#

Ah so it was using the SceneSystem...

misty wedge
#

I think the method is called SceneSystem.LoadSceneAsync and SceneSystem.UnloadScene

wraith hinge
rotund token
#

🥳 Seems they've started working on support for change filters on netcode client

#

Been a good news week

hot basin
#

does anyone use ecs networking?

#

i've checked racing demo and it doesn't look good 😄

wraith hinge
#

maybe biased, but i thought it was pretty awesome when i did a game jam with it

misty wedge
wraith hinge
#

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

misty wedge
#

Yes, it's great

#

I really like it

#

Make a lot of complicated topics like prediction very easy to work with

hot basin
#

then I'll give it a shot

#

and I have another question, where can I find dots physics settings now?

misty wedge
#

I like it a lot more than monobehaviour based networking

misty wedge
hot basin
#

yeah, everything seems to be on components now

misty wedge
#

Yes, there's a PhysicsStepAuthoring component you can put on a subscene

hot basin
#

will NoPhysics option still allow me to raycast stuff?

misty wedge
#

Yes

#

I have the simulation turned off and am doing everything with physics queries

hot basin
#

that's my plan also 😄

misty wedge
#

There's also an ECS specific character controller called Rival that you can look at if you like

hot basin
#

thanks!

hot basin
#

Is this the proper way to get an ECB?

var ecbSingleton = SystemAPI.GetSingleton<EndSimulationEntityCommandBufferSystem.Singleton>();
var ecb = ecbSingleton.CreateCommandBuffer(World.Unmanaged).AsParallelWriter();
rotund token
#

Yes

hot basin
#

In documentation I see this:

EntityCommandBufferSystem sys = this.World.GetExistingSystemManaged<FooECBSystem>();
EntityCommandBuffer ecb = sys.CreateCommandBuffer();
rotund token
#

That's old / doesn't work in isystem

#

Also you need to do addhandleforproducer

misty wedge
#

(in the old version, you don't in the new one)

rotund token
#

^

hot basin
misty wedge
hot basin
#

I see. Sadly documentation is also old 😄

pliant pike
#

yeah its going to take some getting used to with all these changes

misty wedge
#

Just get better at forgetting things jamcat

rotund token
#

Age helps

#

Fresh experience every day

pliant pike
#

oh yeah I'm there

hot basin
#

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

misty wedge
#

Welcome to the club

hot basin
#

all I see in the log is the import request nothing else

misty wedge
#

It happens every few reloads

hot basin
#

oh

misty wedge
#

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

rotund token
#

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

devout prairie
#

how would i get a singleton component from inside a monobehaviour?

rotund token
#

create a query from EM

misty wedge
#

EntityManager.CreateQuery(....).GetSingleton

rotund token
#

^

devout prairie
#

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

misty wedge
#

Yep, that's the intended approach

devout prairie
#

which i think is the advised way to do it

#

yeahh

misty wedge
#

Unless you like to live dangerously jamcat

hot basin
misty wedge
#

Time to wait then 😅

rotund token
#

every 3 hours is a lot better than every 5min

misty wedge
#

^

#

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

hot basin
#

every 3h is inside 3/day range 😄

rotund token
#

but it's not more than 3 per day!

hot basin
#

that's what I meant by in range 😄

rotund token
#

mileage may vary*

hot basin
#

yh sadly unity is still unity

devout prairie
#

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

hot basin
#

seems ok, you can change GetSingleton to TryGetSingleton in OnDestroy

misty wedge
#

I think the more "modern" way to do this would be to store the component on the system entity

rotund token
#

should be fine

misty wedge
#

But it doesn't really matter

rotund token
#

because queries don't return system entities by default

misty wedge
#

Yes, with queries

rotund token
#

but systemapi singleton does (from memory)

misty wedge
#

RequireForUpdate is what always gets me with system components

devout prairie
misty wedge
#

SystemAPI.SetComponent / GetComponent have overloads that take a SystemHandle

devout prairie
#

ah wait, yes i've seen this

misty wedge
#

Like @rotund token mentioned though, be careful as queries don't automatically match these components unless you specify EntityQueryOptions.IncludeSystems

devout prairie
#

is there any benefit to that over just CreateSingleton?

rotund token
#

1 less entity really

misty wedge
#

There's no real performance benefit, it's just less boilerplate-y imo

rotund token
#

kind of nice thematically

devout prairie
#

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

misty wedge
#

Yes, unless you have multiple system entities that have the component

#

At which point GetSingleton will throw

devout prairie
#

hmm yeah

#

probs we just naturally avoid using singletons elsewhere anyway right

rotund token
#

systemapi/getsingleton much better in 1.0 than 0.51

#

(though has some gotchas)

pliant pike
#

I use singletons a ton is that bad 😕

rotund token
#

no, unity made them very fast by not completing dependencies

hot basin
#

in OOP kinda was

rotund token
#

yeah i don't think they're that comparable though

#

you can have multiple worlds with the same singleton