#archived-dots
1 messages ยท Page 221 of 1
Entities supports it under ScheduleParallel(), but it doesn't seem to exist for lambda jobs...
I can't seem to ever get an error by letting sequentially scheduled jobs access the same nativelist via reference, even if it has no starting size...
e.g., one job writes 10000 values to it, the second job can read it just fine
I wish there was some actual documentation on this stuff...
Seems odd, that's not the behaviour I remember. I'll do some testing on my own for a bit.
Also, no there is not. You have to implement an IJobFor in this case.
https://docs.unity3d.com/Packages/com.unity.entities@0.7/manual/ecs_job_withcode.html
Yeah, it's just all very awkward I guess. Since that would mean I can't use SystemBase.Dependency for automatic dependencies
You can use GetComponentDataFromEntity to get the component.
Stay on 2020 LTS. See:
https://forum.unity.com/threads/notice-on-dots-compatibility-with-unity-2021-1.1091800/
Using DOTS with ASMDEFs. I am using a class called BlobAssetStore, DOTS docs say that the class belongs to namespace: Unity.Entities.
I am referencing that assembly...but it's still giving me this error:
The type or namespace name 'BlobAssetStore' could not be found (are you missing a using directive or an assembly reference?)
Why?
According to IDE, the BlobAssetStore actually belongs to assembly Unity.Entities.Hybrid. However, it creates a conflict because if I add that to the ASMDEF, it will no longer error the BlobAssetStore, but it will begin to error for Translation. Is this a bug?
that sounds like a bug, I'd go ahead and report it
I will try that, thanks!
Did you also add references to hybrid rendering?
i am kinda struggling with disabling spawned entities
i go through childbuffer of converted prefab, and then i go through their childbuffer
and add disabled component accordingly
it works in 30% of cases
thsi is the prefab structure that im converting, so this is weird that it does not work completely
https://i.imgur.com/ARCDKlQ.png
I'm not super familiar with conversion but shouldn't each of those children get a Prefab tag already? And thus be "disabled" since they're marked as prefabs? Is there a reason you want to disable the prefab?
Fake 0 may have prefab tag but its children dont
Ok I understand now, some entities have even 3 layers of parents
so i replaced childbuffer loop with linkedentitygroup loop and it works now
is anyone familiar with Convert And Inject Game Object on ConverToEntity.cs ?
I am using hybrid ECS and this conversion type is neccesary for me, however, it only makes the parent gameobject an entity whereas I need the children to be entities as well. how can I achieve this without directly editing the package scripts?
similar issue here
https://forum.unity.com/threads/children-of-a-gameobject-not-acquiring-localtoworld-upon-conversion-to-entity.660820/
you can add localtoworld it should update automatically
or add convertandinjectGO to every child
didn't help
there's no entity to add this to, is what I mean
only the parent comes in as entity, no traces of children whatsoever
in entityDebugger your parent entity has no children?
no childbuffer/no linkedgroup
convertToEntity usually converts whole tree
getting caught up on dots, whats exactly going on?
still on 0.17? 0.18?
this is a depressing thread
https://forum.unity.com/threads/notice-on-dots-compatibility-with-unity-2021-1.1091800/
ah the follow ups are good
Yes I did. And like I said it created that conflict mentioned earlier. Turns out that the conflict was because I didnโt reference Entities.Transform once I did that it all worked. I am 2 days new to DOTS, so I apologize for the noob ness.
@crude sierra use conversionSystem.CreateAdditionalEntity(gameObject)
and then just manually make child entities with your needed components and also make a child buffer to store them
@low tangle yeah its annoying especially with regards to urp / uitk compatibility
two months ago: "0.18 is on the way" id really like to be a fly on the wall because seriously what is taking so long with these releases
yeah skimmed a few threads, seems like things are happening behind closed doors at least
I'm still perpetually stuck in a place where I cant use any SRP's
so I'm stuck on 2019 forever
whats uitk, that a new pipeline?
ah nvrm
UI toolkit
still used to calling it ui elements
yeah not sure if you know of it but subscenes dont work with uitk in 2020(but they are fixed in 2020.1&2), part of the recent announcement pain
I have a new project I'm working on and I decided I want to wrap my head around DOTS. So far, I like it, the concept. I know that since there is no convention set yet, that it's pretty much make your own way at this point. Is it right to assume the following?
For singleton (or very little quantity) of GameObjects, I will just use the regular OOP (MonoBehaviour) approach. But for objects that are going to be vast in quantity, where I might need to utilize an Object Pool and GPU Instancing for, I would then utilize the DOTS pattern.
[DisableAutoCreation] if you want to spawn it in yourself.
Otherwise I guess you could just put Enabled = false; in OnCreate.
anyone know a way of going about joints (hinges/etc) in unity physics?
Im looking at the demos but it looks like quite a bit of code and Im really not understanding after a few days of fiddling with it
galaxySystem.Enabled = true;
this doesnt enable OnUpdate which it disabled before
Hey everyone submissions are now open for the first game jam that you need to sleep at least 8 hours and show your game dev skills!
Is this not enough for you ^^ then we are inviting you to challenge the creator of Latios Framework (https://github.com/Dreaming381/Latios-Framework) with your own Unity DOTS Game!
Join the game jam this weekend: https://itch.io/jam/48-8-jam-2 and weโll see you there !!
Anyone know if there's a good way to call extern functions inside a job
you could make them into structs
I can turn an external function into a struct?
I've got data structure implemented in compiled native code
All the types associated with it are fully blittable
well that is if you can do it
But I read that you can't call native functions from a job
its all by data no refs
So you think I won't have any issues calling an extern function
From inside the job
well a job is like a closed box
everything you put into has to be declared in the scope that it is created in
That doesn't have anything to do with whether you can call functions from another dll
Guess I'll just have to give it a go for science
If anyone has done this I'd appreciate a ping
Anyone know how I can do a UnityWebRequest in SystemBase
Where did you read that? Calling native functions from Jobs/Burst should work fine as long as everything is blittable.
It was in the docs I was looking at
Example
Maybe it's old
I haven't tried it yet in 2021
I had a DLL that exposed some file writing stuff almost a year ago which I used from Burst/Jobs if I remember correctly
Otherwise FunctionPointers will definitely work. I don't think they are required tho
Ok cool
Well hopefully it just works
I have to do some unsafe memory pinning
Hopefully that doesn't mess with it
Otherwise I guess I'll just parallel.for
Memory pinning works just fine with burst and jobs
Sweet
I just tested it myself and I get a error when directly calling the native function.
Passing it through a function pointer works fine tho
[BurstCompile]
public class Externs
{
public delegate bool AnyPopupDelegate( );
[BurstCompile]
[MonoPInvokeCallbackAttribute(typeof(AnyPopupDelegate))]
[DllImport("user32.dll")]
public static extern bool AnyPopup();
}
[BurstCompile]
struct PopUpTest: IJob
{
public FunctionPointer<Externs.AnyPopupDelegate> AnyPopupPtr;
public void Execute( )
{
var result = AnyPopupPtr.Invoke( );
Debug.Log( $"{result}" );
}
}
var externBurstTest = new PopUpTest
{
AnyPopupPtr = BurstCompiler.CompileFunctionPointer<Externs.AnyPopupDelegate>( Externs.AnyPopup )
};
externBurstTest.Schedule( ).Complete( );
Ah ok
Yea I read something about this but it wasn't super clear
That helps alot
Ty @north bay
Can I use a traditional MonoBehaviour Rigidbody physics to interact with ECS physics? Even things like raycasting?
Is there a really comprehensive resource/guide/tutorial about DOTS pattern? Something that dives deeper than just the basic Data, Entity, System explanation. Something that explains how ECS Physics works as well as how to interact MonoBehaviour with ECS, etc?
i interact mono with dots via ecb
I interact mono via go.find oncreate and do stuff in onupdate w/o burst
BTW ive been getting this error A LOT (even after fixing it) in last few days, does anyone know what it could be... fixing this is really random and takes lot of time
maybe its related to crunch compression idk...
or addressables or burst
Is there a way to have a list / array of native collections in a job?
you could Unsafe versions of the collections UnsafeNativeDictionary, UnsafeNativeList etc.
do Linq statements work in jobs / burst on nativecollections?
nvm, you need a lambda function after all...
What is the reason something like NativeArray<NativeArray<int>> isn't allowed? Thread safety?
it's not blitable cause the inner arrays can have different sizes. I hate it
yeah it doesn't make sense to me either. I havn't heard a good explaination for it
There's a way to use them in jobs, but it wouldn't be burst-able
(e.g. NativeArray<int>[])
there's this: https://github.com/Dreaming381/Latios-Framework/blob/master/Documentation~/Core/README.md#collection-components
but I havn't tried it
but I guess that's for components, not jobs
it's still managed... hmmm I dunno sorry
no worries
If I run into any managed issues I just don't use burst, I feel like the automatic scheduling and dependencies are still useful
Anyone have experience with fixed-size buffers?
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/unsafe-code#fixed-size-buffers
I'm having an issue where they don't seem to be... accepting my data properly.. I'm wondering if it's an endianness problem or something?
Nvm it's probably just the usual terribleness of the Visual Studio debugger not supporting them ๐ฆ
Hey i have a question regarding archetypes
are they like arrays containing arrays of components
Has anyone experienced Gimbal Snapping when setting PhysicsVelocity.Angular?
Here is my code
velocity.Angular = Vector3.up * -(lookDelta * player.LookSensitivity * 0.05f);
And it works, but when it gets close to +X or -X (look direction), it kind of slows downs and then all of a sudden SNAPs to the other side. It's still rotating properly, but that snapping makes it feel tacky.
I constrained the physics rotation on X and Z axis, so only Y is affected. Is that why? If so, or not, how do I make for a smooth rotation while updating velocity.Angular value?
i have a question
if i want to implement threading using i jobs on my infinite terrain
on my struct that generates the mesh datat
do i add the ijobs interface
or
the ijobsparellelfor interface
IJob is one thread, IJobParallelFor is multiple threads. If you have a really heavy workload, the latter will be more useful
is their such thing as a native list
you will need to use Unity.Collections
Here is the API: https://docs.unity3d.com/Packages/com.unity.collections@0.0/api/Unity.Collections.NativeList-1.html
Unity.Collections doesn't show up as a namespace?
no
what i mean is
i can add using unity.collections
but
i cant add a native list
only a native array
did you add the collections package?
no
try that, i think list is only in the package
i cant find the package in unity registry
Oh, you will need to add it in the UPM
it's a hidden package
Go to Package Manager, and click the plus dropdown
Select add from git URL
and just type com.unity.collections
๐
now its just stuck on this loading screen
just wait, it takes a while
ok
it means it found it, it's downloading and installing
You need to be logged in to your account
how do i do that inside unity
In the Package Manager if you select the Packages dropdown and choose My Assets it should ask you to log in if you're not logged in.
just check your packages to see if it installed. sometimes theres glitchiness, sometimes you need to restart the editor after installing a package
Sorry for the delay. Ok, so here is my situation. I am using DOTS/ECS with Physics, Mathematics and all that good stuff. Currently I have a player (capsule mesh, rigidbody, convertToEntity, PhysicsShape). I have a cube as a child to that authoring player gameobject called eyes (CopyTransformToGameObject, ConvertToEntity [ConversionMode: Convert and InjectGameObject].
Then I attached a camera as a child to the eyes cube.
When I press play, the player capsule gets converted to the Entities world as well as the eyes. The Player capsule gameobject gets deleted, but the eyes and the camera stay intact. The CopyTransformToGameObject works in copying the translation and rotation to the authoring gameobject.
However! If you see the image, there is an issue I can't figure how to approach. During play mode, the eyes are selected in the Scene view (you the location gizmos shows the eyes local orientation) and the yellow arrow shows the orientation of the player capsule.
As you can see, the rotation of the player happens smoothly without any snapping. However, the eyes snap, and they snap on the 90/-90 degree points for some reason. I have a feeling it has something to do with gimbal locking? Anyways, it's horrible! How can I fix this issue?
I can show you code if you need for the rotation.
is the eyes just a child of the capsule entity?
Yes
tbh im not really great at math, so you can post the rotation code but not sure how much help ill be
how long does it usually take to install a git package
i feel like its taking too long
Ok. Rotation code is super simple. One line. Iโll post it when I get a moment. Away from pc right now.
But basically us PhysicsVelocity.Angular.y = lookDelta
velocity.Angular.y = math.abs(lookDelta) > 0 ? -lookDelta * player.LookSensitivity * 0.1f : 0;
shouldnt take more than a few minutes and the collections package is small in size @unreal wraith try restarting your unity editor if you havent already
so i cant really say that I can mentally work through that ๐ but id check in the entity debugger to see if the values are snapping. for a very simple test id change the code to a constant value and make sure the snapping is something to do with that rotation code and not the physics step.
Thx. Iโll try that out.
Happened to me when I used a limited connection. The package manager just refused to dl anything. Do you have a good bandwidth ?
So I tried a couple more things. I let the eyes just convert to entity and watched it with the rotation as an ECS entity. It rotates as desired (no snapping). When I changed it back to how it was, I realized that it renders BOTH the ECS entity AND the authored game object. And if you look at the screen, you can see them both...except that the authored object orients incorrectly.
Perhaps this is a bug in the CopyTransformToGameObject script? Wonder if anyone else had issues with this.
Probably might have to write my own version of it...
hm weird. I would def try setting the transform directly and not use the CopyTransformToGameObject, should be simple enough to test out if it is the culprit.
found the code they execute:
struct CopyTransforms : IJobParallelForTransform
{
[DeallocateOnJobCompletion]
[ReadOnly] public NativeArray<LocalToWorld> LocalToWorlds;
public void Execute(int index, TransformAccess transform)
{
var value = LocalToWorlds[index];
transform.position = value.Position;
transform.rotation = new quaternion(value.Value);
}
}
Seems the new quaternion(value.Value); is the culprit! I think the mathematics quaternion interprets Euler angles in a different manner than the UnityEngine Quaternion.
when using jobs am i supposed to put in allocator.TempJob like this?
NativeList<float3> positions = new NativeList<float3>(Allocator.TempJob);
You will need to choose which Allocator type to use based on your situation. Here is a list of their purposes: https://docs.unity3d.com/ScriptReference/Unity.Collections.Allocator.html
does can i use vector3's with jobs
not if you want burst(which you do), use float3 instead
So I'm having quaternion issues with CopyTransformToGameObject component. In my search I found out about Hybrid Components. I wrote a simple one and got it to work. The Hybrid component fires the Update and the unity events during ECS runtime. My question would be, how can I write code in my Hybrid component (MonoBehaviour) that can read/write to ECS components of that related entity?
well hybrid components have a sort of strict binding which tie the component's lifetime/control to entities
so updating the MonoBehaviour from a SystemBase would generally be ideal @drowsy pagoda
Entities.ForEach((HybridComponentA a) => { a.DoSomething(); }).WithoutBurst().Run();
ah, simple. Let me try ๐
Sick! It works! Awesome! Thanks man!
Ok. I finally came up with a solution. I did some digging around, and as I mentioned, the culprit was indeed the conversion between Unity.Mathematics.quaternion and UnityEngine.Quaternion they don't play well in certain cases, like my situation I mentioned here: #archived-dots message
Anyways, I found out about Hybrid Components (yeah this is my first time learning DOTS, I'm 4 days into it). And I created a SyncEntityTransform that would do exactly the same thing as CopyTransformToGameObject. I set it up, and just did:
trans.position = ltw.Position;
trans.rotation = ltw.Rotation;
And BAM! It gave me the SAME behavior as the CopyTransformToGameObject. And no matter how I converted the quaternions, (to eulers and back), it always gave me the same result. So then I gave up changing the rotation and simply did this:
trans.forward = ltw.Forward and BAM! it worked!
I think Unity should address this.
Damn. Next issue is that with this approach there is a slight delay for that object to update it's pos and rot ๐ฆ
how do i assign the length of a native array
I believe it's the first parameter when you instantiate it, followed by allocation
dunno
Say I have an entity that has nested children. Is there a way to filter for a child entity that has a ComponentData along with it's parent that has certain ComponentData items?
I know how to filter for ComponentData on a single entity, but is there a way to traverse the tree to look for a combination of ComponentData?
I dont think that's implemented. You'd have to write the iteration and search yourself
Though the way to go would be more along the lines of an EntityQuery
beware ltw.Position & ltw.Rotation will give you unexpected values if you have a non-identity scale. The delay is likely due to e.g. your system running using the previous frames evaluated LTW. You can run your system after the Transform system, but you'll then have to manually calculate the LTW's or force the transform system to run again if you need it updated in the same frame.
No, as Mr K says. Conversion is the ideal place to do this search and then add a Tag to the entity so you can easily query for it later.
I think you'd either dispose and reconstruct it or use NativeList (has an AsArray method if you eventually need a NativeArray from it)
How is the remap info from SerializeUtility.SerializeWorld intended to be used?
Do I need to serialize the remap info too and then use it when deserializing?
iirc in my last testing SerializeUtility handled remapping automatically, but I'm not sure what the remap info would be for then
Guys, where should i report a bug?
Error message:
Assets\Source\Simulation\Systems\AccessToSystem.cs(135,4): error Assets\Source\Simulation\Systems\AccessToSystem.cs(135,4): error DCICE007: Could not find field for local captured variable for argument of WithReadOnly. Seeing this error indicates a bug in the dots compiler. We'd appreciate a bug report (About->Report a Bug...). Thnx! โค๏ธ
Or the forum
In any case you should try to reproduce it in a simple project, helps the team
Ok, thank you. I'm just a bit confused with this 'About - report a bug`
Yeah forum is good enough, include any detail that can help
that might not be a bug though, it might just be you haven't set variables to readonly
Yes, it's actually not a bug. When i commented one job i got more informative error about second one. And a problem was that i use .WithReadOnly with ComponentDataFromEntity<LocalToWorld> which is not used inside lambda.
How can a type have a TypeManager conflict with itself? ArgumentException: MM.Events.EventTag and MM.Events.EventTag have a conflict in the stable type hash. Use the [TypeVersion(...)] attribute to force a different stable type hash for one of them.
Does the TypeManager have problems with namespaces or assebly definitions?
I have many asmdefs and all goes well
The only thing I did was move some files to new folders give them a namespace and an asmdef and now I get a lot of errors ๐ฌ
Thanks for that. Can you direct me to a source about creating tags during a conversion?
How can I reference another entity? Like in editor, attach another game object/component to an inspector field, and then get the reference to that converted entity on the ECS side?
look at your IDE, do you still have just one asmdef which produces an error?
When you use [GenerateAuthoringComponent] your Entity field will be GameObject field in authoring component. So to refer another entity just refer authoring gameobject of that entity, and convertion logic will remap it automatically.
If you want manually write authoring for your component, you can define GameObject fields as well and then just use GameObjectConversionSystem.GetPrimaryEntity(_referencedGameObject) inside your public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
Well... after restarting both Unity and Rider several times with mutliple different errors it now seems to work ๐ค
@pulsar jay do you have <AsmdefName>.Player asmdefs in rider?
i have this for all my asmdefs
no. not currently. are those auto generated? maybe they where there before restarting both?
i don't know. It is mystery for my and i can't google it
Thats weird. Well I will have a look if this happens for me too
Btw I was creating the asmdefs in order to write tests. Are there any good resources on unit tests with dots?
I think generally you should manually create world and then update it inside test and then dispose
for systems testing i mean
i have found this thread on forum which contains same approach i think
https://forum.unity.com/threads/ecs-unit-testing-example.1042648/#post-6804536
Thx I was just trying to use ECSTestsFixture but I am wondering why I cannot access it. The forum thread implies to copy it but why?
I reference Unity.Entities.Tests but cannot acces the namespace of the same name
found the solution: https://forum.unity.com/threads/how-to-unit-test-where-is-the-unity-entities-tests-namespace.540251/#post-4095463
entities package needs to be added to testables in manifest file ๐ฅด
Yet another week. Yet another absolutely no news about DOTS. Fun.
I noticed that JobComponentSystem does not support ScheduleParallel is this something I need to worry about? I have a situation where I would use ScheduleParallel if it was SystemBase, should I change JobComponentSystem to SystemBase? What are the do's and don'ts with this now?
You shouldn't use JobComponentSystem anymore, it's deprecated and will be removed eventually. SystemBase can now do everything it could and more
yep SystemBase also replaces ComponentSystem
Ah! Ok thanks!
How can I reference another authored gameobject which will turn into entity?
Say I have a IComponentData that will hold a reference to another GameObject that I can assign via inspector.
Then I want that assigned GameObject to be converted to an entity and the reference with it. So that way I can access and modify it's component(s) via SystemBase
Or is that the wrong approach? Is there another way?
you can store an entity into a struct
public struct AnotherEntity : IComponentData {
public Entity Value;
}
Then in your IConvertGameObjectToEntity component:
public GameObject Other;
public void Convert(...) {
var otherEntity = conversionSystem.GetPrimaryEntity(Other);
dstManager.AddComponentData(entity, new AnotherEntity { Value = otherEntity });
}
Thanks, I'm very new to DOTS/ECS. Where would I place the Convert method? Do I create a legacy Component and attach IConvertGameObjectToEntity to it? @coarse turtle
So the IConvertGameObjectToEntity would be implemented in a MonoBehaviour
public class SomeAuthoring : MonoBehaviour, IConvertGameObjectToEntity {
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem) {
// Add your conversion logic here
}
}
Make sure that the GameObject has a ConvertToEntity attached or it lives in a subscene for conversion to happen.
This is great! Thanks a bunch!
Another question, when writing Systems and using filtering, is there a way to filter with OR functionality? Say I want a system to run only if (DataA AND DataB) OR (DataC AND DataD)
Or do I need to write two separate systems?
You can use a WithAny in a lambda or define an EntityQuery with the right descriptors.
Entities.WithAny<A, B, C>().ForEach((Entity e) => { /* Some logic */ }).Run();
// Alternatively...
var entityQuery = GetEntityQuery(new EntityQueryDesc {
Any = new ComponentType[] { typeof(A), typeof(B), typeof(C) }
});
In this case any entities that have either A, B, C components would be queried and iterated
But otherwise, you'd have to do 2 jobs for those specific queries (A and B) or (C and D) since you want a specific combination versus at least 1
I see. Thanks again man.
I didn't know about SubScenes so I created objects and attached convert to entity on them. Because of this, I was able to create objects that had camera attached to them and did Convert and Inject and CopyTransformToGameObject and it worked, it actually moved the object with the camera around.
But now with SubScene, I can't achieve the same thing. How would I go about attaching a camera to a gameobject and syncing the transform of that gameobject between it's entity counterpart?
Use Hybrid Components for your camera - unity should create an instance of the camera with the correct hide flags and render everything
Yeah I just read about the Hybrid components. Cool stuff. So I don't really need the camera to do anything but just move along with it's parent. Do I just create an empty Hybrid component and attach to the camera and that's it? Or I need to do some more boilerplate stuff?
Well add the Camera as your hybrid component - have a system to update the Translation, camera should move
Ok, now this part really threw me off track. How can I add a Camera as a hybrid component?
Do I just write a GameObjectConversionSystem and ForEach(Camera camera) AddHybridComponent(camera);? lol
You can do it in a GameObjectConversionSystem or use IConvertGameObjectToEntity - either way works
so you can do this if you want, but the equivalent would be conversionSystem.AddHybridComponent in an IConvertGameObjectToEntity.
Wow. Yeah thanks, that's exactly what I did. The transform get's updated automatically I didn't need to write system to update it! Amaznig!
So why does that work with Camera and not other components? Is it because the Camera script itself does a Transform update?
Like why does the camera's position gets updated?
Yeah
When you add a Hybrid component, Unity also adds things like CompanionLink
which is a 1 way link from Entity -> Component Object
There's a specific system which reads the Translation of the entity and then copies it to the Component Object's transform
I forget the exact name of the system - but that system is pretty much responsible for updating the Camera's position
Ok. I have the following heirarchy. Player->Eyes->Camera Anchor->Camera
I also have a VirtualCamera setup that has target set to Camera Anchor (empty GO).
I can't get the Camera Anchor to sync between entity position so that the virtual camera can update itself on the mono side.
I tried attaching an empty hybrid component to the Camera Anchor to get it to sync, and it did create a companion link, but it did not update the transform.
I tried attaching a CopyTransformToGameObject on it, and no avail.
Well hybrid components are pretty strict to being updated via the Entities, not the other way around - so there are limitations
ok
Is there any way to use Job.WithCode outside of systems or does it just not work with the code generation? I was trying to use it in tests but it does not seem to be replaced by codegen
Has anyone succeeded building il2cpp **release ** build on android without having a crash on game start?
I'm using
Entities Version 0.17.0-preview.42
Unity Physics Version 0.6.0-preview.3
My guess is that the problem is related to this thread: https://forum.unity.com/threads/case-1315723-il2cpp-physics-netcode-entities-android-build-crash.1060103/?_gl=1*y83k07*_ga*OTE1NDc1NDU3LjE1NzY4MzkzMTA.*_ga_1S78EFL1W5*MTYyMzE3NDU2Mi42Ny4xLjE2MjMxNzkwMDYuNTQ.&_ga=2.196188652.1771243602.1622451325-915475457.1576839310
Is it possible to manually modify the ComponentSystemGroup a SystemBase runs in during runtime?
Or is that only possible via the UpdateInGroup attribute
I'm assuming it's ComponentSystemGroup.AddSystemToUpdateList
I guess that should be possible as you can create and destory systems during runtime so it should also be possible to move them to another group
This doesn't seem to destroy the system in the previous group it was attached to however, as I get an exception along the lines of "system has been created twice..."
I guess you would have to call RemoveSystemFromUpdateList on the other group
Yeah, it makes sense. I just wanted to mention that this isn't an automatic process
Is it somehow possible to run a job only if a previous job succeeded? I know they can depend on each other but this will only make the second job waiting for the first to be finished
I mean that's kind of the point of dependencies (wait until the previous dependency is finished)
You can early out the dependency and signal the job if it succeded or not
Also, how would the depending job know if the previous job succeeded or not, without waiting until it is finished?
Sure it should wait till its finished. But it should not start depending on the other jobs outcome. E.g a job queries for an entity and only if this entity exists the next job should run. Is there any way to achieve this?
The job itself wouldnt even have to know if the other job succeded. Only the scheduler needs to know
Let the next running job know if it's dependency was successful or not, otherwise just don't do the computation
So you mean storing JobA's result in a native container, reading it in JobB and then early out depending on the result?
Yeah, or just using something like a NativeArray<bool>(1)
Yeah I just thought there might be an easy way to just stop the dependency chain and cancel all following jobs as this could come in handy in a lot of situations
Atm I am building a simple entity based event system and it would be great to poll for events with a query and depending on that either run or dont run another Entity.ForEach query
Maybe the first job puts a tag that allows the second job to run. But sync-point blahblahblah
Its the usual problem of one job having to iterate over two sets of entities. Although one of these sets is just one event entity
It works already but I have to do the query for the event entity on the main thread and can then decide whether to schedule the ForEach
Would be great if a jobHandle could just have some kind of success flag ๐ค
What is wrong with having the second job always run, even if zero elements to work with ? Schedule overhead I assume ?
The second job should only run if the event is triggered -> the event entity exists
I could use @jaunty heralds approach to early out in the second job. That wouldnt work well with Entities.ForEach though
When I worked on an event system, I always just spawned an entity, which was then processed by a system, which could then create more entities, etc
Yeah thats kind of what I do. The event system is an EntityCommandBuffer system which spawns event entities
Yeah same spirit with network commands
If the reaction to the event was spawning new entities it would only need one ForEach to iterate over the event entities and fill an ECB
but if I have an event that should change multiple entities of another archetype it gets tricky
E.g. EnemyHealthBuffedEvent (which is a bad example as its more a command than an event) that should double the value of any enemy health component
Does anyone face this issue?
Yeah
unity netcode is aka rip? but ecs is still in WIP
No, thats still being worked on. Assuming you mean DOTS NetCode
Yeah that one is in development.
yes but still, seeing no changes by x time is uhm
@gusty comet https://forum.unity.com/threads/notice-on-dots-compatibility-with-unity-2021-1.1091800/
Since NetCode depends on Entities, then that's the reason
Is there any way to get component data via Type (e.g. via DynamicComponentTypeHandle)?
@pulsar jay Multiple ways, what's the context here? SystemBase Entities.ForEach, job, something else?
And what are you trying to achieve?
still working on an event system. for the connection to the classic GO world I am trying to get all event entities and get the data of their other component
they all have an EventTag and e.g. an event specific EnemyKilledEvent component
You could use an EntityQuery or ComponentDataFromEntity
yeah but they both require a specific component type
I am trying to do: Give me the other component data of each entity with an EventTag
where the other component can be any component type (unknown at build time)
I can get the typeId of the other component and I can also get a DynamicComponentTypeHandle from the typeIndex but all public methods require a generic type T to acces component data
Oh, no idea then
Thanks anyway. It should be possible because the entitymanager itself uses typeIndex internally. Its just a matter of how deep to dig I guess ๐คทโโ๏ธ
minecraft mmk idk if its possible to speedup map generation with dots
@north bay idk if you remember helping me the other day with calling external code from a job, but I ended up finding out that as long as you use primitives or raw pointers for the external functions you don't even need to do the function pointer stuff
now I've got a job that can do ~100k raycasts in 0.75ms
Anyone have an idea how I can check if a system has been destroyed? Null check does not seem to work...
That's great! What Burst version are you using? The example I wrote didn't work with direct calls on 1.5...
If you don't mind me asking what's your use case for that amount of raycasts haha
Right now it's stress testing
But I'll be using the bvh to cull physics queries for projectiles
And most projectiles are rays or capsules
That sounds fun. Are you embedding a native physics engine?
not yet
using physx
I need 64 bit precision tho
so I have some jobs that do syncing
and chop things up
You used .GetExistingSystem<>() ?
The error is being thrown when manually changing state in ComponentSystemGroup.OnUpdate. It has a Systems property which is a list of all the systems it should update. If you access this list before calling base.OnUpdate, a destroyed system will throw an exception
So I don't have a type I want to check for, but a reference
Uhm i see. I'm not in front of computer to do some tests.
Surely if you are the one removing them you could keep track somewhere but I never tried
I noticed PhysicsMass does not contain the actual mass (or weight w/gravity) from the Rigidbody. Is this stored somewhere else or it's not included at all?
I see InverseMass, but I don't know how to extract mass from that...
its inversemass,
i think zero is for static things? cant remember how it works but it was explained on the forums somewhere, its more efficient supposedly to calculate things this way
if you poke around in the conversion code it will show how its calculated cant remember where exactly
RigidbodyConversionSystem or something
Ok i'll see what I can find. Thanks
Found it => InverseMass = math.rcp(mass),
Wtf is math.rcp?
reciprocal? (however you spell that lol)
Do I just rcp the inversemass? Or is there another method I need to use?
Just confirmed. Yes, it works! float mass = math.rcp(physicsMass.InverseMass);
Hello I am doing well making a lot of progress
I am wondering how you go about replacing an Index in a ForEach as such?
Im grabbing everything that is movable and putting them into a grid, haha what fun testing of capabilities :)
We would struggle with this otherwise
What do you want index to represent?
If I layed out all movables 1...2...n
so I can take index and figure out row and column
int entityInQueryIndex
Put it before your ref Translation translation
The value is unique for each entity your job executes on. 0..n
Right before the Translation in your query. Unity will assign it for you
.ForEach((ref int entityInQueryIndex, Translation translation)
?
Oh I was missing a ref
No ref/in on entityInQueryIndex. Ref on Translation if you want to modify it
Riiight, ref for write
We want read onlys for cache line
No ref automatically read only?
Everything was running smoothly without issue. I have the latest DOTS setup with HDRP setup. Didn't have any problems creating objects with HDRP/Lit shaders.
Now, all of a sudden I'm getting this error:
A Hybrid Renderer V2 batch is using a pass from the shader "HDRP/Lit", which is not SRP batcher compatible. Only SRP batcher compatible passes are supported with the Hybrid Renderer. Why is it coming up all of a sudden? And how can I fix this?
No, you need ref/in for all components
And it's picky in that all ref components have to come before in
More info here regarding special inputs, under "special, named parameters" : https://docs.unity3d.com/Packages/com.unity.entities@0.17/manual/ecs_entities_foreach.html
OK
I recalled from lectures + reading but I am just hitting code now after 5 days of study
is there an easy way to check if an entity is visible in the active camera, like the old Renderer.isVisible?
the first thing that comes to mind is doing a quick cull check with the camera frustum - dunno if there is any convenience in hybrid renderer v2
mm okay, thanks!
150,00 Game Cubes Spawned and Moved Instantly https://clips.twitch.tv/WrongAmusedYogurtBrokeBack-FadJfCABZ9LkouFW
Success
Thanks!
I guess they are entities not game objects haha
Its like, why did I spend 5 days in the books, what am I doing XD
im not sure, i actually get that error in a build now but not in editor so also looking for a way to narrow things down, though im using urp
I saw one of the Unity developers said that HDRP is supported by Hybrid Renderer. And in another forum I saw a lot of people saying that it was fixed by disabling SRP Batching, so I'm gonna try that next time I get around to it and let you know if it fixed it.
But it doesn't like interfere with gameplay and other functionalities does it? And it seems to be rendering the stuff anyway. Should I just ignore it until they patch it up? Or does this need attention?
well depends, is stuff not rendering that should?
for me nothing appears different so im not too worried, just annoying to see at the start
Dang, yeah it is.
Do we know if Unity is working on this? Like there is already a reproducible bug for them to fix?
for the most part its just an error message saying a shader is incompatible, its not too helpful because it doesnt say which one. if you can reproduce it in a small project and you know every shader should be srp batcher compatible, then should report it
On mine it does, it says that "HDRP/Lit" is not compatible. But that's like the most common one, I don't see why that woudln't be. And where is a list of all compatible shaders? There is no direction on how to deal with this.
And why was it working just fine, rendering and everything, for like 4 days straight. I was working on ti, adding items and new materials. And nothing. But then all of a sudden, bam!
Anyways, do keep me posted on all your findings about this. And I'll do the same for you. Hopefully we can get out of these rough waters intact.
@safe lintel check it out. Unity 2020.2.0 Beta 14 actually has this in their Release Notes.
Virtual Texturing: Fixed an issue where VT with hybrid v2 renderer gave "A Hybrid Renderer V2 batch is using a pass from the shader, which is not SRP batcher compatible" error. (1252572)
Take note of Virtual Texturing part. I don't think I have Virtual Texturing in my project, I just started it, gonna see if anything is enabled by default.
I'm running 2020.3.11 so upgrading won't work for me ๐ฆ
WTF? Look!
According to the 2020.3 Docs Under SRP Batcher compatibility
For the SRP Batcher code path to render an object:
o The rendered object must be a mesh or skinned mesh. It cannot be a particle.
o The shader must be compatible with the SRP Batcher. All Lit and Unlit Shaders in HDRP and URP fit this requirement (except for the Particles versions of these shaders).
o The rendered object must not use MaterialPropertyBlocks.
"All Lit and Unlit Shaders in HDRP and URP fit this requirement". And I found the HDRP Lit Runtime shader, and take a look at what it shows! At the bottom! It says that it's not compatible.
Is there equivalent to Mathf.CeilToInt in Unity.Mathemetics.math?
It returns the smallest integer greater than or equal to x
hmm...so I tried an experiment and found some strange behavior. I examined the HDRP/LitTessellation shader in the default HDRP package. And it said it was compatible. I then took one of my materials and switched it to that shader. After it compiled, it then started giving me the same Hybrid error about incompatibility. I went back to the shader, and now it says not compatible it's as if the Hybrid system is changing the shader to become incompatible...
The library doesnt have intellicense commants to help what these functions
Alright, I think I got it to work. So because of the discrepancy of the docs and the shader compatibility on my inspector reading, I decided to Reimport the Lit shader that it was having an issue with. And when it reimported, it said it was compatible, confirming my suspicions that something was altering the shader or the way it was being read.
The errors went away. But after some time they returned. I then suspected that something happened (because I did import and delete libraries) and I had a couple crashes due to experimenting with code that might have corrupted something somewhere. So I closed unity, trashed my entire library, and opened it and let it rebuild...toook FOORORREEVER. But now it feels clean, no errors, the shader stays compatible, and I'm all giddy about it.
So, TL;DR, but you did anyway, if you know the problem shader, find it in project folder, right-click and reimport. If that doesn't work or you don't know it, trash the library, and let unity rebuild it.
Hopefully this will solve your issue as well!
Something must be wrong on your IDE, I have intellisense on Mathematics
is there a way to parallel write to NativeArray without using Nativelist?
are you doing it in a way that you know you won't be writing to the same index
from multiple threads
[NativeDisableContainerSafetyRestriction]
on the NativeArray in the job declaration
will let you write to it
but obviously then it's entirely on you to make sure you aren't doing anything you shouldn't
@crude sierra
when using completall() how would i get the output from each individual job?
Send in a NativeArray to your job and put your "output" inside it. Then after complete you can access your array to get the "output"
Does each job output things into separate NativeContainers?
The only way to get output from a job AFAIK is from a NativeContainer
so you just... read whatever NativeContainer(s) represent the output(s) of your jobs
how do i make each job output to a seperate native container
You feed them a different native container as input
So you just send in a NativeArray with enough space that each job can allocate to its own index..?
Some code or more details would probably give you a better answer
I.E How many jobs are there? What are they outputting? Do they run parallel?
basically im scheduling a bunch of jobs that generate meshdata (array of verts) and then using CompleteAll(), the only problem is idk how to retrieve the array of verts from each job that is completed
Ah I see, in this case you can probably use a NativeMultiHashMap
It allows for multiple values for each key
it doesn't change any of this but just a reminder that NativeReference exists for getting single outputs out instead of a single length array
if you haven't seen this
it might be useful to you
I am also in the process of jobifying some mesh generation code that I have
I am still struggeling to figure out how to get the data of an unknown (at compile time) component. I can acquire the typeId which in turn gives me the Type, ComponentType and ComponentTypeHandle but the only way to access component data seems to be through generic methods
I basically just need
EntityManager.GetComponentData(Type type) or
EntityManager.GetComponentData(TypeIndex int)
Check the code for ArchetypeChunk, might be something in there that can help you. I am not sure if those type of functions exist
Internally exists: EntityComponentStore->GetComponentDataWithTypeRO(entity, typeIndex);
Hey guys, someone here told me that the JobComponentSystem is being deprecated soon. This is my first time dealing with ECS Physics colliders. I have no idea how to get started on collision/trigger events.
I saw a resource that show how to handle them like this, and here is my boilerplate code: https://pastebin.com/NB4jCGZD
Can I get some feedback on this? If JobComponentSystem is getting thrown out in the future, how can I convert this logic to SystemBase? And maybe there is a better way of this?
In my case, for starters, I want to be able to trigger event when the GroundSensor trigger collides ONLY with other colliders that are NOT triggers. How would I poll for that?
Thanks guys in advance for all your help ๐
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Its what GetComponentData<T> uses internally but I am unsure if I should mess with the usafe stuff
Can I somehow run RaycastCommand multithreaded? I did the same thing as documentation and it is same or worse than just using loop of Physics.Raycast. In Profiler it shows each batch on mainThread running one after another, and all my cores are Idle.
@twilit coral scroll down in profiler to job worker threads and you should see a bunch of commands executed in parallel there
hmm
basically if you call handle.Complete() right after scheduling unity might decide to just run those jobs on main thread because it is a blocking call so main thread might as well help out
and i'm guessing it only schedules 1 job because you set the minimum to same amount as commands
so might be that's why it's running that one job on main thread
You can try scheduling it at the end of the frame and fetching the data at the start of the next frame
yeah or if you really need the result right away for whatever reason you can try reducing the 15 you pass in so it's spread across more jobs
I tried to put it at 1 to see if it spreads onto 15 cores, but it still is on MainThread and just takes 70 more ms to calculate
15 per job
1 per Job
It splits it into multiple jobs but schedules then on Main Thread, am I missing some part of JobSystem hmm
@twilit coral try doing what itsjustblank said, schedule and then check results the next frame
When using ITriggerEventsJob, how can I find out if triggerEvent.EntityA is a collider of type Collider or Trigger? Or any other information about it?
I tried getting the PhysicsCollider from the entity, but I don't see properties that show if it is a trigger or not.
you have 15 raycasts taking 77ms?
No, its around 11700 raycasts
I am just trying to jobifie this part, but it does not want to do on other threads
How do I skip a frame? I call the function, it starts the job and how do I wait for next frame? do I do it in IEnumerator?
I probably am doing something I shouldn't, but I usually just use nativelists for parallel writing only this time I can't because I don't have ( and not allowed to get) the preview packages
i'm doing something as simple as changing transforms, but without ECS so putting the correct values into a NativeArray<Vector3> then consuming this array every frame elsewhere on the main thread
you can write to transforms in parallel
and it's much faster
but you have to use the TransformAccessors
can you give me a reference for that? never heard of them
IJobParallelForTransformExtensions
I will look into it, great thanks!
is it really faster than entity command buffer when using ECS? just for general knowledge
ah this is for game object transforms
you don't want to do this if you are fully DOT
in hybrid gameobjects are converted to entities
and they do this for you
part of the implementation of the conversion
is setting up a system that utilizes these
to sync transforms from entities to GO's
I think in hybrid ecs if you have both entities and gameobjects you have to sync positions yourself
there's a special interface for that afaik
I'm preetty sure
that if you converted the gameobject
using the conversion workflow
it's transform gets synced automagically
it does, when you use Convert and Destroy
if you use Convert and Inject syncing the two is completely up to you
no that deletes the game object
Documentation lead me to an out of date Job implementation, and I am clueless where to head from here uwu
If I can learn to do it once....
I can do it again :D
I just need some assistance with the first one (This one grabs everything and arranges them in a grid)
you don't need to return anything in the OnUpdate because you have Dependency in context
OnUpdate()
{
Dependency = new Job {}.Schedule(Dependency)
}
Ok so far so good
Now that IJobForEach that was deprectiated from between the tutorial to now
yeah, use Entities.ForEach with EntityCommandBuffer
or evne just Entities.ForEach with ScheduleParallel
Entities
.ForEach(
(ref Translation position) =>
{
position.Value = newValue
}
)
.ScheduleParallel();
there u go
that's the general template
Thats a job?
that goes into your OnUpdate
jobs are not needed when using ECS
(some special occasions apply)
the whole premise of the DOTS API is to give devs an API that does the jobs for them, behind the scenes
thats what Entities.ForEach is for. it's an API that implements IJobParallelFor behind the scenes
How are we to test HPC# without job or?
hence why that job interface is deperecated
Is the High Performance C# No longer supported?
like I said, it's implemented for you
This approach will not Vectorize without a job, in the console
the DOTS API wraps it up into pretty lambda functions
Have you vectorized code with this new approach?
Whats your process?
Right now I am to test running multiples of 100K particle systems, simple entities, and complex entities
Right now I am just provisioning and placing multiples of 100K and hitting sluggish
So I need to vectorize
depends on where you are scheduling from, but you could store the jobhandle (can just be a class field if you like) (and track whether or not it's scheduled if it's something that doesn't run every frame), and then call handle.Complete() on the next update frame
how can i use AllocateWritableMeshData to generate multiple meshes at once
you pass in the # of meshes to the AllocateWriteableMeshData, pass the MeshDataArray to a job and for each index you can create a mesh
can you show me an example in some basic psuedocode
"for each index you can create a mesh" each index of what? the allocatewiteablemeshdata or meshdataarray
the example in the scripting API shows a decent example for 1 mesh: https://docs.unity3d.com/2020.3/Documentation/ScriptReference/Mesh.AllocateWritableMeshData.html
AllocateWriteableMeshData returns a MeshDataArray, so you can iterate through each index and set the data/vertex descriptors
for (int i = 0; i < meshDataArray.Length; i++) {
var data = meshDataArray[i];
// Set the vertex descriptors
// Set the vertex data
// Set the index format for the mesh
// Set the indices for said mesh
}
thank you, but the part that i think confuses me is when i reach here Mesh.ApplyAndDisposeWritableMeshData(dataArray, mesh). it seems that entire dataArray is used to only generate one mesh, does this mean if i want to generate multiple meshes on jobs i have to make multiple meshdataArrays with one element?
Aha I get it now
Its not what they taught but I get the lambda thing now with System Base
just one more thing
what do those parts do
also where would i apply the traingles to data
VertexAttributeDescriptors defines the structure of the vertex data (remember you can have vertex colors, texcoord0, texcoords1, position data, etc)
data.GetIndexData gets you a native array to the data you can write to - so when you set the values in the nativearray it sets the triangle data
so if i just want normal terrain is should leave this part like this?
actually, im just gonna assume i dont need that
atleast for basic terrain
you'll need the Position, Normals will affect lighting too
wont that just be done automatically when i do recalculateNormals()
Found a way by setting up RaycastCommands in Job, then have that a dependency for RaycastCommand.ScheduleBatch, then it does run multithreaded, also after that now implemented gatherLightingJob to get values from those raycastHits into usable data
sure - I was under the assumption you're not doing that
oooooohhhh
Neat
Lambdas are neat
You come in expecting database jobs lol
mind = blown
what should i do if i dont know how much of my allocateWritableMeshdata i want to allocate? should i create a list of chunks, and then allocate the list lenght? or is there a more efficent way of doing that
works even better than I expected, this was around 80ms to trace, now its under 1ms
daaymn that's some nice improvement
yeah, I love it, even more optimization will come as this time I didnt implemented occlusion so probes inside of geometry are still being traced, those I can skip later
23 cores are doing their work ๐
15ms on 50x12x50
when putting in an array as an argument, is it pass by reference or pass by value by default
pass by reference is a copy right?
um i forgot which one is the copy
value is a copy
arrays are references
@unreal wraith
class == reference, struct == value
what about when i pass an array as an argument for a function
oh wait
nvm
so your saying
anything thats a class will be passed by reference by default when used as an argument for a function?
@coarse turtle would something like this work?
seems right - idk how you're setting the VertexAttributesDescriptors though
is it ok that with ib im doing data.getindexdata<int> instead of ushort
what's the easiest way to create a "companion" entity for a gameobject? i've got a GO with some IK code that i've had trouble converting to DOTS code (needs parenting and world space transforms), so im thinking that maybe i could have the GO handle the IK, and the companion entity handle DOTS physics interactions.
or, ideally, is there a good way to handle world space transforms with parenting?
depends on your index format, if you set your indexformat to UInt16, but try to receive an int, I don't know if you'll get an error on runtime or unexpected behavior (e.g. if you wanted 12 indices with a short, but ended up attempting to retrieve a NativeArray of ints, then you'd have only 6 indices)
Why can't you just set the VertexAttributeDescriptors/IndexFormat again or is that not the case in this screenshot?
what is VertexAttributeDescriptors?
i thought i dont need to do that since im just doing recalculate normals
also i got an error when trying to run the code
line 272
I recommend looking at the Mesh API: https://docs.unity3d.com/ScriptReference/Mesh.html
the problem is you cant grab any kind of vertex data if you never define the structure of how the mesh is supposed to be.
it doesnt talk about VertexAttributeDescriptors in there
okay, maybe we should roll back a bit since this part ins't necessarily dots related - let's dm this
ok
Anyone have issues with native multi hashmap
I'm trying to iterate over it after putting a bunch of things in, and it's exceedingly slow to tell me if a key was inserted multiple times
I can do like 80k insertions in under 1 ms
But then I spend tens of Ms in the count keys calls
how does the schedule function work
in this tutorial im watching he passes in a list as the first argument and then 100 as the second. why?
In my ITriggerEventsJob I want to scan the entity's parents to see if they match the other entity. What's the best approach?
I assume that doing [ReadOnly] public ComponentDataFromEntity<Parent> Parents; would be too taxing?
Say something like this in the job:
private bool IsParentEntity(ref Entity entity, ref Entity queryEntity, ref ComponentDataFromEntity<Parent> parents)
{
if (parents.HasComponent(entity))
{
var parent = parents[entity].Value;
return parent == queryEntity || IsParentEntity(ref parent, ref queryEntity, ref parents);
}
return false;
}
aaaaa i need help
helps @unreal wraith
So what's your issue man? How can we help if we don't know what's wrong?
ive tried to add multithreading to my game every way i could, nothing works!
@drowsy pagoda
i have to finish this project in 3 dyas
oof, sounds complex
its my infinite terrain i need to add multithreading to
using jobs
can i atleast have a clue on how to do it?
there are no tuturoials online
and ive already tried doing it multiple times
I'm diving into this my first time, so I'm no expert here ๐
if i complete a list of jobs
will that run anydifferently than usin ijobsparrallelfor?
nope.
They'll prolly run one after the other.
which is different than ijobparallelfor.
Not sure what you need? IJobParallelFor allows you do schedule multithreaded work. You usually fill it with arrays of stuff you want to perform work on, then you tell it how many iterations each job should do, and it will automatically thread it out. So if you have 600 things you want to perform operations on and schedule it using 100 as the batch count, you'll have 6 jobs running in parallel (assuming there's enough cores).
IJobParallelFor isn't neccesarily DOTS though, it's just a core unity job type.
peppej help
idk what to do
how can i generate meshdata for multiple meshes using ijobsparrallelfor?
In DOTS or just using normal Unity Jobs?
whats the difference
Very simplified it's programming data oriented instead of object oriented. But since you asked I'm assuming you don't use DOTS.
which ever one will give me faster results ill use
Faster as in better performance or faster as in it's faster to write the code?
faster as in perform better
Then DOTS is most likely to give you better performance, however it takes quite some time to get in to and it's complicated to add mid-development
ill do the dots
In that case I recommend starting with the manual: https://docs.unity3d.com/Packages/com.unity.entities@0.17/manual/index.html. You pretty much have to read through everything on the left.
ok i think i get the just of it
now how is making a job different using ecs
or dots
or wahtever
Well in DOTS you'd have to structure your code to use Entities, Components and Systems. If you're just using the Jobs you can keep on using MonoBehaviour etc without any real issues. DOTS uses jobs for everything.
Using jobs for mesh generation is very common. I found these two complementary code examples while quickly googling:
but these are for single meshes
also do you think using dots will make a huge impact
or should i be fine with normal jobs
You'll be just fine with normal jobs, if you start using DOTS the easiest way would literally be to start from the ground up.
so it seems like the only way for me to retreive meshdata for each chunk would be to use a nativearray of nativarrays
with ijobsparallefor
is that a good approach? someone else told me thats no good but im not sure if i should trust him, plus that seems to be the only way
You can't nest a NativeCollection inside another NativeCollection (native array in native array) In this case you have to use NativeMultiHashMap. But yes it sounds like a good idea.
so this is the best way to go about it right?
i mean i cant think of anyway else
the nativehasmap
In your job you would figure out all the Vertex & Triangle data, then when all jobs are finished you construct your meshes on your main thread. You can use the new MeshAPI specifically made for Jobs but it's probably best to just get it working normally first.
i already did get it working normal on a single thread
whats the way you would do it with the meshapi
I still haven't figured out the new API fully yet personally ๐ Haven't had time to try it out properly yet.
do you know anyone who has?
im kinda desperate
and in a rush
i have to get this project done in 2 days
for my school
๐ญ
Well that's kinda tight. The Scripting API has an example of the new API https://docs.unity3d.com/ScriptReference/Mesh.AllocateWritableMeshData.html
i actually already generated my infinite terrain using that before
just on a single thread
What was stopping you from ParallelJobs-ing it?
Maybe you just tried sending it wrong or misunderstood it? Let me check the code I was working on.
maybe
MeshDataArray is a struct so you should be able to send it just fine to the jobs
In my WIP code I have already done this: https://pastebin.com/TKSgzwcd
Do note that this is written for DOTS.
So I'm pretty sure it would be just fine on a normal IJobParallelFor
Also keep in mind that the code I just sent is still work in progress, and doesn't actually work yet.
But I'd imagine the final solution is very similar to what I already have.
hold on let me revert my code back to where it was before
back when i was using the mesharraydata
@dense crypt
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
heres my code
and those are my errors
What does the first error say?
CreateVerts returns a float3[] you can't have normal C# arrays in jobs. In this case you need to return a NativeArray<float3> instead
Same for CreateTris
Since it's being allocated INSIDE a job you can only use Temp
ok
If you allocated it outside the job and wanted to send it in, then you would use TempJob.
That seems more like issues with your logic for generating the verts & tris
That's honestly very hard to say. But as a test I'd hard code a quad and try using that to see if it works at all.
Also, keep in mind: meshjob.Schedule(chunksToGenerate.Count, 100); This practially means generate 100 meshes per thread. So if the work takes a long while you may want a lower number
it prints wohoo!
yay
so its something below the jobhandle.complete()
@dense crypt you dont have to test it on a qaud beacuse thats not the issue
Okay, yeah the other issue I'm not sure what it could be. Sounds like you have invalid data somehow though. I haven't actually gotten that far yet personally so I can't say for sure.
My own generation isn't working too well either ๐
i think its this
this code was causing me issues when i placed it more above the job.complete(). so i put it after the job completes hoping that would make it work
but idk if it does
nvm its not that
i put a print statement after it and it printed
I mean it could execute properly but still supply invalid data, which breaks in the rendering step.
oh
As you can see in the image I linked I have correct data (red outlines) but I'm probably supplying it wrong, hence the broken mesh. I need to research this more but I don't have the time atm.
That seems very wrong. Can you profile it?
Do you guys think this is a bad idea?
protected override void OnUpdate()
{
var numbofRobots = OP.GetAllPooledObjects(0);
var activeobjsnumb = 0;
for (int i = 0; i < numbofRobots.Count; i++)
{
if (numbofRobots[i].activeSelf)
{
var agents = numbofRobots[i].GetComponent<NavMeshAgent>();
if (agents.isOnNavMesh)
{
var currROBID = numbofRobots[i].GetInstanceID();
Entities.WithReadOnly(currROBID).ForEach((ref RobotCompState curbobstat, in UniqueObjectID currobjID) =>
{
if (currROBID == currobjID.IntVal)
{
if (curbobstat.currrobstat == RobotState.JustSpawned)
{ curbobstat.currrobstat = RobotState.EnteringStore;
agents.SetDestination(entrancenavpoint[0].Value);
}
}
}).WithoutBurst().Run();
}
activeobjsnumb++;
}
}
}```
I'm creating a job for each loop, would it be better to replace that with a simple for loop
any insiders? when next dots update planned?
No one knows
New info will always come from the DOTS team that seems to give it in small drops once every few months or so
@dense crypt the issues was i had some of the code run in an unneccesary forloop, its alot faster now
I have a trigger collider nested in a gameobject that has a physics body. The trigger events display the entity as the parent body instead of the actual entity that contains the trigger collider. I understand this is due to compound colliders, but is there a way for me to quickly identify the exact entity that triggered that event, even though it's part of compound collider body?
How does ECS store the PhysicsShape->Material->Friction value? I need this value during runtime. I can't find it in the PhysicsCollider, PhysicsDamping, PhysicsMass data. Or is this just kept internally somewhere?
When using [GenerateAuthoringComponent] tag, is there a way to get it on the MonoBehavior side (i.e. GetComponent<YourDataAuthoring>) without having to create your own custom version of it?
When I have unity cycle through all components of a gameobject via GetComponents, it actually does list your [GenerateAuthoringComponent] class name with "Authoring" attached, It even says it's in the same namespace. But intellisense disagrees. Does anyone know where unity stores the actual generated authoring component? Or I absolutely need to create my own for this?
i was just looking for this as well. didn't find it easily so i'm just writing my own additional component that i can easily update
You're probably best of making your own AuthoringComponent. They're generated with code gen which means you probably have to jump through a lot of hoops to get it before compile time.
If youโre having trouble, I can give you mine because thatโs exactly what I did. Now with each Physics Shape comes a PhysicsMaterialData by default.
Yeah I figured. I found a way around it with what I replied to Matt.
Oh of that I have no doubt. The issue wasn't that, the issue was that I couldn't find Material anywhere in the ComponentDatas exposed on the entity. After triple checking, I assumed that it did exist (otherwise physics wouldn't be able to calculate accurately), just exists internally somewhere. So maybe this is something Unity will address, but for now I need to make my own copy of it.
Unless I'm overlooking something, I'm all ears ๐
I made a build to test it outside editor, but when it loads it just hangs after splash screen. The logs show that it throws an exception that says this: Cannot find TypeIndex for type hash 7923319918563069127. Ensure your runtime depends on all assemblies defining the Component types your data uses.
This is thrown by Unity.Entities.Serialization
How can I diagnose this issue? I am using asmdefs in my project, and they all have their correct dependencies, everything runs smoothly in editor.
what's the state of Dots?
Burst and Jobs seem to be fine. ECS seems to be a lot more WIP, but it's a tool if you really need it
In active development, next update is unknown. Set back by issues with Unity 2021.X: https://forum.unity.com/threads/notice-on-dots-compatibility-with-unity-2021-1.1091800/
In editor, everything is working fine, no errors. But when I build, the scene loads, it responds to input, my camera moves around, but none of the objects render. I'm using latest DOTS/ECS setup with HDRP. All my materials are just a simple "HDRP/Lit".
And I am getting this error in the log:
A Hybrid Renderer V2 batch is using the shader "HDRP/Lit", but the shader is either not compatible with Hybrid Renderer V2, is missing the DOTS_INSTANCING_ON variant, or there is a problem with the DOTS_INSTANCING_ON variant.
I went to the actual HDRP/Lit shader and inspected it. And it says that SRP Bathing: compatible and Keywords has DOTS_INSTANCING_ON. What's wrong? Please help!
@drowsy pagoda Are you on all the latest versions of the packages?
Did you try looking around the collider ? Should be in there
Oh my god I dont even remember how it's called
Look around the PhysicsCollider, should be referenced there
Yes sir. I even tried all the suggested things that I could possibly find online. No luck.
That was the first thing I tried my man ๐ You were referring to the PhysicsCollider data component I pressume.
Is there a Command Buffer system that would allow me to execute code not related to the entity manager, but allow me to write my own function?
I would like to execute main thread code from a scheduled job using such a buffer. If there is something like that, please let me know! Otherwise, this is something Unity should add.
Ecb.AddCallback(MyMainThreadMethod) ๐
You can create additional entities and system which will react for them and do logic on main thread
This approach will produce one system per action but will work ๐
Thanks. ๐
Is the only proper way to setup an entity query in the ITriggerJobSystem approach is to just check components against triggerEvent.Entity[AB] inside Execute?
Yes, from Collider to Material to Friction
Lemme do a test scene
When I checked, I couldn't find a Material, that was the issue.
Yup works for me https://gyazo.com/24ce2e6f8dc9a169a81f06e1bddbd14e
Left cube is friction 0 , right one is friction 1, middle one is exact copy of left, but dynamically dampened
Anyone can enlighten me on this? A Hybrid Renderer V2 batch is using the shader "Shader Graphs/Health Bar", but the shader is either not compatible with Hybrid Renderer V2, is missing the DOTS_INSTANCING_ON variant, or there is a problem with the DOTS_INSTANCING_ON variant. I'm trying to make a quad shader graph for floating health bars, it used to work too o.o
Or increased should I say
With this code https://paste.ofcode.org/NxSHwNuuQpuCwwdfEwTvDJ
@drowsy pagoda Works for me because I'm using cubes. Which Collider you're using ?
BoxCollider I mean.
Could be the reason why. gtg eat, hope that helped
I've never used Pointers before, so this is definitely new for me. Thanks for the sample code! I appreciate you following through. Why did they set it up this way? So you'd have to use unsafe code for Material?
Does this mean I need to enable Allow Unsafe Code in the Player settings?
The reason why I wanted custom action for ecb is because I was debug logging timestamps and I wanted to see if they match up when the ecb executes the code and not when the job is run.
is ECS still avaiable I cannot find it on my package manager
Go to Package Manager, Click the โ icon, select Add git url...
And type in com.unity.rendering.hybrid
This should install most of the core stuff you need for ECS.
Once its done do the same thing with
com.unity.dots.editor and com.unity.physics
You should be good to go ๐
If inside a ForEach job, there is a condition that would require use of syntax that is not Burst compatible, is there a way to split those up?
Say I would have a system that would dish out 100 entities burst compatible container, but 1 of them would trigger a condition that would make the container not burst compatible. What's a good way to weed that out? Would I have to write another ForEach container under it and schedule without burst for that condition? Or is there a way split it inside the original one?
That helped a lot. I completely scrapped my custom "default" injection for the physics material.
In SystemBase.OnUpdate Before the ForEach I would declare something like this: var rotations = GetComponentDataFromEntity<Rotation>(true);
It only needs to be readonly in my case. But if I do that, I will get an error saying that IJobsomething or IParallelJobsomething (I can't recall exactly) needs to have that marked as [ReadOnly]. I don't have access to that, so I can't. In turn I have to omit the true for reaonly and then it all works.
Does this clog up a little because of write access? If so, how can I get around this safely?
https://pastebin.com/CmdbV6YG heres my code
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
im getting erros that a native array is not being disposed of
I've used pointers because I retrieve the previous values and the colliders are serialized to blobs which are immutable data. So yeah you have to rebuild and reallocate every frame. I'm not sure why they went that way. They followed a few design principles like stateless simulation and such, I guess it's for performance.
But if yo only have a handful of values your Material can be set to, you might want to cache them and swap when needed at runtime, might be simpler. I could have also cached the friction only I suppose ๐
And yes need to activate an option for the unsafe code
did you try using WithReadOnly(rotations)
https://docs.unity3d.com/Packages/com.unity.entities@0.17/api/Unity.Entities.LambdaJobDescriptionConstructionMethods.html
how to do entities.foreach INCLUDING disabled entities?
WithAll<Disabled> (I believe)
does it not exclude enabled ones?
Good point, yes I'd expect it to - what happens if you add it to WithAny? Obviously you'd then have to use WithAll<SomeOtherStuff> otherwise you'd end up with any disabled entity. Worst case, you might have to write an IJEB or use two lambdas.
idk yet
Take a look at lines 36 and 37. You declare NativeArrays, but you aren't disposing them.
does anyone here know how to set up Occlusion Culling? im using a ConvertToEntity script on my object renderers but not sure how to add occlusion culling to that.....ECS used to have components for it but cant seem to find anything under culling anymore....
You can feed an Entity Query to the foreach. They have Options to includeDisabled https://docs.unity3d.com/Packages/com.unity.entities@0.17/api/Unity.Entities.EntityQueryOptions.html
Oh I didn't know about that. I will give it a try thanks!
Umm ive never used entity query
Oh nice, didn't know about EntityQueryOptions ๐
It's easy, just a more verbose syntax
is there any docs for .WithAny
Is there a way to perform raycasts on a scheduled burst? Or is it only on main thread and non-burstable?
You might be able to pass directly the options to the lambda without building thรฉ Entity Query if I trust this docs link :p
if you're using physx you can use raycastcommands
On this page, which conveniently explains how to pass a more detailed Entity Query to your lambda https://docs.unity3d.com/Packages/com.unity.entities@0.17/manual/ecs_entities_foreach.html
I'm on mobile I let you find it
Entities.WithEntityQueryOptions(EntityQueryOptions.IncludeDisabled)
.ForEach((ref Entity modelEntity, ref RenderBounds modelBounds, ref ModelData2 modelData) =>
{
You can also read the page on the Entity Queries, concept of with all/any/none is the same
why people do entity queries?
isnt it faster and with less code too
to do entities.Foreach
There's a few cases
Like accessing it before the lambda, to retrieve the Entity count
You also dont have thรฉ foreach filters
... things like that
I am using Unity.Physics. Thatโs not PhysX right?
are you using ECS physics or monobehaviour physics
- you can have jobs with ZERO foreach lambda if you want ^^ though they are nice and easy to work with
ECS physics should already support bursted/scheduled raycasts by default
Yeah I figured. I guess I just donโt know how to structure the foreach containers for that. I am using the boilerplate code from docs, and because it is doing PhysicsWorld.CastRay, itโs throwing a fit about threaded burst. Do you have a simple example I can follow?
is there any fast and elegant way to add eg a tag to hundreds of entities?
so i can do a clean .ForEach
you get what I mean
i think doing AddComponent 500 times is ugly
but maybe not
Thanks. Iโll check it out.
Perfect. I found exactly what I was looking for! Thanks a bunch!
For displaying many things at once on the screen ....is that the entities package?
It's much better to e.g. add them to a NativeArray and then call the batch EntityManager method.
well rip seems i cant use camera.WorldToViewportPoint inside scheduled jobs
When using SystemBase, when should you end it with Dependency.Complete()? I noticed sometimes itโs used and other times itโs not.
when you want to complete your jobs immediately, but good code schedules all jobs without .Complete() (when we talking about using ECS)
i wonder why disabling rendermesh (that are outside frustrum culling) helps me so much with FPS
maybe frustrum culling is disabled in editor
Using a query with a command buffer allows you to batch manipulate components on matching entities
So something like buffer.AddComponent<SomeTag>(query)
Or the newer method that is a capture
Still unclear which is better performance for mass adding tags in that regard
I feel like just using Entitymananger.addcomponent() is just quicker there's no delay from the playback at least
I use entityquery's quite a lot
in monoboheviours specifically and jobs sometimes require more data
When you add a component you're inducing a structural change, thus forcing a sync point.
yeah I'm more confused why you might use the ECB to add a component, because when you add a component you surely want it to happen immediately, I'm sure there are cases though where its better to use ECB, but I haven't personally found one
ECBs are known sync points in the frame. So you know you can do your structural changes there without disturbing your Jobs much
I guess I prefer a more chaotic program flow ๐
So basically, the goal is to schedule as much as possible with 0 completion on my end. Set things up correctly and you shouldnt need the component added immediately. Some added benefit: Ecb can be bursted.
The completion is handled by the scheduler in this case in the ECB system and normal schedule workflow
I am getting the following error:
: IJobEntityBatch error: job reflection data has not been initialized for this job. Generic jobs must either be fully qualified in normal code or be registered with [assembly:RegisterGenericJobType(typeof(...))]. See https://docs.unity3d.com/Packages/com.unity.entities@latest?subfolder=/manual/ecs_generic_jobs.html
I didn't change or add anything to my code. It was working just fine.
The error shows up if subscene is loaded and livelink is enabled. It just spams the console. If I open the subscene, the error spams once, but all the subscene items don't render. If I close the scene, they render and I get spammed.
The last thing I did was add an asmdef to a system, which btw has nothing to do with the items in the subscene!
I tried Reimporting the scene, I tried restarting the editor too. The error still shows up. Help!
Confirmed. I removed the asmdef that I added, and now it all works. Is this a bug? Or do I need to add something specific to the asmdef?
I put a system inside a folder Editor and threw an ASMDEFs for editor only inside there, attached all the dependencies that I was using and the code compiled, but no subscene would work. Why?
I just hit a snag. It appears that EntityManager.GetName is Editor only code. Is there a runtime equivalent? Or I need to write my own component for name tracking?
you need to store name in component
Oh no! How inconvenient lol.
actually unity names are not very useful during runtime
string comparison is slow too
I have a UI that shows what the player is looking at.
var projectile = commandBufferParallel.Instantiate(turret.index, turret.LoadedWeapon.Projectile);
barrelTransform = GetComponent<LocalToWorld>(children[0].Value);
commandBufferParallel.SetComponent(turret.index, projectile, new Rotation()
{
Value = barrelTransform.Rotation
});
commandBufferParallel.SetComponent(turret.index, projectile, new Translation()
{
Value = barrelTransform.Position
});
I assign a projectile I spawn the same rotation and position of the barrel but it spawns with incorrect values the further the barrel is away from 0/180 degrees. Any idea what I could've done wrong?
barrelTransform.forward shows me the correct direction so its position and rotation values can't be wrong.
is that ok to pass turrent.index? in examples for parralel ecb there was int entityInQueryIndex argument
maybe its same thing
No idea, but that's what I've been doing everywhere and never had issues so far
Rotation is indeed being assigned barrelTransform.rotation, but it doesn't align with the actual barrel
maybe LocalToWorld gets overwritten with local position and rotation values by the TransformLocalToWorldSystem?
even then shouldn't the shell have the rotation of the barrel from the previous frame?
how do you use native array with .scheduleparralel?
I get this error
Index {0} is out of restricted IJobParallelFor range [{1}...{2}] in ReadWriteBuffer.
so i googled and i need to add tag [NativeDisableParallelForRestriction] in front of nativearray
But that tag works only with class variables, and it asks me to create method variable instead
Entities.ForEach Lambda expression uses field 'planeDatas in a reference type'. Either assign the field to a local outside of the lambda expression and use that instead, or use .WithoutBurst() and .Run()
Is some entity in your tank hierarchy scaled by any chance? I remember that there are some issues with scale and LocalToWorld.Rotation (https://forum.unity.com/threads/localtoworld-rotation-affected-by-entity-scale.882133/)
My barrel is in a scaled entity, I guess that's why
I think this is the conclusion of the thread to get the correct rotation math.LookRotationSafe(ltw.Forward, ltw.Up)
I'll take a look in a bit.
That works, thanks ๐
hey guys, anyone have a reference for entities and UI canvases? I need UI elements relative to the entitites, where if I was dealing with regular GOs I would attach a canvas to the object as child
yeah my spawned entities don't have parents for now.
In my game, I just spawn UI elements as gameobjects in a system and position them with respect to my units transforms. There could be better ways.
i'm trying to avoid having many canvases in my scene, it causes lag
I have them in the same canvas, they can be instantiated with a parent
hmmm interesting
We are currently reevaluating our options to find a way to accelerate the availability of new Audio development to all Unity users. Stay tuned!``` ๐ฌ
im genuinely curious if when its finally released will dots audio be a sparkling 1.0 version given the development time or if it will be released as 0.1 super rough like animation
i think you know the answer
maybe this new directive will change things! ๐
The way I do it is I have a system that runs on schedule and updates values to an unmanaged component data. Then I have a managed component data that holds UnityEngine.UI elements like text and image etc. And I create a system w/o burst and run on main thread, and it reads from unmanaged data and writes to the elements stored in managed data. Works very clean no issues. If this is confusing let me know, I can post some examples when I get to computer.
some examples would be great, but also do you have ui elements related to entiities?
what I mean is do you have elements that need to move/rotate with moving entities etc
Not yet, but using this pattern makes it easy to set that up as well. Iโll write you my workflow for this. Gimme some time.
sure. my problem is whether to use one screen overlay canvas and calculate the postions of ui elements in regards to their entities or to use child canvases as world space
Ok here is some test code I was messing with when I was experimenting with ECS for the first time. Read the comments inside for further explanations.
https://pastebin.com/ANxVKh08
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
As to making the UI elements follow your character in world space, you'd simply just add in your player's LocalToWorld in the ForEach of PlayerUiSystem and there you can calculate the Camera ScreenToWorld blah blah blah, and just do a transform.position + offset to the UnityEngine.UI directly and it will work.
very interesting design, I will try it out. thanks!
So I'm thinking of creating a NameData IComponentData that will hold a FixedString64 and simply copy the GO name at conversion. My question will be about performance. If I have this on hundreds of entities, will this give me a performance ding or is this ok? If it isn't optimal, is there an optimal pattern I can use? Any suggestions?
oh wow, at least my DOTS frustrum culling works (and yes, i needed to do my own cause i had noticably higher fps with my own culling)
i will try to move as much code to dots as possible though its probably not much ๐
Why when I finish building it keeps showing me a warning about System.Windows.Forms.dll assembly? I am building for Standalone Win_x64 but forms? Where is it getting this from? I just started this project too, only got like 6 or 7 items in my scene lol. Anyone know what this is about?
are you maybe using a message box somewhere or something else subtle in that namespace?
also strings are just bad for performance in general. better to use an int or something as a unique id instead of a string name
Yeah I know, but this is because my player needs to display on the UI what he is looking at.
do you usually check for HasComponent or skip it? (before eg add component or remove component)
using DOTS/HDRP setup, latest everything. I noticed that if you object is in the Subscene, when mutating the material properties, it doesn't always update in scene/game view. If you take the object out of SubScene and put it in master scene, it updates realtime.
Is there an option for this? Or just a bug for now?
Is having entities check for ComponentDataInEntity<SomeData>() each update costly? Should it be standard practice to cache that reference to prevent such a search each frame?
Can't say what is optimal, but I would put all the names in an array in a blob and then have an index on the entity that points at an element in that array. Or maybe you can have the blobassetreference directly on the entity, but not too sure about that
I too was thinking of indexing them and only storing int ids. But not pulling the trigger because this particular game is going to have a vast variety of items. Thank you for mentioning blobs, I didn't think in that direction. Need to get more familiar with them I suppose.
Is it already possible to use the DOTS for performant realtime graphs plotting? If yes - any legit starting point resource in the topic? Pls tag me/DM me if you have any hints. Thank you very much in advance ๐
When I parent an entity to another, it automatically inherits and sets the scale. In traditional unity, if you set a parent for a gameobject that has a different scale, the gameobject that switched parents automatically gets compensated for it's scale in order to keep it the same size in world space.
However with ECS it is not so, there is no compensation, it rescales it to match the scale of the parent. How can I change the scale of the entity once it jumped parents?
I didn't see any Scale components on it, I tried adding Scale component to it, but nothing happened. Only thing I was able to do was add a CompositeScale, but that gives me a float4x4 and I have no idea how to read that. Can someone help me out here?
Scale is optional, so it will only be there if you need it. It represents a uniform scale. If you need to scale differently along different axes, add NonUniformScale instead. Not sure why adding Scale didn't work for you. Do you have a Translation, Rotation, and LocalToWorld added to your entity as well?
Yes sir. I will try to add it again. I was adding it without setting a Value. Maybe that's why?
I haven't messed too much with parent stuff, but I don't think it will do the magic compensation for you
I tried adding it at authoring level: dstManager.AddComponentData(entity, new Scale {Value = 1f}); and nothing shows up. I can confirm that it indeed does have ltw, rot, and trans attached.
No it doesn't, that's why I wrote the question ๐
Took me a minute to figure out how to parent it. Because just by adding parent component and setting a value isn't enough ๐
Is the Scale component just missing in the entities window? Maybe it removes it automatically if it has a value of 1?
Maybe, let me try setting it to 0.5f;
Nope. Same result. Btw, no default component "auto-removes" itself. I thought this was a behavior for other situations, and when I did some reading, someone from Unity says that no components do that. Just FYI
Well, looks like I will stick to CompositeScale and mess with float4x4
I just found out that float4x4 has a method called float4x4.Scale() and it will convert it from human-readable float3 to float4x4 ๐
dstManager.AddComponentData(entity, new CompositeScale { Value = float4x4.Scale(transform.lossyScale) });
This worked! The composite scale shows up and the object retains it's scale! ๐
๐
It's a shame, it feels like Scale would be a lot easier to work with because I don't have any nonuniform scaling going on right now
No idea what CompositeScale is but I'm glad it worked for you! How are you doing the conversion and parenting? If you are converting a gameobject hierarchy, it should automatically add the correct Scale if the child's transform is scaled
Yea it does. But this parenting occurs during runtime.
Player picks up an item and it attaches to his hand.
instead of syncing transform, I just parent it and let the ecs engine do it for me.
Crap. I don't know how to extract the scale from a float4x4 :S
Okay, I just tried this myself and my understanding was completely wrong. Even without parenting, when I set a non-unit scale on a gameobject, after conversion it gets a CompositeScale added to it. So no Scale component at all
And same for a non-uniform scale
Yup. It seems that it directly correlates the scale from float3 to float4x4 like this:
X = float4x4.c0.x
Y = float4x4.c1.y
Z = float4x4.c2.z
So I'll try messing with them like that and see if it works. But I'm pretty sure there is a method somewhere that can convert it for you...just don't know where to look.
float4x4.Scale(scale)
Yeah that just returns the float4x4.
I want the other way around
how can I get a float3 from a float4x4 ๐
Oh righto, sorry. Found this when digging through the code in CompositeScale.cs so might be other stuff in there.
I dind't find anything. I thought maybe math might have something...nothing either. ๐ฆ
Hmm...the scale remains the same, even after parenting, but the item visually does change scale. It seems it is storing this relationship somewhere else ๐ฎโ๐จ
LocalToParent maybe?
LocalToParnet shows the same values as composite scale!
Ok. I think I get how to approach this. I think you're on the right track. So looking at the hierarchy, the LocalToParent shows it's LOCAL scale in relation to parent. All I need to do is traverse the tree until I get to the root parent, and then I will get it's scale in relation to the world. From there I can perform my compensation and change the composite scale on the actual item...
Or is there an easier way? ๐
Might not be the helper function you were looking for, but you can compute the float3 scale from the float4x4 with something like this.
That looks about right. Where did you get this?
Just wrote it
Thanks, I'll take a look at it
so scaleOut gives you the same result as scaleIn right?
multiplying the float4(1,1,1,0) tells it the relationship between the two right?
I think I'm gonna study this to wrap my head around it:
https://docs.unity3d.com/Packages/com.unity.entities@0.0/manual/transform_system.html
yeah, the matrix can be multiplied with any float4 to get a scaled version of it. In this case, float4(1,1,1,0) represents the unit scale vector
Even if the other values are non-zero? This method specifically targets c0.x, c1.y, c2.z?
No it does a dot product with each row and the float4. So this works because only the diagonal is non-zero. But if you look at the implementation of float4x4.Scale, it only ever sets c0.x, c1.y, and c2.z. Honestly, I'm no expert with matrices so take all of this with a grain of salt, but the math does check out ๐
Sweet. I will implement this approach when I get back and let you know ๐
I think if this formula checks out, then we don't need to traverse and collect all the LTP scales, we can just use LTW and get the scale there in one shot ๐
Btw, this is exactly how Unity does it:
public static float4x4 Scale(float x, float y, float z)
{
return float4x4(x, 0.0f, 0.0f, 0.0f,
0.0f, y, 0.0f, 0.0f,
0.0f, 0.0f, z, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f);
}
guys
i need to efficiently check (inside ForEach) if at least one children is active
i have one idea:
on each chidlren, (i already have children foreach anyway) i will perform the check, then update the nativeArray on parent entity. it can be as simple as bool native array, each children has its index, so i would just set it to false and true
AND then inside another ForEach
id for loop through that native array and check if at least one value is acctive
SECOND approach to same problem:
- skip creation of native array
- instead simply loop through ChildBuffer and check for HasComponent each time
but Second approach may be slower idk
cause first one doesnt do HasCopmonent check
Didn't work. It keeps giving out scale of 1,1,1 each time. Gives it when the world scale is 1,1,1 and gives it even after it's parents and the local to world changes showing it's 1.5,1.5,1.5, but the formula still keeps spitting out 1,1,1.
seems i can use array on ICopmonentDatas, and access them from parrarel jobs?
I don't suppose any knows the correct way to check if an entityquery is null or empty or not valid?
I keep getting an error object reference not set to an instance of an object
I've tried entityquery.IsEmpty and .IsEmptyNofilter they dont't seem to work
IsEmpty is about the results
same as CalculatEntityCount() I guess
is there not a way to check if the entityquery exists, I know why I'm getting the error because the entityquery does not exist yet
@pliant pike entityquery can't be null
sounds like maybe you are trying to use an entityquery that doesn't search for anything?
I just did a null check and it seemed to work ๐
and your IDE doesn't give you a warning that it'll always be non-null?
that's weird since entityquery is a struct
C# lets you check structs for null but IDE should catch that it won't do anything
0.16.0-preview.21
looks like in 0.9 it was a class but since then it's a struct
0.16 should be a struct
struct can't be null
surely an entityquery can still be null though
structs can't be null in c#