#archived-dots
1 messages Β· Page 151 of 1
Problem Solvedπ¬
in EntityQueryDesc desc = new EntityQueryDesc { All = new ComponentType[] { typeof(CircuitComponent), typeof(CircuitInput) }, None = new ComponentType[] { typeof(CircuitCompletedTag) } };
the typeof(which allows RW) causes creation in entities in EntityQuery circuitQuery = GetEntityQuery(desc);
i changed it to readonly by EntityQueryDesc desc = new EntityQueryDesc { All = new ComponentType[] { ComponentType.ReadOnly<CircuitComponent>(), ComponentType.ReadOnly<CircuitInput>() }, None = new ComponentType[] { ComponentType.ReadOnly<CircuitCompletedTag>() } };
and the problem is solved
Thanks sc_balls
Coroutines are out in Unity 2020, right? So how do we make a script wait?
The editor's pause button is terrible
The documentation still shows it working but StartCoroutine() doesn't exist anymore...
it certainly does
Nevermind I'm a dummy. It's a monobehaviour
I've been tooling around in DOTS so long I almost forgot that exists.
I guess in a DOTS system there's no way though.
@gusty comet yea the easy way to 'wait' is to have a timer component that counts down from whatever time you set
i do the reverse as i have a global game time, so i say if gametime > target time
and have that stored in a component
Roger that. Just too engrossed in completing today's work to bother π I'd code with ADHD that I don't have if I fixed everything as soon as it bugs me lmao
Okay, I need advice, I'm splitting up my world generation script to work into DOTS more efficiently. And right now it's like "run one method and it creates the entire chunk" but inside of that there are a lot of loops that could be run in each and every job instead. So my question is, do I break it out into an entire system and make the system handle all these loops where I do a lot of calculations in a job's kind of way, OR do I keep the generation in a class and just call certain methods in jobs from the system?
you're not forced to use a system, you can use the jobs system + burst on their own
No, but what I'm asking is, what would be the most efficient way? and tbf, I have no clue yet how exactly burst works, need to read up on that, I've only used SharedStatic from that library I think
just from an overview, it looks like a system is the way to go for performance
okay, so basically how I understand it is that the Burst compiler makes jobs better, and systems are specialized in working with components and entities, so there is no reason why I should not go full DOTS on these jobs that require a lot of calculations.
actually i think JOBS + Burst is faster then ECS
as Systems currently have a overhead
but you need somewhere to schedule the jobs from
and Unity are working on optimizing systems
Goodies, was there a decent way to run a job once in systems or are they more of a thing that runs over and over?
Or might be better using JobComponentSystem for such things.
probably best to just schedule your job once
Anyone seen this before:
The component type has nothing inside, its a tag
but its after world deserialization
so world was created and saved out,,, then loaded up again later
π€¦ββοΈ
was a class (managed) IComponent by mistake
oh snap, this is today https://forum.unity.com/threads/unite-now-q-a-stacking-up-the-new-functionality-in-dots-physics.907820/
in 9 and half hours apparently
well ill be fast asleep for that, will have to grab it on youtube
I was mainly thinking about the Q&A, but I don't really have time to prepare some tests to validate what I'm asking
obviously would be interested on their future plans too, especially how they plan to handle the fixed timesteps and such by design
theres a post on the fourms about fixed timesteps
it feels like that part is in some sort of limbo atm
its comming soon
and they seem to be rewriting it
well, that sounds like what they'e been doing for year+ now
rather then just having a system group which is added to the PlayerLoop Fixed update
which is like crazy easy
doing some custom patch for this pretty easy
there's been countless ways of doing it in past
but I'm more interested on something that would be built-in and would stay intact from version to another
instead of redoing the hacks when api changes
yea makes sense
their last "built-in" solution didn't even have any failsafe
meaning it would starve on low end cpu's if they can't keep up
it's such a basic thing to take into account even
i didnt read anything like that in the forum post
maybe new one still dosnt have it
you got a link?
ah nevermind found it https://forum.unity.com/threads/fixed-timestep-features-coming-to-entities-dots-physics-packages.899687/
dam
π
too slow
so, reading that... they are still fiddling with it
like, no interpolation at all, they plan to do some minor change to name the system with fixed prefix
maybe next year then
stuff like this makes one lose faith in Unity a bit
such small things that shouldn't take years to implement but still do
which also makes it obvious that they've not actively worked on this issue regardless of the userbase outcry on it
how I see it myself is that they don't want to make a temporary solution so they've postponed it to see what happens on other end of DOTS ecosystem, but then they still made a quick hack that left it half way
if they really wait for netcode and stuff to get this all together before they can unify the workflow for all, I dunno.. it's realistically happening only in following years
(a task that takes few days to implement)
imo, its better to not to force their hand, its a preview technology and they dont even guarantee stuff will work properly, so they did what most developers would, a quick hack π
according to Joachim, DOTS physics was supposed to be released already by Q3 last year
but I totally get that targets shift, especially on DOTS
like, netcode just got additional year on the target
i think they are also learning while developing π
Guys have physic shape and physic body. But where 2d versions?
@halcyon plume No 2d tools yet
maybe something in TINY but unsure where/how that fits with the main DOTS stuff
I made this small project to learn ECS, I keep meaning to post it to the forum but haven't found time to yet so I'll put it here for now. Hopefully someone else might find it useful? It's a battle of spaceships: https://github.com/ElliotB256/ECSCombat
Can you convert game objects to entities at runtime?
yes
give me a few mins, i cant remember how on the fly, but i should have some examples
nvm, i changed all of them to authoring, because an unity staff said runtime conversation will be deprecated eventually
ok, well runtime conversion would be pretty inefficient
a few months ago, an unity staff told us they were working on making entity prefab easy, i am looking forward to that
I hope soon there will be a version of Unity Physics with Entities 0.11
is it better to use Time.deltaTime in a Job or to get the time from WorldTime?
nvm i just saw that WorldTime is internal
@abstract flume what do you mean? latest physics package does work with entities 0.11
that means nothing for the compatibility
it means it depends at least on those versions
you can use newer packages than ones on the dependencies as long as there's no API changes on things they need from eachothers
- which you mainly find out by trying it
it's pretty clear if it works
ok
is there any way I can add one of these to a IComponentData? (or some other type of entity-specific ECS component) cs namespace UnityEngine.Experimental.AI { // Object used for doing navigation operations in a NavMeshWorld. [NativeContainer] public struct NavMeshQuery : IDisposable {
You can have managed ICDs, which are class instead of struct, have some restrictions, and exist "outside" the usual DOTS optimization.
https://docs.unity3d.com/Packages/com.unity.entities@0.11/manual/component_data.html#managed-icomponentdata
It is primarily meant to bridge the gap between MB and DOTS while you port code, so if it is possible to do in a more DOTS way, you generally wanna use that. I don't think we have DOTS navmesh yet, though
when I have a NativeArray in a Component, i get this error
[13:03:55:867] ArgumentException: Magic.SpellSystem.DOTS.Components.ActivateNext contains a field of Unity.Collections.LowLevel.Unsafe.DisposeSentinel, which is neither primitive nor blittable.
what other type am I supposed to use?
Looking at older docs, it has been there since pretty much the beginning
hmm ok, thanks
@abstract flume Can't have NativeArray in normal ICD. Use DynamicBuffer (https://docs.unity3d.com/Packages/com.unity.entities@0.11/manual/dynamic_buffers.html) or managed ICD (see previous link in response to Lecks)
thanks
I'm trying to activate the next Spell parts in Sequence when the previous delay is done, but i cant get this to work
public class NextSystem : SystemBase
{
protected override void OnUpdate()
{
Entities.ForEach((DynamicBuffer<NextBufferElement> activateNext, int entityInQueryIndex, in Delay delay) =>
{
if (!delay.done)
return;
foreach (var entity in activateNext.Reinterpret<Entity>())
{
if (!HasComponent<Delay>(entity))
return;
var nextDelay = GetComponent<Delay>(entity);
nextDelay.started = true;
nextDelay.remainingTime = nextDelay.delay;
}
}).ScheduleParallel();
}
}
what am I doing wrong?
What happens, and what do you expect to happen?
I expect that the other delays get activated and start counting down, but that doesn't happen and i get this error
[14:24:39:047] C:\Users\OmegaRogue\Projects\polygonbuild\Assets\Scripts\Magic\SpellSystem\DOTS\Systems\NextSystem.cs(28,11): Burst error BC1037: The `try` construction (e.g `foreach`/`using`) is not supported
foreach is also used here https://docs.unity3d.com/Packages/com.unity.entities@0.11/manual/dynamic_buffers.html#systembase-entitiesforeach
if you replace the inner foreach with for(int i =0; i < activateNext.Length; ++i) then Entity entity = activateNext[i] does it work? You'll also need a SetComponent call
also it's not necessarily obvious but you can't simultaneously have your lambda take in Delay and use Has/Get/Set Component for Delay - it makes more sense when you understand the code it's generating but still..
how else can i do it then?
now i get this
[14:48:39:776] InvalidOperationException: <>c__DisplayClass_OnUpdate_LambdaJob0.JobData._ComponentDataFromEntity_Delay_0 is not declared [ReadOnly] in a IJobParallelFor job. The container does not support parallel writing. Please use a more suitable container type.
and this
[14:48:41:121] Internal: JobTempAlloc has allocations that are more than 4 frames old - this is not allowed and likely a leak
Consider splitting it into two jobs;
one to fill a NativeArray (it autoscales, but give it a reasonable init-size) with the entities to activate next,
and another one which does the activation
That might make it easier, and the first job only needs to read
if you know that you never write to the same index in the dynamic array within the job, you can use .WithDisableNativeParallelForRestriction() (it's called something like that)
just be mindful that you are disabling the automatic safety system so if your job ever did write to the same index, it could cause a race condition and consequently a crash
how do I iterate over a NativeArray in Entities.ForEach?
You don't, you use a more traditional job
Though as long as there is a local variable of the array in the OnUpdate method you an otherwise access it as usual
how do i make sure that a Job is executed after all calls of a Entities.ForEach().ScheduleParallel() are completed?
I dont think it should crash, but it would just result in data being overwritten @amber flicker
because my IDE is warning me that the Buffer is disposed outside the scope of the Lambda Function
var jobhandle = Entities.ForEach().ScheduleParallel(Dependency)
// Make jobs using jobhandle, and update it as you go
// ...
// Make sure to update the property since you're using the manual dependency method
Dpeendency = jobHandle;
I need to learn how to schedule properly instead of just blasting out code that is independent all the time. It's bothersome to write.
im getting this error now
InvalidOperationException: <>c__DisplayClass_OnUpdate_LambdaJob0.JobData.buffer is not declared [ReadOnly] in a IJobParallelFor job. The container does not support parallel writing. Please use a more suitable container type.
Can you show the code?
protected override void OnUpdate()
{
var buffer = new NativeList<Entity>(64, Allocator.TempJob);
var activateJob = new ActivateJob
{
entities = buffer.AsArray(),
manager = EntityManager
};
var jobHandle = Entities.ForEach((in DynamicBuffer<NextBufferElement> activateNext, in Delay delay) =>
{
if (!delay.done)
return;
for (var i = 0; i < activateNext.Length; i++)
{
Entity nextEntity = activateNext[i];
if (!HasComponent<Delay>(nextEntity))
return;
buffer.Add(nextEntity);
}
}).ScheduleParallel(Dependency);
var handle = activateJob.Schedule(buffer.Length, 16, jobHandle);
handle.Complete();
buffer.Dispose();
}
private struct ActivateJob : IJobParallelFor
{
[ReadOnly]
public NativeArray<Entity> entities;
public EntityManager manager;
public void Execute(int i)
{
var nextEntity = entities[i];
if (!manager.HasComponent<Delay>(nextEntity))
return;
var nextDelay = manager.GetComponentData<Delay>(nextEntity);
nextDelay.started = true;
nextDelay.remainingTime = nextDelay.delay;
manager.SetComponentData(nextEntity, nextDelay);
}
}
What happens if, instead of using .AsArray(), you just use to list as-is?
the same thing
I'm not sure if NativeLists has concurrent write access like that π€
You can't use entitymanager inside a job
I think this might be an alternative to the ActivateJob π€
struct ActivateJob : IJobParallelFor
{
[NativeSetThreadIndex] public int jobIndex;
[ReadOnly] public NativeArray<Entity> entities;
[ReadOnly] public ComponentDataFromEntity<Delay> Delays;
public EntityCommandBuffer.Concurrent CmdBuffer;
public void Execute(int i)
{
var e = entities[i];
if (!Delays.Exists(e)) { return; }
var nextDelay = Delays[e];
CmdBuffer.SetComponentData(jobIndex, e, new Delay { started = true, remainingTime = nextDelay.delay });
}
}
Like what @safe lintel said, you can't use an EntityManager inside a job, so you'd likely need a command buffer which will queue the instructions to change the entity's data on the next frame
what would i use as job index?
Can try using nativequeue instead of list for parallel read/write
i?
how to detect colision of 2 object that not a trigger
@halcyon plume https://youtu.be/uficmLSCuAk
In this episode, we review syntax for setting up a Collision Event, where we crash the Chasers into our Asteroids. First we create a couple of Components, HealthData and DeathColliderTag. Then we create two Systems, one to remove "dead" Entities and one to handle the collisi...
ty
I like the Unity Physics library so much more than the PhysX one...it feels more real in the way it interacts with objects and gravity.
maybe ill make a simulation of Special Relativity in Unity Physics when i get more used to it
I mainly see extra helpers missing from Unity Physics being the thing that differentiates it from say, common physx setup
everything that takes one line on nonDOTS takes 10 lines on DOTS (physics)
I've started making one using Compute Shaders, but floating point imprecisions are too much of a problem
values fluctuate greatly each frame
Is it better to ForEach a set of entities once, running a check against 3 separate arrays of data within the single loop (and therefore needing a lot more data available at each step of the foreach), or to run three ForEach loops on the same set of entities, each going through a different one of the arrays?
I appreciate this may be a "how long is a piece of string" question π
I suppose it comes down to efficiency of running smaller cache job 3x versus larger one once.
If they run on worker threads, then I'd say probably smaller jobs run faster in total because they can be spread out more
I'll test it on my data and see
if there were any "oh definitely do A over B" that'd save me some effort π
one job can only run on one thread, but 3 jobs can run on 3 threads simultanously
mm but the entities being iterated over are the same set
the components being iterated over are the same and are being written to *
then i don't know
but Run() might be quicker than Schedule anyway as it's not that many
If I want to have RenderTextures as part of my component data for some entities, I can only do that in ISharedComponentData since they are reference types, however the docs state Note: Currently, the ISharedComponentData interface allows fields having reference types. However, we plan to restrict ISharedComponentData to unmanaged, blittable types only in a future version of the Entities package. so is there some other way that this should be done?
managed component data @stray topaz
public class SomeManagedData : IComponentData, IEquatable { ... }
i keep getting this error
[19:07:59:844] C:\Users\OmegaRogue\Projects\polygonbuild\Assets\Scripts\Magic\SpellSystem\DOTS\Systems\LoopSystem.cs(45,14): error DC0047: Entities.ForEach cannot use component access method HasComponent with the same type Delay that is used in lambda parameters with write access (as ref).
even though Delay doesn't have write access:
var jobHandle2 = Entities.ForEach((
DynamicBuffer<LoopBufferElement> activateNext,
Delay delay,
SpellTag spellTag,
ref EndDelay endDelay
) =>
{
if (spellTag.done)
return;
if (endDelay.done)
return;
if (!delay.done)
return;
for (var i = 0; i < activateNext.Length; i++)
{
Entity nextEntity = activateNext[i];
if (!HasComponent<Delay>(nextEntity))
return;
parallelWriter.Enqueue(nextEntity);
}
endDelay.started = true;
}).ScheduleParallel(jobHandle);
is there something i overlooked?
You are trying to access the Delay component through the ForEach lambda and attempting to access it using the ComponentDataFromEntity, typically you just pick one way you want to access the said component data
so what you can do is modify your ForEach to take an Entity as a parameter and access the component data via ComponentDataFromEntity<T>
but then why am I not getting the same error for the ForEach above it?
var jobHandle = Entities.ForEach((
ref Delay delay,
ref EndDelay endDelay,
ref Loop loop,
ref SpellTag spellTag
) =>
{
if (!endDelay.done)
return;
delay.started = true;
loop.currentI++;
if (loop.currentI < loop.iterations)
return;
spellTag.done = true;
}).ScheduleParallel(Dependency);
nvm
I've spent a few hours trying to troubleshoot this, with no success.
i get these two errors:
[20:38:16:012] A Native Collection has not been disposed, resulting in a memory leak. Allocated from:
[20:39:02:995] InvalidOperationException: The NativeArray <>c__DisplayClass_OnUpdate_LambdaJob0.JobData.delays must be marked [ReadOnly] in the job LoopSystem:<>c__DisplayClass_OnUpdate_LambdaJob0, because the container itself is marked read only.
and i have no idea why, basically the same thing in NextSystem doesn't throw these errors.
https://gist.github.com/OmegaRogue/dcb6815843f26dbb42a7204b0f372fef
@coarse turtle Thanks thats exactly what I needed
hmm how is rendermesh gonna work in the future if they make it blittable types only?
@abstract flume LoopSystem.cs: 26 add a .WithReadOnly(delay) to get rid of the InvalidOperationException
The native collection memory leak warning might be a side effect, I usually tackle those after other errors in a system because sometimes they only come up because ecs system refused to execute a job chain because of some other error.
Hi guys, I just got into DOTS and I'm having a blast with using jobs. There is one problem I'm facing right now and I'm not sure I could solve it.
At some point in the for each entity call I want to use the Unity.Mathematics.Random function to set a random value when a certain condition has been met. However I get receive an error in the console saying that function can only be called from the main thread. My question is what would be the correct approach when you a function must be executed in the main thread but is called from a job?
You can use a thread friendly API call like the Random struct in the Unity.Mathematics package instead. Although you'll need to provide a seed value.
is Shader LiveLink some DOTS thing?
just saw these:
https://issuetracker.unity3d.com/issues/shader-livelink-srp-batcher-and-shader-livelink-do-not-work-together
https://issuetracker.unity3d.com/issues/shader-livelink-number-pragma-editor-sync-compilation-has-no-effect-on-shaders-when-shader-livelink-is-enabled
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
I know they demonstrated DOTS livelink with adjusting materials in past
just wondering if this is something related
@coarse turtle Do you mean like this?
private static void GetNewTarget(ref SeekBehaviorData a_seekData)
{
Unity.Mathematics.Random rand = new Unity.Mathematics.Random((uint)100);
a_seekData.targetPos = rand.NextFloat3(-a_seekData.targetMaxRange, a_seekData.targetMaxRange);
}
Yea something like that
@spark glade thanks, I'll try it tomorrow
That is strange because thats how i have set it up now, but it throws the error of only being allowed to called fromt the main thread π€
@solar turret what line is throwing it? might have to create the random struct on main thread and pass it into your job
nextfloat can be non-main thread for sure
Its throwing this line
@solar turret I suspect that the recommended way would be to create a NativeArray of random int's to pass to your job
@solar turret unityengine code can only be called from main thread yes
Is the method outlined here still fine for random nums? https://reeseschultz.com/random-number-generation-with-unity-dots/
How to idiomatically generate random numbers in Burst-compilable jobs with Unity DOTS.
check if vs didn't create a Random using alias to UnityEngine at the top of your file
you need to use Unity.Mathematics.Random
Wow thanks for the article link! seems like very good read!
@solar turret RandomRangeInt means you're calling unityengine.random somewhere in your code not in the snippet you posted
Thats strange, because when I remove the snippet. I don't get the error at all.
Maybe that's how unity references all random errors?
i think Unity.Mathematics lacks slerp of float3 maybe they added it in newer versions also many handy methods from classic unity math libraries
@storm ravine thank you for answer about LinkedEntityGroup. But now i can't figure out how to use ECB with dynamic buffers. Simple ECB.SetBuffer<T>(Entity).Add(T) rewrite whole buffer. Is there a way to add an element to buffer by ECB without using CopyFrom?
you first add the buffer once, then Get it
I mean i'm already have buffer on my entity and try to add an element to this buffer through ECB.
and you can manipulate a DynamicBuffer as a NativeArray btw
and you don't need a ecb to handle buffers ??
unless you're creating them
i need use ECB because i want to add an entity that i creating with this ECB
I don't think you can access the buffer & write to it before the command has been executed
doesn't SetBuffer has a 2 parameter version with input data ?
it has no parameters
all i need is schedule adding an element to dynamic buffer. And it works, but in the end buffer contains only last added element
like it's creating new dynamic buffer every time i use ECB.SetBuffer
then just get the buffer with it's ArchetypeChunkBufferType or w/e's the method to access it from the kind of job you're using
ofc SetBuffer will recreate your buffers
if i will edit buffer directly from job it will add a 'null' entity that returned by ECB.Instantiate(...)
urg, show your code
AppendToBuffer
Exists in both - regular and concurrent ECB version (was added recently)
var createdEntity = bS_ECB.CreateEntity(entityInQueryIndex, localEntityArchetype);
bS_ECB.SetComponent(entityInQueryIndex,createdEntity,
FoodConsumptionMembers { consumer = entity, consumed = bestTarget.entity });
bS_ECB.SetBuffer<LinkedEntityGroup>(entityInQueryIndex, entity).Add(hungerSolveControllerEntity);
@storm ravine thank you. Didn't know that. Will update my dots))
Does NetCode have some sort of NetworkTime implemented?
@abstract flume LoopSystem.cs: 26 add a
.WithReadOnly(delay)to get rid of theInvalidOperationException
@spark glade but why delay? delay is a local variable inside the lambda function
never thought a line could say f you as much as this throw new System.ArgumentException("EntityCommandBuffer.AddSharedComponentData does not support shared components with Entity fields.");
throwing an exception for what is a good practice but with correct edge cases where you actually want that is rly not fun
@ocean tundra That's a good question, I'm not actually sure. It must??? I am strongly considering switching to DOTSNET which looks much more featureful and seems to be getting much more aggressive releases currently
@ocean tundra That's what i use to get the duration since a given tick
public static float DurationSinceTick( this ClientServerTickRate tickRate, uint tickToGetTheDurationFrom, uint currentTick )
{
return (currentTick - tickToGetTheDurationFrom) * (1f / tickRate.NetworkTickRate);
}
one of the solution against AddSharedComponentData throwing exceptions for types containing Entity is to create a "fake" entity that contains the index & version and just create a entity from it when I need it
I hate this --'
that thing shouldn't throw for that 
ah yes ecb, bootleg entitymanager.
yeah, afaik, I can't even add archetypes.
@abstract flume sorry typo, I meant delays
thanks, it works now
Is it possible to have dots generate my meshes procedurally (terrain, trees) but have their collider + physics interact with classic unity physics (rigidbodies, colliders). I'd really like to use dots for terrain + vegetation + some simulation but not sure I want to go the full way to have it handle everything just yet
collider + physics interact with classic unity physics (rigidbodies, colliders)
for this... I think you can.
remember the dots sample? the one with the snakes?
the player is actually both an entity and a game object.
attach a convert to entity script on the GO, and instead ofConvert and DestroyuseConvert And Inject Game Object
although I myself haven't test it out.
mm so objects would still have to exist in dots world, you can't have dots-created procedural entities instead exist in legacy-unity world?
(which makes sense to me, just curious)
it's preerable to have GOs in DOTS (low extra overhead) vs entities in the GO world (high extra overhead)
yeah I was really just wondering if I have a game in classic unity, but wanted to offload the whole terrain + vegetation generation to ecs
but because physics for terrain have to be built in dots, I don't think it's compatable
(without first converting the entire game over)
If you have an existing game, but it's too much of a bother to move things into ECS, you can still use jobs. They're a great first step for multithreading code π
You can also do ConvertAndInjectGameobject on your GOs to make them exist as entities that are linked to their GO counterparts
But from the sound of it, merely jobifying the generation code could be a benefit, without affecting anything else
Is there a specific Profiler for ECS stuff ? To see which system is taking too long to complete and co ?
I remember people posting screenshot of something like that in forums, but I can't find it in the Editor.
Yeah I know that one but it only list which system are applied to an entity. The thing I saw had different bar length for each system but here it's just as long as the name.
@scenic oracle I believe you're lookign for the profiler
The timeline view should show the "length" of each system
something like this?
Yes, that's it !
Crap, all those years and I never noticed the profiler could display stuff in other ways than the hierarchy. >_<
Thanks.
Well, look like I found which system is slowing me to 30 fps.
looks like burst is off
It was, I had forgot to turn it back on after some testing.
That system is still my bottleneck tho.
hello, is entity command buffer playback each frame automatically?
who can help me?
does anyone know if theres an up to date guide on saving and loading in unity ecs? all that i can find are from 2018ish
I'm trying to figure out how to tell an Entity System to call a Monobehavior function. I have no idea what I'm doing... I want my Entity-based grains of sand to affect a non-ECS tilemap based on their position...
public class ChangeToStaticSystem : SystemBase
{
EndSimulationEntityCommandBufferSystem m_EndSimulationEcbSystem;
protected override void OnCreate()
{
base.OnCreate();
m_EndSimulationEcbSystem = World.GetOrCreateSystem<EndSimulationEntityCommandBufferSystem>();
}
protected override void OnUpdate()
{
var ecb = m_EndSimulationEcbSystem.CreateCommandBuffer().ToConcurrent();
Entities.ForEach(
(Entity entity, int entityInQueryIndex, ref SandPhysics sandPhysics, ref PhysicsCollider physics, ref PhysicsVelocity velocity, ref Translation trans) =>
{
{
if (sandPhysics.settled)
{
//---> How can I do THIS on a MonoBehavior --> GameManager.Instance.SetTile(trans.Value, Color.red);
ecb.DestroyEntity(entityInQueryIndex, entity);
}
};
}).Schedule();
m_EndSimulationEcbSystem.AddJobHandleForProducer(this.Dependency);
}
}
@safe mica your game object has GameManager Component?
currently GameManager is a Monobehavior, not a component.
@radiant sentinel if you get it from the Begin/End BufferSystem then it will play back during that systems update. If you're just instantiating your own then you have to manually play it back.
@mint iron if i use b/e buffer system, then i have it on every OnUpdate. is it true?
@safe mica a mono behavior is a component that u can assign to object. at ecs foreach you can set any thing, u should reference to it. please write more information about your target. how you have access to this behavior ?
sry for my english
@radiant sentinel right now, I have a GameManager component on a separate, non-ECS object. GameManager is a Singleton, so, when not using ECS, I can access it anywhere by calling GameManager.Instance.whatever(). If I try to do that from within ECS, it tells me that SetTile (a tilemap function) can't be used in a Job. Has to be on the main thread. If I use .Run and .WithoutBurst, then the ecb doesn't work. Maybe I need to break this out into two systems...
yes you cant run none static function on jobs, u want dedicate your code to two part, processing and main menu function calling. what is your process?
you should work on your gameManager setTile, u cant use it on jobs. @safe mica
I'm using VS on PC, and when I attach a breakpoint to Entities.ForEach I am unable to inspect any component data properties. I have to create a temp var to inspect a value. Is there a way to fix this?
@sand prawn @north bay Thanks guys, I'm currently using a network time implementation based on what Mirror does, but want to replace it with a ECS version will see what i come up with
Learn whatβs new with Unity Physics and Havok Physics for Unity. In this video you will get a brief recap of our Unite Copenhagen talk, then a deepdive into a cool example of how you can convert a GameObject-based simulation over to the Data-Oriented Technology Stack (DOTS).
...
hi guys, i dont know why my update override function of some systembases dont run
i add my systembases to a custom world
using
world.GetOrCreateSystem<myName.OctreeGeneratingSystem>().Inicializar();
it looks that create funct run but update dont
doesnt*
cool to see philsa at the end of the physics talk present his work with kinematic charactercontrollers
@undone torrent Have you tried putting [AlwaysUpdateSystem] on it?
It could be that it doesn't run because the engine optimizes it away
thanks u man π
They matter as long as code is made with the assumption that they do
well if you are literally parallel-for-ing on a capsule sweep, of course it does
ah totally skipped over the gamecraft presentation in the talk
https://i.imgur.com/VlaPqr3.png any reason why would the debug physics drawcomponent not spawn ?
and all the the display systems not work at all
while having entities marching their queries --'
- matching
I'm trying to convert my code from JobComponentSystem to SystemBase so I could use ScheduleParallel().
How do you access to data from other entity inside those ?
The compiler is throwing a fit about using ComponentDataFromEntity[] in the lambda, but I can't find what is the ScheduleParallel/SystemBase-approved equivalent.
Use GetComponent inside the job or otherwise declare the CDFE outside the lambda and you can use it inside without issue @scenic oracle
Entities.ForEach cannot use component access method GetComponentDataFromEntity with the same type Translation that is used in lambda parameters with write access (as ref).
For context, this one emulate transform parenting by copying another Entity's position & rotation.
Wait. I can just remove it from the lambda and extract it for the main Entity too.
Yes - either CDFE or lambda param, not both - looks like that error has improved since last time I saw it π
Yelled victory too son :
._ComponentDataFromEntity_Translation_0 is not declared [ReadOnly] in a IJobParallelFor job. The container does not support parallel writing. Please use a more suitable container type.
Compiler is fine, but execution doesn't like the write with ComponentData.
use .WithNativeDisableParallelForRestriction(myCDFE) if you want to disable the safety restriction
Nice, everything work.
... doesn't it mean what I'm trying to do is frowned upon tho, if I need to lift safety for that ?
Or are those only intended for complex-er stuff than just copy-pasting data ?
'cause I'm about to upgrade this to all my other old JobComponentSystem, most of them being a bit more fancy.
pretty sure that exists for a reason. I use it extensively, though there are far better people to question about the pitfalls of using it than me π
Oh well, as long as nothing explode guess I will keep using it then.
Edit : Unity's own ECSsample use it too apparently.
Thanks !
JobComponentSystem disables those checks for you already because the Job scheduler does safety checks anyways
but if you dont use JobComponentSystem then you have to disable the native collection checks yourself
i suppose
my understanding is: basically any assurances of not overwriting data from other threads is disabled, it wont explode, it just may not necessarily be "correct", someone else please correct me if i am wrong
yes the first part is correct
but it can still explode because race conditions can lead to very obscure bugs that are hard to debug
thats kind of the point of having these safety systems in place, to avoid race conditions
I spoke with topher a while ago about this, he mentioned it shouldnt explode(i will blame him if things do π )
Like two writes at the same time would most likely result in losing one
"fine" in terms of not crashing, not "fine" in terms of your data validity :sweat_smile:"```
omfg that was an ordeal in 2019 LTS (esp with project on external usb drive) but it runs /!
i was sleeping half a year and dont know nothing about new (for me) SystemBase. How to use ECB with it? I need do ECB.AddJobHandleForProducer(JobHandle) so i need to get jobhandle from scheduled job. But then unity throws strange errors.
instead of stuff like var myjobHandle = new Job().Schedule(inputDeps); return myjobHandle; you just use Dependency which is a property of the system itself as the jobhandle for everything
so Dependency = new Job.Schedule(Dependency); or ECB.AddJobHandleForProducer(Dependency);
thank you, all a needed is set Dependency property to new jobHandle every time i schedule a job
i thought it's just get only and dependency updates automatically
is there a way to get a nativearray<component> from a list<gameobject> working on parallel ?
i tried certain jobs, parallel.for but i get some problems always like ecs job cannot handle gameobjects or nativearray parallel restrictions
NativeArray<Bounds> list_bounds = new NativeArray<Bounds>(list_occluders.Length, Allocator.TempJob);
NativeArray<Matrix4x4> list_localToWorldMatrix = new NativeArray<Matrix4x4>(list_occluders.Length, Allocator.TempJob);
Parallel.For(0, list_occluders.Length - 1, i =>
{
list_bounds[i] = list_occluders[i].GetComponent<MeshFilter>().sharedMesh.bounds;
list_localToWorldMatrix[i] = list_occluders[i].GetComponent<Transform>().localToWorldMatrix;
});
list_occluders is actually a GameObject []
okay... this is weird...
Lemme show a dumb down version of the code.
Entities.ForEach((/*SomeComponentsHere*/) =>
{
//the idea is to spawn 10 entities at once with ECB.
for (int i = 0; i < 10; i++)
{
Random rand = new Random((uint)salt);
Entity spawnedEntity = ecb.Instantiate(entityInQueryIndex, spawnData.prefabEntity);
//Here is the problem.
Random rand = new Random((uint)salt);
var radians = math.radians(rand.NextFloat(180, 360));
ecb.SetComponent(entityInQueryIndex, spawnedEntity, new Rotation
{
Value = quaternion.Euler(0, 0, radians)
});
}
}
);
soooo see the rand? yeah.
I'm "new" ing it every time.
then I do a rand.NextFloat right after.
so you would thing that all 10 entites would have random rotation.
but nope!
for some ODD reason they all have the same rotation!
Salt is the same, so yeah.
because Random is a struct π
But I did nextfloat so nextfloat doesn't randomize?
Use (Salt + i) instead, or something like that.
what i do is i make a shared static that holds Random struct and then call it from a job, it will give different result each time you call it, since its all same Random struct
Random number generators always give the exact same sequence. Salt/Seed/etc is just the starting point.
And your code reset the sequence at the same value each loop so ...
so if I have the same salt... it will give the same values over and over.
Yep.
That's why you generally use the current time or something like that, so your salt is always different.
Zelda Wind Waker's devs forgot to do that (salt always starting at 100,100,100), and speed runners could exploit it with hilarious effects.
wow the difference in the rotation is so small!
How do I avoid aliasing when what I want to do is this:
protected override void OnUpdate()
{
var translationComponents = GetComponentDataFromEntity<Translation>();
Entities
.ForEach((int entityInQueryIndex, ref Translation pos, in FollowEntityTarget target) =>
{
pos.Value = translationComponents[target.Entity].Value;
})
.Schedule();
}
(That gives exception InvalidOperationException: The writeable ComponentDataFromEntity<Unity.Transforms.Translation> <>c__DisplayClass_OnUpdate_LambdaJob0.JobData.translationComponents is the same ArchetypeChunkComponentType<Unity.Transforms.Translation> as <>c__DisplayClass_OnUpdate_LambdaJob0.JobData._lambdaParameterValueProviders.forParameter_pos._type, two containers may not be the same (aliasing).)
you cant do ref Translation in your ForEach, you have to have "Entity entity" in your ForEach and access current Entity's translation via translationComponents[entity]
you cant have the same type in both GetComponentDataFromEntity and ForEach lambda
Right, so Entity in the signature, and use the GetCDFromEntity, of course
Doesn't seem to work, but in this case that might be because the thing I'm trying to move is a ConvertAndInjectGameObject Convert To Entity GO
Nope, also doesn't work with pure entities - this seems like a by ref/by value issue.
Well, I'll just have to use an ECB for that, then
Made it work in general, but GO position does not update. How do?
yea this situation is a little annoying - you only want to write to the transform of the entities yet you have to make it safe to write to all Translations if you schedule parallel - unless I misunderstand something - would be nice if this was improved in the future. As for updating your GO I think you should still just be able to add a CopyTransformToGameObject component to your entity? Though I haven't tried
Well, it works at least
I suppose we'll quickly find out if an update breaks in, given the problematic go/entity is the camera
ah yea, seems I'm out of date. I'm unsure under what conditions they're supposed to be automatically synced. i.e. just in subscenes? I'm guessing you're using the convert monobehaviours in a regular scene?
Anyone know if there is a way to get ICollisionEventsJob to run in parallel ?
Yeah, this is outside a subscene. Will look into using subscenes later if it comes up again
Only Proxy deprecated, component itself here and not being deprecated until replacement will arrive.
Just write your own IConvertGameObjectToEntity for CopyTransformToGameObject if you donβt wanβt to see this message
NativeArray<Bounds> list_bounds = new NativeArray<Bounds>(list_occluders.Length, Allocator.TempJob); NativeArray<Matrix4x4> list_localToWorldMatrix = new NativeArray<Matrix4x4>(list_occluders.Length, Allocator.TempJob); Parallel.For(0, list_occluders.Length - 1, i => { list_bounds[i] = list_occluders[i].GetComponent<MeshFilter>().sharedMesh.bounds; list_localToWorldMatrix[i] = list_occluders[i].GetComponent<Transform>().localToWorldMatrix; });
@undone torrent
Someone could help me ?? please π
it is about concurrent restrictions and that stuffs
@storm ravine what is the replacement?
No replacement yet
does anyone have any experience with 2D Entities package ?
@gilded glacier What is the difference between a 2D and 3D entity? O.o
that you work with one axis less ?
I don't know, I just found it when searching for 2d stuff
it is a custom unity package
2D entities is part of project tiny at least.
I'm not sure if it just happens to be used for that or if it doesn't support "normal" DOTS.
Going by the name, it sounds like it's not supposed to be used at the same time as the entities package.
Yeah, 2D entities has the project tiny package as a dependency
too bad, I was expecting such essential being already created, so I don't need to make everything from scratch
But, can't you just spawn an entity with one axis set to 0 <.<;
Unity is always 3D, there are no major differences other than perspective really.
For now it seems like if you want tooling for a pure 2D project, you should go with tiny. The extra hoops you have to hop through in order to, say, make entities with sprites in normal DOTS is annoying, though.
Really? you can just convert a game object with all the sprites on it and so on really.
Ugh, the gameobject conversion process is messy, though. At least unless you make custom authoring, but that's entirely different set of boilerplate.
But, can't you just spawn an entity with one axis set to 0 <.<;
Unity is always 3D, there are no major differences other than perspective really.
@cursive cosmos
normally yea because gameobject transform system inherently uses 3d for everything
but for ecs everything is C# side so you can do anything
you could make your own Translation2D and Rotation2D (with for example only Z angle) components and convert that into LTW, skipping 3d Translation and Rotation entirely
and because you're setting LTW you'd still be able to use hybrid renderer
any tip to solve that error ? error DC0047: Entities.ForEach cannot use component access method GetComponent with the same type size that is used in lambda parameters with write access (as ref).
I fixed my case, at least; what are you trying to achieve?
Or put differently, what type are you using, and for what?
For the record, how I solved it:
protected override void OnUpdate()
{
var ecb = _ecbSystem.CreateCommandBuffer().ToConcurrent();
var translationComponents = GetComponentDataFromEntity<Translation>();
Dependency = Entities
.WithAll<Translation>()
.ForEach((int entityInQueryIndex, Entity entity, in FollowEntityTarget target) =>
{
if (!translationComponents.HasComponent(target.Entity))
return;
ecb.SetComponent(entityInQueryIndex, entity, new Translation
{
Value = translationComponents[target.Entity].Value + target.Offset
});
})
.Schedule(Dependency);
_ecbSystem.AddJobHandleForProducer(Dependency);
}
so i am noob at ecs but reading the code i guess u use GetComponentDataFromEntity to avoid the problem , is that right ?
yeah
InvalidOperationException: The writable NativeArray <>c__DisplayClass_auxiliar_LambdaJob0.JobData._lambdaParameterValueProviders.forParameter_size._type is the same NativeArray as <>c__DisplayClass_auxiliar_LambdaJob0.JobData.lookup2, two NativeArrays may not be the same (aliasing).
i read about using [inject] to solve that
but i dont know much
Are you using the same ICD in the GetComponentDataFromEntity and Entities.ForEach lambda?
yeah
That's a no-go
Like how I did in the example above
First, you need the Entity, and grab the ICD via GetComponentDataFromEntity
could it be i am using scheduleparallel ?
Second, you then need to use an ECB to set the component. That means some boilerplate needs to be added. Generally you want
public class SomeSystem : SystemBase {
EntityCommandBufferSystem _ecbSystem;
void OnCreate() =>
//Grab the ECB system _once_
_ecbSystem = World.GetOrCreateSystem<EndSimulationEntityCommandBufferSystem>();
void OnUpdate(){
// Create ECB from ECB system, make it concurrent
var ecb = _ecbSystem.CreateCommandBuffer().ToConcurrent();
// "Dependency" is the jobHandle of the system's dependencies
// Setting it sets your system's "output" jobhandle
//Done automagically with "Schedule()" with no args
//The special named parameter "entityInQueryIndex" is the "index" of the current job. Required for concurrent ECB
Dependency = Entities.ForEach((int entityInQueryIndex, /*lambda signature*/)=>{
//Some code with ECB
ecb.DoSomething(entityInQueryIndex, /* other args*/);
})
.Schedule(Dependency); // Use Dependency as input jobhandle!
// When using Dependency, we need to set it manually as well!
_ecbSystem.AddJobHandleForProducer(Dependency);
}
}
That's just the boilerplate for using ECB in Entities.ForEach, but with explanation for what's going on and why
If you need more specific help I'd need to see at least some of your code
var lookup2 = GetComponentDataFromEntity<size>(true);
var lookup3 = GetComponentDataFromEntity<vertices>(true);
JobHandle j = Entities
.ForEach((Entity e, ref DynamicBuffer <OccluderRefBufferElement> occludersAtached, ref size size, ref vertices vertices, in workTag workTag, in parentRef parent) =>
{
size parent_size = lookup2[parent.entity];
vertices vertaux = lookup3[parent.entity];
size = new size { siz = parent_size.siz/2 };
....
})
.ScheduleParallel(this.Dependency);
i also added some disableparallelrestrictions
but always i get the same error or one about readonly stuff
Youre' using DynamicBuffer <OccluderRefBufferElement> occludersAtached in the lambda signature as well as var lookup = GetBufferFromEntity<OccluderRefBufferElement>(true)
Though I can't see lookup actually being used
Is this the code you got the error you posted previously with?
it is only a part of it but lookup is used as the same one , only for read
i am sorry if i cannot explain well , as i said i am noob with ecs , sorry π¦
That's a nogo - can't have same thing in signature and the lookups
so if i use lookup i cannot use ref Dynamicbuffer<OccluderRef ....
Remove ref DynamicBuffer <OccluderRefBufferElement> occludersAtached and related code, and see if it runs
okey i will try
Actually, you have the other lookups as well
By the way, is WorkTag just a tag(no data)? If so you should use .WithAll<WorkTag>() instead of putting it in the lambda signature
so the main lesson i have to adquiere is that if i use GetBufferFromEntity i cannot use its type as a parametter on Entities foreach
at this moment has data cause my mate did it like that but i have to rewrite it and separate the data on other new component
You can't use the same type in a GetXFromEntity and in the Entities.Foreach lambda signature, no
so it is apply for buffers and componentdata , isnt it ?
Correct
The snippet you sent, fixed would be:
var ecb = _ecbSystem.CreateCommandBuffer().ToConcurrent();
var occluderLookup = GetBufferFromEntity<OccluderRefBufferElement>(true);
var sizeLookup = GetComponentDataFromEntity<size>(true);
var vertexLookup = GetComponentDataFromEntity<vertices>(true);
JobHandle j = Entities
.WithAll<Worktag>()
.ForEach((int entityInQueryIndex, Entity e, in parentRef parent) =>
{
size parent_size = sizeLookup[parent.entity];
vertices vertaux = vertexLookup[parent.entity];
ecb.SetComponent(entityInQueryIndex, e, new size { siz = parent_size.siz/2 });
//....
})
.ScheduleParallel(Dependency);
oh , thanks man !!!
Then you need to do similar to the other places where you would set the components
yeah , i think i could handle it now
Replace componentFromForEach with an ecb.SetComponent() call.
Haven't used that for DynamicBuffers before, but the var buffer= ecb.SetBuffer method clears your buffer completely, so you need to use the return buffer to fill in the new values
Also, I suggest naming things better than just "lookup", especially if someone else is working on the code or you ask for help. Otherwise it's really hard to understand what it is.
But even for yourself -imagine taking a 6-week break and coming back to this code. Would you remember what each of the lookups are?
(6week break could just be working on different parts of the game, btw)
yeah , u are right , sometimes when i dont know much about the features i am working on i name the variables like that , it is a bad behaviur i have to improve, i really apreciate your tips
i dont know if the sentences its clear cause i have to improve my english, what i wanted to say is that i have to fix that behaviour
"Fix that habit" or "improve that habit" would be appropriate here. "Habit" being little behaviors you do "automatically" because that's what you usually do.
yeah that is the word i need , thanks π
Hi, I am starting to look into DOTS but I am facing something I don't understand at all...
How is it possible that:
GetSingletonEntity<Translation>()
throws the exception
System.InvalidOperationException: GetSingletonEntity() requires that exactly one entity exists that matches this query, but there are 18.
YET
GetComponentDataFromEntity<Translation>()
returns an EMPTY array?
How are you using GetComponentDataFromEntity<Translation>()? Are you just looking at it with debugging tools, or are you using compDataFromentity[entity];?
Though, GetSingletonEntity<Translation>() sounds like a bad idea if you have more thatn, I dunno one entity
Since everything with a position will have a Translation
I was actually using it to get some other entities in the scene
GetComponentDataFromEntity<PickupTag>(true);
Which was working until... it didnΒ΄t work anymore.
ThatΒ΄s why I tried one getting Translation, because all the entities should have it. Yet it is not working at all...
Unless 100% sure the entity has the component, you should use compDataFromEntity.HasComponent(entity)
I don't know what you're tying to do, but it sound like you might be going about it the wrong way
GetComponentDataFromEntity<TComponent>() returns a helper to access the data from entities you have the Entity struct for
If you want a list of entities with the component, it would be better to use an EntityQuery
I am trying to get an array of entities with a PickupTag component to detect some collisions. Just following an online example on how to implement collision triggers.
I'm following this example in particular:
https://github.com/UnityGameAcademy/DOTSTriggerEvents/blob/78df4c8599a128555fcfe8ff9b1bba66ab5d1ed0/Assets/Scripts/Systems/PickupOnTriggerSystem.cs#L61
If you want to learn trigger events, I recommend watching this playlist:
https://www.youtube.com/playlist?list=PL-05SQhI5rIY2MVt5s_EfvddNXS2GNAtA
I suggest watching all the videos, but skipping ahead when it's stuff you already understand, to get a better understanding of the demo project they're using
I am watching that particular one π
And I am following the proposed example
A query seems to work fine though, returning a NativeArray<Entity> π€
Ah ok I get it now. ComponentDataFromEntity is a helper as you mentioned.
I can see that, when asking if an entity exists in it, it returns the correct value.
Got confused there, sorry about that.
If I have a Job (IBodyPairsJob, actually) that has this:
[ReadOnly] public ComponentDataFromEntity<Owner> Owners;
... it doesn't necessarily only run for Entities that have an Owner IComponentData, right?
public unsafe void Execute(ref ModifiableBodyPair pair)
How do I know which pairs this is then run on? I keep stumbling into invalid pairs and I don't know how these are even produced.
(Interested in both the general case, and this specific job type)
Yes. ComponentDataFromEntity is just an access tool, it doesn't filter anything.
As for knowing "which" pairs those are, you will have to manually add some form of ID into it.
Ok I was just wondering if somewhere there was an entityquery that I didn't realized was being built.
Thanks π
My current challenge is to programmatically make a specific collider in a compound collider permeable (or to just deactivate it alltogether).
I can't seem to properly reach it when I modify the broadphase pairs (which I do to make certain other colliders permeable for objects they "own", i.e. things launched from within).
So I'm now thinking about a system that can do it in a simpler way. I don't understand how the PhysicsCollider component works though.
Sorry. I've been avoiding dealing with the inner working of compound colliders for now, so no idea.
My current solution for having multiple hitbox&co is to just have each one on a separate entity and slap a pseudo-parenting effect to keep them in the expected position.
Yeah kind of seems like it, because the collider is baked together somehow. I've tried working with custom tags but I don't even get to the collider in question, i.e. can't test for the tag.
I might capitalize on this and make the shields for my spaceships act in interesting ways as they follow the main rigidbody around. Hmm
Only problem is my owner system needs some more features and edge cases then
Yes. Slapping several colliders on the same entity get then baked. Might be possible to separate them somehow, but I stay away as much as possible from unsafe code.
Your case definitively need shields to be a separate entity tho.
what's the "good" way to convert nested GO at runtime since ConvertGameObjectHierarchy is considered bad practice ?
the most important word here is "at runtime", because I want to set some authoring data before converting the GOs
IConvertGameObjectToEntity?
can you call it manually ?
You would make a MonoBehavior implementing the interface.
Then, whatever you write in the interface would be performed as part of conversion.
It may override the default conversion, though, so not sure if it's exactly what you need.
I already do that..
what I want is to be able to decide when to trigger the conversion process; if I just add the ConvertToEntity component when I'm done setting things up I'm getting a dealocated error on my physics debug drawing component
and I have no idea why that is
cuz the conversion process is a big black box..
So... you want to draw a debug thing before you convert?
no
I'm using the Physics Debug Display component with Physics shape, and when I convert this go to entity Unity.Physics.Authoring.DisplayBodyColliders+DrawComponent.OnDrawGizmos throws a NativeArray deallocated error
so I'm gessing I'm doing my conversion wrong but I don't know how
How are you doing conversion?
The standard is either to put the GOs in a subscene(seems like least work per GO), or to add ConvertToEntity on each GO
rn I'm adding the ConvertToEntity on the root GO once everything has been set up
I'm trying to reproduce that error on a fresh scene & prefabs
ok... where can I find a good guide on making my own authoring component for a dynamic buffer that has more than 1 variable
https://docs.unity3d.com/Packages/com.unity.entities@0.11/api/Unity.Entities.IConvertGameObjectToEntity.html
IConvertGameObjectToEntity lets you do whatever you want/need with the EntityManager
Not really a guide, but implement a MonoBehavior with the interface, and in the interface method you can do what you need, I've seen you around, so I assume you can take it from there
yup yup.
So it's the same pattern huh.
I thought for a sec that ibufferelementdata has a different way for authoring.
ty ty
Heyo,
Newbie here to DOTS.
I just went through the Unity DOTS Pong tutorial and I had a few questions.
I noticed that I was getting between 100 and 180 FPS for a basic pong game, when I can get 1000+ FPS using monobehavior.
When does a person decide that a game should use DOTS or plain mono when it comes to performance?
Then can DOTS be used for extremely intense mathematical calculations?
hey @lunar coral I haven't personally tried the pong tutorial but that sounds quite slow - is that in a build? You may or may not be aware the safety checks in the editor are very expensive so it's worth making sure they are disabled if looking at performance at all.
+1 to editor being very slow compared to full build
I don't think there's much where DOTS isn't faster - though there are two major caveats. The overhead of a job doing almost nothing is quite high (this is currently actively being optimised by Unity) so sometimes if you have many jobs/systems there can be a substantial overhead. The second caveat is just because a lot of dots makes things faster doesn't mean it's always best as there is very limited support for many features atm.
The only performance worthwhile to check is comparative - does it run faster with the code like this, or that? Which systems are using the most resources, compared to others? And so forth
It was in the editor only.
I will do a quick build of the game, with a FPS print out and compare.
I was looking at the Profiler as well and noticed that the PlayerLoop was running at 95.81ms.
It seems fairly long, which might the safety checks?
that sounds very high (and would lead to a lot less than 100fps - do you mean 9.5ms?) - please try a build and feel free to post a screenshot of the Timeline view of the profiler if it's still slower than you expect
Here's the current snippet, from in editor
You can get close to build performance by disabling the safety checks in editor -> Jobs->Leak Detection Off, Jobs -> Burst -> Disable Safety checks and also make sure Burst is enabled.
I guess you probably haven't got burst enabled.
wow
Disabling that made a massive difference
Down to 4.73ms.
Still only running at 178 FPS though, but no more spikes.
sounds more like it - that's with Burst enabled?
Yea, with Burst
What's taking the most time? Perhaps share another timeline screenshot? This time ideally with the main thread expanded and the jobs too.
physics step looks brutal - is this example up to date with latest packages do you know?
The tutorial was done in December.
Although I'm running the latest packages with it
Can anyone correct me and explain something regarding Hybrid Renderer V2 please? I'm still very much confused by it. (I'm back at it again)
I don't even know why pong would need physics.. :/
So, Hybrid Renderer V2 utilizes a neat concept by using a giant compute buffer on the GPU and uploading delta data via a special compute shader.
Yea, the example of this pong was done using 3D Physics with bouncy materials
This compute shader also calculates inverse of matricies if those are submitted, which further, theoretically, improves the bandwidth.
However, I'm confused to why it is needed in the first place. Isn't SRP Batcher quite the same in that it uses ten or so big buffers and updates those before rendering so each individual drawcall is cheap afterwards?
Why all this necessity for a single giant buffer and updates via a compute shader?
sorry @lunar coral I'm not familiar with physics at all - I'm not sure if a 3ms cost just for having it in the project is normal at this point or not. Safe to say it shouldn't take that long but as I said, they're actively working on optimising the cost of jobs atm. Do test it in a build though as some safety checks can't be disabled in editor.
I can't really understand that bit, because iirc SRP Batcher already solves this issue. Why can't HRV2 benefit from it?
Thanks @amber flicker
You've already helped a lot.
I've disabled some unnecessary rigidbodies and the FPS went up to 360.
Not even sure why that was in there in the first place.
Checking the build version out now
What is HRV2's "excuse" for not doing things the way unity does it with MeshRenderers and SRP Batcher?
Do you have jobdebugger enabled? That's a huge performance killer inside the editor.
I'll check in a bit.
I'm having a odd issue in my build.
The game runs fine in the editor but when I build it falls over on these lines in the GameManager:
blobAssetStore = new BlobAssetStore();
GameObjectConversionSettings settings = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, blobAssetStore);
ballEntityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(ballPrefab, settings);```
Interesting error in the stacktrace
InvalidOperationException: This should have been initialized by code gen
at Unity.Jobs.IJobBurstScheduableExtensions.Schedule[T] (T jobData, Unity.Jobs.JobHandle dependsOn)
typically, what I did was regenerate the burst interop
DOTS -> Regenerate Burst Interop
giving it a go
Still same issue unfortunately
Busy going through this Thread
https://forum.unity.com/threads/code-gen-related-invalidoperationexception-with-latest-packages.898742/
Anyone know what kind of advantage I get by using JobComponentSystem instead of a SystemBase?
By the naming convention, I feel like the new SystemBase should be the way to go always, but it does not seem like it.
SystemBase always preferred - ComponentSystem and JobComponentSystem will become obsolete in the future
But how would I go about doing jobs once only with a systemBase?
exactly the same way you are currently? Only the Dependency handling is slightly different.
yeah, not handling it currently, that is the problem π
if you're using JCS you must be handling it
I am only researching, so have not actually seen it in action yet.
Most examples I've seen have done foreach or just used filters, but most things are done more like an "update" method instead of only running once.
Although there are ways to avoid Update/ForEach my guess is you might be slightly falling into an oop trap here. What things are you imagining can only ever happen once? Are you worried about the performance of a system that's not running? Mostly, a system is there to manipulate data whenever data takes a certain form. By trying to run once, this is slightly working against the paradigm imo.
It's more like, the initial spawning of the voxel world I have only needs to be run once, I could potentially handle this in an update thing checking if there are "chunks" that are not close to the player and generate them accordingly.
In reality, I'd argue your spawning of a voxel world wants to happen e.g. when you load a level or when you change parameters. So have the system require e.g. a 'NeedsGeneration' tag and remove this tag once it's generated the world.
It's open world <.<;
the world is only limited by viewing distance
well.. "limited" the interractable world is only limited to what you can see, but if you walk further, it just automatically generate a new chunk based on the world generator, much like minecraft
sounds like it needs to run quite often then...
yep, every 32 meters roughly. to generate new chunks
well, only if they move further that is. When they are in a dungeon for example, it won't be needing to generate a lot of new things.
So your system requires an ICD with certain configuration let's say struct ChunkToGenerate : IComponentData { public float3 Coordinate; } or whatever you like. That system runs and at the end of frame ChunkToGenerate gets removed from the entity or the entity gets destroyed.
I'm not understanding it anymore.
This right here is the creation of that giant, persistent buffer and the creation of an uploader that uploads data to it via a CS.
Where exactly does SRP Batcher come into play? How does it help in the first place if we're already doing all the work from the HRV2's bursted code?
How does SRP Batcher help if it's HRV2 that keeps the bandwidth and upload rate under control?
How do these two work together at all?
I don't understand that at all, because SRP Batcher's duty is to create big buffers and render a ton of objects with a prepared buffer beforehand.
Here, in HRV2, we're setting up a single big buffer and delta-update it ourselves, which in turn accomplishes the same thing as SRP Batcher.
They seemingly don't interact with each other, but people (and the engine itself) claim that they do. I can't understand how.
And if indeed those two aren't used together in HRV2, then, reiterating, what is HRV2s "excuse" of not doing it with or like SRP Batcher (besides bandwidth reduction)?
I've noticed in some examples that you need to call AddJobHandleForProducer when you use the Entity Command Buffer. I have code that doesn't use it, and it works. Is this needed?
it is for determinism, you should do it all the time
ah thanks
There was a video about ECB in Unity's YT channel, you can check it out for more detail
Another question, when I instantiate my entity, it pops in: ``` var powerUpInstance = buffer.Instantiate(entityInQueryIndex, powerUp);
buffer.SetComponent(entityInQueryIndex, powerUpInstance, new Translation() { Value = powerUpPosition });```
is there a way to set the position when it is created?
wait... you're already doing it.
π
that's what I dont understand. the powerup shows up, then pops to the position
should I set the 4x4 matrix?
I just had a rubber ducky moment. I was using the wrong Command Buffer. I switched it to BeginSimulationEntityCommandBufferSystem. Which makes sense, as it took another frame to update the position. before I was using EndSimulationECBS....
I put my spawner in endsimulation
hmmm, maybe I should watch that YT video on ECB
the thing is... underneath ECB is just an entity manager.
so you're still creating sync points
btw, what yt vid is that on ECB?
Hello. I have a question. I am using a JSON file to spawn 2m objects as entities. The JSON file contains the transform data, and which sprite graphic it should be. My question is, what is the current preferred method for spawning/saving entities?
Do I do it at editor time, creating sub-scenes of GameObjects? Do I do it at run-time, and call something that creates a binary file of just the asset data?
Right now, I am just loading this giant JSON file and spawning my entites at runtime everytime, which is obviously slow and very memory intensive.
@deft stump I think this is the one that @opaque ledge was talking about: https://www.youtube.com/watch?v=SecJibpoTYw
Not all gameplay needs to happen immediately. In fact, there are many cases in which deferring commands may offer a better outcome β improved user experience, performance, etc. This session explores thinking about where deferred commands are needed and provides examples on how...
@unborn totem you might be able to load the json as an async job, in a different world
and then move the entities from that load-world into the main simulation one
@vagrant surge ultimately I wouldn't mind not having to load the JSON file, or only doing it once. The JSON file contains static information, basically.
I was under the impression that ECS had some way of saving entity information to disk to load very quickly
@prisma anchor oh shit the boring talk. I skipped this out
I just don't know what that way is.
I guess ultimately my question is, what is the proper way to spawn 2m entities who will always be in the same location and look the same.
I think, probably, spawning my entities at editor-time as GameObjects in many, many different sub-scenes and then loading those sub-scenes at runtime is the answer, but please correct me if I am wrong
Or maybe I use these things called BlobAssets? I don't know a whole lot about them.
yeah blobassets are good, but they are pretty complicated and convaluted
Why is this _densities.Dispose(); line getting called?
{
if (_densities.IsCreated)
{
_densities.Dispose();
}
}
Got it fixed, not really sure what was causing it but that was also getting called in my unit tests [TearDown] method so that could have been the cause
@unborn totem you're not wrong, SubScenes is the way they've talked about to load stuff fast from disk, everything in Editor in a subscene gets smushed into a blob that can (in theory) be easily/quickly loaded into the ECS world, the reason being that they've pre-processed it as much as possible and stored it close to the runtime format. BlobAssets are a way to have non-(entity/component) stuff stored/loaded in a sub-scene - so configs, static data, shared data, acceleration structures/ databases etc.
I don't suppose anyone knows if or how you can update a system after another system thats in a different group?
@pliant pike put it in the same group with UpdateAfter?
how do I figure out what group the system is in and will it work if one is a GameObjectConversionSystem
GameObjectConversionSystem only run in the conversion world(s)
thanks @mint iron
figured that might not be viable, I guess I could disableautocreation and create it a bit later on
@pliant pike what are you trying to do?
you can make new conversion systems if needed
is there some kind of method that fires when a GameObject gets turned into an Entity that I can put some custom code into?
ok, thanks
I'm just creating a Bezier with the GameObjectConversionSystem and another system requires that Bezier to exist when its OnRunning() method runs, which it doesn't
@unborn totem you could also make a custom Conversion system but thats more complex
looks like they changed the name to IConvertGameObjectToEntity at some point
i always get the names wrong π
thats definitily it
@pliant pike Can the 2nd system just wait untill the curve exists?
well that's what I'm trying to figure out how to do
do some sort of check like entitymanager.exists or has component?
actually I did but I guess I didn't do it properly
is it possible to call the OnStartRunning from the Onupdate of a system π€
i wouldnt
OnStartRunning is meant to do what it sounds like π will get confusing
well I just want to use it to set up some variables would be much easier if I could use it that way
sounds like the system only runs once?
maybe a singleton would work?
then you can do requireforupdate<SINGLETON>
the Onupdate needs to run more than once though
basic question how are you supposed to dispose of a Persistent nativearray, I've put dispose everywhere and none of it works?
Is it a class variable?
I've typically called Dispose in OnDestroy() if it is a class variable
I am disposing it in that but I still get the error π€
what's the error?
I think I may have just accidently created 500 odd nativearrays 
What are these duplicated checkboxes on Trigger and Raises Collision Events?
They behave super erratically
@warm panther thats weird, never seen checkboxes on those
you might have a editor tool or something adding those
fixed it disposed in Stoprunning() thanks
Sorta unlikely but I'll check.
@warm panther This is mine:
i have none of those extra checkboxes
you seem to have 1 for everything
Yeah so weird.
It has pretty much always done this (literally months), and now I have some odd rigidbody issues and am trying to get to the ground of all those mysteries.
And worse.
yea so my guess is you have something adding that first checkbox
in that first vid the 2nd checkbox matches what mine does
but the first seems to do nothing?
oh no it does do stuff
yea
just saw
i think you need to review all your propertydrawers and custom inspectors
does it happen on any other types?
No. However, the collision filter entries also behave very weirdly on nested prefabs.
unity version?
im on b7
I threw out the last thing that had any property drawers...
Yes, I think it's intentional
Do you use material property templates?
It seems like it allows to override.
First box is override.
2nd box is locally serialized value
when greyed out, it will show the material's value
that acually makes sense
clearly the ui needs some work to explain that
Ok so now I realize what it does.
Yeah a single tooltip would have saved me some worries.
But ok. THIS isn't the source of my weird bug that all of a sudden makes all my rigidbodies impossible to move (but if I give them a linearvelocity at start, see them go?)
You get trigger events if you check IsTrigger.
However, if IsTrigger = false, and RaisesCollisionEvents also = false, then you get no collision events. At least one part of a collision needs the flag.
Source: Struggled with collision event for an hour before I thought to open the adv. settings to see if -oh- Oh. Damn.
Can anyone get intellisense when debugging jobs? It seems that I lost that ability in VS
i actually never debug in unity sorry, tried the usual close and reopen?
also turned off burst?
Doing this should add Components to my entity when they get converted from a GameObject, correct?
{
dstManager.AddComponent<MainTexTiling>(entity);
dstManager.AddComponent<MainTexOffset>(entity);
float4 tiling = new float4(_Tiling.x, _Tiling.y, 0, 0);
float4 offset = new float4(_Offset.x, _Offset.y, 0, 0);
dstManager.SetComponentData(entity, new MainTexTiling {Value = tiling});
dstManager.SetComponentData(entity, new MainTexOffset {Value = offset});
}```
yea
_Tiling and _Offset are variables off-screen
you can change that to
AddComponentData
instead of add component and then set data
well for some reason, when I look at my entites they aren't there
you have IConvertGameObjectToEntity?
i'm not sure how to interpret this
showing you all entities that dont have those components
ah ok, thanks
theres 2 options for every component type in that tool
i cant run atm so cant show you mine
ok, i see the other one
yes, 0 of my components have MainTexTiling and/or MainTexOffset
ok, well, I mean, if I just select one, it also displays 0 results
when you say component, do you mean my script that has the Convert method?
oh, ok, well I know this works when spawning at run-time and adding it
i'm trying out the sub-scene method now
using Unity.Entities;
using Unity.Mathematics;
using Unity.Rendering;
namespace UnityEngine.Experimental.Rendering.ECS
{
[Serializable]
[MaterialProperty("_Tiling", MaterialPropertyFormat.Float4)]
public struct MainTexTiling : IComponentData
{
public float4 Value;
}
}```
so the components do their job, at least when not using sub-scenes
something I did notice is the Entity Debugger does show my components if I have the subscene "checked for editing"
aka, when LiveLink is active
but when I shut off LiveLink, the components all go away
honestly im not sure about subscenes
ive had so many issues with them i gave up on them
LiveLink on
LiveLink Off
let's see
Yea, it seems to happen when I converted to Entities.ForEach
looks like no
@prisma anchor its probably cause entities.foreach does a bunch of code gen
so your foreach dosnt get called
@unborn totem wtf?? i dont understand those sub scenes
thanks for the help Roycon, looks like I may take this one to the forums then
@unborn totem maybe try a conversion system?
@ocean tundra That's my assumption too
I've never written one of those before, this is all still brand new info for me
is that like what the BoidSchool example uses?
yea me too
my requirement was to convert at runtime so i ended up ruling out subscenes pretty quick
umm not sure sorry
Ah I see. BoidSchool spawns at runtime.
question about dynamic buffers.
when I do in DynamicBuffer<SomeBufferElementData>
does it pull in everything in that dynamic buffer?
my use case is, I have dynamic buffer that contains set data for my spawned Entity.
and all I really want is to get only the data of 1 index.
I imagine that it's quite excessive to use dyanmic buffer if does pull in the entire buffer.
@deft stump so thats a yes no maybe type question π
dammit XD
so yes = depends on your internal buffer capacity
i think those are all pulled into the cache with your entity
but if you over flow that capacity then its no
wont be pulled unless you access it [index]
so you could set your capacity real low
then it wont be in the cache
but with all this low level stuff, get it working,, then scale it
then start profiling it
so for my use case.
I can do InternalBufferCapacity(1)
since I only really need just the data of 1 from an X number of indexes
oh so that applys to the whole buffer
so if the buffer is 1 or smaller will be in the cache, else will be in memory
(those are the wrong words but i hope you get it)
so with an InternalBufferCapacity(1)
if I do in DynamicBuffer<SomeBufferElementData>
it only caches in... index 0, unless I say I want index 99. or something.
it only caches if the size is 1 or less
then its not cached
so you cant choose what index or anything
actually would be very usefull to be able to specify what indexes you want cached
you could probably do that with 2 dynamic buffers that are almost exactly the same, but you move items out of 1 into the other if size reaches your capacity
tho not sure if the perf gains will be worth it or not
So it seems like the Entities that get written to a Subscene's binary file may not go through that Convert method?
This is me turning LiveLink off and on, and my Convert method is simply changing the Entity name to the name it had when it was a GameObject
using UnityEngine;
public class ItemProxy : MonoBehaviour, IConvertGameObjectToEntity
{
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
dstManager.SetName(entity, gameObject.name);
}
}```
So if that doesn't even work, then adding components won't work either.
I found an obscure thing in an example project
apparently if you add this Attribute to the top of your IConvertGameObjectToEntity script, it (I am guessing) causes the cached entities to actually update using the Convert method?
[ConverterVersion("joe", 2)]
and everytime you make a change that you want the binary results of SubScene to accept, you increment the version number
it didn't work with SetName but it did work with adding IComponents
@unborn totem Nice job working it out
and Set name not working makes sense
as the world serialization (which i think sub scenes use) dosnt save names
and out of editor entity names dont even exist
Hm, I wonder if saving a subscene with 100,000 gameobjects just takes over 5 minutes, or if I am doing something wrong
@unborn totem na i would expect it to take a long time, look at megacity, everyone was complaining it was super slow to author
and they broke it all up into a bunch of smaller subscenes
I have 2,000,000 gameobjects I want to convert into entities, so I'll probably need a way to automate this π
sprites from an old MMO. I'm trying to import the Ultima Online map and item data into Unity
I haven't looked into the 2d renderer because the terrain is technically a 3d terrain
terrain isn't rendered here in my screenshot, just the sprites
DrawOrder is all messed up, but haven't tried to tackle that problem yet
looks cool tho
Thanks π
I loved UO's art style, and it's what got me into C# and eventually Unity about 10 years ago
trying to render the entire thing in ECS seemed like a good use-case and learning experience
hybrid entities?
@ocean tundra yup. Can be any prefab loaded via an identifier enum. So could be a particle system like in this case (or even a vfxgraph, or well anything else)
Now onto DoT and AoE π
i keep mucking with netcode instead π
I'm at a point where unity keeps dying on me whenever I try to start my scene. So close to calling it a day π
thats the worst
Oof, each of my subscenes with 100,000 GameObjects are like 270mb
Merp. I'm just a doofus. Forgot to call base.Oncreate() in my custom system so that a nativehashmap was uninitialized which would just nuke entire unity because it's somewhere in unsafe territory π
Would be nice if there was some Roslyn thing to yell at me when I forget it again π
======
Anyone knows if there there a nominal/measurable downside to grouping systems in SystemGroups? My OCD is hitting hard rn looking at an ever growing list of systems and not seeing any structure there :D
I'd imagine the scheduler might not be able to optimize as good as in a more flat system group structure, given additional constraints?
======
TIL: bytes in C# are 0-255 (and not -128 to 127) and sbyte exists π #nevermakeassumptions
bytes are commonly used for enum flags, and I have yet to see them used for anything other than enums (flags or otherwise)
I'm using bytes and bits lots more with DOTS
mainly for network type stuff to optmize on bandwidth
this was a good read for what you can do with simple types
@ocean tundra yeah similar for me, mostly to minimize component size, especially with enums
Hey All, If I have 2 worlds accessing the same NativeCollection (NativeList mainly) what do I need to do to make it safe?
I have world A producing messages and then world B reading and clearing them
World A updates first, followed by B
Effects Over Time are done, weeeeee π₯³
Notes:
- Red team
- Lower/Left corner: Fireball projectile with Damage Over Time on Impact
- Upper/Right corner: Arrow projectile with simple Damage on Impact
- Green team:
- Front: Melee attack
- Back: Heal (see little +++ effect), Explosion (Immediate aka no projectile) with Damage Over Time
how can i execute systembaseupdate on editor mode
i found about
ScriptBehaviourUpdateOrder.UpdatePlayerLoop(EditorWorld);
but i dont know why it still doesnt work
I have a Kinematic PhysicsBody that needs to follow another object (its "Owner")
I have many of those relationships (a couple dozen at any given time, possibly into the hundreds)
My copy system doesn't feel right:
[UpdateAfter(typeof(VesselControl))]
public class ShieldFollowing : SystemBase
{
protected override void OnUpdate()
{
Entities.WithAll<Shield>().ForEach(
(ref Owner owner, ref Translation translation, ref Rotation rotation, ref PhysicsVelocity velocity) =>
{
translation.Value = EntityManager.GetComponentData<Translation>(owner.entity).Value;
rotation.Value = EntityManager.GetComponentData<Rotation>(owner.entity).Value;
velocity.Angular = EntityManager.GetComponentData<PhysicsVelocity>(owner.entity).Angular;
velocity.Linear = EntityManager.GetComponentData<PhysicsVelocity>(owner.entity).Linear;
}
).WithoutBurst().Run();
}
}
(I'm copying the velocity along with the transform data because I think it is relevant for collisions)
How can I make this so it works without the sync point through EntityManager? ... I suppose I can use ComponentDataFromEntity<PhysicsVelocity> etc.
But I think I will need to allow it to concurrently read and write to the same CDFE, even though the entities affected are never the entities read?
I'd love to use/abuse the Parent/Child system for this, but I think PhysicsBodies in children will be unparented (at least it is automatically unparented at app start)
Parent/Child sys doesn't work ^^ But there is a chance I set the relationships up incorrectly.
Is there a way to add an existing scene as a SubScene?
Cdfe is your only real option @warm panther
I'm only aware of adding SubScenes through right-clicking the Hierarchy and adding them as "new" there
but I want to use editor scripts to populate a bunch of scenes and then add them as subscenes afterwards
Anyone here tried building and running a game with Unity 2019.4.0f1, Burst 1.3.1 and Entities 0.11.0?
Game runs fine in Editor but fails in the build.
Others seem to be having the same problem.
https://forum.unity.com/threads/code-gen-related-invalidoperationexception-with-latest-packages.898742
btw did you submit your project for them for this @lunar coral ?
It's their own DOTS Pong tutorial that's giving the issue.
well maybe you found some edge case in using it? anyway its probably your best bet in terms of getting a fix towards this
They seem to be aware of the issue on the thread, although they don't respond that often.
I was just curious how many others are experiencing this
i couldnt reproduce it when i got it and it was only in editor
I see
Weird, I'm getting it consistently.
Will try a new project as see what happens
anyway, submitting the project via bugreporter or uploading it somewhere and sending a link in the report would help them fix it faster, you can share the case number in the thread to get it to them faster
I'll try the bug reporter, and see what happens
Would be nice to get DOTS stable.
It looks very promising, but my first few attempts at it makes me think that it shouldn't be used in games that you want to take to production.
So it turns out a SubScene is just an empty GameObject with the SubScene component added to it.
Not yet at least, since it is still in it's V0.x
So I can add existing scenes by spawning empty GameObjects in my main scene, attaching a SubScene monobehaviour component to them, and then pointing it to my existing scene that I want to be a subscene
Does the job system offer considerable benefits over threads even without DOTS? I have some CPU intensive stuff that I want to get out of the main thread.
Which should I learn?
Jobs and Burst can be used separately even though they're a part of the stack.
So yes, they do offer considerable benefits.
for learning how to use them in your monobehaviour classes... hold up... lemme find the vid.
@surreal sable
here https://www.youtube.com/watch?v=vSxcZVfJn74
@deft stump Will check it out. Thanks.
anyway, submitting the project via bugreporter or uploading it somewhere and sending a link in the report would help them fix it faster, you can share the case number in the thread to get it to them faster
@safe lintel
I'm getting the exact same issue on a new project.
This line specifically it seems:
GameObjectConversionSettings settings = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, null);
I logged a bug report now with the Player.log and all my entire Assets folder.
So hopefully they get some time to look into this.
i believe null takes a blobasset right?
have you tried making a blobasset and then just disposing right after using that?
Yea, with the latest version it takes a blobasset, which still results in the same error
I see it's actually happening on:
manager = World.DefaultGameObjectInjectionWorld.EntityManager;
Resulting in:
System.InvalidOperationException: Reflection data was not set up by code generation
manager.Entities = Could not find a member `Entities` for `manager`
Ok so I got it working now.
Originally I had everything in the Awake() method, as per the Unity tutorial.
Out of interest I changed the Awake() to Start() and now it's working!
Seems like it's a timing issue
Might be that the EntityManager doesn't exist yet when the Awake() is running.
It's my best guess
I have a NativeHashMap<float3, int>.ParallelWriter
Is there any way I can get the value based on a key because it's a ParallelWriter?
I need to be able to both read and write to the hash map
Nevermind, got it fixed. I removed the .ParallelWriter part, and added [NativeDisableParallelForRestriction] to it.
Probably dumb question re generics:
public struct Bob<Transform>{} is valid but public struct Bob<UnityEngine.Transform> isn't? Am I being dumb? Is there a way to fully qualify the type if there's a conflict?
Cdfe is your only real option @warm panther
@safe lintel
Simplified system works. Wish I could parallelize it... but let's not prematurely optimize.
[UpdateAfter(typeof(VesselControl))]
public class ShieldFollowing : SystemBase
{
protected override void OnUpdate()
{
var transforms = GetComponentDataFromEntity<LocalToWorld>();
var velocities = GetComponentDataFromEntity<PhysicsVelocity>();
Entities.WithAll<Shield>().ForEach(
(Entity entity, ref Owner owner, ref Translation translation, ref Rotation rotation) =>
{
rotation.Value = transforms[owner.entity].Rotation;
translation.Value = transforms[owner.entity].Position;
var owner_vel = velocities[owner.entity];
velocities[entity] = owner_vel;
}
).Schedule();
}
}
I'll likely refactor this to a "Follow" ComponentData that contains the target (owner) when needed.
if you are syncing the translation and rotation is there really a need to sync the velocity too?
@amber flicker you can only define the T (variable name) in that place, what takes that T is defined by a where clause (Generic Type Constraint) https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters public struct MyThing<T> where T : Transform { }
Thanks - I realise I was indeed being dumb π¬ - time to take a break
man im jonesing for some new packages, feels like its been a while since something significant dropped
I'm looking forward to .enabled and job/scheduling optimisations but I hope there's more exciting stuff in the wings - editor & prefab improvements, some animation integration etc. Anything in particular you're hopeful for?
oh so many things
so animation might top it, with that I think i could make all my characters pure entities and leave a good chunk of monobehaviours behind
that recent physics talk mentioned some integration between animation and physics and they also said(on the forums) that they were reworking some of the api's
id really love to get some high level audio solution too but given whats been communicated I dont see anything new happening there for some time, same with navmesh/pathfinding
yea.. best to keep expectations low π¬
oh they are π
If I am using a MonoBehaviour to pass Serialized information to an Entity using the Convert method, do I have to use the Convert and Inject Game Object Conversion Mode of the ConvertToEntity script?
and is there some drawback to using Convert and Inject Game Object vs Convert and Destroy ??
basically at runtime your monobehaviour and gameobject dont exist if you use destroy
so do you need it at runtime? if yes then use inject, if no use destroy(assuming all your desired data is converted)
I should also mention I am using SubScenes
well if its in a subscene it will be destroyed when a subscene is recreated
ok, so the Conversion Mode doesn't really matter for SubScenes
pretty much
as far as drawbacks are concerned
is there anything special I need to do to make a build that has SubScenes work?
it's just a desktop build in Windows that I am attempting
use the new build package/s
ok, so there is some special steps
cant use the old builtin(file >build project)
where are the new build packages?
i believe the official examples repo should have somewhat updated uses of the build packages but its Platforms, and for windows desktop im also using Platforms Desktop & Platforms Windows
ok, thanks
i did notice that project but skipped over it
man I can't wait until there is a nice way to alter the kMaxGPUPersistentInstanceDataSize value in Hybrid Renderer V2
unless I am doing something wrong, I can only render a few hundred thousand entities before it fills up
and going in and editing code in a Package...well Unity likes to overwrite that stuff whenever it feels like it
heh a non buggy version of hybridrendererv2 is also something im looking forward to
not sure I can tell what is a bug and what isn't at this stage
I'm just happy I can finally change material properties without ruining the chunking system
Hey All, If I have 2 worlds accessing the same NativeCollection (NativeList mainly) what do I need to do to make it safe?
I have world A producing messages and then world B reading and clearing them
World A updates first, followed by B
I'm starting to think i should use a Queue instead, then anything in World A uses the concurrent version to write to the queue?
I realized that my Monobehaviour scripts are no longer working after converting to Entities.
Is there an equivalent I must use?
I tried doing it in jobs, but I can't get direct access to the game camera that way.
@lunar coral How are you converting? most conversion ways strip MonoBehaviours
Using the ConvertToEntity on a Prefab and spawning it via the EnityManager
But the prefab has a monobehaviour script attached, which no longer functions
the convert to entity has 2 modes, you need a specific one to keep the gameobject/monobehaviour around
Ahh I see
ConvertAndDestory and ConvertAndInjectGameObject
yup that 2nd one
π
but if you can you should move things out of the monobehaviour
Any suggestions on what to use instead?
I only started with all this stuff yesterday π
as much in Components and Systems as you can
but currently visual type stuff (particle effects, sounds, vfx, timeline, camera stuff) all still needs to be in old gameobject world
but the less gameobjects you have the more performance you have
also depends on what you want to make
Cool, I'll have a look at what is out there.
I am guessing collision/trigger detection are all still in the monobehaviour world?
The Unity Physics package has DOTS physics
Think also about which thinks can be converted to entities without needing other entities - or vice versea, things which number few and have few links to entities. These are, respectively, good to convert and good to leave.
Cool
I'll keep all those in mind
Thanks
Well, what's easy and hard to convert is kinda hard to tell until you play around some. If you have a monobehavior project, I encourage you to jobify heavy-ish code, but don't make converting that your first DOST project - though, recreating parts of it from the basics can be helpful as a "real case"
Theres a great vid somewhere of a guy using DOTS just for bullets in his game
which shows how to use DOTS in a existing project for slow/limited parts
I've already played around some and did some tests, with really good results.
My currently challenge is, if I have 100,000 Entities each having to reach with the camera in some way, it seems like a I'm in a pickle.
Cause I can't get reference to the camera within the job.
I'm currently just playing with limitations.
I was trying to get them to move towards the camera, react differently if they're in front or behind the camera.
cool so all you need for that is camera pos and direction? you can get those via camera.main before you schedule the job and pass them in
ideally you want to grab the direct data, not just camera, as any class's that you try to pass into jobs will give you a error, but data like vectors (struct) will be fine
I wonder if there's a different way to get the camera though, cause Camera.main is quite tough on the system isn't it?
But I'll check it out quick
yea its not great
does a lookup via tag i think
but its quick to get started
then at some point you could have it read from a hybrid camera entity
or a camera singlton entity
could just cache the camera result
i dont know if you saw roycon but joachim mentioned something about taking how addressables works and implementing it in entities directly
for prefab lookups etc
Oooo where??
guessing it will be like a year before we see anything though π
yea
that hacky work around thing will do untill then
been using it tons and so far hasnt exploded
but im also not really touching my assets
instead all code and chaos atm
Hello, can somebody help me?, probably itβs something very simple but I cannot find a solution. I have a system with 2 jobs, the first one works with Schedule while the other with Run because some reference types. Both read & write a NativeArray and thatβs the problem, I cannot find a way to tell the second job to wait for the first other than jobHandle.Complete(). So my question is, what is the proper way to tell the 2nd job to wait for the first?
I think calling jobHandle.Complete() on the first job is the correct way
But it will have to complete all jobs on which job1 depends, isnβt that really bad?@toxic mural
Or maybe there is something Iβm missing
I guess it depends on how much job1 depends on
Hmmm, I was looking for a schedule(dependency) like but for Run(), like telling explicitly to job2 to wait for job1 without actually stoping everything else just for this
Because right now does not depends on a lot o jobs, but maybe later will
I dont think you can schedule with Run() since its main thread
I could be wrong though
So Run runs immediately?
Yeah, I think its like putting code in your Update(). It just gets executed
Does job2 actually read data from job1? Or it only depends on it because they write to the same container?
Because of the container
Oh then you can use a parallel writer I think
you Run() runs, writes to the container, then schedule your job1
Or not even a parallel writer, just move your job2 code so its above job1 and I think the local variable capture when the lambda is created will take care of the scheduling
Hmm, sounds good, Iβll try that. If it doesnβt work Iβll be here again haha. Thanks
Yeah I might be telling you wrong, Im not great at ECS but I think what you want might be easy
good luck
I also thought so, but its been like 30 minutes and no results so far haha
Hey 30 minutes for one success is a good deal
yeah its a never ending journey
Well, it looks like Run() is not exactly the same as putting code directly on update, because switching order gets the same error
Oh I understand now why job2 depends on job1
My guess is, since NativeList is a struct, when it gets passed into TimedRequestProgress, the changes (.Add) to requests is maybe not being "saved" or propagated
Im not sure if local variable capture applies to incoming parameters?
and anyway the copy of requests being passed to ExecuteRequests would be a copy of the original
I think there is no problem with the parameters and local capture, I had this system running correctly yesterday, that made me think that dependencies between both jobs were updated automatically. But suddenly it started to throw the error about the nativearray
Whats the error?
InvalidOperationException: The previously scheduled job BaseInteractionExecuterSystem:<>c__DisplayClass_INTERACTION_ANIMATION_DELAY_RUNNER writes to the NativeArray <>c__DisplayClass_INTERACTION_ANIMATION_DELAY_RUNNER.timedRequests. You are trying to schedule a new job BaseInteractionExecuterSystem:<>c__DisplayClass_INTERACTION_ANIMATION_DELAY_RUNNER, which writes to the same NativeArray (via <>c__DisplayClass_INTERACTION_ANIMATION_DELAY_RUNNER.timedRequests).
I wonder if you need the Dependency = handle, if you're already calling handle.Complete()
Oh that wasnβt really in my code, I was testing things and didnβt delete it when taking the screenshot
Just ignore that Dependency = handle line
I wonder if its how you're creating the TimedRequests list
or maybe you need to use AsDeferredJobArray()
I dont know man, sorry
My guess would be its how you're passing the native lists as arguments to functions
Let me try with the jobs directly in the update, just to be sure haha
I dont know man, sorry
@toxic mural haha donβt worry, If I donβt find anything today Iβll leave the handle.complete() for now
Let me try with the jobs directly in the update, just to be sure haha
itβs the same
has anyone here made builds with a project that uses Subscenes?
Yea
Do I have to do something to manually load SubScenes in a build?
It seems like the Auto Load Scene option for the SubScene Component doesn't work
Did you make that build with the new buildtools?
so, I don't really know where to learn how to do that. I discovered the the Empty Build Configuration asset, but anytime I press Build it fails
Did you download the Platforms package for the platform you use?
if you're talking about the old build system, yes
then I don't know what you mean
I've tried googling for info on the new buildtools but came up with nothing
What results do you get when you search for platforms inside your package manager?
After that you get a new option under Assets/Create/Build/
thanks for getting me on track
No problem, i had a hard time as well
There's very little documentation out there for that
@north bay to build with my SubScenes, do I have to do them here in the Build Config?
I hope not, because I have 200 SubScenes π
I'm pretty sure you have to
Oh nice
oof, my subscenes folder is 5GB total, haha
