#archived-dots
1 messages · Page 43 of 1
This?
I don't see anything about domain reload in this migration link: https://docs.unity3d.com/Packages/com.unity.entities@1.0/manual/upgrade-guide.html
Unless there's another guide
Now my Unity editor keeps crashing when using ECS 1.0.
I think I'll stick with 0.51 for now :p
Mine is crashing quite a bit too
Code in the foreach body always runs on the main thread
Does anyone know if this will this change with the full release of ECS 1.0?
No
That's the whole point of query
wdym?
SystemApi.query
Is just boilerplate help for manual chunk iteration
Main thread only
Is it normal that the burst compiled code is different in builds than in the editor playmode?
Could MethodImpl AggressiveInlining cause differences?
Is there something like ComponentLookup<> but for aspects? or is it just better to have many ComponentLookup<> in jobs?
Yes. There are several options for burst compilation. Speed vs build time
You can find it in preferences I think or Project Settings
Burst AOT settings
Aspects generate their own
Try TransformAspect.TypeHandle
Thanks, i'll have a look into it
idk where to ask so i ask it here, general ECS question, not specifically DOTS
can i store some static data somewhere? for example i need to make simple timer in my system, but system cant have state, i can make component and entity just for that timer and that system, but its kinda strange, is there any other ways?
Entity related data should belong on component
If it's Singleton per machine - static will do
Otherwise
It's fine to store inside systems too
Assuming it's one timer per world
I also use a Singleton struct per world mini feature by mr
Me
yes, its singleton, one per world, i guess i just put it into my system then
That's one way
Found final solution
I like to have data available to all systems
Without having to get specific systrm
Thus I made this little feature
i dont rly understand how it works, im not using dots
Just a pointer reference to struct
Which gets created or gotten from cache
Alternative to storing data into Singleton entity
Not a fan of static singletons, since they are made with the explicit intent to work outside your dependency scructure, which makes them hard to debug and manage.
My implementation uses native reference which has thread safety. But yeah, no dependency since no entities involved
The discussion in this thread https://forum.unity.com/threads/isystem-vs-systembase.1357655/ implies that the overhead of scheduling jobs is quite large, and that for most cases if the workload is small, using ISystem is preferable. I’d like to ask though what’s the general cutoff for a job’s workload being too big or small? Plus, wouldn’t offloading work to worker threads be a priority?
Maybe a better question is: what performance test results would warrant shifting some smaller jobs into ISystem?
Not really. I want to be able to modify value from jobs tbh.
Just set bool to true basically
Well that implementation won't allow it because it's outside the dependency chain
Imo always schedule jobs
But just do it from ISystem
It's much improved in 2022
I didn’t know that was possible. Thanks, so burst compiled job scheduling removes a lot of the overhead?
people often benchmark this in isolation and see that running main thread is faster and completely overlook the cost of sync pointing your entire dependency chain
I think a more interesting determination is whether to schedule parallel or not
Parallel is definitely overused
I should say scheduling threads vs main thread does depend on your game and platform
If you had only dozens of entities total targeting low end android devices, maybe consider just running everything main thread
Thanks, this is great info
Isn't that more of an issue with using ECB than parallel jobs?
if ECB has to wait for sync points why does it matter if you are scheduling parallel or not?
well yeah you should avoid ecb for the same reason you should avoid executing code on main thread
I'm confused. I thought it was good practice to offload your work to jobs with an ECB to write changes back
even better to not have to use the ECB
but yes that is standard practice
but the topic was about not scheduling jobs and instead just running it on the main thread inside a bursted ISystem
Oh right. You use a bursted ISystem Update directly instead of the overhead of adding jobs.
I'm still confused what you mean by better to not have to use ECB?
Isn't the alternative to made a change immediately, causing a sync point?
what i mean is don't make avoid making structural changes
What if I use the ECB to offload component enable/disable?
Iirc component enable/disable using other means would count as a write dependency
So I’m currently planning on doing component enable/disable using ECB so that jobs that enable/disable a certain component could run in parallel
OMG for some reason I thought changing component values was a structural change. I can't believe I thought that
Any Idea why it won't let me do this?
I saw a tutorial on youtube from a week ago where it is used
do you have physics/netcode in your project?
physics yes
this is the new V2 transform system but currently physics/netcode dont support it
so you can't use it yet if you're using them
you have to stick with the old transform/rotation components
That sucks
Hi everyone, I already asked this yesterday but I'm still wondering how it's possible to bake / IConvertGameObejctToEntity to a specific world.
Apparently the new netcode solution bakes to different worlds but I couldn't find out how they did it.
I think for now I'll just bake to the default world and move entities with specific tags to other worlds afterwards.
Just load subscenes manually
Based on world
Do you already use some sort of filtering on systems?
Based on which world it belongs to
I add systems to worlds based on namespace
or do you mean a different kind of filtering?
My systems in different worlds don't necessarily have different queries
Yeah, since you create different world for different purposes
I assume you have different sets of systems
i believe netcode / entities will support baking to specific scenes (or at least baking multiple ways with different configs) in the future
but this is not supported out of the box yet
there's a lot of mention in the backend though for it
Is there way to display any physics debug info when using Unity Physics?
Yes
There's a component
Attach it to go in subscrene
Physics Debug key words
Can't remember exact name of monob
thank you
Hi guys, I have a question about Aspect, I have a DynamicBuffer feild in this Aspect, but Aspect only allow to use readonly. So how can I modify a element in that DynamicBuffer?
readonly means that the DynamicBuffer reference can't change, but its contents can still change. Have you tried it?
Is this correct? I have tried but it doesn't work
When I load subscenes to specific worlds in 0.51 I can't see the entities within those worlds properly.
This subscene only has one entity with a name but instead it shows 3 nameless entities.
When I open the subscenes in the editor the entities are displayed correctly but then the subscenes seem to be loaded to all worlds.
Is this actually the case? Is the editor loading subscenes to all worlds or is this just a bug in the editor UI?
Different question:
Is it a good idea to .gitignore the SceneDepencyCache folder?
You could remove the element and insert a new one in its place. Idk if that's the best way to do it though.
With RemoveAt and Insert
What's the error message?
Yes. That's how it works sadly
No names for closed subscrnes
And no proper logic for open subscenes
Is it the same in 1.0?
Yes
wtf
How do I create an extra entity in the IConvertGameObjectToEntity Convert method?
This is how I tried it and the extra entity with the SolidStrobeLightTag is shown as None (Entity) in the DOTS Hiererachy
public class StrobeLightPrefabMono : MonoBehaviour, IConvertGameObjectToEntity
{
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
var prefab = dstManager.CreateEntity();
dstManager.AddComponent<SolidStrobeLightTag>(prefab);
dstManager.AddComponentData<StrobeLightPrefab>(entity, new() {Value = prefab});
}
}
I can't find any docs on IConvertGameObjectToEntity :p
Do I need to recreate TransformAccess for it's job every frame?
I figured it out. I think this would be much simpler in 1.0.
public class StrobeLightPrefabMono : MonoBehaviour, IConvertGameObjectToEntity, IDeclareReferencedPrefabs
{
[Required] public GameObject Prefab;
public void DeclareReferencedPrefabs(List<GameObject> referencedPrefabs)
{
referencedPrefabs.Add(Prefab);
}
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
var prefab = conversionSystem.GetPrimaryEntity(Prefab);
dstManager.AddComponentData<StrobeLightPrefab>(entity, new() {Value = prefab});
}
}
CreateAdditionalEntity in system
CreateAdditionalEntity also requires a GameObject as argument so it's just as akward I think
Error message: Struct 'this' reference is immutable in 'readonly' structs. Cannot modify struct member when accessed struct is not classified as a variable
I also tried this way, but it doesn't work too
Sorry idk, I haven't used aspects yet. Perhaps RefRW<DynamicBuffer<StatDataElement>>> works or DynamicBuffer<RefRW<StatDataElement>>>
can you show the full code? is this an ijobentity?
probably
Is there something similar like unitys job system for plain c# ? Like a lib or framework ?
I actually found a couple of different "job" libs, however those were quite bloated and not intended for highperformance usecases... so i wonder if i missed any ( since thats actually quite easy, most wont show up on google )
just use Tasks? async/await etc
Here is the full code, I'm creating a Aspect and trying to modify a element of a dynamic buffer
Not very highperformance... Too many allocs and stuff ^^
I hope that theres anything similar to unitys way of processing jobs
They arent ? 😮
hm, i have no aspects but unity has this testcode: ```readonly partial struct AspectWithDynamicBuffer : IAspect
{
public readonly DynamicBuffer<MyBufferElement> MyBuffer;
public TestData Read(TestData data)
{
data.Data = MyBuffer[0].Value;
++data.OperationCount;
return data;
}
public TestData Write(TestData data)
{
if (MyBuffer.Length > 0)
MyBuffer.RemoveAt(0);
MyBuffer.Add(new MyBufferElement { Value = data.Data });
++data.OperationCount;
return data;
}
}```
You can use managed data inside jobs by creating a GCHandle, here's a blog with more details https://coffeebraingames.wordpress.com/2019/03/17/run-managed-code-in-unitys-job-system/
oh, I don't know that, let me try this way. Thanks
oh that's pretty cool actually. haven't thought of doing it this way.
i think the lateUpdate that just frees the handle could move to Update before ScheduleTask so just previous jobs get freed and save a .Complete call
You can also create a separate Job that frees the handle(s)
you can also use managed code in jobs fine as long as you aren't passing it in
The docs say that Unity will eventually forbid static data inside jobs, who knows if they'll ever actually implement that though https://docs.unity.cn/2022.1/Documentation/Manual/JobSystemTroubleshooting.html#:~:text=Because of this risk%2C future versions of Unity will prevent global variable access from jobs using static analysis
i'm not meaning static data
i simply mean something like
Execute() { var myClass = new Class(); }
(obviously not bursted)
Do not allocate managed memory in jobs
Allocating managed memory in jobs is incredibly slow, and the job is not able to make use of the Unity Burst compiler to improve performance.
does warn you about it being slow though
I wonder if that's because of managed allocations being slow in general or if it's because of some particular implementation detail of the job system
not sure
it is useful though if you need to do a single managed operation at end of job chain
that works fine in a thread
The reason behind Unity ECS and Jobs usage - burst
Both made with it in mind
Can someone please point me to some documentation on how to set Material properties.
Can I only used SystemBase for material overrides ?
material overrides are just components with the [MaterialProperty] attribute
you can set them anywhere
that and check out the samples (linked from the above link)
(you can also set them up via authoring and the material override asset)
Thank you
Does ISytem not show timing info
that arrow is meant to point at the empty space
timing info is a bit useless anyway
and often leads to the wrong conclusion
it's only main thread timing, not the cost of actually running its jobs
it usually all just stacks up on the first sync point
should just use profiler for actual timing
Is there a less convoluted way to set up prefabs with IConvertGameObjectToEntity?
public class SimulationUnitPrefabMono : MonoBehaviour, IConvertGameObjectToEntity, IDeclareReferencedPrefabs
{
[Required, SceneObjectsOnly] public GameObject EmptyGameObject;
public float MetersPerMS = 0.1f;
public void DeclareReferencedPrefabs(List<GameObject> referencedPrefabs)
{
referencedPrefabs.Add(EmptyGameObject);
}
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
var prefab = conversionSystem.GetPrimaryEntity(EmptyGameObject);
dstManager.AddComponent<Prefab>(prefab);
dstManager.AddComponentData<TraversalPropertiesDC>(prefab, new() {MetersPerMilliSecond = MetersPerMS});
dstManager.AddComponentData<SimulationUnitPrefab>(entity, new() {Value = prefab});
}
}
You don't need to add the Prefab component, i can tell you that much
The other components you're adding, can be setup with an authoring ICGOTE component on the prefab gameobject itself -
say you have SpaceshipAuthoring, applied to a spaceship prefab, it can add all the relevant spaceship components and will run at conversion time
but still use a ICGOTE script like you have above to actually pull in and create prefabs
So just to explain what i mean, this is how i currently do it.. ( bearing in mind this is all anathema in dots 1.0 which uses bakers and subscenes ):
I have one gameobject in my scene holding my main IDeclareReferencedPrefabs mono:
It pulls in a ScriptableObject which holds all of my object data and gameobj prefabs..
It then iterates that scriptable database and parses it to a Blob, and creates a singular PrefabBlobComponent entity which holds a reference to the data blob:
The blob also takes references to the prefab primary entities:
On the prefab gameobjects themselves, i have specific conversion mono's which add components etc specific to that asset:
I need to add the prefab component or else it would participate in entity queries.
(I'm using ICGOTE within subscenes for best possible future compatibility with ECS 1.0)
Yea but I though it would be simpler to just have a single MonoBehaviour which takes care of the prefab setup.
Interesting approach, I wonder if something like this would also work in ECS 1.0.
Thanks for your explanation.
One job can have multiple dependencies right ?
You combine it into one before schedule
Thanks ^^ secondHandle.Schedule(firstHandle) does not block & wait... or does it ?
I mean if the secondHandle depends on the firstHandle, than it would make sense to schedule it after the firsthandle was completed... or whats the intentional behaviour ?
Alright so Schedule(firsthandle) will actually block the main thread till the firsthandle was completed ? And than after it was completed the secondHandle will be scheduled ?
Ah i see... so after the firstHandle is done, the scheduler looks up which jobs should run next and executes them ?
You schedule jobs that run either in full parallel
If all input deeps are default
Or with rules based on which jobs depend on which job handles
Oh alright thanks, thats pretty cool ^^ Thats why my code doesnt work as intended xD
I wonder how it works under the hood, how is it possible to combine multiple jobhandles ? Atleast in theory... i know c# WaitHandles and i dont remember any way to combine them xD However i guess unity uses something else right ?
It's c++ internal
But it's easy to figure how it can be done
Tons of ways to achieve that behavior
urp
entities 1.0?
is your shader/material supported?
i would suggest try getting a basic cube to render
Try opening the Preferences window (Edit > Preferences...) then on the Entities tab make sure "Scene View Mode" is set to "Runtime Data" not "Authoring Data"
Yup that worked, thanks
Has anyone looked closely at the enabled implementation?
If I'm reading this right, all components regardless if they are flagged as enabled have a bit flag stored in the chunk header
{
return ComponentEnabledBits + (ComponentCount * chunkIndex) + typeIndexInArchetype;
}```
this would make my serialization/deserialization much easier because i don't need to check the component
and i can always write back the flags regardless if they're valid or not
and if someone added/removed enabled in future it'll maintain backwards compatibility
the Prefab component should be added automatically as it's a referenced prefab..
What's the correct way to construct a CompositeScale component float4x4?
random question but is there a way to directly just get all entities that are in a collsion filter, belongs to type?
anyone know if entitiesjournaling.initialize is still internal in 1.0?
annoying that most world init related things are internal
why would you need to call this?
i'm getting errors that are saying "enable entitiesjournaling for more helpful error messages"
EntitiesJournaling.Initialize()
is called on world creation
but not using defaultworldinit which seems to be the one place where it's being init and shutdown
if you have a world, any world (even editor)
it's been initialized
{
#if (UNITY_EDITOR || DEVELOPMENT_BUILD) && !DISABLE_ENTITIES_JOURNALING
EntitiesJournaling.Initialize();```
it just means you haven't been recording
have you turned it on?
lemme try
also you can toggle recording in the journaling window
(it seems to turn off by default entering play mode, not sure why)
i still get the 'enable entitiesjournaling for a more helpful message'
also no journaling window, i imagine that's 1.0
also don't see any entitiesjournaling inits in World.cs if that's where you mean
only place i see it is defaultworldinit
also on 0.51? is it supposed to be under windows > DOTS?
it still gets called in 0.51
in World
{
RegisterUnloadOrPlayModeChangeShutdown();
#if ENABLE_PROFILER
EntitiesProfiler.Initialize();
#endif
#if (UNITY_EDITOR || DEVELOPMENT_BUILD) && !DISABLE_ENTITIES_JOURNALING
EntitiesJournaling.Initialize();
#endif```
there is no window in 0.51 - full journaling isn't a feature until 1.0
you can only really browse it in 0.51 by using a break point
and inspecting the entity
(it will debug some info out from ECB failures though)
isn't this code from DefaultWorldInitialization.cs?
that's where I'm seeing it
/// <summary>
/// Initializes the default world or runs ICustomBootstrap if one is available.
/// </summary>
/// <param name="defaultWorldName">The name of the world that will be created. Unless there is a custom bootstrap.</param>
/// <param name="editorWorld">Editor worlds by default only include systems with [ExecuteAlways]. If editorWorld is true, ICustomBootstrap will not be used.</param>
public static World Initialize(string defaultWorldName, bool editorWorld = false)
{
RegisterUnloadOrPlayModeChangeShutdown();
#if ENABLE_PROFILER
EntitiesProfiler.Initialize();
#endif
#if (UNITY_EDITOR || DEVELOPMENT_BUILD) && !DISABLE_ENTITIES_JOURNALING
EntitiesJournaling.Initialize();
#endif
i'm not using DefaultWorldInitialization
am just doing new World()
oh you are right
it's kind of required to call DefaultWorldInitialization.Initialize
because it sets up things like this ^_^'
wow i see now there's a whole bunch of internal stuff in there, that sucks
can i use that without having unity update my world?
yes
if you implement ICustomBootstrap it won't do anything
if you want unity to update your world from ICustomBootstrap you have to
ScriptBehaviourUpdateOrder.AppendWorldToCurrentPlayerLoop(world);
yourself
alright i'll look into that, thanks!
if you don't add it to the playerloop, it won't update it
Anymore tried latest burst 1.8.1 at dots 1.0?
been using it for a while
Hey guys, given a simple weapon system how do I store state that doesn't change? Say a gun "Foo Pistol" has Ammo and Max Ammo. Ammo will change as you play and shoot, but Max Ammo will not. Do I store Max Ammo as a component, or do I maybe store it on say a ScriptableObject (blob asset?) and then access that from runtime? What are your guys thoughts on this type of "config data (data that doesn't change and is same for a specific thing)"
Also if storing Max Ammo as a component, wouldn't I just be storing duplicate state when I have multiple Foo Pistol?
i would never store anything at runtime on a scriptable object
you have 2 options
- store it on component
- store it on a blob
storing it on a blob means the same value will be shared across a lot of entities so you aren't duplicating state anymore
however it costs 8 bytes to store a blob so for 1-2 int/float field you aren't saving any memory, just increasing it
so if you were only storing max ammo in the blob not worth it, just store it on a component
if you have more configuration than just max ammo then it makes sense to store it in a blob asset
it's basically the point of htem
immutable data that is shared across multiple entities
wtf, I read on the forum that you can add components to system itself?
you mean on their entities?
each systems have their entity?! XD
is it 1.0exp feature?
should I use it or rather it's not recommended?
i mean GetComponentData<T>(SystemHandle) and SetComponentData<T>(SystemHandle, T)
🤔
yeah, now I don't need most of my singletons
I can leave only those which are used in multiple systems
public static void SetComponentData<T>(this EntityManager manager, SystemHandle system, T componentData) where T : class, IComponentData
{
var access = manager.GetCheckedEntityDataAccess();
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
if (system.m_WorldSeqNo != access->m_WorldUnmanaged.SequenceNumber)
throw new InvalidOperationException("System is from a different world.");
#endif
var type = ComponentType.ReadWrite<T>();
access->SetComponentObject(system.m_Entity, type, componentData);
}
I took a look
and it's literally just adding data to entity
what's more, it adds managed data it seems
ah nvm, it also works with unmanaged
but still, all it does - add data to entity
but before there was no system entity to add to
this feature includes SystemBase or is it only for ISystem?
any
all systems have their SystemHandle now
as entity
Under the hood it doesn't work any different to normal entities, for now
it's more about the principle
which one? stateless systems?
Yea, at first I got a lot of crashes but it was due a library I had installed.
Ever since I deleted the library yesterday I didn't have any major issues.
Am I reading the Unity Physics package documentation right, that you're only really supposed to do raycasts in the PhysicsSystemGroup? Or am I missunderstanding it? https://docs.unity3d.com/Packages/com.unity.physics@1.0/manual/interacting_with_physics.html#physics-data-types
what are the risks of doing it outside of this group then?
Ah ok, would I need to care about it if I want accurate raycasts, but everything I wan to raycast against is static? And nothing gets destroyed after it's created
If you destroy an entity and you're ticking than the physics world you will still get it in your results
Or is you create an entity or won't exist until physics run
Yes? But this is for casting outside of fixed update
I personally just update the bvh every frame of the physics hasn't ticked
This way my spatial map is always accurate
(simulation is not updated though)
If I have a completely static world, with data that can't change position, only entities that can be enabled/disabled. Can I then just update the BVH when I enable/disable an Entity? @rotund token
Yeah v riding did something similar
Changed how he bvh updated (or more like, stopped it updating)
For all their statics
Huh, Good to know. Thanks for the info :)
Is there any performance concerns with using blob assets or should it be nearly the same as accessing a component, but with pointer lookup as well? I understand their concept but never used them on something yet
blob is pointer to memory, yes
so
kind of annoying we have to edit the physics package to stop updating static physic objects
it's not as fast as having data on component
The only thing that seems to fix this for me is to either remove all gameobjects from the subscene and re-adding them again,
or to simply open the scene belonging to the subscene and re-saving it.
If that doesn't fix it restarting the editor seems to be the last resort. Quite annoying :p
https://docs.unity3d.com/Packages/com.unity.logging@1.0/manual/getting-started.html saw this recently - looks like it has burst support based on the getting started page? Might give this a try 🤔
It's been around for quite a while but yeah if you're looking for like a full logging library like log4net should work well
I haven't looked at it since pre 1.0 but it appears like it's been greatly improved
Maybe I will revisit it myself
cool - yea I'll take a look later tonight/tmr since I only saw it via the changelog through the transport layer
wow ok this works a bit different to the last time i looked
it codegens custom method overrides for you
seems to use incremental as well
very fast, basically works on the fly 👌
I hope they add a method to IJobEntity that sets a shared component filter, I feel it's very counterintuitive to re-write the query just to use a filter..
How come GenerateAuthoringComponent was removed? O.o I thought they intended to decrease boilerplate code not increase it?
iirc they said it was a really sloppy implementation for what it did, so it was removed. afaik the plan is to add a proper replacement for it in the future
Is it possible to use UI toolkit data binding with entities? Or there has to be a shim between SerializedObject and IComponentData?
no need to rewrite though?
SystemAPI should do it, no?
Well yes but the query is implicitly embedded in the components that IJobEntity requests in the Execute method
under the hood yes, but you can pass your own
I see your point though
having to add just 1 line for filter would be nice indeed
yes, but that's what I don't want to do, it's just extra boilerplate
yes, just like Entities.ForEach / Query is able to do
can't wait for Unity to create some manual on how to add-on to codegen
I think that would be one of the best library features
Yeah that would be cool
Can i run into deadlocks with unity jobs ?
It's actually not that hard
you can't use locks in burst jobs so it's unlikely!
I don't doubt it, but I couldn't force myself to figure their codegen all by my own
Alright great ^^
it's more just learning source generators
and there are plenty of tutorials out for that
just load up com.unity.entities@1.0.0-exp.12\Unity.Entities\SourceGenerators\Source~\SourceGenerators.sln
Is there any way to check if an EntityManager has been disposed ?
Yes but every access to the entity manager triggers the GetCheckedEntityDataAccess() and log an error in the console. even accessing the World.
I'm asking because I have bidirectional destruction of the entity and gameobject (for hybrid use).
It works well but every time I exit play mode, I get spamed with error messages in the console
public void OnDestroy()
{
if (!EntityManager.Equals(default))
{
EntityManager.DestroyEntity(Entity);
}
}
ObjectDisposedException: The Unity.Entities.EntityManager has been deallocated, it is not allowed to access it
no, a monobehaviour
oh yeah
and I dont' need the world.
I could cache it but just for that it's painfull ^^
but this is why i have a hard rule of never accessing entities from MB in my projects
systems can access MB not the other way around
the timings are not compatible
causes huge issues
i'd say we've had at least a dozen different timing cases due to this
and it behaves different in builds than in editor
Hmm, you kinda throw a wrench in my next video :/
we learnt this the hard way
Was not aware of those issue and you would like not to share bad practice
in work project we still access entities from MB
but we have to have layers of checks
and i would personally not recommend this approach
maybe there are safer frameworks to handle this
but we find all sorts of problems with entities being destroyed before gameobjects
or gameobjects async loading
(addressables)
but it's owning entity has already been destroyed
before the gameobject actually spawned
basically have to throw exist checks in everywhere
it's definitely not uncommon for people to do this though
so there's definitely value in a video about it
but i think people should just be aware of the risks with timings
(and i personally won't allow it in my libraries and future projects at work)
isn't the issue the other way around true to, where the entity tries to acces a GO that no longer exists ?
100%
I get it's more common with adressables but not all project need adressables
but i find it to be more reliable with the timings
and i avoid it by attaching the gameobject to the entity when spawned
so if you query the gameobjects + entity/data
the query won't run while the gameobject doesn't exist
you can avoid the missmatched states from your queries
without having to manually check everywhere
GetEntityQuery(typeof(MyComponent), typeof(Animator))
won't return if the animator hasn't been attached (i.e. gameobject hasn't been attached yet)
and if gameobject is only destroyed from entity side
it will never return a destroyed case
I do the same thing but have a generic EntityGameObject I attache to all the hybrid go and it that's how I do the bidirectionnal destroy
And for my next video it's actually the GO that create it's entity and manages it.
I think I'm good. In the last video I warned about destruction of one before the other and tried to provide a way to handle it. i'll reiterate the warning in the next video.
There isn't much choice when you need hybrid approach anyway...
Does this statement still true for idiomatic foreach?
yes, best to use RefRO<T> or RW
I've noticed that memory leak tracking, and multiple jobs debugging tools (like forcing stuff to run on main thread) is not present in 2022.2b13, even though I have both the collections and jobs packages installed. Is this the case for any of youas well?
The jobs menu only looks like this, when it should look like this:
all settings hvae moved to preferences
Aah great, thank you :)
While I kinda liked having them in the jobs menu it's at least good to see that they now reset on editor restart like the burst safety thing.
yeah as you can see preferences have been added to my pinned window list
though, that's more for constantly clearing subscene caches
since 0.51 old Colliders are beeing converted and are interacting with the DOTS PhyiscsColliders. I used the old colliders to bake a navmesh and the DOTS Colliders for actual physics. Any way to remove the baking of Old colliders?
interesting
generally you use meshes not colliders for baking navmesh
but i guess that works fine
anyway yeah you can remove them still
just use a baking system that updates after the physics baking systems
and remove them in that
oh wait
i totally missunderstand what you're doing
let me have a quick look, i have an idea how this could be done
I am trying to use the unity tools as much as possible here. they use colliders for navmesh obstacles
one way would just to be disable the colliders
unity physics seems to ignore disabled colliders
pretty sure default navmesh setup is to use the mesh from renderers
yes thats an option as well but not in my 2.5D case
i assume you don't want to edit package?
if i can avoid it
i am also thinking about writing a baker for NavMeshSurface and giving Entities with old Colliders NavMeshBuildSourceComponents. Then build the navmesh at runtime from that
thats kind of what i do
though i wrote my own replicate of navmesh source stuff
to like double the features
^
with my 'super advanced' options ^_^'
okay i love it ^^
and you are using the navmeshbuilder api with it?
or did you do your own navmesh implementation
do you really merge navmeshes? or do you create links between them?
i wrapped recast myself
and a bunch of detour
im slowly porting sections to burst over time
but its low on priority
unity just doesn't expose the data enough for me
i needed to get edges of the grid
i've managed to build polygons aroun dthe outside of the navmesh
so i can feed it to my orca simulation
for avoidance with knowledge of the world
Is leak detection broken or something now? I can't get it to trigger in obvious situations.
what version of unity
2022.2.0b13
well those aren't going to leak until you do a domain reload i don't think
Pretty sure I've done domain reloads.
i haven't wrapped the off mesh link stuff yet (i have the stubs in i just haven't needed to yet and I have so much other things to do)
but i do generate tiles of navmesh as seen above for performance
so i can just update small sections at runtime
those auto link together
Jepp, def done domain reloads.
(dont mind the errors, i opened project first time in a while without opening unity)
i basically just wrapped each section in recast with a native call
so i can go through 1 at a time and slowly port to burst while being able to validate
i needed that too. was pretty annoying to get my playercontroller to smoothly slide on edges of the navmesh.
Recast is not on asset store anymore?
each of those Recast.X methods are just native calls
Recast is open source
but its a c++ library
it's what unity, unreal and pretty much everything uses under the hood
though they all probably have their own implementations with tweaks etc
hmm okay atleast i got an option more to explore.
atm im still leaning towards writing the baker for NavMeshSurface. Cant be that hard to figure out how to construct NavMeshBuildSources from Meshes/Colliders
it's not
i posted my solution on the forums like 2 years ago
back when i first wrapped unitys navmesh
before i decided to go my own way
i remember the thread
wow
3 years ago
27 oct 2019
time flies
info might be a bit rough due to my improvements since then
but the concept probably fine
afaik i only need to feed a list of navmeshbuildsources to BuildNavMesh() and be done with it
oh yeah i even added it to that popular giant asset
yeah if you're not doing runtime updating it's so much easier
i wanna do runtime updates. but isnt that just using UpdateNavMesh() with the same list of buildsources?
yeah
and afaik it incrementally builds it
but maintaining that can start being a bit of a pain
once things are deleted
it requires same order for hashing otherwise it triggers a lot larger update
hmm dont you think its rather easy if you just query all entities with a NavMeshBuildSource comp and put those components in a list? chunk layout wont change that much right?
i wish youd could make Combined NavMeshSources.
hmm maybe baking a static mesh per subscene and using that as a navmeshbuildsource would be better.
change a single component
and your order is messed up
what i did was do the first X elements as my static navmeshes
then the next Y elements as the dynamics
so only the end of the list of sources is changing right?
yes
anyway cant remember why that mattered but i think it only updates the point after the list that diffs
but yeah been 2 years since i looked at this so ah, investigate yourself 😄
thanks for the input! sounds actually really easy right now
StaticOptimizeEntity removes linkedEntityGroup? Not sure i like that. i think LEG has nothing to do with something beeing static or not but more like what composes a static object.
looking at the source i cant find the part where it is deleted / not added ...
are you sure?
like if it was a prefab with children the children would not spawn
when you spawned parent
leg not added to root objects in subscenes
unless you add it via the authoring component
this is what im seeing. for prefabs its fine
for example i have this in my subscene. id expect homebase to have a LEG so i could destroy everything together.
my actual usecase would be to have a huge LEG on my Level Object in order to be able to add a NavMeshSourceComp to all viable children with ecb.AddComponentForLinkedEntityGroup()
leg are not added in subscenes
but with this they are?
hmm works but somehow breaks if i click on the object with the LEG
scene stops rendering then 0.o
well i need it for baking only anyways.
You guys have found any good solution to the Adding a component multiple times during baking?
easy example :
i have a projectile component and a cooldown component. both require the AbilityTag to work. Cooldown and Projectile can be present on the same gameobject. ATM i cannot just add the AbilityTag inside both Bakers and be done with it. I need an extra component on the Gameobject adding the Tag exactly once. That component could in theory be missed by someone creating that object since he doesnt know that the tag is required for a projectile to work. (RequireComponent would solve this but still adds clutter to the GO)
I totally see the merit of disallowing it for non tag components since you could overwrite data but for tags it can be really annoying.
(RequireComponent would solve this but still adds clutter to the GO)
definitely solution to that setup
but yeah i know why it works like this, it's required for live baking/incremental stuff - which baker adds something is important
but i have had a few situations it's a tad annoying
that said, i've basically gone to single authoring components per library feature for the most part
so i it's all configured in 1 place and the baker for it can handle the case - but i still have to write this handling
it's a pain for designers having to remember all the different authoring components you need to add to something new
so i prefer to just group them in 1 place and present it to them
im doing that in all my newer features. my ability system is some old baggage im dragging around. ill need to improve the authoring at some point but dont have the time to do a full UI graph solution atm.
Still i have cases where i want to use some core utility in multiple libraries which might need the same Components for baking... but oh well i can live with RequireComponent for now
hmm
I just started to wonder
since new .net MAUI is cross platform
will Unity ever think about making it compatible?
would make so much more sense to just have one native UI framework over tons
especially considering it's also open source
Any easy way of getting the mesh from a PhysicsCollider?
I dont get what i need to supply to the source Object
{
transform = l2w.Value,
size = new float3(scale.Value),
shape = NavMeshBuildSourceShape.Mesh,
area = 0,
generateLinks = false,
sourceObject = ???
component = null
}; ```
Unity has thrown possibly millions of dollars into UIE. No way will they give up on it.
🥲
@rotund token
Cause we talked about baking issues:
Stumbled across this when i looked at LegacyColliderBakingSystem:
AddComponent(colliderEntity, new PhysicsColliderBakedData()
{
BodyEntity = shapeBakingData.ShapeComputationalData.Instance.BodyEntity,
BodyFromShape = shapeBakingData.ShapeComputationalData.Instance.BodyFromShape,
ChildEntity = shapeBakingData.ShapeComputationalData.Instance.ChildEntity,
// It is a leaf if the Shape Entity equals Body Entity
IsLeafEntityBody = (shapeBakingData.ShapeComputationalData.Instance.ShapeEntity.Equals(shapeBakingData.ShapeComputationalData.Instance.BodyEntity))
});```
i was not aware that we need to add the component inside the baker instead of the bakingsystem to make sure it is correctly removed from baked entities when it is removed from the GO (if i understand the comment correctly here)
That will be a huge source of unexplainable bugs for me
I have a weird error I don't understand, is it possible for a collision filter raycast to get the wrong objects, that arent in the filter at all?
it only seems to happen when the ray is cast over another object that does hit the filter though, so does that seem like a bug
i havent encountered that yet. but make sure your subscenes are closed. open subscenes somehow change physics behaviour
I'm not using subscenes currently in 0.5 I get weird errors sometimes
did you look at the physicsdebugger component? mabye it can help you visualize whats going on
oh yeah that's a good point thanks
the collisionfilters really are hard to understand sometimes but maybe its because I've got lots of overlapping ones but then that's what I figured the filters solved 😕
i found it weird that both objects have to detect a collision in order for it to count.
or am i wrong here?
as far as i understood an object1 with BelongsTo:1 and CollidesWith:2 and an object2 with BelongsTo:2 and CollidesWith2 would not trigger Collisions with each other since object 2 cannot collide with Layer 1
i would have expected that object 1 gets collisions here and object 2 does not
but neither get collisions
Yeah I think that's how it works
maybe thats how your raycast is not registered on certain objects
But I only have it registered to collide with 1 object type
And the other objects don't have it on there collides type
and that one object type also has CollidesWith of what the RayCast belongs to?
Nope the raycast is of type raycast which the ground for example does not have a collides with for, for example
sry just to clarify:
Raycast: BelongsTo:RayCastLayer , CollidesWith:RayCastObjects
Objects you want to hit: BelongsTo:RayCastObjects , CollidesWith:RayCastLayer
Yeah pretty much
then if its still not hitting id call it a bug
@rotund token any idea how defaultArea of NavMeshSurface is implemented? essentially i want to be able to navigate everything at first and then incrementally spawn colliders into the world that restrict navigation.
Is the defaultArea=walkable just a huge plane that is fed as a buildSource?
The runtime generation is working but i still need to implement the NavMeshModifier features now.
I don't think they have a default mesh plane
You can certainly add a giant plane though
hmm might be the tilemap collider that is used by navmeshsurface2d then. cant explain that baked plane with any object i created.
But yes i can just add it if its missing. just wanted to make sure i get as close to the navmeshsurface monobehaviour as possible.
Is there currently support for using Addressables with Entities?
It doesn't look like it currently, but I can't find any hard confirmations on if they planning to add support, or if you just have to work with both yourself
there's an "Entities Addressables" being worked on heavily atm
it's separate from the current Addressables package though
Makes sense. Alot of the addressables technology follows a separate workflow so you would have to rework alot anyways
subscenes load using similar techniques from addressables
Is there even a good way to dynamically load in entities then?
I guess they have to be setup as separate subscenes and then load those...?
it looks like for large pieces of data, loading them as entities doesnt make much sense currently
IIRC its supposed to be released with official 1.0
subscenes are exactly for this
if you have multiple subscenes, dont you have different entity managers?
I'll need to look into subscenes more then
It looks like they can fill a similar role to Addressables (which i guess should have been obvious, since its just dynamically loading data)
maybe?
SubScenes are just a way to load/unload entities fast
entities can contain any data at the same moment
Ultimately I'm just trying to load weapons as entities at runtime. I don't need all the weapons preloaded into the scene so addressables would have been ideal. For now I'll see if i can make it work well with subscenes
@jolly palm the new Baker workflow helps here in making the subscene easier to manage, then just get the GUID of that and load it via your normal Addressable methods, then use the new World loading stuff to move the loaded entities into it
As it turns out one of my dependencies don't work with entities yet so the weapons need to be gameobjects anyways. Instead I just have to link the gameobjects with the entity for proper data processing
how do EntityCommandBuffers with multiplayback policy work?
Does calling Playback() clear them?
multi can be played back multiple times
once you played it back once you can't add commands to it anymore though
ah ok. i was considering a weird usecase where i would have to create an ECB per entity in a loop. thought multiplayback might help but it wouldnt if i could record only once
can i use the SortJob to sort after Length of LinkedEntityGroup?
I am not familiar with that API
also how do i get a list of DynamicBuffers out of a query?
var linkedEntityGroups = query.ToComponentDataListAsync<LinkedEntityGroup>(Allocator.TempJob, out var listDependency);
this doesnt work for buffers
maybe you need <DynamicBuffer<T>>?
for generics to work
no i tried that 😦
what's the best way to store a reference to a Mesh per-entity without using SharedComponents or dictionaries on systems? make a new IComponentData that has an unsafe pointer to Mesh and process that? Any new ideas in Entities 1.0 that could help with this?
I'd suggest creating a singleton entity with reference to it
which would be your dictionary within World
I would really like to "attach" it directly to the entity without going through yet another "manager" entity
btw
you can use blob array if your mesh data is unmanaged
or managed components
which will basically just do the boilerplate for you
mmm blob array I did see that in action in PhysicsCollider but not sure if it would work for such a managed class like Mesh?
only unmanaged
I do generate the mesh data via Burst jobs (Mesh.DataArray and stuff) but ultimately I need a Mesh to render with... argh
for our purposes we just use a simple scatter-gather a NativeList of ents to render, then loop on it with Graphics.RenderMesh()
entities graphics (hybrid renderer) really really doesn't like it when we generate hundreds of meshes per frame 😦
I'll look into managed icomps and see if it fits our workflow this time... thanks!
why not modify meshes instead of creating them then?
graphics uses BRG
which requires registration of meshes
yeah that's the problem, agreed
so as long as you keep same mesh modified, it'll be fine
will BRG perform OK with lots of submeshes instead?
haha yuppie! what I meant was to register only one mesh per "family" of entities, then store the per-entity data in submeshes
will that trigger BRG updates or funky stuff like that?
I guess you better read on it's API Instead, I'm not familiar with it
Graphics.RenderMesh() already has a submesh index, so I'll definitely look into it!
so does unmanaged render data on entity
so this is appearing in my assetimporter logs Exception thrown during SubScene import: System.ArgumentException: Junk.Cameras.BillboardSystem+BillboardJob must already be filtered by ComponentSystemBase or ISystem but quite honestly I have no idea what it means and what it has to do with my subscene
it means you have run into a common bug
and you require to restart unity, clear your cache
and continue on your merry way
over and over 😦
yeah been busy with other things and getting back into the swing of things. ive been restarting for the past hour, when does it stop 🥲
sigh, feel like the more I try to fix things, the more obscure errors I get A BatchDrawCommand was submitted with an invalid Batch, Mesh, or Material ID. BatchDrawCommand index: 0 (index in range: 0), BatchDrawRange index: 0 This is not supported when rendering with a BatchRendererGroup (or Entities Graphics). MaterialID (0x7) MeshID (0x4) BatchID (0x2)
@safe lintel which version of DOTS are you using? sometimes it's maddening to try and track down what's happening in the innards, agreed!
I guess the problem is that your subscene import is mangling the data somewhere related to the mesh/material that is attached to the entity for the graphics...
I don’t have DOTS installed because my game is already very far ahead and I don’t want to start all over again. I tried searching for this and couldn’t find any information on it so I’ll ask here. Is it possible to create SubScenes without DOTS? My game is an Open World game and having a large seamless world is something I am hoping to create
no, subscenes are inherent to the entities package within dots @fast crater
subscene is just entity data serialized
oh ok. So there isn’t a similar way to do SubScenes without DOTS?
Ok
just so you don't get confused:
subscenes is just a way for using addressables + game objects but for entities
it's not actually related to scenes
they are definitely a good tool for streaming in large worlds though
definitely in their thought process when they were first developed
I'd guess same can be achieved for GOs using addressables though, no?
they just kind of evolved as a more general purpose tool
it's not ideal
large chunks of gameobjects cause huge stalls
well yeah, it's GOs 😅
you're better off streaming in 1 (or small groups) at a time
we limit it to like 12/frame i think
any more than that and it becomes noticeably problematic on their initialization
you need to pool instead usually
ugh really feels like im swimming upstream in terms of trying to instantiate an entity during a baking system and set up the graphics vs just using a hierarchical gameobject and going by baking that. feels like this kind of setup was way easier in the GameobjectConversionSystem days
what are you having trouble with?
everything 😅
but in this case: instantiating a prefab, parenting it to another entity. seems simple enough right? but I click that entity inside the editor during runtime, it unparents and sets itself to the parent's parent, and then visually something in the editor kind of borks itself(for lack of a better term?)
are you instantiating a prefab during baking?
inside a baking system
also a note: I am parenting to an instantiated prefab(weapon model), previously parenting (the muzzleflash) to the weapon root(not instantiated during the system), it worked
im uploading a gif because this result is ridiculous
im still not sure if prefab instantiating inside of a baking system is even meant to work or just works by accident
Do you have your subscene open
yeah subscene was open
Yeah doing this stuff just doesn't work with live baking
If you close your subscene probably be fine
come on gfycat, encode faster
yeah it does seemingly not bork itself with the subscene closed but so much easier finding things with names
do you do any instantiating inside of baking systems?
ah wait no im not instantiating inside the baking system, entity came from the baker, maybe this is tripping up the editor but technically I think I should be fine to change the hierarchy inside of the baking system?
Only for my saving to create per subscene meta data of each entity so I can restore state
But I never have my subscenes open
So I just avoid all the issues people have
well given how this is manifesting itself not sure if its me or unity as it didnt happen previously
btw have you setup any graphics inside of bakers? the rendermesh setup in the docs seems like its applicable to runtime but not baking
I only bake from the gameobject
I do as little generation as possible
I treat them as conversion as much as possible keeping logic minimal
Pretty sure once project scales up the bake process will become critical to iteration
And I don't want to wait 30 seconds to bake on code changes to enter game
yeah i feel like gonna need to take a step back and rely on builtin baking systems for some things i was doing before
sad thing is, was trying to setup some things through code instead of a gameobject hierarchy, not even for other people, just to protect myself from myself(i am so likely to futz around with placement inside the editor and not realise im doing it)
In the Asteroids demo, if you change the input for shooting to GetKeyDown and remove the weapon's cooldown, the weapon will sometimes fire multiple times per button press. I can't figure out why. The input gathering system in InputSystem should only add a single ShipCommandData with shoot = 1, yet when SteeringSystem reads the data for the current frame, sometimes the next few frames have shoot = 1. I think it has to do with prediction?
Ok after doing some search I found a way to do multiple scenes without DOTS. But still, thanks for the help. Who knows? I might use DOTS for a future project and used what I learned from you guys
probably has to do with the input sampling, i had this error in my test project and was hunting for what's going on. i had problems with jumping - the asteroids demo doesn't have a proper one because it assumes it just shoots on keyDown. tbh i thought they would fix this. that's just a bad learning experience. anyway, there are multiple solutions. here's one: https://forum.unity.com/threads/how-to-deal-with-trigger-input-and-lagging-clients.1294587/#post-8200437
this was my fix from 3 years ago ```if (inputBuffer.GetDataAtTick(serverTick, out var input) && input.Tick != serverTick)
{
// new frame, new input
input = default(PlayerCommandData);
}
input.Tick = serverTick;
input.jump |= jump;
inputBuffer.AddCommandData(input);```
the gist as far as i remember it is that inputs are generated during prediction but then are overwritten. so its important to gather all inputs during prediction until the next server tick
that's why i use the or logic and only generate a new struct on new server ticks
trying to switch something from regular arrays to native arrays, but im not quite certain how to construct this as a native array, some tips would be appreciated ```cs
int[][] triTable = {
new int[]{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
new int[]{ 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
new int[]{ 0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//etc
};
The arrays all seem to be the same size
So best way is to just pack it as a single array
Index = y * width + x
oh, that is clever, just like pointers, only with native arrays instead! Thanks so much!
There are other ways to hold containers of containers in dots
But if your arrays are all the same length I think just packing into single array is best
got it, thanks so much for the info!
if your data is not changing, there is also the option of blob assets
Actually if your data's not changing you can just use a static readonly int[] array
This is a very common use case for things like tri tables
You could just flatten that array into an int[] coolkat
Same indexing rules but avoids need to manage native memory
And you can still access it direct in burst jobs
wait really, that is cool, and would probably save me time lol, thanks!
Burst can access static readonly primitive arrays
thanks so much for the info!
v2 transform system still not available for physics right?
why is the TransformBakingSystem removing and resetting my transform components i added in baking 😢
You need to assign appropriate transform options
It's in Baker
ahh lifesaver
Had this problem with shooting bullets(newest physics, entities) where on 1st frame bullets were a kind of stretched and problem gone when i set scale of localToWorld to 0(when instating bullets)(setting other values seems not fixing the issue) but losing that 1st frame and afterwards bullets are scaled ok - hmm idk how this can be fixed some other way
is there anyway to get native arrays to show in the inspector, a bit like how regular arrays show up?
Are box casts significantly more expensive than ray casts? Would it be worth it to perform ray casts until there is no hit and then verify that direction with a box cast to ensure the object can avoid obstacle. Or am I just better off sweeping with box casts only?
box casts are not that expensive
it really depends on your scale of what you're doing
sphere cast is cheaper
i notice when dealing with pointers that you cannot interpret vector4* as float4*, wondering why this is? Are they setup differently in memory?
thx
hmm there should be no issue with that
you can reinterpret pointers to anything, there's no type checking
you'll just break things
but in your case they have the same memory layout so should work fine
how exactly do i reinterpret pointers then incase im doing it wrong lol? (currently im doing it like this: (*whatever_new_type) )
wait nevermind, im an idiot, and i somehow forgot to type one of the asterisks, whoops lol
probably being a bit stupid as per usual, but i cant seem to work out what this error means exactly, it only ever appears if i try to modify a writeonly nativearray<int>, anyone know what this could mean?
aha, from a bit of googling it appears that it is tryna stop me from creating race conditions, and using [NativeDisableParallelForRestriction] i think ive fixed it lol yay
that feeling when you make Unity produce an error
ExecutionEngineException: An unresolved indirect call lookup failed
that has 0 google results...
i know that generics have limited support in il2cpp, it's just annoying this worked in IL2CPP in Unity 2021 and is now broken in 2022
ah zero google results, life of a pioneer 😉
reported another bug to unity earlier this week
supposedly one they've seen rarely but haven't managed to get a repo for
well i had a 100% repo
😦
its kind of odd but like a good chunk of my last reports have gone like they couldnt repro it, ask me for more info(which i try to follow up on but often forget) but usually ends up in failure, it gets closed and then a few weeks later they did repro it and its logged
i am very good at getting reliable repos
i swear I upload decent repros 🙂
yeah that's annoying
so yeah my il2cpp issue is basically calling a generic interface method
even if i explicitly have an implementation somewhere in project
full generic sharing just doesn't seem to be working for me
in Unity 2022.1, IL2CPP no longer produces an ExecutionEngineException, eliminating a whole class of errors that are difficult to rectify.
ha lies Mr Peterson
ok i've got it working when not using full generic sharing
just need a gross workaround but i can mostly hide it
ok trying to make sure i understand that, so if i have an int[whatever][16] as a 1d array and i want to get to [x][y] of that array, then i do [y * 16 + x], correct?
it's [y][x]
ah, i see, thanks for the info!
its a tad confusing but
int[][] arrays;
int[] xArray = array[y];
so if y == 0
then the value is just x
0-15 in your case
im afraid that is a bit beyond me, but hopefully with the new knowledge that i was doing things in reverse, i should now work things out somehow, thanks!
i[0] = new int[16];
i[1] = new int[16];
i[2] = new int[16];
i[3] = new int[16];
var j = new int[4 * 16];
var a0 = i[0][0];
var a1 = j[0 * 16 + 0];
var b0 = i[0][5];
var b1 = j[0 * 16 + 5];
var c0 = i[1][0];
var c1 = i[1 * 16 + 0];```
hopefully that's an ok comparison
ok yes, that makes a lot more sense, thanks a ton!
This may help : https://www.noveltech.dev/csharp-flatten-array/
thanks for the info, luckilly ive managed to get something working already though lol
Thanks for the link. Comparing to the previous tick indeed solves my issue. I finally figured out why, too: GetDataAtTick returns the latest data older than the tick, not the data at exactly that tick. Since the input gathering isn't tied to the server ticks, it skips some ticks, which means my system reads stale data. Thus, I need to monitor for how the input data has changed instead of what it says exactly.
doing some marching cubes, and trying to optimise the way i workout if a gridpoint is activated or not, currently this is it:
[BurstCompile]
public unsafe struct CalcEmptinessJob : IJobParallelFor
{
[NativeDisableParallelForRestriction]
public NativeArray<int> Emptiness;
[ReadOnly]
[NativeDisableUnsafePtrRestriction]
public float4* PosArray;
[ReadOnly]
public float3 Pos;
[ReadOnly]
public float DistanceToCount;
public void Execute(int i)
{
if (math.distance(new float3(PosArray[i].x, PosArray[i].y, PosArray[i].z), Pos) <= DistanceToCount)
{
Emptiness[0]--;
}
}
}
```, currently got the batch size set to 64, which i think is good, wanted to get you clever people's opinions on it though?
ok from further testing, it appers 32 batch size speeds up things quite a bit, still very slow, perhaps this cursed for loop is not the fasted way of checking if something is nearby, especially when the for loop is looping over 30 thousand particles, fascinating!
What?
Ok it works.
Hi everyone, how can I force that all jobs from a world to complete?
I suppose one could create a sync point by spawning an entity but that would be ugly.
Dependency.Complete() wouldn't work, right?
Different question:
How can I check if all jobs of a world were completed?
Thanks @uncut rover , I just found it aswell
Haven't found a way to check if all jobs were completed yet
You can look at the implementation for the method I linked. It probably contains some internal way to get all tracked job. From that you could check all the job handle.isComplete.
Not on my PC, can't check :/
Good idea, I found in ComponentDependencyManager.cs m_World.ResolveSystemState(m_World.ExecutingSystem)->m_JobHandle.IsCompleted() should do the trick
Is it possible to query something like this? Or should I manually write IJobChunk and manually filter with ArchetypeChunk.DidChange(typeHandle0) || ArchetypeChunk.DidChange(typeHandle1)?
state.Entities.
WithChangeFilter<T0>() OR WithChangeFilter<T1>
Entities foreach is not working with ISystem anymore
i'm on 0.51
you mentioned IJobChunk 😅
yeah, you can just use WithChangeFilter
I think you can list them <T1,T2> like that
in 0.51 you use IJobEntityBatch though
it is not the same think i guess
yes, though not all tasks resolved through IJobEntity, sometimes you need more control about what entities you want handle
ohhh, that is what you mean
Are build config files still supported when using ECS 1.0?
That's unfortunate, did they mention if the scriptable build pipeline will later be supported again?
I couldn't find anything about this topic :/
no, they stated its getting canned as they dont have resources to support it separately from the classic build pipeline
im hoping builtin build gets similar features over time, kinda seems like an area ripe for improvement(among many others tbh)
public void Execute(int i)
{
if (math.distance(PosArray[i].xyz, Pos) <= DistanceToCount)
{
Emptiness[i]--;
}
}
For a start. Also not sure why you have Emptiness[0] if intended, if it is 1 variable you can use NativeReference<int> Emptiness. Then set the array boundary with Schedule(PosArray.length, 32)
luckily i think some of the things are pretty accessible with using BuildOptions: https://docs.unity3d.com/ScriptReference/BuildPipeline.BuildPlayer.html
I ended up creating something similar to the build config because I liked how you could slot in shared configs
ah hadnt seen that before. will have to try to remember it next time I mess around with my build settings
Generic message code 233 has not been handled anyone ever figure out what this meant? thought I was done with that particular message but I guess I thought wrong
Thats just the unity hub dying. Close the editor and close the hub (right click on the taskbar button then press close) and reopen everything.
such a random error message, but that worked
hmm so entities journaling is telling me the RenderMeshPostProcessSystem is removing a RenderMeshArray from my entity(and then re adding it) but the system itself doesnt appear to have any remove component lines? also the array definitely doesnt appear on my entity
stupid question but when I set the translation of an entity does it then automatically set the translation of all the children entitys?
No. It must also run through ParentToChildTransformSystem (or whatever it's called).
The component itself is just a float3 variable. A system needs to operate on it for anything to be done.
TransformV2 might be different. I think they're trying to do some of that instantaneous component changes with aspects and methods on components.
doesn't it do that automatically 😕
It seems like it is working to but its just not putting the sub entities in the correct place
It does but you need to wait until after the system runs for children transforms to be properly changed.
I dont know how hierarchy works in DOTS personally. Everything is largely flattened or manually parented.
yeah I think I've just got the problem you have with gameobjects where if you have the gameobject not at the zero position the suboject position is just all over the place
wow never knew about native reference, that should actually improve improve my code in quite a few areas, thanks for all those tips and tricks!!!!!
You're welcome
another think you can do with math.distance, if performance really is an issue, is unwrap it
this loop runs 30 thousand times a physics frame, if not more, any performance gain is going to probably be good lol
when i say unwrap, with any formula, just cut it back to the algorithm
i found distance can be enhanced quite a bit doing this
fascinating, so essentially just check the distance source code, and then just do whatever it is doing?
well im one of those annoying micro-optimisers
but
i just love it haha
[BurstCompile]
public static void GetDistance(in float IN, in float3 A, in float3 B, out float OUT)
{
OUT = IN + math.sqrt((A.x - B.x) * (A.x - B.x) + (A.y - B.y) * (A.y - B.y) + (A.z - B.z) * (A.z - B.z));
}
[BurstCompile]
public static float GetDistance(in float3 A, in float3 B)
{
return math.sqrt((A.x - B.x) * (A.x - B.x) + (A.y - B.y) * (A.y - B.y) + (A.z - B.z) * (A.z - B.z));
}
woah cool!
you can also unwrap sqrt, but, thats a little more complicated
fascinating, if performance is bogging me down ill try it! Thanks so much for all this info!
im no whizz, but i like messing around with code!
same lol
if you want to get a pure pointer to a native array, use NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks( x )
ooh fascinating, thanks for the info!
but as always, take care in pointer world haha
ye lol
I really wish there was a better integration between SRP and DOTS.
There just needs to be a struct based compute buffer API. So I can upload data in a job
id love for more struct based job friendly apis
Just a struct. I dont even care if it's burstable or not. I just wanna be able to write to a compute buffer without a bunch of redundant arrays.
There's actually quite a bit that are job friendly. A lot of internals though
any idea if delegate* are compatible?
Delegates, as in the C# dynamic functions, are not supported in Burst.
ive been using these for testing, as hardly any latency on calling static methods
well i know delegates won't be, these are delegate*
probably not, but you know, maybe they are!
Delegate pointers? Uh, no clue. We have burst function pointers?
yes not sure they are the same thing, those do use delegate i think
Interesting. Material property block's constant vars can be set from a thread. MPB is a class however so it'll need to be an actual C# thread and not a job.
Yes you can use delegate pointers in burst
You can just wrap them in functionpointer<t>
Which can potentially point to a burst method but it doesn't have to
I use this for to make data migration easier in my save library
Though I've mandated them to be burst compiled because no reason not to and makes initial reflection quicker
As I can broad phase using burst attribute
Rather than making users use another attribute
When using a CastAll, are the results guaranteed to be sorted by hit.Fraction? If not, is there a specific order or is it just random?
Anyone know if there is a way to get access to a mesh's internal array on the cpu-side? I want to update mesh without copy, essentially. Checking the advanced mesh api, I can only see methods that copy my vertices over.
Or it it impossible because they use managed arrays internally or something?
v2 transform isn't available for physics yet
Does anyone else have problems with physics in ECS 1.0 seemingly jumping ahead in time ever so often, making it look very glitchy?
I modified physics and am updating the world manually, so it might just be my modifications which are messing things up.
In 0.51 this problem isn't present 🤔
Anyone knows a good tutorial to get started with Unity Netcode for Entities? Or is making a multiplayer game with DOTS not yet a viable option?
How did I miss this?! Thanks
Hope it helps
I'd start with looking at the samples linked in the forum post here: https://forum.unity.com/threads/netcode-samples-for-experimental-version-1-0-exp-8.1350743/
Hi
The samples for the recently updated version of the Netcode for entities package released with the Entities Experimental 1.0 release are available....
But wait, this cannot be used on existing meshes, right? Since we need a Mesh.Meshdata and that can only be readonly for an existing mesh.
Not sure I follow, but there's an API for writing mesh data if you need it: https://docs.unity3d.com/ScriptReference/Mesh.AllocateWritableMeshData.html
Yes, but that one creates a new mesh, I want to modify an existing mesh's vertices in place.
Well, can't you apply it to an existing Mesh with ApplyAndDisposeWritableMeshData ?
I saw in the source code here: https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/Export/Graphics/Mesh.cs that there are public overloads for AllocateWritableMeshData such as public static MeshDataArray AllocateWritableMeshData(Mesh mesh) but they are not showing up for me, nor are they in the documentation. I only have access to public static MeshDataArray AllocateWritableMeshData(int meshCount)that is designed to create new meshes.
Although if your goal is to avoid all temporary allocations, I don't think there's a more direct mechanism
I can do that, was just looking for a way to avoid having to keep two buffers of my vertex data. One that I modify and one that is in the mesh.
Yeah, I'm not sure direct access is even possible because of where vertex data lives
Where does it live?
Oh, I'm not an expert, I'm just speculating
It was my guess also, maybe that they were managed arrays, and as such it would not be possible to give out a persistent pointer.
I was thinking something more along the lines of the real data living in GPU or write combined memory or something where it actually does need to get copied
But I mean if we can mesh.vertices, surely it must also exist a vertex buffer on the cpu?
Well, as I said I don't want to overrepresent my subject matter expertise, but I imagine you have the original mesh data from the asset load which you keep around after uploading. And if you were to update it, the CPU side copy would also get updated and then either explicitly uploaded or cached on the GPU.
Mhm, I'm looking at this: https://docs.unity3d.com/ScriptReference/Mesh.UploadMeshData.html So it seems there is not a persistent buffer cpu side, since we can specify that the buffer should disappear with markNoLongerReadable.
Here's what it looks like, it suddenly snaps.
Did anyone else have this problem?
I've never used IJobChunk before, how can I turn this into an IJobChunk?
[BurstCompile]
private struct UpdateRotationJob : IJobEntityBatch
{
public ComponentTypeHandle<Rotation> rotationHandle;
public float deltaTime;
public void Execute(ArchetypeChunk batchInChunk, int batchIndex)
{
NativeArray<Rotation> rotations = batchInChunk.GetNativeArray(rotationHandle);
for (int i = 0; i < batchInChunk.Count; ++i)
{
Rotation rotation = rotations[i];
// Modification
rotations[i] = new Rotation
{
Value = math.mul(
rotation.Value,
quaternion.RotateY(math.radians(100 * deltaTime))
)
};
}
}
This is where I'm at with IJobChunk but don't know how to proceed.
I guess that chunk.GetNativeArray is no longer the way to go here, right?
private struct UpdateRotationJob : IJobChunk
{
public ComponentTypeHandle<LocalToWorldTransform> rotationHandle;
public float deltaTime;
public NativeArray<int> ChunkBaseEntityIndices;
public void Execute(
in ArchetypeChunk chunk,
int unfilteredChunkIndex,
bool useEnabledMask,
in v128 chunkEnabledMask
)
{
var enumerator = new ChunkEntityEnumerator(
useEnabledMask,
chunkEnabledMask,
chunk.Count
);
while (enumerator.NextEntityIndex(out int i))
{
}```
i could be wrong but I think the ChunkEntityEnumerator is mainly for use when you are dealing with components that use the enable disable functionality
ive been upgrading all my old jobs just to use chunk.GetNativeArray for the time being as I havent yet used enableablecomponent in any meaningful way
Would still be interesting to know how this enumerator can be used
cuz the documentation example doesn't make much sense to me
theres use inside CreateRigidbodies job inside of PhysicsWorldBuilder.cs
Using SystemAPI methods with generics is not supported within utility methods and aspects 😕
Does anyone know if this will change in the full release of ECS 1.0?
I love ECS but it basically has ANTI-synergy with every other system Unity has. ECS hates managed code but all of Unity's common systems (physics, animations, collision, meshes) were built in an object-centric black box that makes it really hard to interact with.
Trying to roll my own animation setup with ECS while I wait is also a nightmare, since I cant access AnimationClip curves as unmanaged data. So I either have to convert and save all my clips into a custom format in the editor that plays nice with ECS, or throw away all the benefits of ECS by using a janky managed entity setup
Either that or roll your own animation rendering pipeline. It's literal pain
I got a method that runs before a ScriptableRenderingPass Execute() that pulls entity data from the client world and uploads them to the GPU for rendering. I really wish there was a direct way to transfer ECS data to GPU side without dipping into mainthread.
Is the performance hit of moving data to the GPU that big of a hit on the main thread?
I don't know the ideal way of moving data to the GPU, but i imagine it isnt too big a hit since you are expecting the GPU to do the work anyways
Ok i am honestly considering rolling my own animation export pipeline from Blender to Unity since I've already done something similar in the past and I hate the current limitations
On a semi related note, does anyone know the best way to manage 2D collision events in ECS?
It looks like that might be a part of the Unity physics package, but that only appears to have 3D collision support
Just use 3d with constraints
Korn flaks did very efficient 2d constraint for physics
Is there a way (or, what is the best way) to work with different systems within different scenes? To motivate why I'm wondering, often when I prototype stuff I create different versions of the prototype so I can easily switch between the different prototypes. There's usually different scenes and different monobehaviours for the different versions of a prototype. However, this doesn't seem to be as easy to do with ECS as with monobehaviours because the systems self register and run irregardless of what scene you're in. Anyone have any ideas?
for quick prototype or comparing simply adding a RequireForUpdate<Prototype1>() to the systems in the prototype works pretty effectively
also allows you to switch between prototypes at runtime if you wanted to compare
alternatively a systemgroup is an easy way to group a bunch of systems
I would either add [DisableAutoCreation] to toggle systems if it's important to have them not run at all, but it's not as fluid as scene switching. You could also bail out early based on a custom data component for example if you want more complex runtime control
then in your system group you can just do OnUpdate() if (SceneManager.CurrentScene == "MyPrototype) base.Update();
so systems in that group will only update in a particular scene
-edit-
{
protected override void OnUpdate()
{
if (SceneManager.GetActiveScene().name == "Prototype1Scene")
{
base.OnUpdate();
}
}
}```
On a side note what did I stumble upon "that’s the problem with irregardless—it has two negations. The ir- prefix means “not,” and if you add it to a word that already means “without regard,” you get “not without regard.” This double negative is what makes irregardless a mess of a word, and an insult to the army of people who are passionate about English vocabulary. Many of them go so far as to assert that irregardless is not a real word."
if you want a more complex setup i think dreamings library handles this type of stuff
Oh well tertle's solutions are way better as expected :D
wondering if there is any current way of getting native arrays to show up in the inspector like regular arrays, or should we just use regular arrays and copy them to native arrays later on?
Is there a way to work with SystemHandle's and ecb's? Or a way to get the system's entity?
the systems entity is intentionally hidden away
you can get it but it takes a tiny bit of work
Is that the way to go if I want to set a system's data component with an ecb?
so yeah does not really work with ecbs by default
Awesome, thanks for the ideas @rotund token & @ocean portal :)
i have an native array of a custom struct that is essentially 8 ints and 1 vector 3, i cant modify any of these ints though for some reason, apparrently they aint variables, is there a workaround?
aha i see, thanks so much!
will there be another release pre official 1.0?
its such a pain to work with the current version...
What problems are you running into?
mainly subscenes not importing correctly. Sometimes it just hangs and i need to restart the editor and other times the entity header file cant be resolved. Then i need to clear the entity cache and restart editor.
Im doing a lot in the baking process right now and thus have to reimport scenes quite often...
Ah, gotcha. Yes that is painful.
Does entities 1.0 not show detected leaks for persistent allocations when exiting playmode anymore? iirc it used to at some point
It should, but it might not taken until domain reload or something
even with something like this in update new NativeArray<int>(5, Allocator.TempJob); I don't seem to be generating any leak messages
Leak detection is turned on in preferences, also tried with stacktraces which also doesn't show anything
What version of unity
It seems it only doesn't work for NativeArray, not sure if that's intended or not
What decides the version of NativeArray being used, since it's not part of the Unity.Collections package? Is it part of the engine?
Is leak detection just broken in collections 2.1.0? Even in an empty project I can't get it to detect any leaks with a stacktrace
Yes, leak detection right now is known broken.
Ah, good to know.
Is this something new or it never worked after the move away from dispose sentinels?
There is a new system in-place for replacing dispose sentinels, but it is not fully hooked up yet. So it never worked after the move away from dispose sentinels.
Alright, thanks for letting me know 👍
Will be interesting to see how many leaks I have after it works again 
Is there a way to disable compound shape creation with Unity Physics (DOTS)?
Can i somehow reinterpret a dynamicbuffer as a System.Collection.Generic.List?
theres probably something like .ToNativeArray() -> .ToList()
var buildSourcesReinterpret = buildSources.Reinterpret<NavMeshBuildSource>().AsNativeArray().ToList();
but seems slow
to LINQ Tolist makes a copy doesnt it?
You don't have to use buildSources.Reinterpret
I think you can just do myDynamicBuffer.ToNativeArray().ToList()
Or even myDynamicBuffer.ToList()
oh the reinterpret is there because the buffer actually just wraps NavMeshBuildSource
Perhaps you could iterate over the dynamicbuffer and fill a list that way to make it more performant
i just thought i can somehow directly treat it like a list without copying anythig
I think as long as you don't add multiple colliders compound shape creation is not a thing
Can't you just access the dynamicbuffer directly like myDynmaicBuffer[0]?
but a dynamicBuffer isn't the same as a list of course.
my goal is to get the data from the dynbuffer into this function
NavMeshBuilder.UpdateNavMeshDataAsync(navMeshData,buildSettings, buildSourcesReinterpret, bounds);
Yeah but that is the problem. I need a normal collider for collision and a separate one for damage zone. I am going to go around it by decorating the parent (base) entity with the damage component but I will not be able to create two separate damage zones.
I don't know how you could do that. If you could somehow get a pointer to the dynamicbuffer that would be neat.
Otherwise NativeArray or NativeList would be the other option with less overhead than List
Idk, Unity Physics is too complicated for me to wrap my head around the internals.
Perhaps you could use Latios spatial querying system for damage zones but it still uses 0.51. Just an idea, never actually tried it
https://github.com/Dreaming381/Latios-Framework
Is it normal that the temp pool climbs over normal usage? If so, what's the reason for it?
It's also growing pretty quickly, this is just a few minutes apart
Does it eventually stabilize?
Nope
I just took another capture and the persistent allocator also allocated something, but that also wasn't from me. This is a project using netcode and physics though, so not sure if they periodically need to allocate something using a persistent allocator
All my persistent allocations just happen once on startup, so I'm confused on what the origin is
I'll wait until leak detection works again though, maybe something is actually leaking somewhere
Is this child baker okay?
For some reason the child doesn't follow the position and rotation of the parent :/
public class ParentMono : MonoBehaviour
{
}
public class ParentBaker : Baker<ParentMono>
{
public override void Bake(ParentMono authoring)
{
var buffer = AddBuffer<Child>();
foreach (Transform child in authoring.transform)
{
buffer.Add(new() {Value = GetEntity(child)});
AddComponent(GetEntity(child), new Parent {Value = GetEntity(authoring)});
}
}
}```
I am not using 1.0 yet but before that it needed some more components for the children to follow their parents. Fore example a LocalToWorld and LocalToParent component on the child. But afaik the transformation systems have been reworked so I dont know if thats still true
Is there any good way to time ECB actions? I want to sync the destruction of an object with a vfx effect. So a user interaction should trigger the vfx effect and the destruction of an entity half a second later.
Would be nice to have a special kind of ECB that just accepts a delay.
Ah yes, I think I'm missing LocalToParentTransform. Thank you!
(Transform related components are already baked)
I now have these two bakers but it's still not working
public class ParentBaker : Baker<ParentMono>
{
public override void Bake(ParentMono authoring)
{
var buffer = AddBuffer<Child>();
foreach (Transform child in authoring.transform)
{
buffer.Add(new() {Value = GetEntity(child)});
}
}
}
public class ChildBaker : Baker<ChildMono>
{
public override void Bake(ChildMono authoring)
{
var parent = authoring.GetComponentInParent<Transform>();
AddComponent(new Parent {Value = GetEntity(parent)});
AddComponent(new LocalToParentTransform());
}
}
What are you trying to do?
The Child buffer from the transform system is automatically updated for you and as a result, you can't update it. You can however change the Parent comp, and the system should update everything for you :3
I would like to bake children.
I deleted the parentbaker now and changed the childbaker to this
public class ChildMono : MonoBehaviour
{
}
public class ChildBaker : Baker<ChildMono>
{
public override void Bake(ChildMono authoring)
{
var parent = authoring.GetComponentInParent<Transform>();
AddComponent(new Parent {Value = GetEntity(parent)});
}
}```
what do you want to get in the end out of it?