#archived-dots
1 messages ยท Page 157 of 1
I do have gravity, and friction
if you drop it onto the ground does it keep doign that?
also set in the inspector, on physics body and physics shape, respectively
they are both a few decimal points above the surface. theyre dropping a tiny bit at the start of the video
if I increase the height, the result is the same
im very curious as to what is going on that causes that infinite lateral drift lol
hmmm thats very weird
because I was actually struggling to remove friction before lmao
are you adding it in code? its definitely a really easy property in the physics shape authoring component
the surface it collides with also has a body and shape right?
well, it has a shape, not a body
but friction is a property of the shape, and when it has no body its just treated as static
well damn i have no idea why it doesnt just stop
what happens
if you put the cube
INSIDE the ground
if it doesnt move then we can be sure its colliding properly
lol, if its in the ground it gets flung out
which is normal, im pretty sure. Ive never seen anything that clips just get stuck
you know, I wonder if it would work if the surface, rather than being flat, was, like, corrugated
because that's how it works in real life, I think. when moving in line, the "bumps" hit more of the surface thats moving laterally, whereas one moving in line would ride over all the bumps and only the front part of the ice skate would hit the bump
... how do physics materials work? would that help me here?
I don't know the first damn thing about them, but from the name alone it sounds relevant
Well you basically need a friction tensor that works similar to the inertia tensor.
you might get it to work well with the inertia tensor really.
Try it and set a higher y and z value, making it harder for the skate to turn sideways.
(it's in the mass distribution for your physics shape authoring)
You can also try wheelcolliders, but I don't know if these work in DOTS Physics yet.
can an inertia tensor be used with DOTS physics?
Oh that's interesting. You're saying that the forward momentum would try to be converted to angular momentum, and then with the inertial tensor the angular momentum would be diminished, so the effect is that it would slow down
Quick ? How do you change the size of a SharedStatic and reuse the key?
Example: You have a SharedStatic<Component>, and Component contains other SharedStatic. Later, as your design has been worked out, Component doesn't need SharedStatic data anymore, so you drop that. Now, the SharedStatic<Component> needs a new key. But how does Unity remember the old one? How do we get rid of that old junk?
well, in a couple of patches ago i changed some stuff in shared statics and when i press start Unity complained about shared static size being less or great (idk the exact error), so i simply restart the editor and it worked
Help - something is... waiting... in my prototype game. (2020.1 beta)
As in, CPU is locked to a suspicious 16.7 ms. Generally, it should be around 5 ms, and from ECS alone, around 5 ms. Profiler shows a significant waitstate. The frame rate used to be around 150-200 fps, now it's at 60 and drops into the 40s. Interestingly, it feels worse on the screen.
I think this came in with either VFX Graph or the newest Render Pipeline.
Maybe it's Odin inspector.
Not really though, something in the game is also waiting.
So I suspect it's SystemBase Job Dependencies.
add a GPU profiler
Profiler got some problems actually...
that makes the GPU profiling pretty unreliable But render thread is at 1.1ms ...
And in edit mode, I get exactly the frame rate I used to. I had a similar problem before, it went away between render pipeline updates.
When I had the issue before, the negative "saved by batching" figure was also there.
That seems to be a problem with the Hybrid Renderer V2
I'll try the 2020.2 alpha
But looking at that profiler output I posted at "not really", it seems clear that some dependency in my systems that live in simulationsystemsgroup causes this wait.
I hate ECS System Dependencies.
I would really like a "Postupdatecommands" type EntityCommandBuffer equivalent in SystemBase.
Maybe i don't understand the new "Dependency" property though.
It's not new at all. Just renaming. It works absolutely the same as it was at beginning of input deps of JobComponentSystem.
public class VesselFocusManagement : SystemBase
{
private EntityCommandBufferSystem _ecbs;
protected override void OnCreate()
{
_ecbs = World.GetOrCreateSystem<EndSimulationEntityCommandBufferSystem>();
}
protected override void OnUpdate()
{
var buffer = _ecbs.CreateCommandBuffer();
var targets = GetBufferFromEntity<EntityListElement<TagCameraTarget>>();
//Propagate UI focus to all vessel children that gained focus
Dependency = Entities
.WithChangeFilter<TagUIFocus>()
.WithNone<UntagUIFocus>()
.WithAll<TagPlayer, Vessel, TagUIFocus>()
.ForEach(
(Entity entity) =>
{
var cam_targets = targets[entity];
for (var i = 0; i < cam_targets.Length; i++)
{
buffer.AddComponent<TagUIFocus>(cam_targets[i]);
}
}
).Schedule(Dependency);
_ecbs.AddJobHandleForProducer(Dependency);
}
}
This is what a lot of my systems look like.
i suspect this fucks over the dependency, but they won't schedule unless I tell the ECBS to wait.
(slightly shortened so I could paste it here, it has one more .Schedule that also deals with the UntagUIFocus component)
Negative saved by batching it's known for SRP batcher. For profiling real batches with SRP batcher you should use script which Unity posted on forum (currently, definitely will be improved in future).
Well 2020.2 alpha has HALF the framerate, so change is good? ๐
This is HALF not because 2020.2 or 2020.1.
More over what is first error of list of your errors above
This EndSample errors it's just result of earlier error which prevent some loop finishing which should close profiler marker
Yes.
But there's none.
Let me turn on stack traces etc.
(the no camera target found is a controlled execution path one of my monobehaviours, no exception)
Stack traces was actually on in alpha, weird. I'll go back to beta. I was just switching to see if I accidentally used a package that required a future version (like using Hybrid V2 in Unity 2020.1 pre beta9)
This with Burst compilation disabled and and Full stack traces enabled? And Jobs Debugger enabled?
Let me turn off burst.
Project doesn't import without crashing now, even after reverting in version control system. Fml, I'll try to get it to load again.
Btw you can remove Dependency = and replace Schedule(Dependency) to Schedule(), Entities.ForEach and Job.WithCode will handle it automatically by codegen.
_ecbs.AddJobHandleForProducer(Dependency) will work the same even without Dependency = and Schedule(Dependency)
thanks
This system it's not what will run
Open DOTS compiler and look to what it will be compiled
This is why you can have magic like ForEach delegates, automatic Dependency etc. because it's just template for codegen
I turned on stack traces and the debugger and turned off burst compilation
No change in console output
It seems like its impossible to put a native container into another native container. I am trying to build a data structure for layers of tiles. Any idea how to do this: NativeArray<NativeHashMap<CellData, Entity>>?
Are empty systems costly for performance? i.e. systems where I may override OnCreateManager or OnCreate, but not really do any work in OnUpdate
@wary ibex I dont think so they should not be run at all if they dont have any entities to operate on
It seems like its impossible to put a native container into another native container. I am trying to build a data structure for layers of tiles. Any idea how to do this: NativeArray<NativeHashMap<CellData, Entity>>?
@pulsar jay you can use unsafe collections for that
Mhh will have a look at it. Although it sounds... unsafe? ๐ค
native collections use them under hood
Still struggling to decide if another data structure is even necessary or if I should query for the specific tile via entity queries somehow
Only difference is native collecttion wrappers have dispose sentinel and safety handle for tracking memory leaks and race conditions
I see. But I guess there is a reason they wount allow nesting native collections? I am afraid I will run into the exact problem they are trying to prevent with this restriction
Well with unsafe collections you shuld understand what you're doing ๐ This restrictions here for safety
(safety handle\dispose sentinel)
But about nesting problem here a bit different
do you have any good reading materials on unsafe collections?
Source code
ok I see ๐
About nesting itself - this is not safety restriction itself
But just native container restriction
It should contain only unmanaged data
But native containers itself contains managed fields, which prevents you for nest them in to each other ๐
But native containers itself contains managed fields, which prevents you for nest them in to each other ๐
@storm ravine Ahh, didnt know that. I thought it was unmanaged
And this managed thigs it's exactly what Unity using for leak detection tracking
For example class DisposeSentinel
This is managed, thus whole NativeArray (for example) struct will fail unmanaged check
thats goo to know thx ๐
I have one doubt about EntityCommandBuffer. Can I create it once (i.e. on OnCreate) and reuse it, or I am forced to create it every time? My problem is that it's used in methods that can be called thousands of times per frame
it seems from the code that once it's flushed it's self disposed
The normal pattern is
class SomeSystem : SystemBase {
private EntityCommandBufferSystem _ecbSystem;
void OnCreate(){
//Exchange type with whichever you need. Typically EndSimulation[ECBS]
_ecbSystem = World.GetOrCreateSystem<EntityCommandBufferSystem>();
}
void OnUpdate() {
//With .ToConcurrent if using .Schedule or .ScheduleParallel
ecb = _ecbSystem.CreateCommandBuffer();
Entities
.ForEach(/*...*/)
.Run();
//For .Schedule or .ScheduleParallel you need to use Dependency
Dependency = Entities
.ForEach(/*...*/)
.Schedule(Dependency); //Or similar overload for -Parallel
_ecbSystem.AddJobHandleForProducer(Dependency);
}
}
Okay, I am 99% sure my frame rate problem is some kind of dependency constellation that reaches into the next frame, causing effectively double or triple frames with a single render or something.
As soon as I stop rendering all my more complex entities, the framerate goes way up. If I render even one, the framerate tanks to < 60.
I can count the number of systems I have on two hands. So this shouldn't be so hard.
I wonder:
[UpdateBefore(typeof(ExecuteFire))]
What if both these systems (the one the attribute is on, and the other) both call AddJobHandleForProducer for their Dependency on the EndSimulationCommandBufferSystem?
And in fact, what do UpdateBefore and UpdateAfter even do, with systems that have their main workload sheduled in Jobs?
Simpler example: I need to run a system that copies a Translation and a PhysicsVelocity from another entity after it has been changed.
[UpdateInGroup(typeof(VesselSimulationGroup))]
[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();
}
}
[UpdateInGroup(typeof(VesselSimulationGroup))]
public class VesselControl : SystemBase
{
// ... update a bunch of PhysicsVelocities for a number of entities, n ~= 100
Entities.Foreach(blahblah).Schedule();
}
anything wrong with that?
[UpdateInGroup(typeof(SimulationSystemGroup))]
[UpdateBefore(typeof(BuildPhysicsWorld))]
public class VesselSimulationGroup : ComponentSystemGroup {}
ah forgot, that might be crucial info.
I think I'm doing this way wrong.
The normal pattern is
class SomeSystem : SystemBase { private EntityCommandBufferSystem _ecbSystem; void OnCreate(){ //Exchange type with whichever you need. Typically EndSimulation[ECBS] _ecbSystem = World.GetOrCreateSystem<EntityCommandBufferSystem>(); } void OnUpdate() { //With .ToConcurrent if using .Schedule or .ScheduleParallel ecb = _ecbSystem.CreateCommandBuffer(); Entities .ForEach(/*...*/) .Run(); //For .Schedule or .ScheduleParallel you need to use Dependency Dependency = Entities .ForEach(/*...*/) .Schedule(Dependency); //Or similar overload for -Parallel _ecbSystem.AddJobHandleForProducer(Dependency); } }
@tawdry tree yes. I understand that patterns are designed around the normality and not the exception, but in my case I need to use it inside a callback not an update. I thought maybe I can hold the ECB and update it every OnUpdate
even if the callbacks will not be called
In a callback? Then you've already broken from the ECS/DOTS patterns
What are you using callbacks for?
it's on entity add and remove, but it's not UECS
I understsand that ECS usually works with polling, in svelto the only exception is Add/Remove entities. I may change it one day to optimize it though
If it's not UECS, then you need to find an appropriate forum for whatever you're using
sure so you are saying that there never will be a case where it will be used inside a method that is not called from an Update
if you are sure about it, then fine ๐
anyway the holding it + update actually works
ECB are specifically made for using within Update, to buffer any changes until later, when they can all be replayed in an efficient manner
yes that doesn't mean that must be used from inside an Update tho
but I can accept that is the normal pattern
Changing entities outside the unity frame/game loop is already a bit sketch, but if you want to use ECB for that the pattern should be the same -store the _ System_, grab the ECB before each use
well you don't have to go much far to see this pattern broken. Physic ECS uses a lot of callback in forms of jobs
Those jobs are within the ECS system loop, though
ah but mine is too
that's not the problem, the problem is that the framework calls it, not the system
So it is ultimately called from an update method?
of course, where else?
but I call it once per entity removed, not once per tick
so in one tick it can be called hundreds of times
So whatever makes the callback should have one ECB it sends to all the other calls, then?
sure I understand your point
but the framework knows nothing about ECB in this case
I mean in an ideal sense -you only want to make one ECB per frame loop
Are you using some other framework together with UECS?
yes Svelto ๐
this works and I will go with it:
public void Remove(ref UECSPhysicsEntityStruct entityView, EGID egid)
{
_entityCommandBuffer.DestroyEntity(entityView.uecsEntity);
}
protected override void OnUpdate()
{
_entityCommandBuffer = _submissionEntitiesCommandBufferSystem.CreateCommandBuffer();
}
EntityCommandBuffer _entityCommandBuffer;
wait
I will need to re test it haha
but regardless I agree that I should remove this exception from the framework. It should be called once for all the entities added/remove. it's in my to-do list anyway. In any case I wanted to have the confirmation about the fact that it's better to have the ECB creation just once
thanks
How do I properly order the execution of SystemBase descendants (that .Schedule their workload?)
UpdateBefore and UpdateAfter seem somewhat meaningless in that context.
I'm currently fighting some kind of system dependency hell where I suspect I have a system that waits until the next frame for a dependency to finish.
this fucks up the profiler, making it impossible to find the actual culprit; among other things, and cuts my framerate down to 33%
Step one here would be to disable systems until you find the offender
Other than that, minimize synchronization points and dependencies as much as possible.
I disabled all of them.
I boiled it down to a single cube in a subscene
Cube is there: frame rate tanks
Cube is gone: framerate 180+
And what systems affect said cube?
However, the profiler issue remains with or without the cube, so... (there are some more entities, admittedly)
If I deactivate these, only the time they are listed with in the entity debugger gets deducted.
If I deactivate ALL systems in the entity debugger, the frame time still stays high
if I remove the cube (either from subscene or from main scene disabling ConvertToEntity), the frame rate stays high
If I remove the Meshrenderer, the speed is high.
Physics shape seems irrelevant.
damned hybrid renderer again
Well, there you go
Rebuilt the entire packages directory from scratch. Now the cube renders at 350 fps.
I could puke... this is my vacation, I want to work on my project not on unity's package dependency bull...
But my old friend "very slow entity conversion" is back.
Yay.
First time I enter play after bigger file changes (packages, or checking out a different Git branch) I tend to get somewhat longer load time.
I haven't had issues in my (admittedly rather simple) toybox project, but in another one that's constant.
Long time to get to play is one of the things which put me off from UE, too, so I would rather not have it.
usually it's 200 ms
except when it isn't.
then it's 20+ sec. this one didn't finish in 4 minutes.
Nice.
after a good start & end yesterday, today definitely took a turn for the worse.
well, I got my fps back up to 170 with a few hundred entities
Profiler still doesnt work though
Render seems healthy-ish (I remember getting over 1000 fps on this machine with 1 or 2 models like that)
but that was with a simpler camera stack.
framerate still drops in half when the game runs though. I still think there's the dependency problem with the systems.
So. QUESTION - how do I properly and deterministically Schedule() several SystemBase descendants so one runs when the other is done, and all of them need to finish within their System Group?
And each runs on every tick. (later on, I might want them to consume a Tick entity of sorts so i could pump them multiple times in one playerloop, or not at all, but for now, just once per frame is good)
Hi, i'm looking at the Animation package changelog, and it seems that they added an automatic Animator Conversion. Does somebody had test it ? I tried it, the conversion is working, but I don't know how to play an animation after converting it. I look at the samples, but it was not updated from 0.2 version.
Does somebody have feedback to give about this? (sorry for my bad english)
https://docs.unity3d.com/Packages/com.unity.animation@0.5/changelog/CHANGELOG.html
i also briefly did the same, but there seems to be no examples on how to actually trigger an animation.
So sad...
@spark glade maybe you tested the last version ? I saw on github that you played with the Animation package
@warm panther UpdateBefore and UpdateAfter - use only one per "link".
Consider making a dependency flowchart and see what actually needs to finish before others start. You can likely say that a set of systems need to finish before some other system, which in turn needs to finish before some others can run, etc. Simplify the graph where possible.
The earliest systems can use .Run() if they aren't too heavy.
Disable all systems, then turn on only one (and possibly dependencies) to do some basic profiling and see if anything is particularly heavy.
just some ideas off the top of my head - most likely you've created a bug with dependencies. (bug as in you caused it to do bad stuff, not "found" a bug)
Ultimately I want my gameplay simulation to be 100% deterministic. That means money can't be spent before it's been earned, collisions need to be resolved at the same time, etc.
I thought UpdateBefore starts the Update before the other system, but there's no way to tell it Completes before the other sys starts... or does it?
Is SystemBase more preferable than JobComponentSystem?
Definitely not deprecated in the version I'm using (which I think is the latest), but ECS is a bit confusing sometimes ๐
I dont get any warnings about it being deprecated
@spark glade maybe you tested the last version ? I saw on github that you played with the Animation package
@wanton apex I have not yet tried 0.5, mainly because the changelog didn't mention URP compatibility
Ok thank you, so I will wait for samples, it's look too much complicated for now
Can I modify a value of ISharedComponentData?
yeah
If you guys were to have an input component applied to thousands of entities, would you use a singleton or shared component data?
singleton
try to get away from shared component data as far as you can, they are not really for gameplay, i think they are more for advanced ECS stuff
having shared component data in your entities with different values actually split the chunk, which makes things go slower
why?
dont singletons destroy the benefits in cache line that we get in ECS while looping entities?
because.. thats what they do ๐
you get the singleton value in main thread to a local variable and use that in your job
techincally you might be right, but since that data will be used throught the job your hardware will properly cache it
@storm ravine can give you more info if you are really interested in it
i myself a just a random scrub
why did you mention shared component data with different values?
because of parallel jobs? so that if I change the value it wont be synchronous?
shared component datas with different values split your chunks
while having 'normal' ICD, wont
Purpose of SCD - filtering and grouping things.
well they are used for rendering meshes
@warm panther UpdateBefore and UpdateAfter should guarantee that the Dependency of the later system effectively "contains" the JobHandle of the former.
Using the .Schedule(JobHandle) overload means you can (and have to!) control the output JobHandle yourself.
Entities with same SCD will be divided to groups in chunks with same SCD hash code.
I want a good way to store the input for the current cursor position
This gif is just using regular components, so I have the same component value in 20k entities
but I have a natural repulse to the word singleton
@wary ibex WTF am I looking at here
Also, singleton entity sounds correct for storing the cursor position in an ECS manner
The singleton pattern, like any other, is merely a tool, and as long as you use it wisely it's not bad
Im glad you asked, I call it DETERMINISTIC REALTIME RECTILINEAR CONTROLLER ON A PLANAR ENVIRONMENT
thats pretty cool name
well they are used for rendering meshes
@wary ibex Yes because class ICD wasn't a thing at beginning and Material haven't blittable equivalent yet. And it used for rendering (also) for exact same purpose - grouping same render mesh to different chunks (with additional MaximumChunkCapacity(128)) for better packing data for batch render group.
What do you mean by class ICD?
class implementing IComponentData interface which can contain managed stuff (but without splitting entities to different chunks)
And of course only for main thread work
oh right, IComponentData
Would you mind telling me the difference between a class and a struct implementing ICD then? or is there a place I can read about this?
Why would it replace ISCD?
Class ICD can use managed datatypes in fields (so classes), struct ICD can only use blittable types (structs built from primitive types)
You cannot use class ICDs in bursted jobs.
is the data shared between entities in any way?
For rendering specifically, class ICD would let you reference Material and Mesh, which is the datatypes used by the renderer. Both of them are classes.
It is "shared" only so far as in grouping into chunks
one per chunk?
If you have four otherwise similar entities, but one of them have a different value in the ISCD, you will have two chunks, and the different one will be alone
One ISCD value can still have multiple chunks, but you will never have different ISCD values in one chunk
"value" is a keyword here, and can be either a reference (so any class) or a struct/primitive value
And changing the ISCD for one entity does not change other entities with a same-value ISCD.
heads-up new urp preview for those interested
I tried using a class ICD and it's null when I loop it ๐
nevermind, I had to initialise it because it's a class
This gif is just using regular components, so I have the same component value in 20k entities
@wary ibex why you even need store cursor position on every entity? Why not just pass cursor position to Job\ForEach?
Using a singleton you mean?
I am trying to go with class ICD now if it means only one component per chunk.
Would you mind telling me the difference between a class and a struct implementing ICD then? or is there a place I can read about this?
@wary ibex https://docs.unity3d.com/Packages/com.unity.entities@0.11/manual/component_data.html#icomponentdata
I am trying to go with class ICD now if it means only one component per chunk.
@wary ibex it doesn't mean that.
class ICD behave similar to struct ICD difference only storing managed things (and as result only for main thread processing)
Using a singleton you mean?
@wary ibex singleton entity, just direct value inside system, etc.
so for shared data, what should I do?
@wary ibex depends on what it's shared data
For cursor input using ISCD on entities - make no sense
just direct value inside system
not sure what you mean by this
in my case the cursor position is obtained by adding user input to a float2
For things like RenderMesh (same mesh\Material for group of entities) - make sense
Cursor input - not shared data in meaning of...well shared data despite it used by everyone ๐ cursor input similar to some input data for jobs, like delta time. You don't need store it on entities.
not sure what you mean by this
@wary ibex your system which moves cubes just read cursor position in OnUpdate and pass it in to job\ForEach as just raw value
If input processed by different system
Just write this input value to singleton entity
and use this entity in your system which move cubes through singleton entity
and then again just get raw value from this singleton entity and pass into job
sounds good, thanks a lot
just another question, about performance, if you know what's going on here: https://github.com/Unity-Technologies/EntityComponentSystemSamples/blob/master/UnityPhysicsSamples/Assets/Demos/6. Use Cases/CharacterController/Scripts/CharacterControllerOneToManyInputSystem.cs
they read the singleton data and pass that to a component which all character controllers have. I was wondering why they do that in this sample instead of reading the singleton in the character controller system directly. Is it for performance purposes?
This is the same as I described
They have input system
which process input and store in singletone
and then some consumer use that
it's just sample that's all
They can do that (for example) if you have part of objects which should have one target
then you select other group and move them to other target
all depends on use case
yep but they dont use it directly in the character controller, they pass it further to a component. I was wondering why they do that. Would accessing the singleton in the character controller system directly be more costly than doing it through CharacterControllerInternalData?
I am assuming it doesnt affect performance other than perhaps delaying input change, but they did it in this way for just modularity purposes?
Read again what I wrote ๐
It's just sample
There is no performance hit of using singleton data directly
alright, ty
an example of why you could want to do that is if you want AI to use the same character controllers, then you could have your player use actual input but have the AI have their input.movement etc be driven by their AI code
while still being able to use same controller code
Yeah I understand that I was just wondering if there were performance reasons in this sample
Not. And tbh this sample is bad sample at scale ๐ On small amount of controllers it's doesn't matter as it will be anyway only one chunk and not valuable cache miss (as there is just small amount of iterations). But when you'll have 1000s of controllers then ISCD can be suitable , BUT again, it depend on case and how this shared data using, as if all controllers just use same values for all of them every frame - using data from input singleton directly will be more performant and less cache wasteful.
Well, in my case I do have 1000s of controllers
But you have same input
every time
for all of them
Then why you even want to store input on all of them ๐
Of even on ISCD
It will be just unnecessary layer in-between
Is there a way to prevent the hybrid renderer from automatically converting MeshFilter and MeshRenderer?
is there a way to hide certain objects from a ConversionSystem?
yeah, there is stop script i think
like, "Entity Convert (Stop)"
supposedly that gameobject and its children wont be converted
But I still want to convert some of the components...
I specifically want the Hybrid renderer only to stop converting
everything else I want to convert properly. Is that even possible?
hmm, i dont think so, you could try to remove it after conversation
yeah, I guess it's not gonna work with the conversion systems
hmmm...
in the past there was this copyTransform proxy component
is there still something like that?
Is there some kind of system that automatically syncs entity to GO transform?
or should I write my own system that does it?
Write conversion system which will run in GameObjectAfterConversionGroup and in this place remove RenderMesh, RenderBounds etc.
Write conversion system which will run in
GameObjectAfterConversionGroupand in this place removeRenderMesh,RenderBoundsetc.
@storm ravine ah, that's fine. I decided to go a different way.
more importantly this:
in the past there was this copyTransform proxy component
is there still something like that?
Is there some kind of system that automatically syncs entity to GO transform?
or should I write my own system that does it?
It's still here, only Proxies removed. CopyTransfromToGameObject component still here and you can add it in your IConverGameObjectToEntity
should I add it as object or data?
or HybridComponent?
What's the difference between these 3 anyway?
first is for just adding, componentdata is adding + setting
I'll leave it for your own self-education๐ It works the same as before, look at source code for such type of questions ๐ (spoiler struct CopyTransformToGameObject : IComponentData)
duh. Not even docs. You send me to source code? ๐
But I think I got it from the spoiler.
that being said I wish this kind of things were clarified properly in the docs ><
Yes. It's preview, and if you wont to use source code for information....well DOTS will be hard for you ๐
You always can open docs and read API reference
like this
But just fall into definition in IDE - faster
thx teacher. Btw, regarding source code. Where can I find it?
do I need to dig into the packages folder in my ide/unity project window?
or is there a "comprehensive DOTS code compilation 2020"?
or is ctrl+clicking in my ide the commonly accepted way?
Ctrl + click fine (in Rider or VS with Resharper atleast)
But you always can open Packages folder in Project tab in Unity or in Ide in Packages or just directly in Library PackagesCache
I see
alright. Thanks for the info. I feel like I'm understanding that conversion workflow a bit more now.
Ah. one more question: I get this error in my custom conversion script:
InvalidOperationException: The entity does not exist
public void Convert( Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem )
{
conversionSystem.AddHybridComponent( animator );
dstManager.AddComponentObject( entity, animator.gameObject );
dstManager.AddComponentData( entity, new CopyTransformToGameObject() );
}
I assume it's because the entity doesn't exist at that point? How can I make sure that it exists?
Are you sure error points to this? To which exact row it points?
I couldn't find it pointing to my script
mostly points to conversion systems and other stuff too long to paste here.
InvalidOperationException: The entity does not exist
Unity.Entities.EntityComponentStore.AssertCanAddComponent (Unity.Entities.Entity entity, Unity.Entities.ComponentType componentType) (at Library/PackageCache/com.unity.entities@0.11.1-preview.4/Unity.Entities/EntityComponentStoreDebug.cs:301)
Unity.Entities.EntityDataAccess.AddComponent (Unity.Entities.Entity entity, Unity.Entities.ComponentType componentType) (at Library/PackageCache/com.unity.entities@0.11.1-preview.4/Unity.Entities/EntityDataAccess.cs:530)
Your system usually will be in a middle of stack trace
Which workflow you're using?
It's not a custom system though
Inject or Destroy?
lol convert and destroy I mean
sorry it's almost 4 am here, and I'm still trying to dig into ecs ><
guess I'll just drop that CopyTransformToGameObject charade and create my own system to update the transform each frame๐
It's not necessary as CopyTransformToGameObject works.
Well if you Convert And Destroy
What the point of CopyTransformToGameObject then
If GO will be destroyed
CopyTransformToGameObject suitable for Convert And Inject or if you manually create entity which will affect some GO transform.
I have this setup Paren GO with animator and some other components I don't want destroyed, child GO with convert and destroy and this custom converter component to link the animator in the entity.
And I wanted this entity to control the movement of my parent GO.
basically I want a character that is mostly controlled by ecs systems, but has an animated model that is synced to it's position. I wonder why it's so hard to achieve...
Maybe I'll just create a entity from scratch on the same object...
Your setup is wrong here a bit ๐
If you remove AddHybridComponent here
it will work
then how am I gonna access it from systems?
Or replace it to AddComponentObject
As AddHybridComponent is for things when you fully convert GO to entity with it's components
It will create hidden companion GO for storing MB components
but they wouldn't appear in hierarchy
and will behave "like" class (not struct) IComponentData with main thread restriction
AddComponentObject(animator) seems to work. But I still get the error.
I assume that's because I don't actually have an entity representation of the parent object...
Your setup a bit weird. Why just not use Convert And Inject then
because then I have 2 renderers. The hybrid one and the regular
And just clear RM
RM was typo
I guess I'll try that
tomorrow
btw, this seems to work to some degree, but the GO transform is not being updated:
public void Convert( Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem )
{
dstManager.AddComponentObject( entity, animator );
var e = dstManager.CreateEntity();
dstManager.AddComponentObject( e, animator.gameObject );
dstManager.AddComponentData( e, new Translation() );
dstManager.AddComponentData( e, new CopyTransformToGameObject() );
}
perhaps because of the animator...
Yes because CopyTransformToGameObject require to be on entity which is injected GO
makes sense
Anyhow. I've gotta sleep, but if you have any good advices to share, I'll read them in the morning! Thanks in advance!
Sirawat wrote good article for newcomers in conversion workflow
If you don't want to dig in to sources
read this
Last question
You want your GO stay alive only because of animator?
If yes then you should use Convert and Inject. If you don't want to remove RenderMesh just put your GO with animator\mesh renderer in to dummy parent with Convert and Inject and CopyTransformToGameObject
@willow plaza You could have CopyTransformToGameObject on the parent, and use a simple "MatchOtherEntityTransform" system to match position (and/or rotation/scale) with the child.
When is it advisable to use a DynamicBuffer vs. a FixedList in a ComponentData?
(space considerations aside)
@willow plaza i believe CopyTransformToGameObject requires a LocalToWorld, it doesnt directly use translation.
Translation, Rotation, Scale and all of those transform components are just for the user to use; the transform systems will then translate these value into the LTW/LTP matrices
@warm panther imo main thing is to convey intent
with a fixedlist you know it's going to be a fixed size and is always located in the component chunk
with dynamicbuffer you can still have it be in the chunk at a fixed size with buffercapacity, but you're able to go over this limit and then it'll automatically copy the array outside of the chunk
so basically dynamicbuffer can do more but just like with arrays vs lists, you could still use the simpler one if you know you're only going to use it for that
@storm ravine @tawdry tree @safe lintel thanks for the input.
@storm ravine and I already read that article through and through twice actually, although there were a few things I didn't understand due to the language. But as I grew to understand gameobject conversion more, I feel like I understand that article better too.
updated events package finally: https://github.com/jeffvella/UnityEcsEvents to latest unity package version. the example project still needs work though.
I have an entity in conversion world (created via createAdditionalEntity) that I'd like to find the matching of in the editor world. Anyone know the right way to go about this? There's an EntityGUID component but value seems to be per-gameobject not per entity. (Obviously I could add a component with a unique hash but I'd like to avoid that and have to think the mapping must exist somewhere)
wouldn't event conveyed by entities be super detrimental to ecs performance ?
because that could be alot of created/deleted entities
no its pretty damn fast. there are like 100 tests in there some perf tests comparing some pretty high volumes. Having said that i probably wouldn't use the MonoBehavior routing part for main gameplay just UI interaction.
Alright, here is the set up I ended up with. Seems to be the best solution out of the options I tried:
Parent GO has only Transform, ConvertToEntity with inject and a custom proxy component. The child GO carries all of the monobehaviour components that I don't want/can't be converted to entity.
This way only the transform, and the components that I specified are carried over to the entity version. No unnecessary clutter from the automatic conversion systems like RenderMesh and stuff.
Here's the very simple custom proxy script:
public class GameObjectRendererProxy : MonoBehaviour, IConvertGameObjectToEntity
{
[SerializeField] private Animator animator;
private void Start()
{
if (!animator)
animator = GetComponentInChildren<Animator>();
}
public void Convert( Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem )
{
dstManager.AddComponentData( entity, new CopyTransformToGameObject() );
///add mono components to access from systems
dstManager.AddComponentObject( entity, animator );
}
}
I wonder if everyone else is doing it the same way and it was something extremely simple that took me half a day to figure out? ๐
what is the general difference between Component and ComponentData
**okay nevermind all that that was a dumb question
a better question, can you add authoring components in code, or do you have to just duplicate all their logic? Id really like to programatically set up physicsbodies for entities when I add my custom authoring script, but the physicsbody set up internal logic is all tied up in the convert to entity logic and Id really rather not muck around with that.
Id prefer to just use the authoring component so that if I upgrade the unity physics or entities package and it changes the way the convert to entity process works it doesnt break everything :/
@tight blade you mean you want physicsbody to do its conversion and then you modify the resulting components?
I mean I want to set up the inputs to the physicsbody authoring component in code
edit: simplified
basically, Im setting up two objects which are attached to each other via a fixed joint, and I want to specify the combined mass of both of them and a ratio of mass between them (among other things), and have a script work out the rest without me having to manually set up all those things
mmm
not sure what that means but if you really want to, adding/modifying an authoring behaviour to the gameobject should work as long as it's before conversion
though if you're doing this at runtime then ideally you'd want to skip conversion altogether
how would I know it it was before conversion? is there like a "before convert" function I can override?
there's a beforeconversiongroup if you wanna do this in a system
@grand plover is this a dots question
ruuude
but yea still not sure if i understand right but i think skipping the whole authoring level would be better, all physicsbody really does is add a couple of basic components with given values
should be able to just modify those components directly
gotcha, so its basically "no, you have to duplicate the logic" if I want to do it at conversion time?
I mean that's a fine answer and at least I can resign myself to it knowing I looked into the alternative
not sure what logic you mean you'd be duplicating
@grand plover Keep it in the relevant channel and have some patience.
I actually havent looked up what is involved, I just know that they have changed the components that the physicsbody authoring component expands into a few times. If they were to change it in the future, my code is fragile and would not respond to that change, because rather than using the authoring component logic, I'm duplicating their current implementation of what the authoring component does with those inputs
if they added, for instance, a PhysicsIntertiaTensor component that is generated from the authoring component
well, if I used the authoring component that change would automatically apply when I upgraded
as opposed to duplicating the way they decompose the authoring component as of physics 0.4.0, entities 0.11.1
ah i see
again, is my life over if I have to accept some fragile code? no.
despite that i think trying to force using the authoring behaviour is still more trouble than worth when you could just add your own conversionsystem that runs after, and sets the component values to your liking
it'd work even if they change their authoring behaviour since it runs directly on the components, altho if they change those then yea
and physicsbody authoring doesn't do much, no fancy math, just adds a couple components
yeah. I mean just library wise, authoring components are basically wrappers around adding components. I just wish that wrapper was exposed to code
I can duplicate the current wrapper logic, if I must.
yea the convo earlier today about conversion was basically about that too i think, unity does an automatic conversion on meshrenderers if you're using hybrid renderer and i don't think you can just replace it with your own conversion or change the existing one
yeesh, man I cant even find where in the code they actually create or add these components. It seems split up all over the place
you can select in packages when you search
dunno how familiar you are with the conversion system but most of the time the authoring behaviour just contains data and the conversion system does the actual conversion, so you'd have to look at PhysicsBodyConversionSystem in this case
my exposure is just making monobehaviors with IConvertGameObjectToEntity
I know pretty much nothing else
yea that's the basic way
the other way is to make a conversionsystem that implements the IConvert so sometimes you can do stuff more efficiently if they're the same for all converted types
e.g. rather than each seperate monobehaviour doing its own expensive calculations despite being the same every time, it'd just be done once in the system and passed to each
makes sense. thanks, thats a very useful explanation starting point
where did you run that search, by the way?
https://discordapp.com/channels/489222168727519232/497874303463850004/730267503242248244
in project window
oh, nice! hey thanks for all the help
np
also protip if you go in preferences and tick generate csproj for Registry packages
under external tools
autocomplete and shit should actually work since otherwise visual studio just thinks you're opening a single standalone file at a time
and you get to F12 on any unity component that's in a package and directly jump to source with unity's comments and stuff intact unlike if you let vs decompile it
ohhh sick
Well this is a new one...
Parameter name: obj
at Unity.Entities.ManagedObjectRemap.RemapEntityReferences (System.Object& obj, Unity.Entities.EntityRemapUtility+EntityRemapInfo* entityRemapInfo) [0x00000] in <00000000000000000000000000000000>:0
at Unity.Entities.ManagedComponentStore.PatchEntities (Unity.Entities.Archetype* archetype, Unity.Entities.Chunk* chunk, System.Int32 entityCount, Unity.Entities.EntityRemapUtility+EntityRemapInfo* remapping) [0x00000] in <00000000000000000000000000000000>:0
at Unity.Entities.ManagedComponentStore.Playback (Unity.Entities.ManagedDeferredCommands& managedDeferredCommands) [0x00000] in <00000000000000000000000000000000>:0
at Unity.Entities.EntityDataAccess.FillSortedArchetypeArray (Unity.Entities.ComponentTypeInArchetype* dst, Unity.Entities.ComponentType* requiredComponents, System.Int32 count) [0x00000] in <00000000000000000000000000000000>:0
at Unity.Entities.Conversion.GameObjectConversionMappingSystem.CreateDstEntity (UnityEngine.Obj
ArgumentNullException: Value cannot be null.
Parameter name: obj
at Unity.Entities.ManagedObjectRemap.RemapEntityReferences (System.Object& obj, Unity.Entities.EntityRemapUtility+EntityRemapInfo* entityRemapInfo) [0x00000] in <00000000000000000000000000000000>:0
at Unity.Entities.ManagedComponentStore.PatchEntities (Unity.Entities.Archetype* archetype, Unity.Entities.Chunk* chunk, System.Int32 entityCount, Unity.Entities.EntityRemapUtility+EntityRemapInfo* remapping) [0x00000] in <00000000000000000000000000000000>:0
at Unity.Entities.ManagedComponentStore.Playback (Unity.Entities.ManagedDeferredCommands& managedDeferredCommands) [0x00000] in <00000000000000000000000000000000>:0
at Unity.Entities.EntityDataAccess.FillSortedArchetypeArray (Unity.Entities.ComponentTypeInArchetype* dst, Unity.Entities.ComponentType* requiredComponents, System.Int32 count) [0x00000] in <00000000000000000000000000000000>:0
at Unity.Entities.ComponentSystemBase.HasSingleton[T] () [0x00000] in <000000000000000000000000
Error when loading 'AsyncLoadSceneJob(jar:file:///data/app/com.legioncommander-wHk8pzUNPbviiUMywse5ag==/base.apk!/assets/SubScenes/987d636b4216f478daa2ad6112bccebc.0.entities)': System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Unity.Entities.ManagedComponentStore.PatchEntities (Unity.Entities.Archetype* archetype, Unity.Entities.Chunk* chunk, System.Int32 entityCount, Unity.Entities.EntityRemapUtility+EntityRemapInfo* remapping) [0x00000] in <00000000000000000000000000000000>:0
at Unity.Entities.ManagedComponentStore.Playback (Unity.Entities.ManagedDeferredCommands& managedDeferredCommands) [0x00000] in <00000000000000000000000000000000>:0
at Unity.Entities.EntityManager+EntityManagerDebug..ctor (Unity.Entities.EntityManager entityManager) [0x00000] in <00000000000000000000000000000000>:0
at Unity.Entities.EntityManager+EntityManagerDebug..ctor (Unity.Entities.EntityManager entityManager) [0x00000] in <00000000000000000000000000000000>:0
at Unity.Scenes.SceneSectio
on "com.unity.entities": "0.11.0-preview.7"
Anyone seen something like this before?
It's a relatively simple subscene
Works in the editor, crashes on Android
something about build settings
i never did subscene stuff, but in order to include them in your builds you have to do extra stuff
check platforms package doc
alright, well glad you figured it out ๐
Issue was my "mainmenu subscene" had a light in it.
which is an actual error in 0.11 I guess (was fine in โ0.6)
and that (naturally) leaves ecs in a fucked up state when loading subsequent scenes
hmm, how can it have light and your subscene can work in editor ? i thought lights arent supported yet in subscenes
Where would I usually put "helper" functions in ECS. For example in the case of my grid CellToWorld(int2 cell)
ah, dang it...
Should it be part of a system?
If it's used across multiple systems I put those things into Util classes.
Like GridUtils?
I usually have these kinds of methods a lot. But maybe its because im still thinking to object oriented.
I think you're fine
so I guess I would always have to pass the grid into each method then
it feels like a slight drawback to me especially to replace properties like that:
public Vector3 Up
{
get { return Grid.Swizzle(this.CellSwizzle, Vector3.forward); }
}
With sth like:
public static GetUpVector(Grid grid) ...
I don't have a lot of context, but you can still do stuff liek this:
public struct GridThingy : IComponentData {
public int CellSwizzle;
public float3 Up {
get { return GridUtils.Swizzle(this.CellSwizzle, Vector3.forward); }
}
}
I guess its more about how it should be in ECS
Sure can I still add properties to a grid component but should I? I could even add the CellToWorld method to it
But I think that would contradict the separation of data and logic
Just trying to figure out if there are any "standards" yet. Good to know you use Util classes. Would be interesting if others have the same approach
Anyone had any success with integrating navmesh or any other pathfinding system? I was trying to get this package to work, but I keep on getting errors, possibly because of version differences...
https://openupm.com/packages/com.reese.nav/
"Write your own" (C) EIZENHORN
hahah I guess I'll have to do that. Although I don't feel confident at all...
Thereโs actually a good thread on the forums fairly recently on this
When I see some packages on github I feel like it's a completely different level from me. What's with all that technical and complex vocabulary... ><
Still stuck on getting a reference to an entity (via CreateAdditionalEntity) in the Editor world upon conversion. Anyone tackled this?
This is a system to gather user input and save it in a singleton. But it saves the state directly, given the input, instead of just the input, which is the calculated position of the cursor (it's not the mouse cursor, it's just a 3d position).
I don't like this approach of getting the singleton just to increment the position value, so is it better to store the current position in this system instead? Or is this fine?
(ignore the 1st assignment there, it should just be Entity singleton;)
ehh its fine, GetComponent isn't free but its probably insignificant here, if the system time is getting above 0.05 then maybe investigate, otherwise move on.
thanks!
so platforms 0.6.0-preview 1 has has some breaking changes huh
There's a new platforms package? What's new?
I just spent like 2 hours trying to fix some weird lag I didn't have before with my Jobs but then realized it was because I had turned off Burst Compilation
๐
is anyone here is actually using dspgraph for their audio in something more complex than just a test project?
was too low level stuff for me, so no for me
yeah mrfragger, we need to wait for next entities package
i doubt it, last i tried dspgraph it was half broken, seemed like an extreme alpha.
I'm having a bit of a problem with transform scaling and RenderMesh. If I leave my transform scale unchanged (1,1,1), the mesh does not seem to render at all. And the collider is not matching the mesh. I tried scaling the mesh (vertices * scale) and leaving the transform scale (1,1,1), but that didn't work either.
Has anyone ever had something similar happen?
collider is whole another thing, its a different component
I am aware, I tried setting the collider size the same as the transform scale but that didn't work as intended
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
Entity bar = World.EntityManager.CreateEntity(barArchetype);
float3 position = new float3(i * (barWidth + barDistance), 0, j * (barWidth + barDistance));
float3 scale = new float3(barWidth, 1, barWidth);
EntityManager.SetSharedComponentData(bar, new RenderMesh() {
mesh = barMesh,
material = barMaterial
});
EntityManager.SetComponentData(bar, new Translation() {
Value = position
});
EntityManager.SetComponentData(bar, new NonUniformScale() {
Value = scale
});
PhysicsCollider collider = new PhysicsCollider() {
Value = BoxCollider.Create(new BoxGeometry() {
Center = position,
Orientation = quaternion.identity,
Size = scale,
BevelRadius = 0.01f
})
};
EntityManager.SetComponentData(bar, collider);
...```
Can anyone find anything wrong here?
I just want the collider to align with the mesh
Alright, the problem was the Center of the collider is local and not in world space, obviously ๐
Heads up: There is a Compound collider if you want to reduce Entity count and still have a complex collider built from multiple basic shapes
@tawdry tree
whats faster
using 2 colliders
or using 1 collider and doing 1 collidercast only WHEN i need to check for the other collisions?
What's the use case here? Why are collision happening? Is this every frame? Are you doing it manually? Or letting the Physics package systems do it (as part of normal collisions)?
Also: Have you tried whichever is simplest?
I suggest doing that.
Then, if you test that and see that perf is unacceptable, only then should you look at more complex alternatives.
Most likely my advice will not change - go for whatever is the simplest.
1 collider for landing in a single lilypad and stopping it AND the frog
WHEN I land I do a collider cast
and sweep across the lane
This smells like premature optimization.
As in: Using resources to optimize before you know if you even need to optimize, and without
Resources here being mostly time, but also potentially creating worse(harder to maintain) code
so
like
either compaundcolliders
collidercast like im doing right now
does
will it be fastewr to use IsharedComponentData
does it make sense in this case?
is ISCD used for this?
my idea is just
have the same SCD for the whole lane
and when I land i can just change the SCD from the lilypad I landed
and at runtime I would stop all the other lilypads
but honestly I think doing the ColliderCast should eb the easiest way
For something this simple, with this few elements, do what makes for the simplest code.
makes sense, doesnt really matter because most likely im just gonna be fighting for probably nanoseconds here
since there are only l;ike 64 lilypads at any given time
Collidercast, or a couple of raycasts (center of frog + each "corner" of it's collision area") looks to be a good method for what you're doing
anyone figured out how to use the animation package yet ? ๐
Virtually no one is down to sink time into it without the examples ๐ข
There are examples though.
High! I heard around that one of the advantages of the DOTS is that the BURST compiler uses a lot of SIMDI instructions. Does that mean that if conditions in systems are going bog SIMDI instructions down?
@gusty comet dont worry unless you are heavily tryharding
I'm tryharding.
most of the simd burst uses is the AoS type of simd, where a vec4 parameter is basically a vec4 simd vector
as far as i know its basically just the autovectorizer from llvm
tho with hints so it can do its work well
Gotcha, guess I wont bother doing much branchless programming
going as far as to try branchless is just when you are going absolutely ham on the tryharding
making sure your chunks are well filled and your data is as minimal as you can get (to save bandwidth) is generally more important
also remember that many branches can be filtered at the archetype level
instead of having a bIsStatic, you can have a Static component and then filter for it
@gusty comet if your use case lets you use it, there's math.select which you can use if you need something more optimized
(on the new mathematics lib)
more info about this here on this post: https://forum.unity.com/threads/math-selects-performance-vs-inline-if.532282/#post-3505501
there is also the important distinction beetween uniform branches and vector ones
for vector ones, yeah def math.select
but uniform branches (scalar) might just be better to leave the branch predictor do its wokr
that's pretty much what the forum post said
I know Burst doesn't do exceptions yet, but try {} finally {} has been the defining feeling for my development work recently. ๐
for vector ones, yeah def math.select
@vagrant surge Is math.select a branchless select?
I suppose it is.
yes
Cool. ๐
If I have a FixedList64<float3> I can assume the data is packed tightly for SIMD purposes then? Is there a way to optimize a math.select over these elements (without indexing and thus likely recalculating the address for each element?)
Or is this premature musing about optimization possibilities...
I might expect Burst to optimize this for me at some point.
Because I realized I could drastically optimize my distance sorting calculations, which can at times be o(mnยฒ), with m averaging 5 to 10, and n being 1000-5000.
Can we really not use unity's Entities package outside of unity? that's so depressing
I think I'll need some help now, ppl. I'm getting this error message, but the suggestion seems to end abruptly leaving me with no solution...
InvalidOperationException: The previously scheduled job NavSurfaceSystem:<>c__DisplayClass_NavSurfaceTrackingJob reads from the NativeArray <>c__DisplayClass_NavSurfaceTrackingJob.JobData.physicsWorld.DynamicsWorld.m_MotionDatas. You are trying to schedule a new job Solver:ParallelApplyGravityAndCopyInputVelocitiesJob, which writes to the same NativeArray (via ParallelApplyGravityAndCopyInputVelocitiesJob.MotionDatas). To guarantee safety, you must include NavSurfaceSystem:<>c__DisplayClass_NavSurfaceTrackingJob as a dependency of t
What is "t"?
@wary ibex well, there are alternatives
you have flecs and entt for cpp which work amazing (flecs is very similar to unity ecs)
Entitas also works standalone for C#
other languages have others
remember that ecs is a very old architecture
unity just re-popularized it because PERFORMAAAAANCE
Anyone has a clue why this simple plane is not getting a RenderMesh when it's converted?
While the same simple cube does:
nvm, seems to be the Nav Surface authoring that does something...
Feelsgoodman.jpg
I see many people use LocalToWorld instead of Translation component. Is it more performant or something?
I understand that Translation is kind of a proxy to LTW, but how much overhead does it produce? Is it something I should worry about and change all of my code to use LocalToWorld instead?
I need the Forward vector. ๐
It has cached precalculated vectors and I also use it for the matrix transform for my fudged inertia tensors.
Ah. I thought Forward and co were in Translation? Strange...
Perhaps in the past...
@warm panther regarding your SIMD questions; its mostly based on the types used, if you use bool4, float4 int4 and your structure is set out linearly then there is a good chance it will be vectorized. Its best to isolate the code in question in a job that you can easily find in the burst inspector and read the ASM to figure out if its working. The docs have an example here https://docs.unity3d.com/Packages/com.unity.burst@1.3/manual/index.html#loop-vectorization and there is a more detailed presentation here https://www.slideshare.net/unity3d/intrinsics-lowlevel-engine-development-with-burst but you should be able to get the idea from comparing float3 arrays against float4 arrays. Also here's an example of mask/compress https://github.com/jeffvella/NativeOctree/blob/4032420b842dfc7808c0643d8d94c6a519f242e7/Assets/Octree/NativeOctreeRangeQuery.cs#L60
Or I just have false memories about Translate... ๐
Translation contains only one field, Value (float3)
Rotation contains only one field, Value (quaternion)
Yeah, I've jut checked it in the docs. But I just have that memory dated more than 1 year ago, that it had more fields...
From my memory it was like Transform just a struct...
qq everyone
how to use particals in ecs?
and animator
and other things wich not ecs
Are there any examples?
For example, I have a character. How can I make him an animation?
just add the animation component like a normal go.
once you convert it to ecs, and inspect its components, you'll see it holds a ref to the animation component.
???
Are there any examples?
@halcyon plume there aren't any decent examples of how to set it up. I had that problem myself. Took me several days to figure it out.
I ended up having a character base GO that is convert and injected to entity. As it's child I have all the non ecs gameobjects and components like animator and skinned mesh renderer. and authoring component on the character base injects copyTransform and animator as a componentObject into the entity to be controlled from systems.
It was really such a simple setup but I couldn't wrap my head how to do it and couldn't find any updated tutorials that demonstrate it.
Is there any good authoring workflow besides using conversion? I am using entities in the editor and would like to edit some of their values. ATM most of it is managed through a custom editor creating/updating/destroying the entities but this workflow does produce problems when mutliple custom editors are required
im confused, you're using entities for non-runtime scripts?
@willow plaza translation is local space(with a parent, acts same as ltw without a parent), localtoworld is the world space, the TransformSystem in the Entities docs contains a far better description than I can hope to explain
just a note, dynamic physics entities will use translation and rotation over localtoworld(also ignore other transform system components)
@mint iron exactly. As my tilemap data is loaded from scriptable objects anyway it does not make sense to construct it from gameobjects in edit mode and entitis only at runtime
can Unity.Mathematics.Random be used in jobs?
yes
thanks!
@pulsar jay interesting, i'm using the SubScene/LiveLink and its conversion for editor time setup that becomes BlobAsset in the SubScene at runtime.
is there any reason to create a native array of random values and pass them into a job vs calling random.next inside the job?
@mint iron & @pulsar jay I'm also doing stuff with livelink/edit-time. Current issue is trying to force conversion to run again for a particular gameobject. Irritatingly I think GameObjectConversionUtility.ConvertIncremental may do what I need (and used to) but I get an error that it expects the world to be empty... which I'm pretty sure is because Unity is automatically adding a 'WorldTime' entity to the conversion world. Either of you dealt with similar issues?
@amber flicker I did not know about that yet but it seems to be exactly what I was looking for
I got my tilemap editing workflow to work now. But atm I have the problem of DefaultGameObjectInjectionWorld being null at some point. Either at the beginning of playmoder or in between editing and playmode
Unity just crashes ๐
you probably want to avoid if you can - if you're working with SO's and it does what you need you may want to use the super handy but hard to find exists: conversionSystem.DeclareAssetDependency(gameObject, yourScriptableObject);
if you disable Burst and enable job debugger, you should get errors rather than crashes but yea - you need to call the lazy create method
DeclareAssetDependency sound interesting. Will definitely see if that helps. Thx
it will trigger a re-conversion whenever the SO updates is the idea (though in practice doesn't happen instantly for me)
yeah, its full of bugs i think at the moment, i have to be very careful about editor time state of BlobAssets because its trying to do all this black box magic voodoo. Unitys hacks on top of hacks to make it work.
I didnt even think of using conversion worflow for scriptable objects yet. ATM my workflow is Custom Editor using publically assigned scriptable object in script and constructing the tilemap
it's frustrating because EditorApplication.QueuePlayerLoopUpdate(); works most of the time for me (i.e. running my systems at edit time) but it doesn't seem to trigger the LinkedEntity stuff (which inherits from ComponentSystem) - if I focus away and back to Unity, conversion happens instantly ๐ฆ
oh geez.. I just found something ugly in the packages but I think it's what I need to replicate: ```static class EditorUpdateUtility
{
#if UNITY_EDITOR
public static bool DidRequest = false;
public static void EditModeQueuePlayerLoopUpdate()
{
if (!Application.isPlaying && !DidRequest)
{
DidRequest = true;
EditorApplication.QueuePlayerLoopUpdate();
EditorApplication.update += EditorUpdate;
}
}
static void EditorUpdate()
{
DidRequest = false;
EditorApplication.update -= EditorUpdate;
EditorApplication.QueuePlayerLoopUpdate();
}
#else
public static void EditModeQueuePlayerLoopUpdate() {}
#endif
}```
I am having a similar implementation
without the didrequest
@amber flicker Thx disabling burst helped preventing the crash. I still get a null reference exception with this though: World.DefaultGameObjectInjectionWorld.EntityManager
Any ideas?
if outside of subscenes you'll need DefaultWorldInitialization.DefaultLazyEditModeInitialize();
yeah I am using this. I needed it to work during edit time at all
It seems like OnEnable and OnDisable is triggered during playmode change and DefaultGameObjectInjectionWorld does not exist during this time
don't really understand but you can call a method e.g. OnEnable or whenever you want that checks if a cached version the World exists - if not set it equal the above in edit mode, or DefaultGameObjectInjectionWorld if Application.isPlaying
Playmode change does indeed trigger Disable, Enable, Disable, Enable on my Execute Always Monobehaviour. The middle 2 seem to be happening during the playmode switch where the world does not exist
beware of what happens with domain reload disabled too
yeah will keep that in mind. It might even work better without domain reload ๐
I have been using ExecuteAlways alot but I only just figured out that OnEnable/Disable is triggered one additional time between playmode change. It seems like the whole scene is initialized and then destroyed again
Just tested it with a simple script. Is this really intended? I dont see any reason for this behaviour
is there any reason to create a native array of random values and pass them into a job vs calling random.next inside the job?
@willow plaza here you can find my explanation "why" with proofs and examples https://forum.unity.com/threads/solved-gen-random-number-in-job-execute-causes-hang.779987
are you using dspgraph for diplomacy is not an option, eizenhorn?
probably not, probably something like "custom-graph"
No, we left audio at the end, and anyway it will be regular audio sources with our custom solution, as we don't need sound per unit or sort of. As we will build some smart merge tool which will combine areas of things and run for them 1-2-3 audio sources.
Like marching crowd can be represented as 3 audio sources with crowd march sounds mixed ๐
individual sound per unit could be kinda amazing or a total cacophony ๐
Yes this is why we'll write own solution ๐
InvalidOperationException: Process.query.__impl uses unsafe Pointers which is not allowed. Unsafe Pointers can lead to crashes and no safety against race conditions can be provided.```
Any ideas why I'm getting this?
it's thrown at line 51
I want to use IJob directly instead of Entities.ForEach because I think it will be much better to test the code this way. But I don't think I'm doing it right
replace EntityQuery in your Process job with the native array
basically get the native array from the query on the main thread, feed it into your job, use [DeallocateOnJobCompletion] with the nativearray
also not sure if you can do foreach, might need to make it a for loop
thanks, I'll try that
@willow plaza here you can find my explanation "why" with proofs and examples https://forum.unity.com/threads/solved-gen-random-number-in-job-execute-causes-hang.779987
@storm ravine true, also you won't be able to build your game if you have random.next inside your job
it doesnt warn you when just using the editor, only at build time
(honestly it should warn you the editor too)
Hey guys, any idea why EntityQuery.CopyFromComponentDataArray does not change chunk's component type change version? Is this the intended behavior?
Updating Translation through CopyFromComponentDataArray does not update LocalToWorld in my project, from what I see the reason is the Translation's change version didn't change (LTW system filters out unchanged Translation versions)
@storm ravine true, also you won't be able to build your game if you have random.next inside your job
@frigid needle That's wrong. It works in build just fine we using it since beginning. Even if you just pass Unity.Mathematics.Random directly to job and will use it like random.NextFloat it will work, just random will be the same on all threads as it will use the same initial seed without taking in to account already called steps (if you use it in parallel, which you can see in my sample in thread linked above). You can even create random inside job and it will work just fine (with the same problem of similar random on multiple threads (depends on seed) ). This random designed exactly for working inside jobs and burst.
And fast, ugly written, simple proof that it works.
public class Randomizer : SystemBase
{
[BurstCompile]
public struct SomeJobWithRandomOutside : IJob
{
public Random random;
public NativeArray<float> Result;
public void Execute()
{
Result[0] = random.NextFloat(0, 10f);
}
}
[BurstCompile]
public struct SomeJobWithRandomInside : IJob
{
public NativeArray<float> Result;
public void Execute()
{
var randomInsideJob = new Random( 345345345);
Result[0] = randomInsideJob.NextFloat(0, 10f);
}
}
protected override void OnUpdate()
{
if (RandomShower._inst == null)
return;
var randomOutsideJob = new Random(345345345);
var resultOutside = new NativeArray<float>(1, Allocator.TempJob);
new SomeJobWithRandomOutside()
{
random = randomOutsideJob,
Result = resultOutside
}.Schedule().Complete();
RandomShower._inst.createdOutsideJob.text = resultOutside[0].ToString();
resultOutside.Dispose();
var resultInside = new NativeArray<float>(1, Allocator.TempJob);
new SomeJobWithRandomInside()
{
Result = resultInside
}.Schedule().Complete();
RandomShower._inst.createdInsideJob.text = resultInside[0].ToString();
resultInside.Dispose();
}
}
How do I change a CollisionFilter on a Composite Collider?!
public CollisionFilter Filter
{
get => m_Header.Filter;
set
{
// Disallow changing the filter of composite types directly, since that is a combination of its children
if(m_Header.CollisionType == CollisionType.Convex)
{
m_Header.Version++;
m_Header.Filter = value;
}
}
}
The code to set it literally silently fails.
Really cost me some time.
I'd be fine if I could just set a groupindex (even on the parent).
How does Groupindex work for compound colliders anyhow?
To start a separate thread of conversation... is there any way to resize the individual panels on the entity debugger or is that behavior just broken in 0.4.0?
I "solved" my problem by making the collider not compound ๐ Which is annoying, because now I need two copy jobs of velocity and translation/rotation to kinematic bodies for the other components of my collider. Also I need to make my main collider "force unique", but I guess that's acceptable.
i think theres a memory leak lol
By Golly!
even with that, only %81 lol
Hi people, I have an issue, hope somebody can help. I have some 2 systems, one collect user input, and modifies a component, and the other has ChangeFilter for that component. The problem is that if the second one is executed with Schedule(), the ChangeFilter never stops being triggered, but if I execute it with Run(), it behaves as I expect. So my question is, Is this a bug or something? Which one is the actual expected behaviour?
say I have an entity with a Position component and a Velocity component. I want the Position component to be removed from the entity in 10 seconds, and the velocity component be removed in 5 seconds
how would I do that?
You could have a system that decrements a lifetime per frame, somethint like myPositionLifetimeComponent.lifetime -= deltaTime.
Then you have another (or the same system) that deletes it when myPositionLifetimeComponent.lifetime < 0
I use this pattern in many places, i.e. to remove the "coins/gems" loot that appears out of killed enemies: https://youtu.be/upDWz-AFOys?t=10
@spark glade how do you call such systems?
and say I have 8 components that have a lifetime, do I have to create a distinct lifetime component for each of those components with a distinct system with each of those lifetime components with duplicate system code 8 times? would there be a way to code a single lifetime component and attach it to any component that needs a lifetime?
if they are on same entity yeah
I've been looking through the physics docs and found this example where they use unsafe in onupdate definition. Anyone can a plain why?
using Unity.Entities;
using Unity.Transforms;
using Unity.Physics;
using Unity.Mathematics;
using UnityEngine;
public class AttractSystem : ComponentSystem
{
public float3 center;
public float maxDistanceSqrd;
public float strength;
protected override unsafe void OnUpdate()
{
Entities.ForEach(
( ref PhysicsVelocity velocity,
ref Translation position,
ref Rotation rotation) =>
{
float3 diff = center - position.Value;
float distSqrd = math.lengthsq(diff);
if (distSqrd < maxDistanceSqrd)
{
// Alter linear velocity
velocity.Linear += strength * (diff / math.sqrt(distSqrd));
}
});
}
};
https://docs.unity3d.com/Packages/com.unity.physics@0.4/manual/interacting_with_bodies.html
Also, how is that query(or how do you call it?) gonna work without .Run or .Schedule?
this is ComponentSystem, which is the oldest system i believe, it automatically runs on main thread and crates garbage and such, they should be only be used for debugging or prototyping (was said so in their older manual)
Ah, didn't notice that it's a ComponentSystem...
about unsafe, you use that for pointer stuff, i remember someone said if you remove unsafe it will not work properly even tho there wont be any compile error
I see. That might actually explain an issue I have atm...
But I don't see any pointers in that script... ๐ค Did they just add for no reason?
I'm trying to use an implementation of navmesh pathfinding in ecs, but when I use it with physics components I get tons of errors related to memory leak and lack of deallocation of a native array or something...
that's the package btw: https://github.com/reeseschultz/ReeseUnityDemos
Try enabling Jobs -> Leak Detection -> Full Stack Traces and dispose your arrays after they're done
The problem is that it's not my code, but the package that throws the error apparently.
Here're the first lines of the the first thrown error in that situation:
InvalidOperationException: The previously scheduled job NavSurfaceSystem:<>c__DisplayClass_NavSurfaceTrackingJob reads from the NativeArray <>c__DisplayClass_NavSurfaceTrackingJob.JobData.physicsWorld.DynamicsWorld.m_MotionDatas. You are trying to schedule a new job Solver:ParallelApplyGravityAndCopyInputVelocitiesJob, which writes to the same NativeArray (via ParallelApplyGravityAndCopyInputVelocitiesJob.MotionDatas). To guarantee safety, you must include NavSurfaceSystem:<>c__DisplayClass_NavSurfaceTrackingJob as a dependency of t
Unity.Jobs.LowLevel.Unsafe.JobsUtility.ScheduleParallelFor (Unity.Jobs.LowLevel.Unsafe.JobsUtility+JobScheduleParameters& parameters, System.Int32 arrayLength, System.Int32 innerloopBatchCount) (at <3dc54541a2574ac7826a004a212a4332>:0)
hm.. it's hard when the errors are in package
Yeah, I've extracted it to try and modify the package code, but I can't figure out what the problem is.
Here's the system with the job that appears in the error: https://hatebin.com/ccacrwskuh
Sorry to detract any conversation but I have a question
How would you make entities interact with one another in ECS?
If i have 2 armies of NPCs fighting each other, how would i get each individual to know where their target is, fire a projectile, and then process the hit?
There doesn't seem to be any functionality regarding pointing out a specific entity as far as I can tell for ECS, unless I'm missing something
Similar to Total War where the soldiers would pick a rival individual and engage in combat with them
Same is with regular architecture, except you'll let the systems handle the interactions.
First some kind of ai system chooses targets for each entity, then it issues a movement order or something, making the movement system kick in and move the entities towards their targets.
then an attack system will handle the attack
you just have to get the mindset of systems processing everything that's going on in the game
entities are just containers for components, which hold data.
hey, i want to check if a new item i want to pick up is already in my list. the list is a scriptableobject in a class -> list <class>
public bool Contains(List<Class> list,Class class) // SO in class -> list<class>
{
foreach(Class item in list)
{
if(class.item.itemname == item.name) // i cant reach the scripting object
{
return true;
}
}return false;
}```
cant reach the scripting object int this method. any ideas?
@willow plaza
I understand that but my question is more about pointing those targets
If I want entity A to attack the nearest enemy entity, how would it figure that out?
@mortal knot are you not in a wrong channel? It's dots related channel. ๐
wysystem recommended to put it in here
@sturdy wolf many ways, loop through all the entities and find the closest one, target the first entity that collides with a trigger collider or something. Completely depends on what you want your logic to be.
@mortal knot well, I guess he was wrong then. Unless you want to implement your inventory in dots related way. Should probably ask back in #๐ปโcode-beginner .
@sturdy wolf remember that in Entities.ForEach you can query the entity itself.
you can also query a separate native array of components or entities and check against it.
Ah, I get it now
Thanks
Hi,
I'm trying to implement a SphereCast utility function, but Unity crash every time i'm using it, so I don't know how to debug it. Does somebody can explain me the problem with my script?
PhysicsCategoryTags belongTo, PhysicsCategoryTags collideWith,
CollisionWorld collisionWorld,
out NativeList<ColliderCastHit> e)
{
var filter = new CollisionFilter()
{
BelongsTo = belongTo.Value,
CollidesWith = collideWith.Value,
GroupIndex = 0
};
SphereGeometry sphereGeometry = new SphereGeometry() { Center = float3.zero, Radius = radius };
BlobAssetReference<Collider> sphereCollider = SphereCollider.Create(sphereGeometry, filter);
ColliderCastInput input = new ColliderCastInput()
{
Collider = (Collider*)sphereCollider.GetUnsafePtr(),
Orientation = quaternion.identity,
Start = RayFrom,
End = RayTo
};
e = new NativeList<ColliderCastHit>(Allocator.TempJob);
ColliderCastHit hit = new ColliderCastHit();
bool haveHit = collisionWorld.CastCollider(input, ref e);
if (haveHit)
{
return true;
}
return false;
}```
And here this is where I call it. I'm new with SystemBase, and not sure about how I have to capture the NativeList Variable
protected override void OnUpdate()
{
ComponentDataFromEntity<LocalToWorld> ltw = GetComponentDataFromEntity<LocalToWorld>();
ComponentDataFromEntity<PlayerTagComponent> players = GetComponentDataFromEntity<PlayerTagComponent>();
var colWorld = collisionWorld;
NativeList<ColliderCastHit> hits = new NativeList<ColliderCastHit>(Allocator.TempJob);
var buffer = World.GetOrCreateSystem<EndPhysicsSimulationCommandBufferSystem>().CreateCommandBuffer();
Entities.
WithAll<IATagV2Component>().
WithNativeDisableParallelForRestriction(buffer).
WithNativeDisableParallelForRestriction(colWorld).
WithNativeDisableParallelForRestriction(hits).
WithReadOnly(ltw).
WithReadOnly(players).
ForEach((Entity entity, IAV2SensorComponent sensor, ref Translation tr, in IAV2AttackData attackData) =>
{
var e = Entity.Null;
RaycastECS.OverlapSphere(tr.Value, tr.Value, sensor.detectionRadius, new Unity.Physics.Authoring.PhysicsCategoryTags { Value = ~0u }, sensor.detectionPhysicsTag, colWorld, out hits);
}).Run();// WithBurst().ScheduleParallel();
hits.Dispose();
World.GetOrCreateSystem<EndPhysicsSimulationCommandBufferSystem>().AddJobHandleForProducer(this.Dependency);
}
You can have a Component "DisabledTagComponent", and exclude entities with this tag in your systems, so they don't affect them.
In your queries have a Entities.WithNone<DisabledTagComponent>().Foreach()=>
so anyone affected by that tag.
I can just remove the rendermesh component and make it seem like it's invisible.
alright
Ho your talking about rendering, I saw in documentation that Disable rendering is supported with the Hybrid Renderer V2, but not with the V1
it must be something to be add on runtime I guess...
Yes it is
@wanton apex instead of creating a collider every time you spherecast, try storing one in ICD somewhere and using that as to cast with
I will try this, thx for feedback
does anyone know how to set world rotation of an object? a lot of the answers are like 5 years old
set the localtoworld directly
@tight blade so
var ltw = new LocalToWorld
{
Value = float4x4.TRS(localToWorld.Position, myDesiredRotation, scale)
};
nice, okay awesome
let me try that
hmm, that seems to reset the location too
oh wait
I should be assigning it to the localToWorld.Value, not fully replacing the component
the entities documentation has an in depth explanation to how the transform system works
so if you have other components that feed into the localtoworld it might get overwritten
I don't, this is a very simplistic set up
I want to write my own movement system and physics system in dots to get more performance. I need to read the height of the terrain to know where to place my entities that walk on it, how would you read the height of terrain in dots?
im not familiar with terrain but assuming its regular unityengine object stuff, just need to access it on the main thread and then pass it into your job like using any other stuff that requires mainthread access
@safe lintel so, my assumption is that float4x4.TRS(localToWorld.Position, quaternion.identitiy, scale) would set that to have a world relative 0 rotation..., so it should face directly upward... would that be right?
eh I guess that depends what the how the model is setup
so hum i was using IJobForEach to run a job on a background thread but it is now deprecated, i searched a bit online but haven't found a clear example telling me how to rewrite this job with an up-to-date syntax...
the job looks like
namespace Systems {
public class Movement : JobComponentSystem {
private struct MovementJob: IJobForEach<Moving, PhysicsVelocity, Rotation> {
public void Execute(ref Moving moving, ref PhysicsVelocity velocity, ref Rotation rotation) {
// stuff to move the moving
}
}
protected override JobHandle OnUpdate(JobHandle inputDeps) {
MovementJob job = new MovementJob();
return job.Schedule(this, inputDeps);
}
}
}```
so yeah if someone has a clue i'd be grateful to know
the new API uses Entities.ForEach
indeed i'm starting to read that, what i'm wondering now is among the bazillions of system class there is which should i use ?
the doc is not always clear about that :(
Like SystemBase vs JobComponentSystem for example
it seems to me that they are completely interchangeable but there has to be strong and weak points right ?
You're supposed to just use SystemBase now. for everything.
Thanks, so I would do something like this for example ?
namespace Systems {
public class Movement : SystemBase {
protected override void OnUpdate() {
Entities.ForEach(
(ref Moving moving, ref PhysicsVelocity velocity, ref Rotation rotation) => {
// stuff to move the moving
}
).ScheduleParallel();
}
}
}
Would you guys mind terribly if I re asked my question from above? I've been working at this for hours and its really bumming me out. I'm trying to, in a system, reset an object's rotation so that it is world relative 0 (so I want to re-align the entity's translation axes with the world translation axes). This page about how LocalToWorld and rotation interact is really dense....
My situation should be the simplest case, too. I only have Rotation, LocalToWorld, and Translation components. Everything is uniform scale -- in fact the scale is 1,1,1
I just cant figure this out
@tight blade did the setting ltw directly suggestion not work?
so, I set it as follows, and this did not work:
localToWorld.Value = float4x4.TRS(localToWorld.Position, quaternion.identity, new float3(1));
wait...
- are you using
reffor the ltw? - unity's transform system might overwrite it, make sure you update it after
TransformSystemGroup
ohhh thats interesting. I thought that that dependency would have been managed automatically by specifying ltw as a ref... no wait, thats if I specified it as "in".
how would I control that? Can I tag it with [UpdateAfter(typeof(TransformSystemGroup))] or something?
yea that should work
also yea unity handles job dependencies if you use entities.foreach, but if your system schedules first, then the jobsystem will execute yours first
I'm about to get into ECS, and it seems like im also getting into DOTS. Does anyone have any tips or precautions before I go in?
@balmy horizon check the pinned messages in this channel, and further down that list there's a link to the Copenhagen Unite youtube playlist which as a lot of good explanations in it (although some of the code itself will be out of date by now).
I think I've managed it @hollow sorrel
its kind of hard to tell, but it seems to be holding steady
good to hear ๐
๐ ๐
Thats one major issue with dots in general. The constant rehashing of things utterly fractured the tutorial and documentation space
Heck even the official documentation is not up to date in some parts
Picture an octopus entity connected to 8 arm entities by physics joints. If two octopus arms are close enough together, they can link together to hold a gun and pull the trigger. There can be many octopuses in the world. I'm designing a way to detect, in a system, whether or not two arms are close enough together for this condition to be true. For purposes of this discussion, assume octopuses may varying number of limbs, but usually around 8.
I have 3 candidate ideas -
-
use the common entityID (the octopus ID) as a shared component value. Then iterate through chunks and check proximity only against other arms in the same chunk, since the arms with the same octopus id would be in the same chunk (right?) Possible cons: lots of octpodes mean pretty small chunks. and in theory isnt it possible that an octopus's arms could be split onto multiple chunks?
-
Use the octopus ID as a shared component value, then when the system updates, run queries with .SetFilter to select the arms for each octupus and load them into arrays. then I guess do some processing against those arrays? I dont really know what iteration mechanisms I have at my disposal in this case.
-
give the octopus entity a buffer of children. then during the octopus system, walk through each of those children using the entity manager to get their translation components. if any are found to be close enough together, use the entity manager to walk to those children and somehow indicate that this condition is true so that during the arm system that fact can be used. This seems the least performant/ most random access.. although perhaps has the least unknowns
I guess a 4th option might involve raycasts during the ForEach(Arm) system
I think raycasts on that large a scale might be far too expensive
yeah, same.
spatial hashmap like what boids uses?
and by boids i mean the boids sample in the ecs samples repo
oh yeah? I haven't seen it. I'll go take a look now. "spatial hashmap" sounds like an interesting concept
its like you organize your world into a 3d grid, and then operate on entities on a per cell level, so they dont end up being compared to every single entity, just neighbours(or neighbors in neighboring cells)
I see. So that sounds kind of halfway towards the chunk batching approach. cell batching would be better, but doesnt it still leave the risk that octopus arms would land in different batches? thats such a small risk I doubt it matters
weird
the colors of my shadergraphed material is turning white instead of blue when instanciating
aaah
crap it's the directional light
Oh man, I tried updating from 0.9.0-preview.6 to 0.11.1-preview.4 (and physics 0.3.2-preview to 0.4.0-preview.5 ) and everything went to shit again :/
My positioning system doesn't work anymore because now it seems to be overwritten by physics ๐ค
As soon as I disable ExportPhysicsWorld things work again.
Ok, so what's the correct approach to have a system that modifies PhysicsVelocity? Do I have to UpdateBefore(BuildPhysicsWorld) aa well as BuildPhysicsWorld.AddInputDependency(Dependency) ?
@spark glade afaik you shouldn't need the addinputdependency but yea physicsvelocity should be modified before buildphysicsworld
Yeah, maybe the dependency isn't needed because they'd both touch physicsvelocity and that should be done automagically.
It probably shouldn't hurt though ๐
So I'm more and more running into the issue of my systems (which I group by "game state") needing such kind of dependencies. I.e. i have two game states. Say:
- Before the Battle starts (things like drag'n'drop units on the battlefield)
- Battle has started (the actual battle simulation)
So I set up two groups
- SimulationSystemGroup (the build in one)
- GameSetupSimulationSystemGroup (custom)
- GameRuntimeSimulationSystemGroup (custom)
So now I have a system in GameRuntimeSimulationSystemGroup than needs to UpdateBefore say BuildPhysicsWorld.
Since they aren't in the same group, the dependency resolver will ignore it.
Looks something like this:
This attribute can only order systems that are children of the same ComponentSystemGroup.
Make sure that both systems are in the same parent group with [UpdateInGroup(typeof(Game.Systems.Simulation.Runtime.GameRuntimeSimulationSystemGroup)].```
Which makes perfect sense.
Now... how would I add this necessary depdencency?
you'd just do updatebefore(gameruntimesimulationsystemgroup)
update before/after the entire group
Have the entire group UpdateBefore(BuildPhysicsWorld) doesn't seem like a good solution.
ah i see what you mean
yeah it'll work I guess
But I can easily see a case where I need some dependency chain that will be impossible
you'd need to have two groups if you need a before and after
sure you could do that as well
yea i suppose that's up to you
i think if the main assumption is that these groups run somewhat isolated from eachother then should be fine grouping them like this
if you expect to need a lot of after and before physics you could always split them up into two more groups
things would start to get tricky if you got stuff in gamesetup relying on gameruntime and other way around at same time but when is that the case
setup and runtime are 100% isolated
But in the end I think the only real solution, possibly also performance wise, would be to flatten it out completely.
Flat seems to be better than having like 10 systems:
GameSetupBeforeBuildPhysicsSimulationSystemGroup
GameSetupAfterBuildPhysicsButBeforeExportPhysicsSimulationSystemGroup
....
GameSetupAfterPhysicsSimulationSystemGroup
๐
yea that's true
btw AfterBuildPhysicsButBeforeExport i know this was just example but i don't think there is a reason to ever actually do this
buildphysicsworld = read componentdata and convert to internal simulation format
stepphysicsworld = update simulationdata
exportphysicsworld = write simulationdata back to componentdata
so generally you'd either want before build or after export
hm true
But that's just physics. I see this getting cancerous and hard to debug.
So a simple System that just sets fetches a bunch of systems with GetOrCreateSystem in OnCreate and sets .Enabled whenever I want feels easier.
Btw, just confirmed that a [UpdateBefore(typeof(BuildPhysicsWorld))] on GameSetupSimulationSystemGroup is the one liner stop gap fix ๐
Hey. Is DOTS visual scripting (https://forum.unity.com/threads/dots-visual-scripting-6th-experimental-drop.795807/) dropped? I can't find it package manager
nope. it's still l very much in alpha that's why you can't find it in PM.
@deft stump so it was there and then removed? Because I see some dudes in YouTube creating tutorials with it?
it was never there in the first place as of yet.
they manually installed it by modifying the manifest.json file
@deft stump OK, so whatever. I do need production ready tech, so this is not relevant anyway
ยฏ_(ใ)_/ยฏ
But it's damn promising > https://www.youtube.com/watch?v=nqt3p1n342A
ECS + Visual Scripting = Bomb
Damn. Trying to understand navmesh pathfinding dots implementation drives me crazy ><
DOTS is being in development now for an eternity, can they just nail it with all the resources they have
Lazy devs ๐
as far as I understand, navmesh with dots is basically doing it yourself
pretty odd to see that after 2 years of ecs development tbh
makes me wonder if we would have a stable ecs if unity had developed games instead of demos
2 years is a pretty significant amount of time imho
as far as I understand, navmesh with dots is basically doing it yourself
@gusty comet wdym?
iirc existing navmesh solution(s) doesn't work for dots since they are single threaded, not jobified
can't remember if navmesh generation is jobified, but pathfinding certainly wasn't
Didn't they expose the low level navmesh stuff?
all of the dots examples use low level pathfinding, some aren't even pathfinding at all
its there, but if you want to find a path with a system, you are on your own
there are community projects though, but they all have their own caveats
They have exposed the jobified part and there are a few implementations on github
those implementations are super basic, thats what I'm saying
I'm currenly trying out this one: https://github.com/reeseschultz/ReeseUnityDemos
their nordeous demo can't even be called pathfinding
thats community stuff, not unity official stuff
I've never said anything about official stuff. It builds on the stuff that they exposed though.
It's based on the NavMeshQuery (https://docs.unity3d.com/ScriptReference/Experimental.AI.NavMeshQuery.html).
I'm not even sure what you are saying at this point, all I said was, if you want dots + navmesh, you have to do it yourself, which is basically what you are doing by having trouble understanding the community solutions since there is no proper solution by the unity devs
anyway, thats all I'm gonna say
Well, that's what I was saying myself as well ๐
any tips for logging / inspecting intermediate values from jobs/ non main thread code?
oh nice! let me go look into that
huh... onUpdate supposedly runs on the main thread but I'm not even seeing this go to the console
query is stored in onCreate. maybe ill print in there..
okay, log statements in the onCreate run, but log statements in the onUpdate do not
okay weird. The system doesnt even show up in the entity debugger, even though the statement in the onCreate is being logged
ah hah! you can check "show inactive systems"
can someone explain me what's the point of:
Dependency = JobHandle.CombineDependencies( Dependency, buildPhysicsWorld.GetOutputDependency() );
if the system is set to update after physics systems (I think):
[UpdateAfter(typeof(BuildPhysicsWorld))]
is it because some job is not guaranteed to be complete when the system has finished updating?
Correct
Alright! I feel like I'm getting smarter. ๐
I'm trying to install all the necessary packages for ECS, but the Hybrid Renderer package is throwing me errors
@balmy horizon are trying to set up project tiny?
Yes, but I don't intend to build for mobile platforms, I'm just installing it because I think I'm supposed to
Is tiny necessary?
no, tiny is a separate package that is built upon ecs.
So I don't have to use tiny at all if I'm just making something for desktop?
If you only need ecs you need to import the Entities package and it will download most of the dependencies automatically.
try to start a new project and import only the Entities package.
No errors this time, just 2 warnings. Thank you
How to reproduce: 1. Open the attached "Repro.zip" project 2. Open Windows Task Manager -> Notice the CPU usage 3. Open Entity De...
HIGH CPU USAGE WHEN ENTITY DEBUGGER WINDOW IS OPEN
Please vote
Ok it's really dumb but for some reason I can't find it: how do i round a float3 ?
@mighty whale math.round(new float3(1.2, 1.5, 6.6))
nevermind i finally found it
lol
thanks
for some reason the doc was not loading
and i couldn't ctrl+f it
I know how it is
what is a good way to access, say, a textmeshpro from an ECS system?
in order to edit the text
im having a bit of trouble using ui and ecs because im pretty new to the whole thing
same way you would access stuff in a monob
just put it in OnCreate to not nuke your performance
i was hoping i could declare a public variable in the system where i could dragdrop the textmeshpro object into ๐ @zinc plinth
can you explain about the OnCreate a bit more?
you can't ref it in editor, you have to search for it with normal gameobject code
maybe create a mono with a static field and save it from there ?
ah and that's what I should put in the oncreate?
you should learn a bit of unity before starting dots
yea im probably trying to bite more than i can chew ๐ฆ
so i got a system that calls something that has to create entity, it seems i need to use this https://docs.unity3d.com/Packages/com.unity.entities@0.10/manual/entity_command_buffer.html
however I cannot access the "World" outside my system, is there any way to acquire the entity command buffer properly outside of a system ?
why can't you access the world outside your system
I just mean that an instance of World is an attribute of SystemBase
and i think i need to grab an instance of world but idk maybe i can make a new one
i just want to know if there's any clean way to use entity command buffer outside of a system
uuuh it's complicated 
should be able to use ecb from outside a system but you're still gonna need a reference to it somehow
ok imma try to sum it up
yeah ok
mmmmh
ok thank you i'm going to think about changing the structure
is there an example of a 2d grid implementation in DOTS? I want to have a 2d spatial grid to organize my entities, each cell can contain any number of entities.
my first thought was, for every entity that is in cell coordinate (0,0), I will give them the tag Cell_0_0, so that I can query my entities for the tag Cell_0_0 to obtain all entities in this cell. but I don't think it's the right solution because I can't generate tag names.
if every entity that is in a same cell share a same tag and archtype, then all entities that belong to a cell should be next to each other in memory. but I can't generate tag names, so how would you do that otherwise
@odd ridge there's a billion different ways to implement 2d grids but as for your example, if you're looking to do it that way then it sounds like you want ISharedComponentData
for example you could have a GridPosition : ISharedComponentData that holds a int2 Value with its position, then everything with a different value will be grouped and put into its own chunk
all entities in same cell would be next to eachother in memory
My ExecuteInEditMode Scripts are enabled/disabled between playmode changes where the DefaultGameObjectInjectionWorld is null which throws a null reference exception. Anybody has an idea why this happens? Is this intentional? Any way to avoid it?
public class PlayModeTest : MonoBehaviour
{
public void OnEnable()
{
if(!Application.isPlaying)
DefaultWorldInitialization.DefaultLazyEditModeInitialize();
Debug.Log($"OnEnable World:
{World.DefaultGameObjectInjectionWorld?.Name}");
}
public void OnDisable()
{
Debug.Log($"OnDisable World:
{World.DefaultGameObjectInjectionWorld?.Name}");
}
}```
The output is this:
The OnEnable/Disable in the middle should not happen imho
are there examples using NativeBitArray ? I am mostly curious about how it could be used with special SIMD instructions
@hollow sorrel how else would you do it? what would be the best way
@pulsar jay You should probably add some brackets to that if statement
@odd ridge do not use shared components for grid coordinates
use a buffer on your primary grid entity and flatten your 2d array into 1d
tho that's only possible for a finite grid
I don't suppose anyone knows how a GameObjectConversionSystem works and runs, like does it require something in the scene to be referenced in it for it to run?
why, what's your usecase ? @pliant pike
if you're wanting to use ConvertGameObjectToEntityFields outside IConvertGameObjectToEntity, that's not possible
I'm trying to convert some scriptable objects into entity's
then you need to "convert" by hand using your own script
you have EntityManager available inside the main thread
- World.Default.... EntityManager
ok, I guess I'll have to use a monobehaviour then?
not necessarily, you can have a method in your so which have all your entity creation logic, and you can call it from whereever you like on the main thread
I'm using addresables to load them that part works at least
did you mean you can have a method in the scriptable object that converts it?
there's no conversion from SO to entity, you have to create the entity you want yourself
np