#archived-dots
1 messages · Page 246 of 1
where can I find that setting?
bottom right corner of unity
(there's a setting in preferences that changes default start unity behaviour)
do you have jobs debugger + safety off
and are you maximized? (to turn of inspector/project/etc drawing)
because if you make a mono build vs editor it's pretty much identical code
if you are building il2cpp though that's a different thing
yep ok so thats off
as for now it's unchecked
turn off leak detection (especially avoid full stack trace)
maximize your view
and see how it goes
240 fps vs 450
🤷♂️ not sure you'd have to profile editor
to see what's updating
losing 1.94ms/frame somewhere
oh oh oh
hold on
I think I forgot burst
I assume
builds by default
have it on
yes
this info is really useful to know because testers/qa, management, design etc don't need to have it on
and they play the game in editor and complain it's performance is so bad
yeah, I was surprised by 10 and 10 on threads
especially the release vs debug modes
maybe keeping safety etc on is important for QA testing but no reason they need to attach a debugger
it's one of the best features that was added to 2020.X
because it has such a huge effect on performance
is there some kind of resource that has info on all of those buffer systems?
I guess SimulationEntity is per frame buffers on Start and End respectively
FixedStep is fixedUpdate
but what about Presentation?
and Initialization
theres 3 system groups by default in entities
initialization, simulation, presentation
fixed executes in simulation but not every frame
Is there any way to see the implementation of the Unity.Physics.QueryWrappers? I'm trying to implement a custom collector and some examples would be nice...
I assume the ICollector itself holds the e.g. NativeList used to collect results?
you should be able to navigate to the package in your IDE and just look at the code. the package isn't compiled
Yeah, I can look at e.g. CollisionWorld, but I can't find QueryWrappers
it's in \Library\PackageCache\com.unity.physics@0.6.0-preview.3\Unity.Physics\Collision\Queries\Collidable.cs
Looks like no, only the derivative for all hits holds a collection. Any and closest hit both return a Single
See this file \Library\PackageCache\com.unity.physics@0.6.0-preview.3\Unity.Physics\Collision\Queries\Collector.cs
Or filter with collector in the searchbox here if you're only interested in the implementation API : https://docs.unity3d.com/Packages/com.unity.physics@0.6/api/Unity.Physics.ICollector-1.html
Thanks!
Are rotation quaternions any different in dots?
x = math.clamp(x, -90f, 90f); for some reason
this won't let camera go above horizont
meanwhile bottom clamping is fine
Quaternion rot = rotation.Value;
float x = rot.eulerAngles.x;
x -= 15f * movement.deltaMouse.y * delta;
x = math.clamp(x, -90f, 90f);
rot = Quaternion.Euler(x, 0, 0);
rotation.Value = rot;
pretty sure, same code worked for GO transform
They are in radians not degrees
yup, they take in radians
oof
x = math.clamp(x, math.PI * -0.5f, math.PI * 0.5f);
Now it's locked to horizont
pls, any tip in this regard?
I have no idea what I'm doing wrong
doesn't matter what max clamp value I use
it's always stuck on horizon
and if you move camera higher
it just stutters it back
and not stops, before it actually rotates, but instead it moves it back somehow
Just so you know, math package comes with quaternion. Can't remember all the differences other than still utilities missing + order of rotations applied different than unity engine Quaternions
hm
thing is I transform to quaternion
using Unity engine
math
not dots
well, I logged angles:
bottom = 90~0
horizon = 0
above horizon = 270~360
just to be sure: is this telling me that my job is compiled with burst? im a bit confused because of intelisense
100% idle means that there are no jobs on the worker thread?? i know stupid question but im so confused by this
How does changing values in a DynamicBuffer work with jobs? Do you need to use CommandBuffer.ParallelWriter or anything to save changes made to the DynamicBuffer?
From a parallel job, yeah
Anyone has any tip on character controller?
I'm trying to figure out the one in sampe but:
- it doesn't even work in sample scene
- 700 lines of code I don't understand
there are better implementation from the community. Honestly I don't even look at it
Just to be more clear, if you want to use a commandbuffer, yes you should use the parallelWriter version of it from a parallel job. But you can access it without a commander buffer (if I'm not mistaken, only adding and removing the buffer itself should be a structural change, not inserting elements to it)
any free tho?
Something like this without commandbuffer is okay too :
public void Execute(ArchetypeChunk batchInChunk, int batchIndex)
{
BufferAccessor<YourDynamicBuffer> buffers = batchInChunk.GetBufferAccessor(SomeBufferTypeHandleYouPassToTheJob);
for (int entityIndex = 0; entityIndex < batchInChunk.Count; entityIndex++)
{
DynamicBuffer<YourDynamicBuffer> buffer = buffers[entityIndex];
for(int i = 0; i < buffer.Length; i++)
{
// buffer[i].Value
}
}
}
I remember seeing one on a well-known blog. But my memory is baaaad
I would google unity ecs charactercontroller
and learn from the 3 to 5 upmost results, should give enough food for thougths 🙂
😭 I fell into the trap. Someone can explain why ?
So no other way than getting a ptr + length and clear MemClear() ?
yea pretty much, don't think there was an overloaded method to do a memclear
Alright, thanks blank !
any idea about PhysicsUtils class?
I can't seem to find any mention of i'ts reference
do you guys know why my Capsule collider is Composite?
oh wait
I forgot to remove GO comps...
bbruh
I wasted hours into this research...
Should I ask stuff about DOTS NetCode here or in #archived-networking ?
Okay so. I have an interesting problem to solve.
I have a large, multi-level struct with various data types, not all of them blittable, that I need to store as an entity. What these are for is basically, reading a config file and storing the result for quick and repeated access.
How would I go about this the most DOTS-ey way? The best way I came up with was to somehow, flatten the struct into a long list of keys and values, but then I need to figure out how to query that? Maybe I could serialize it into a long JSON string and then unmarshall it when I need to grab the data? but both of those sound inefficient
Anyone know how to create a constraint in physics? All the forums seem to have outdated code.
You can store them in a BlobAssetReference
but only if the config data is immutable
i dont know how to mark it as immutable, but the data wont be changed. Are there any good resources to learning how to use Blobassets, because I haven't the faintest clue
Here's a resource https://coffeebraingames.wordpress.com/2020/11/29/getting-started-with-blob-asset/
You mentioned the data is complex with arrays and stuff, and that it's pretty big. This could be a solution
You also mentioned some data is not blittable, which is a use case for BlobAssetReference
i wouldnt say it's super large (although for data components it is pretty big) it's just pretty complex and not blittable
Will a lot of entities be. trying to access the config data?
Basically, if you stored the config data in a component, will there be a lot of instances of that component?
I was pretty vague, so I'll elaborate: Every block type has a config file that determines its properties. Each block entity stores a hash denoting which block type it is, and the data from the config file is stored as a component in its own entity for fast access. The system that works on blocks (it's basically a cellular automata thing) then references the parsed and stored data file, rather than rereading the data file for every block on every frame
that may be too much irrelevant information
But a cursory glance makes it seem like a blob asset is the right call
as these config files are read from disk and simply used to determine behavior, there is no need to mutate them
Yes I agree. And one major benefit of BlobAssetReference is data deduplication. The data is hashed, and if another similar one is generated, the reference just points to the first data
Question: How would I construct a blob from a structure that is already defined, like from the deserializer?
I don't know enough about deserializing to answer that, sorry
Well it’s not specifically about deserialization. The tutorials have you have the blobs as an array of your struct and then define them through code. What if I had already made a struct elsewhere and want to make a blob asset out of that?
Or maybe I’m getting ahead of myself. Maybe I should just read all of them at startup instead of reading them as they are needed to conserve memory
i figured it out, I can just Construct it
Did you check the physics samples ?
what the
why component is empty in inspector
ah
if you use Properties
instead of fields
they aren't visible in debugger
If I want to modify a collider in DOTS Physics, how would I go about doing it? Since modifying the geometry pointer modifies it for all instantiated entities of that type.
Should I create a new boxcollider each time? Is this performant?
I guess this applies:
// NOTE: this approach affects all instances using the same BlobAsset
// so you cannot simply use this approach for instantiated prefabs
// if you want to modify prefab instances independently, you need to create
// unique BlobAssets at run-time and dispose them when you are done
Seems like quite the hassle though...
e.g. if I want to animate a sprite with varying colliders I would need to create a blobasset for each frame of each spriteanimation
Also, is storing a NativeCollection inside a BlobAssetReference safe? I swear I read somewhere it isn's supported...
you can just set up each frame's colliders beforehand and then switch them out to the corresponding one when the animation plays
Yeah, that's what I meant
maybe just simplify collider? so it's not 60 colliders per 60 frames, but 6 (for example)
It's just a hassle to set it up, I don't really have any performance concerns
But I think for a 2D game a simple box is fine for all animation frames
@karmic basin Thanks for the reply, I figured it out after some trial and error. Thanks!
You can set the collider to be unique in the physics shape authoring and then just modifier the collider. Doubt making a new collider per frame is efficient at all @misty wedge
Not per frame. I would generate all colliders when the game starts and then assign them as needed.
I stepped away from my full ECS project for some time to work on some other things, around 6 months ago I attempted to update packages but found compatibility issues, I am attempting to revive this project but once again seeing major issues with the package dependencies... Its looking like I need to be running "Jobs" package that's over a year old now. Is this accurate?
Last update is quite a while ago, so it might be accurate
I'm on:
Burst 1.6.0
Entities 0.17.0-preview.42
Physics 0.6.0-preview.3
Collections 0.15.0-preview.21
Mathematics 1.2.5
Jobs 0.8.0-preview.23
NetCode 0.6.0-preview.3
for reference
anyone has any idea how to create Capsule collider?
var col = new PhysicsCollider()
{
Value = CapsuleCollider.Create(new CapsuleGeometry()
{
})
};
I'm not sure
how to assign fields in this struct
Radius is obvious
but
Vertex0
Vertex1?
I basically need to copy this collider
but make radius different
Yeah, looks like that's the jobs package I was using, looks like I will revert. Thanks
I assume Vertex1 and Vertex2 are the two vertices used to span the capsule
well, thing is I have no idea how to manipulate them xD
I found some examples
any idea what does it mean?
I'm not sure what you mean?
I need to create collider
It's setting the vertex values with the X coordinate equal to armlength / 2, all other values 0
capsule of heigh2 and radius 0.4
but I don't know relation between that and vertexes
Ah, my bad
Probably this:
new Unity.Physics.CapsuleGeometry
{
Radius = 0.4f,
Vertex0 = new float3(0, 1, 0),
Vertex1 = new float3(0, -1, 0)
};
@rustic rain
Wait you decompiled the assembly through a program ?
okay good
Some IDEs might show a decompiled version. Others might find the package source and display the real file content
Is this both VSCode?
vscode here
Not sure if vscode understands packages correctly atm
It might not find the correct source
@rustic rain if you want to convert the exact settings to a collider I assume formula would be something along the lines of (not tested):
Vertex0 = center + orientation * (0, height / 2, 0)
Vertex1 = center + orientation * (0, -height / 2, 0)
Actually works pretty well for me. I just open the folder and it's linked fine
you can generate the .csproj files for embeded packages and browse the source code in vscode or w/e ide you want
oh, center and orientation
That's it yeah. I checked the checkbox from Unity to generate first
@rustic rain they usually include Tests, often a good idea to have a look Library\PackageCache\com.unity.physics@0.6.0-preview.3\Tests\PlayModeTests\Collision\Colliders\CapsuleColliderTests.cs
Can anybody help with this (probably burst related) crash?
The method Void _mono_to_burst_Hash64Long(Byte*, Byte*, Int64, Byte*, UInt64 ByRef) must have MonoPInvokeCallback attribute to be compatible with IL2CPP!
I'm confused
The crash seems to happen in EntityQueryImpl_GetSingletonEntity. Does the game just crash if the singleton does not exist?
You can add the physics debugger to your scene to easily visualise colliders
how? Normal debugger shows nothing with entities
well, anyway
I cast this collider in system, it's not attached to any entitiy
okay never tried if it draws them at runtime
Yep it does
Thx I guess I will have to remove this dependency then
@pulsar jay are you not using RequireSingletonForUpdate in conjunction with GetSingletonEntity?
new details on batch renderer group
Heck yeah. New update!!
In the coming year, the Hybrid Rendering team will land improvements to the Hybrid Renderer package to use this interface ecs second class citizen to gameobjects 🥲
well entities won't support 2022.1 for a while so hybrid renderer can't really support it till entities does
yay, I finally made dots character controller that is not shit kek
implementation makes me worry tho
when character stuck in corner, it tanks 1 ms of cpu main thread
lol
i mean it doesn't immediately have huge effects on dots anyway
@last jasper actually the same as it was 6 months ago
any particularly newsworthy stuff since that forum post about providing more updates?
latest stuff is in that thread unfortunately
ok so I have this code to create a blob here
public struct RawBlobStruct
{
public BlobArray<ParsedRawData> Arr;
}
public static BlobAssetReference<ParsedRawDeserializationStruct.RawBlobStruct> CreateRawBlobAsset(ParsedRawData data)
{
using var blobBuilder = new BlobBuilder(Allocator.Temp); //new builder
ref var parsedRawBlobAsset = ref blobBuilder.ConstructRoot<RawBlobStruct>(); //ERROR HERE
var arrays = blobBuilder.Allocate(ref parsedRawBlobAsset.Arr, 1);
arrays[0] = new ParsedRawData();
BlobAssetReference<ParsedRawDeserializationStruct.RawBlobStruct> blobAsset = blobBuilder.CreateBlobAssetReference<RawBlobStruct>(Allocator.Persistent); //create reference
blobBuilder.Dispose();
return blobAsset;
}
but it gives me this error: error Assets\Scripts\Mono scripts\ParsedRawDeserializationStruct.cs(66,9): error ConstructBlobWithRefTypeViolation: You may not build a type RawBlobStruct with Construct as RawBlobStruct.Arr[].General.name.m_HashMapData.m_Buffer is a reference or pointer. Only non-reference types are allowed in Blobs. What on earth does this mean?
has anyone seen these errors when adding a component data to a gameobject? Further investigation leads me to believe I'm setting up InputActions wrong
@white island Only non-reference types are allowed in Blobs sort of self explanatory, your ParsedRawData hashmap or hashmap.buffer is a reference or pointer type which you cant have inside of blobs
Blob assets can contain primitive types, strings, structs, arrays, and arrays of arrays. Arrays and structs must only contain blittable types. Strings must be of type BlobString (or a specialized unmanaged string type such as ).
Can I use FixedString32 instead? Apparently I cant use BlobStrign as a key
not sure tbh, try it
Well that's what im using that causes the error. Here:
public enum Types
{
Block,
Creature,
Fluid
}
public enum BodyParts
{
Arm
}
public struct ParsedRawData
{
public GeneralData General;
public PropertiesData Properties;
public BehaviorsData Behaviors;
public NativeList<BodyParts> Anatomy;
}
[System.Serializable]
public struct GeneralData
{
public FixedString32 id;
public NativeHashMap<FixedString32, FixedString32> name;
public NativeHashMap<FixedString32, FixedString32> desc;
public FixedString32 texture;
public Types type;
}
[System.Serializable]
public struct PropertiesData
{
public NativeList<FixedString32> tokens;
public int hardness;
public NativeHashMap<FixedString32, int> species_stats;
public NativeHashMap<FixedString32, int> lifecycle;
public NativeHashMap<FixedString32, int> stats;
public NativeList<FixedString32> custom_props;
}
[System.Serializable]
public struct BehaviorsData
{
public NativeHashMap<FixedString32, NativeList<FixedString32>> behaviors;
}
public struct RawBlobStruct
{
public BlobArray<ParsedRawData> Arr;
}
you can't use any native container in a blob
More like landing order of things in repositories. Hybrid Renderer is our teams main focus. We just need to land the Unity part first
Is there any info on what's the current workflow to get skinned mesh animations on DOTS? I'm trying to animate some character models but all the info I found online is not very clear, contradictory and/or appears heavily outdated
There's this published sample which should be up to date. Not sure it contains everything you need though https://github.com/Unity-Technologies/EntityComponentSystemSamples/tree/master/HybridURPSamples/Assets/SampleScenes/SkinnedMeshes
I usually do. Turns out this is not always the case. And in this case the system should not really depend on it. So I rather try to get rid of it instead of depending on it
Hmmm
I have player controller, that modifies character controller component for player body
and I have NPC controller
that also modifies character controller comp, but for npcs
and thing is, they will never write in same components
but
Dots is angry about dependencies
is there any way to make it ingored?
or how do I combine those dependencies considering my PlayerController runs on
ForEach
while npc run on IJobChunk
how are you scheduling them
are you not using a systembase for npc?
I use JobComponentSystem
oh
anyway the issue is you're not passing inputDeps into your ScheduleParallel()
as a dependency
if this was a systembase you'd pass in Dependency instead
ok, I'll try to rewrite it for SystemBase first
annoying part
most tutorials
use deprecated stuff
kek
no reason to use componentsystem/jobcomponentsystem over systembase anymore (except for conversion systems which still inherit from componentsystem but i'm hoping 0.50 does away with that)
well, so
protected override void OnUpdate()
{
Entities
.WithAll<ZombieBodyTag>()
.ForEach((ref CharacterControllerComponent controller, ref Rotation rotation, ref Translation translation) =>
{
float3 targetPos = float3.zero;
float3 deltaDistance = targetPos - translation.Value;
float3 direction = math.normalize(deltaDistance);
float magnitude = ((UnityEngine.Vector3)deltaDistance).magnitude;
float mod = math.min(magnitude, 2f);
controller.CurrentMagnitude = mod;
quaternion targetDir = quaternion.Euler(direction);
targetDir = UnityEngine.Quaternion.Lerp(rotation.Value, targetDir, 1f);
rotation.Value = targetDir;
controller.CurrentDirection = ((UnityEngine.Quaternion)rotation.Value).eulerAngles;
}).ScheduleParallel();
}
now I schedule NPC like that
let's see if it'll keep erroring
oh, no errors
ok
poggie woggie
ok, so
what are my options if I want to make a target finder job?
Basically I have NPC's query
and I want them to chase another NPC's query
chasing closest one
the most straight forward solution - ForEach inside ForEach
but I think that's not compatible with burst
you can execute an query and that will return a nativeArray of entities. you can pass that into your entites.ForEach
excecute query? With what method?
or from what class
I remember I saw smth similiar
I just need to know where to find it
you can basically create a query with GetEntityQuery(defineWhatYouWantHere) and then call ToEntityArray
imo the docs a pretty good for the most part. it just takes some time to connect it all together
NativeArray<Translation> translations = targetQuery.ToComponentDataArray<Translation>(Allocator.Temp);
Entities
.WithAll<ZombieBodyTag>()
.WithNone<HasTarget>()
.ForEach((in Translation translation) =>
{
}).Schedule();
translations.Dispose();
So just like that?
and then I use translations inside foreach?
NativeArray<Translation> translations = targetQuery.ToComponentDataArray<Translation>(Allocator.TempJob);
Entities
.WithReadOnly(translations)
.WithDisposeOnCompletion(translations)
.WithAll<ZombieBodyTag>()
.WithNone<HasTarget>()
.ForEach((in Translation translation) =>
{
}).Schedule();
pretty much yes. just some tiny things you could improve, see code above
(added the WithReadOnly because i assume you only need the data readonly, this allow for more optimizations in the background)
yeah
apologies if i added some typos, wrote that from memory
I'm getting the following Burst exception that I'm having trouble debugging: Burst error BC1020: Boxing a valuetype RockMine.C4.Core.EntityCommandBufferWrapper to a managed object is not supported. The type EntityCommandBufferWrapper implements an IEntityCommandBuffer interface that I created so that I could use the same code no matter if the job is single or multithreaded (I have another EntityCommandBufferParallelWriterWrapper type that also implements the interface). That's the only unique thing about it; I don't think that should be causing issues, but I thought I'd mention it in case.
The frustrating thing is that the line the exception refers to doesn't even have any mention of EntityCommandBufferWrapper.
Any thoughts on what could be causing this? The only mention I could find online of error BC1020 said that it's caused by calling Debug.Log, but I've removed all those references. Not sure what could be going on.
var buffer = bufferSystem.CreateCommandBuffer().AsParallelWriter();
Entities
.WithAll<HasTarget>()
.ForEach((Entity entity, int entityInQueryIndex) =>
{
buffer.RemoveComponent<HasTarget>(entityInQueryIndex, entity);
}).ScheduleParallel();
bufferSystem.AddJobHandleForProducer(this.Dependency);
Do I need to dispose of anything in this case?
EndSimulationEntityCommandBufferSystem
it keeps giving me this
I don't see any allocation here, but regarding the dependency for the ECB, you shoul add the one from the Job, not from the system. Because the end of the execution of the system doesn't mean the Job will be finished (you'll just know that it's scheduled)
And IIRC I had strange warnings for container I allocated but never actually used, should keep an eye open for such a thing too 🙂
Entities.ForEach will return a JobHandle
doesn't seem so
hm
okay im clearly wrong lemme check again the doc
dammit xD
Oh I see
only the overloaded calls with a dependency themselves return a JobHandle
so this means the Dependency in SystemBase is already updated for you 🤔
I guess
So nevermind what I told you xD
I'm still learning everyday with that dependency chain management 😛 sorry for that
Am I even doing everything correctly?
I basically want to remove HasTarget
from all entities
aka find targets again
Yes the code looks correct to me. And yes @karmic basin the dependency is updated automatically in SystemBase
Well for now looks like you remove HasTarget immediately. You surely need another condition fullfiled before removing
Was confusing to me as well as in some cases Unity is doing some magic dependency management and in other cases it doesnt
thing is
it doesn't work
my entity has HasTarget comp it was assigned once
and it's never changed
You mean between ICD vs DynamicBuffers ? Or more like between systems vs jobs ?
are you sure that there isnt any other sytem adding it again?
EntityQuery targetQuery;
EndSimulationEntityCommandBufferSystem endSimulationEntityCommandBufferSystem;
protected override void OnCreate()
{
var queryDescription = new EntityQueryDesc
{
All = new ComponentType[] { ComponentType.ReadOnly<Translation>(),
ComponentType.ReadOnly<PlayerBodyTag>() },
};
targetQuery = GetEntityQuery(queryDescription);
endSimulationEntityCommandBufferSystem = World.GetOrCreateSystem<EndSimulationEntityCommandBufferSystem>();
}
protected override void OnUpdate()
{
NativeArray<Translation> translations = targetQuery.ToComponentDataArray<Translation>(Allocator.TempJob);
var buffer = endSimulationEntityCommandBufferSystem.CreateCommandBuffer().AsParallelWriter();
Entities
.WithReadOnly(translations)
.WithDisposeOnCompletion(translations)
.WithAll<ZombieBodyTag>()
.WithNone<HasTarget>()
.ForEach((Entity entity, int entityInQueryIndex, in Translation translation) =>
{
float curDistance = float.MaxValue;
int ind = int.MaxValue;
for (int i = 0; i < translations.Length; i++)
{
float distance = math.distance(translation.Value, translations[i].Value);
if (distance < curDistance)
{
curDistance = distance;
ind = i;
}
}
if (ind != int.MaxValue)
{
var comp = new HasTarget()
{
Position = translations[ind].Value
};
buffer.AddComponent(entityInQueryIndex, entity, comp);
}
}).WithBurst().ScheduleParallel();
endSimulationEntityCommandBufferSystem.AddJobHandleForProducer(this.Dependency);
}
my second system is supposed to add updated comp
but maybe I'm wrong?
or maybe I need to get entity query on update?
E.g. dependencies between systems are handled automatically by checking their read and write components but ecb systems have to be given an explicit dependency
I would recommend testing you systems in isolation. If you disable the other system and just create an entity with the HasTarget component you can check if it is properly deleted
Ok I see. I'm still figuring this out, recently physics dependencies backfired at me. That's confusing sometimes
Btw. you dont need to state WithBurst() anymore as thats the default now
That gets especially confusing as most of physics has its own update loop/timing
Exactly 🙂
nah
keep getting this
EntityManager.RemoveChunkComponentData<HasTarget>(query);
I tried this
no allocation warnings
but still no comps get removed
system that adds them is disabled
Is HasTarget a ChunkComponent?
I am also getting these warnings in some cases. But I suppose it is connected to me doing wierd stuff with entities during edit mode
query = GetEntityQuery(queryDescription);
EntityManager.RemoveComponent<HasTarget>(query);
ok, this works
oof, these errors make me sick
float dot = UnityEngine.Vector3.Dot(targetDir.eulerAngles.normalized, currDir.eulerAngles.normalized);
I guess
I'm supposed to do smth else for it?
1 - shouldn't use Vector3.Dot()
Regarding this question, I put together a test interface/struct and modified the file in question to pass it as an argument in a method call. The same error is being thrown for the test interface/class. Is it not possible to use an interface as the argument of a method that gets called by a job? That's a huge limitation if so.
Essentially, if I have a helper class that's meant to be used by both jobs that run on the main thread and in parallel, it seems like I have to create two implementations of the helper method: one that takes an EntityCommandBuffer, and another that takes an EntityCommandBuffer.ParallelWriter. That seems absurd, but is it the kind of absurdity that comes with working with DOTS?
i think the only time you can use an interface as an argument is when it's generic and has constraints with unmanaged types. Otherwise interfaces can be boxed into an object.
Sorry, do you have a code example of what that might look like?
public static void Foo<T>(T value) where T : unmanaged, Interface { }
Oh, interesting, let me give that a shot. Thanks!
Looks like it won't be possible. The following error is being thrown: The type 'RoadGrowthStrategySystem.Test' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T2' in the generic type or method 'RoadGrowthStrategySystem.Expand. The only field I have is an EntityCommandBuffer field, which means that one its fields is nullable.
Well, was worth a shot.
I guess it's the EntityCommandBuffer's DisposeSentinel which is causing EntityCommandBuffer to not be entirely blittable
hm
how to get CollisionWorld collisionWorld = buildPhysicsWorld.PhysicsWorld.CollisionWorld;
this into my ForEach loop?
I get error that wants me to put ReadOnly tag onto it
but I'm not sure how I can do that on local variables
ok, looks I just can't do character controller paralleled
any idea about ComponentDataFromEntity?
I'm trying to rewrite code from IJobChunk
to SystemBase
and it uses this container
to check for collisions
ComponentDataFromEntity<PhysicsCollider>
I assume I don't really need it
but question is, how can I access PhysicsCollider of any entity in world
by Entity?
let's say this NativeArray<PhysicsCollider> ColliderData = query.ToComponentDataArray<PhysicsCollider>(Allocator.TempJob);
you dont need to rewrite a chunk job for SystemBase
anyway for foreach use .WithReadOnly(collisionWorld)
oooh
Hm, is camera stacking a thing in dots?
What do I use instead? just a normal Dictionary/List
?
you should probably read up on managed and unmanaged types @white island its really a fundamental part of dots
isnt native unmanaged? I thought thats what i was supposed to use with blobs, no?
well the question is why do you need a dictionary and list in a blob? Since blobs are linear data in memory, if you want a dictionary like behaviour, then you can add in hash function so that you can get the index within the blob array. If you want a list - that's pretty much only an array in blob assets.
I guess its never spelt out but as tertle said, you cant use nativecontainers for blobs, for that you have BlobArray(and you can have nested blob arrays afaik unlike nativecontainers). Nativecontainers - your goto for burst job array/list/collection functionality
what are my options besides camera stacking (as it seems, it's not possible with dots) for weapon overlay?
I mean, gun that character holds in first person
@rustic rain in urp you can do the render object feature to change the fov(example in universal rendering example repo), for hdrp theres a shadergraph of doing something similar in the FPS sample, but last time I tried it with hybridrenderer, it broke
change fov? for what?
oh, because how it works is to make your weapon so small it resides inside any collider's radius so it never clips through geometry
apparently thats how modern games tackle this
I'm also considering hybrid approach
where cameras will be GO
will actually simplify a lot of things
yeah, I think I'll go with hybrid approach
doubt dots has anything as pog as current GO camera does
thats really the only option for cameras currently 😉
well, I used conversion thingy
for simplest thing as being local to entity container
it works fine
The list can be an array but the dictionary is because it is a deserialized file
i guess I need some context - if it's from a file why do you need it to be a blob asset? I imagine you can just stream the file into memory and just read the memory address
what is better:
- updating transform of camera inside of Update()
- updating transform of camera from system
?
I think its better organization to update your gameobjects from systems, ie your systems control the gameobjects but functionally I dont think it matters
anyway this is for urp what I mean by tiny weapon https://gfycat.com/unacceptablebelovedhadrosaurus
the sample repo is https://github.com/Unity-Technologies/UniversalRenderingExamples
the only thing that bugs me about this approach is shadows are sorta on or off with something so small, you dont get a more nuanced partial shadow casting if you do this(or if theres a solution for it, I dont know about it yet)
damn, I didn't think of it
that lightning
will not affect overlay elements
like gun and hands
allthough
i mean it does but you dont get that transition time when moving into shadow or light as you would with a normally scaled object
I mean for stacking approach
when actual gun and hands will be far away
from ingame environment
from my experience it makes a huge difference, life cycle management is a huge pain if you don't do it this way
it's a deserialized YAML file I use to determine behavior in my game
yea I guess ymmv, but i think about it more like - if it's from a single file, read it into a static readonly field and you can use it in system logic. But if it's a serialized dictionary, then it probably makes more sense to transform the dictionary into a persistent NativeHashMap (either through a custom yaml deserializer or pretty much copy the dictionary's contents into a NativeHashMap). Imo it doesn't really make sense to bind it to an entity if it's some global kind of data.
Basically, each entity is a certain kind of object, and each kind of object has a configuration file. So I am deserializing the YAML file into this struct and then storing it as a blob asset, and then each entity keeps track of what kind of object it is by storing a BlobAssetReference
I can only think of these 2 ways from the top of my head. Pretty much your blob struct can contain a method which acts as your key accessor like in a dictionary and perform a similar hash look up, or keep it simple - loop and do a find in the BlobArray to get the correct entry.
Either way you'll still need to do some data transformation on the managed dictionary -> some blob compatible struct
You mean, flatten the dictionary?
yea pretty much.
You'll have a single bucket + potentially a hash function to do your value look up given a key. (If it's just an array, your index would be the key)
has anyone done any subscene loading via LoadSceneAsync? I keep getting a nativearray was disposed error when doing this but resuming play it ends up loading
What about an UnsafeHashMap? Ive read that may be able to work. I could write my own hash map implementation that's in theory blobbable but getting that to work with YamlDotNet is a bit beyond my depth.
are we talking about subscenes?
yeah, do you reset world before loading new scene?
@rotund token yes
I imagine it would be like BlobPtr<UnsafeHashMap>>? No idea if the runtime/compiler would complain, plus if that's the case it would just be pointing to some other memory address which would make it non linear i guess 🤔
you should really load all subscenes using RequestSceneLoaded
not any direct method on scenesystem
unignore me i was right the first time
buffer.AddComponent<RequestSceneLoaded>(entityInQueryIndex, entity);
just add that to your subscene entity to load it
i think you should only use LoadSceneAsync for your first set of scenes
otherwise you get issues
(been a while since i've played with this, but this is how my scene management system works and i vaguely remember having issues)
just twiddling my thumbs for an editor restart but appreciate the info 🙂
i have a bounds system for loading/unloading subsystems
Loading
this.Entities
.WithNone<RequestSceneLoaded>()
.ForEach((Entity entity, int entityInQueryIndex, in SceneSectionData sceneData, in LoadWithBoundingVolume load) =>
{
var boundingVolume = (AABB)sceneData.BoundingVolume;
var maxDistanceSq = load.LoadMaxDistanceOverrideSq > 0 ? load.LoadMaxDistanceOverrideSq : loadMaxDistanceSq;
foreach (var ltw in playerPositions)
{
var distanceSq = boundingVolume.DistanceSq(ltw.Position);
if (distanceSq < maxDistanceSq)
{
buffer.AddComponent<RequestSceneLoaded>(entityInQueryIndex, entity);
return;
}
}
})
.ScheduleParallel();```
Unloading
this.Entities
.WithAll<RequestSceneLoaded>()
.ForEach((Entity entity, int entityInQueryIndex, in SceneSectionData sceneData, in LoadWithBoundingVolume load) =>
{
var boundingVolume = (AABB)sceneData.BoundingVolume;
var maxDistanceSq = load.UnloadMaxDistanceOverrideSq > 0 ? load.UnloadMaxDistanceOverrideSq : unloadMaxDistanceSq;
foreach (var ltw in playerPositions)
{
var distanceSq = boundingVolume.DistanceSq(ltw.Position);
if (distanceSq > maxDistanceSq)
{
buffer.RemoveComponent<RequestSceneLoaded>(entityInQueryIndex, entity);
}
}
})
.ScheduleParallel();```
basically just add/removes RequestSceneLoaded to load/unload
ok what is the difference between a reference type and a pointer, is there any
ok so I was getting errors(a nativearray was disposed etc) inside of LoadEntitySceneAsync
// old
foreach (var s in EntityManager.GetBuffer<ResolvedSectionEntity>(sceneEntity))
EntityManager.AddComponentData(s.SectionEntity, requestSceneLoaded);
// replaced with
for (int i = 0; i < EntityManager.GetBuffer<ResolvedSectionEntity>(sceneEntity).Length; i++) {
var s = EntityManager.GetBuffer<ResolvedSectionEntity>(sceneEntity);
EntityManager.AddComponentData(s[i].SectionEntity, requestSceneLoaded); }
but that fix resolves it(?) not that im happy about moving another unity package into my packages folder
haha yeah i can see why the unity code breaks
well pointers are just addresses to data and reference types store (typically in C#) a pointer to data objects but are managed by the garbage collector. E.g. classes can store references to other classes.
they're hardly the same
the GC can move reference types in memory
a pointer always going to point to the same location
LocalToWorld
what is 4x4 matrix in this component?
I basically want to extract position out of it
oh nvm
it has property for it
lul
Man, I really dont know what to do here with this dictionary thing... I can't avoid it...
could start simple and create a struct like
public struct KeyValuePair {
public K Key,
public V Value;
}
public struct Blob {
public BlobArray<KeyValuePair> Collection;
}
When you want to look something up - you can loop initially. Once you see it working you can optimize for something a bit better (hash lookup, binary search, etc)
I get how I could do that, but how would I make it work with the deserializer? That's the most important part.
copy the content over from the dictionary once it's deserialized into memory?
generates GC sure, but it's a quick solution
unless you write your own deserializer/use a compatible library i'm not really sure of an out of the box solution
I have a prefab that has a light source in it, when I use the "convert to entity" component to create an entity of it in my scene - I see my prefab model, but the light source is missing - does the unity dots package support the light source at this moment? or is there something else I need to configure before it shows up?
none of light sources worked for me in subscene, I assumed there's no light in entity world
Is DOTS good for huge numbers of game objects? Any good tutorials out there to get me up and running in a short time frame?
I need for game jam.
moetsi dots tutorial is great
and up to date
I'd say, dots is good for strategical kind of games
personally I think, RPG, FPS and similiar genres are way better be done in classic OOP
This is for Kaiju Jam.
We're building procedural cities out of tens-of-thousands of cubes.
We want each "cube" to be destructible etc.
Is DOTS appropriate for this?
I'm afraid you're gonna burn all the short amount of the jam fighting with DOTS, and not achieve a lot
Do you have any suggestions for accomplishing strong performance with 10,000s game objects in default Unity?
do hybrid
do whatever it is you want for shitload of objects with dots
while keeping link to your GO world
you don't even have to use entities
jobs + burst
can be enough
They aren't even doing anything yet and I'm only getting like 12 FPS, after dynamic batching 😭
if it's cpu overhead of processing those draw calls
(not logic)
you might want to consider indirect gpu instancing
I'll look into all that. Thanks man 👍
@floral lynx This ^ for a game jam
Unless you especially want to use the game jam to learn DOTS. But if you do, don't expect to finish your experiment
Or divide scope by 3 🙂
oh lord yeah didnt see that rendering graph
This is with both batching off, and GPU instancing & receive shadows off on all materials.
~150 batches per second frame?
I can't say for sure but
as far as I know
dynamic batching can't be as good
as manual batching through code
I was able to make simple mesh drawing with 40k meshes for almost free (for CPU) by storing buffer of precalculated matrices on GPU
and then just accessing that buffer by index
had to make a special shader for it, but in the end perfomance was magic
I have kind of a weird question does anyone know if its possible to convert a gameobject mesh frozen part way through an animation into a full entity
I know we can't use animations in dots yet, I'm just wondering if I couldn't do some kind of stop motion method where I flip through a bunch of mesh's 🤔
But you can use animations in dots (though its harder than gameobjects) 🙂
you can, how so
no worries I just found a couple of tutorials although, it may be too complicated for me 
So I have Unity.NetCode installed on a clean project with Havok and Unity Physics both installed as well, for some reason it seems to be throwing the following exception when I enter playmode
Should I uninstall Unity Physics if I want to use Havok? Is that the issue?
Or do I need to downgrade one of my packages?
The error was coming from Havok, so I guess I'll just stick to Unity Physics for now
definitely turn gpu instancing on
if you are on the latest lts it might be https://forum.unity.com/threads/2021-2-8f1-broke-asdeferredjobarray-and-deferred-jobs.1225635/ @left zenith
i think it's totally that
(scroll like 3-4 comments down for fix)
kind of annoying i have to be the one to tell the community the fix instead of unity just stickying a post or something 😐
dont they have tests to catch something like this? 😩
That didn't work for me with Havok installed again, don't know if that makes a difference. Apparently the bug actually exists in netcode. This worked, though. https://forum.unity.com/threads/2020-3-16f1-physics-world-history-objectdisposedexception-cannot-access-a-disposed-object.1158956/#post-7525850
oh this is the physics history world one is it
should have looked at stack closer
yeah that broke back a few versions ago
i really should make a post with all known issues in dots packages
Yeah me too really, I just figured it was one of the physics libraries since that was at the top of the stack trace
and when I uninstalled both physics packages it didn't throw the error anymore, but once I installed Unity Physics package again it did, prompting me to just google it 😆
I am trying to make constraints so that my player doesn't move in the Z. But nothing seems to be happening. Any suggestions?
public sealed class PhysicsConstraint : MonoBehaviour, IConvertGameObjectToEntity
{
public bool3 Linear = new bool3();
public bool3 Angular = new bool3();
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
var worldFromA = new RigidTransform(
dstManager.GetComponentData<Rotation>(entity).Value,
dstManager.GetComponentData<Translation>(entity).Value
);
RigidTransform bFromA = math.mul(math.inverse(RigidTransform.identity), worldFromA);
var joint = PhysicsJoint.CreateFixed(new BodyFrame(worldFromA), new BodyFrame(bFromA));
joint.SetConstraints(new FixedList128<Constraint> {
new Constraint
{
ConstrainedAxes = Linear,
Type = ConstraintType.Linear,
Min = 0,
Max = 0,
SpringFrequency = Constraint.DefaultSpringFrequency,
SpringDamping = Constraint.DefaultSpringDamping
},
new Constraint
{
ConstrainedAxes = Angular,
Type = ConstraintType.Angular,
Min = 0,
Max = 0,
SpringFrequency = Constraint.DefaultSpringFrequency,
SpringDamping = Constraint.DefaultSpringDamping
}
});
dstManager.AddComponentData(entity, joint);
}
}```
Total DOTS newbie here. I was reading about ECS today and I'm considering starting to use it. I was confused about one point, though. It said objects with all exactly the same values are grouped together in memory, and I assume this grouping makes it go faster in some way. The problem in my mind is, there's almost no real-world situation, other than perhaps "zeroed" objects in an object pool waiting to be used, in which you'd ever need a lot of objects in a game that all have exactly the same values. I imagined a bullet hell game with tons of bullets bouncing around. Almost never would all the bullets be in the exact same position on the screen. So my question is, in a situation like this, is DOTS still faster? Or is there some point where the overhead of moving thousands of non-identical objects whose values change every frame into new group after new group after new group isn't worth the benefit anymore?
If I'm using Havok Physics for Unity, do I still use a rigidbody and just add the Physics Step component and it just works?
havok uses the exact same conversion and components as Unity Physics
not 'values' are meant but individual archetypes
bullet has position, collider, damage for example. all bullets are together. what values these components hold is totally irrelevant
also from your last sentences, i think you haven't really understood dots
Fair enough. You're probably right, I don't. I want to make a 2D action game with multiple enemy types and upgrades that affect how the player's projectiles work. Let's call it something like Nova Drift. Lots of player projectiles and lots of enemy ships means lots of moving objects and many-on-many collisions. Is Unity2D+DOTS+Collision Layers the best tool for the job or not?
it certainly is
It's kinda spooky because whenever I look at a unity forum thread about it it's always game devs describing pretty ubiquitous gameplay situations and then debating the pros and cons of hackey workarounds in the most abstract terms with no example code. 😨
most of the time you can easily grasp what they're talking about
Updating a thing more than once per frame is a common theme
usually you don't update anything more than once per frame
like 99.99% of the time
No, I'm saying usually when somebody cares enough to ask a question about DOTS in a forum thread, it's because their design compels them to update something more than once per frame, which necessitates hackey workarounds.
And my brain is like "I understand the problem but not the solution. That could be me someday, stuck implementing hackey workarounds!"
-
- it doesn't
-
- most questions are not about updating more than once per frame
the only* thing needing hacky workarounds is a hybrid workflow.
and that has to do what with your example? i can see 0 correlation
your system sounds way simpler
You're assuming I've described everything I'd ever consider adding to the game. I'm a solo dev, and I'm still in the planning stages of the project. It's not like I'm bound to a design doc yet. My point is the examples people come up with that require hackey workarounds are all surprisingly pedestrian features I've seen in games before. Enemy-targeting. Pathfinding. Modifiers that modify other modifiers. The classic First-Person Camera controller. Examples like these make me worry that DOTS might be too fragile to make games with. Not even cutting-edge, AAA games, but game archetypes that have been performant since the 90s.
I'm hoping this is more of a perception problem than a legitimate concern. I won't know until I try. And it's true that this is the opposite of survivorship bias-- I'm only hearing from the people who've managed to paint themselves into a corner.
Examples like these make me worry that DOTS might be too fragile to make games with
I mean. it IS an experimental package.
Working my way through a slide set. This actually sounds a lot like one way I did things way back in the heady days of Flash Actionscript. Make an array of object references, make an array of X positions, make an array of y positions, make an array of xSpeeds, make an array of ySpeeds, iterate through them all every update. OOP came years later.
Except it seems like a lot of the array work has been abstracted away by ECS. Nice!
My EntityID was just the i in a for-loop... which I suppose also served as a fixed-length object pool by default. Other than that, it's pretty similar, conceptually.
Actually, that reminds me. One of the things I needed to unlearn when coming to Unity from Flash, like 10-15 years ago, was unity doesn't like for (i = 0; i < enemyCount; i++) when iterating through gameObjects. It needs foreach instead. Was that a consequence of Unity's OOP system, I now wonder?
fairly certain thats not a thing
that's bullshit
I'm trying to remember.
I remember now. In really old pre-OOP Flash, like AS1 or AS2 or something, I fell into the anti-pattern of not using an array at all to iterate through my MovieClips, but rather giving them a name that had the string literal value of i at the end. I'd name them like enemy[i] or something, I don't even remember how to do it now, and it would come out like enemy1, enemy2, etc. at runtime. And then access them the same way after object creation. I asked how to do that in Unity, and they were like "dude what are you doing just use foreach."
Everything was these bodged-together tricks you learned from a friend online. There was a formalized discipline, but it wasn't involved in the flash scene. You had to check out a library book on AS1 coding or whatever if you wanted to learn from academic sources, and even that would be full of little mini-examples. Maybe one or two full game projects, if you were lucky. It was a more primitive time. Not even sure if W3Schools even existed back then. Was that Web 2.0? If it did exist, teenager me sure didn't know about it. I was in full-on cowboy mode. I'm not sure if I've gotten better since then or if Google has just made my bad habits more scalable. Probably a little bit of both.
Gonna go out on a limb and say the fact that I'm researching DOTS before using it is probably an improvement.
what gets bursted by default? entities loops and IJobs?
OnUpdate of systembase doesn't?
only jobs that you add attributes to (and function pointers)
entities.foreach/job.withcode will by default code gen to a job with the burst attribute unless you tell it not to
and ISystemBase onupdate is burstable (function pointer rules)
any tip how to make smth like weapon equipping with systems?
basically an animation of weapon equipping is what breaks my mind
let's say I have shotgun, I want to equip rifle, I want some animation of switching to happen
what are you talking about? for loop works on a collection of gameObjects
I used to Flash/ActionScript too back in the days. And you're right, this mindset helped me get a grasp on DOD. But at the core only, Unity DOTS and multi-threading add more tricky concerns on top of that :p
it's stuff like this that ends up being a little bit more of a headache with full dots/ecs compared to just gameobjects with components and classes.. with dots if you're keeping EVERYTHING within the framework of jobs/systems and adhering to sync-points you are basically having to manually build systems that do stuff in little modular chunks..
so for example with a mono/component you maybe have a method called SwapWeapon that has a bunch of code that destroys or hides the old weapon, instantiates the new weapon, updates the characters weapon stats etc.. this makes things really easy but at a relatively huge performance cost compared to an efficient ecs/dots system.. the dots version would probably have maybe 2 or 3 separate jobs, one which takes inputs, sees that a swap weapon is requested, and passes that request onto another system, which maybe tells an ecb to destroy the existing weapon, and instantiate the new one, and maybe applies new values.. there would then more than likely be a whole other system dedicated to character animation which would then run the weapon swap animation..
so the problem is, it could all be seen as over-optimization, you might be easier just keeping it gameobjects and components.. i'd say you have to be pretty brave and committed to go down the dots route for stuff like this.. personally, i've done it, and it definitely has it's advantages, but depending on your situation might not really be worth the hassle
I'm fine with hybrid approach
I have my gun models and cameras as GO anyway
for sake of camera stacking of urp
Is Unity2D+DOTS+Collision Layers the best tool for the job or not?
Not always. Could also go for keeping GOs then use Jobs + Burst for heavy computation parts only. Especially if only need for bullets and enemies
You'll find you'll have a hard time using 2D with DOTS
if it's for your fp character, it probably is way easier just to keep it GO's yeah.. as Mr.K mentioned above to something else, there's maybe more of an overall benefit to keeping jobs/systems for heavy stuff
at this point I'm not sure what to use dots with kek
in FPS shooter
I mean
with only about 50 enemies simultaneously
I guess it still makes threading way easier
for AI
pathfinding
it's going to be interesting to see how dots evolves over the next year or two.. it is such a conflicting paradigm with the old way of doing things, it's like chalk and cheese, i'm curious how unity will encourage or suggest or help people to integrate it or transition to it.. i think it's hard to decide how and where to use it until you've actually worked with it for some time and even then mixing dots with mono stuff is a headache in itself and adds an extra layer of complexity
50 characters probably means in terms of using Animator etc you're probably not hitting any huge bottlenecks so yeah.. dots does make multithreading 1000x more accessible and bursted jobs are incredible performance gains, so yeah using for AI stuff, targeting, anything that's doing a lot of iterating and processing in bulk would benefit a ton from it
personally dots is perfect for tycoons, simulators and etc
not for rpg's
or simple shooters
Still
I don't want my game even, if it's simple to run on single core
I want to use jobs+burst at some point
hehe well yeah and, in some ways no, as i say there's stuff in shooters that can benefit hugely from dots and burst
other thing i find interesting with dots is just the potential not just to spawn 140 billion cubes and all that, but actually to just build apps/games that are 100x more efficient
i genuinely think we're going to see a squeeze on the cost of energy and penalties for devices/apps/whatever that consume more than their fare share and aren't efficient
maybe that's a few years out, but i think it's going to be imporant
classic unity or mobile game is the typical, play for an hour use 80% battery and really bad memory/storage efficiency
hm
if I do some expensive calculation in OnUpdate of my system
does it mean, that I'm stopping execution of all systems until I free main thread?
OnUpdate is always run on the main thread. But if you schedule a job inside that it won't run on the main. It's basically the scheduling call. You are supposed to set up jobs there and then check for whenever those jobs are done in a later update or next frame
I mean
If one of my systems
Runs some code itself, not scheduling
and if it's code expensive
and will take let's say 0.5ms
will that mean that all systems will be stopped
well it'll run on the main thread yeah, unless you create a job or Schedule to do the expensive code, which is kinda the idea, cos then you can use burst and it should be much quicker
can you schedule without burst tho?
or more like
can you schedule
job with reference type
inside
nope
usually i do WithoutBurst if i'm accessing something that's a class or mono ( something outside of ecs )
one way is say for example you need to access the cam's transform inside a burst job, get it first and then use those values inside the job
I'm doing opposite, I'm applying values of my entities to GO
maybe I should do it from GO instead
so my system queue isn't clogged
how do I get info from system then
hm
well there's different approaches to that..
you could have for example an entity that represents your camera or GO that you want to push values to.. it could have some component that collects the values.. so in your burst job/system you apply the values to that entity/component, and then later on the main thread you just copy the values from the entity/component and apply to your gameobject
I already have them
other way is to use an entity with a buffer of data you later apply to gameobjects.. another way is you have a NativeArray which collects the data and later copy to GO's
Entities
.WithAll<PlayerCameraHolderTag>()
.ForEach((ref Rotation rotation, in LocalToWorld ltw) =>
{
camera.transform.SetPositionAndRotation(ltw.Position, ltw.Rotation);
}).WithoutBurst().Run();
here's how I do it rn
tbf, if you're only iterating one object and applying it once, it's kinda negligable
if you were doing something like that say 10k times, then it'd be worth looking at it
it's singleton entity
I think
I'll just access entity manager
outside of system loop
tbh a lot of player stuff that only ever has a single object could just be done as mono's or whatever
the benefit of jobs/ecs is where you have a lot of something to do, or some computationally intensive stuff like finding nearest enemy from a long list of enemies etc
well
world entities can only interact with entities
they don't know nothing about game objects
so I keep player entity as entity
thus it helps
with having character controller
and etc
yeah i mean it's def possible and useful to keep your player code inside a system loop, and use entities for it, that can be referenced by say other ecs systems or code
so, how do I access Entity components from my GO?
You can use entities package
and through the entitymanager, or foreach lambda and such
Actually did a quick test and not the lambda but can still put it in a system and access it, or call ToArray() on a query and iterate the container, and so on and so on...
And for the EM, you access it through the World.
I think I can, but Scriptable Objects play well with DOTS?
that was the plan
if im starting from scratch, I shouldnt use them at all? Just use AuthoringComponents or something instead?
Just wanna be able to let my designers create objects and stuff
depends on scope I guess. I find scriptable objects nice when you have a custom editor window. So I use them pretty often for designer folks to customize data - then stash the data into a blob asset on conversion
you can easily use a SO in an authoring component and then simply transform the data
best of both
Interesting. Why is that?
I disagree, 2D is just dimensions
if you have 2D rts
you're gonna love it
if it's 2D platformer with bosses...
well
hard time
I'm confused. Why would game genre make a difference? You have things doing stuff to the other things every frame. The only difference I can think of is inputs. And I guess RTSes might have some kinda build or movement queue if you get really advanced with it.
Don't really know, I'm kind of building a platformer with dots and it works? I use my own custom physics system instead of Unity Physics.
I think it's more of understand how data is transformed and what data requirements you need that trips ppl up when building a game in an ECS/DOTS fashion 🤔
I mean there's no 2D support yet, right ? You'll have to handle everything yourself. Last time I checked you had to texture a quad mesh to render something.... Project Tiny is discontinued, right ? Maybe I lost track and that's not the case
maybe not discontinued, sorry wrong choice of wording here, but releases are slow ?
havent done any 2d games but have to imagine there are a lot of convenience stuff that you would miss making a 2d game in dots, 3d dots is already pretty bare bones but theres really nothing for explicit 2d(sprite) conversion unless you use tiny which as mr.k notes looks kinda abandoned
yea - no 2d IK unless you roll your own 😦
why not?
handling 2D seems easy
how much was involved in making your own custom physics @coarse turtle ?
I think it took me a few weeks?
It's pretty much setting up how I wanted to handle collision contacts and how that information was being passed around that took up most of my time, but otherwise it was fairly straight forward
heh i feel thats the amount of time it took to repurpose the unity physics character controller 😩
lol, yea I tried looking at that and I closed the example 😦
but I don't really support like everything that like unity 2d physics comes out of the box
just the stuff I need so, n sided polygons and everything has to have a rigidbody 👀
no such thing as a collider only
Entity entity = cameraHolderQuery.GetSingletonEntity();
I assume that's legal to use ONLY if query has only 1 entity?
Yea
var desc = new EntityQueryDesc()
{
All = new ComponentType[] { ComponentType.ReadOnly<PlayerCameraHolderTag>() }
};
cameraHolderQuery = world.EntityManager.CreateEntityQuery(desc);
query should be created only once right?
per world
Yea
it does a look up internally to find the best matching query if you attempt to create the query again
damn, I just realised
that if I assign camera position without running all other jobs for positioning it
I'm 1 frame behind
isn't that fine?
I am not a fan of only getting all the transform stuff updated in one system at one point
idk, I kinda aim for fast paced game
like, read input, turn player entity, now the weapon who is a child is one frame behind, spawn the bullet, its a mess
not sure yet what is the proper way
in some tests I ended up making the transformsystem run at multiple points
my read input is always ahead of systems
because it's in mono
kek
my controllers run in special group
but I would love to have a formal static helper utility that allow you to change some transform in the whole hierarchy for an entity
sure, for a ton of stuff handling in on a system is fine, but sometimes I would like to pay the cost of updating the transform inlne, like it happes with regular GO
i guess could just have a system that runs last, updating the transform and child transforms, after all other systems..
yeah this is what i was hinting at earlier today.. basically with dots, to conform to sync points and still have things update within a single frame, and do all the same stuff that a monobehaviour takes for granted, you kinda have to reinvent the wheel in a way.. what you end up with is a bunch of jobs or systems that all do specific separate tasks, being really careful about what data is being updated and being really specific about the order of things within the frame and in relation to ecb's and sync points
there are currently some annoying little caveats with parenting, you mentioned child objects being a frame behind.. it is possible to fix that problem though.. basically i ended up with a manual parenting system that does it
@wooden canopy couldnt you just introduce a counter that starts and then when its 1 frame, then spawn the projectile after the transform system and next frame occurs?
Is it common to get Access Sharing violations when saving scripts while using DOTS? I have to kill Unity several times for it to stop
maybe once every other week I might get something like that? certainly not a common occurence though
hmm. I wonder if its because I wake my computer up
Do you have the DOTS Inspector open by any chance?
I vaguely remember that it tends to throw these errors
yea, i'll try closing it next the the errors happen
hmm
I wonder how to handle different weapons shooting
like, some guns do full auto, while other will only shoot one per click
while making system for each seems like a really bad design
why would it be bad design to have a system for each?
Your system only runs if Weapon, WeaponAuto and WeaponEquiped are there on the entity.
Perhaps that might be what is needed if I wanted to make a simulation for a million units, but if you are making something more normal, and you still like what ECS brings to the table in terms of architecture and organization, then I think it stops making much sense.
Some stuff is super reasonable to have delayed and processed in a mega optimal way, but for other stuff you want stuff to be more instant.
For example, a common choice is should new entities start being processed the instant they are created or should they be delayed to the next systems update.
In the overwatch gdc talk they mention that at first they delayed entity creation, but ended up changing to have it work in sync, because it solved a ton of difficult to fix bugs related to 1 frame off issues.
Unity went with an intermediate solution, you delay the changes until you reach a sync point.
you could write chunk logic instead of having a system for each weapon type 🤔 But i imagine it depends on the scope and how many systems/jobs you have running simultaneously
I just use a bool for if its a single shot vs auto 🤔
suppose you could predict the future position based on current velocity and spawn it there? I dont do any delay for my bullet instantiation and tbh im not really sure if its noticeable at regular fps movement speeds(im not making overwatch 🥲 ). if you were doing a anything else moving faster like involving cars then maybe this is more of a big deal, or maybe im not seeing how important it is 🙂
i might be wrong but i think maybe you're kinda mixing a few different problems together.. having 1 frame delay is actually a matter of choice it's not a rule or something fundamental.. you have a bunch of pre-defined sync points with ECB's, it's your choice whether you instantiate something at an early sync point, then change some data at a later sync point, then do something else at an even later sync point, all within the same frame..
the kinda default way of thinking is, you have one system that say spawns some bullets and sets positions etc on them.. whereas you might have one system to spawn them, then a separate system at a later sync point which grabs all shoot positions and sets bullet translations to those positions etc..
so it's kindof an architectural problem/decision
maybe with overwatch they were restricted to one sync point within a frame, or maybe the problem they were having was that instantiating objects and those kind of structural changes were causing a lag if they tried to do it all in one frame
Ooof! Well you guys asked for it, and it's up there in complexity for this channel! XD In this video I demonstrate how CPU Extensions can be used in your C++ programs via Compiler Intrinsic Functions to perform SIMD parallel operations. First I demonstrate how these extensions look and feel, then I implement the Mandelbrot Fractal generation cod...
I found this gold mine of a video
time to dive deep into intrinsics in burst
https://docs.microsoft.com/en-us/cpp/intrinsics/x64-amd64-intrinsics-list?view=msvc-170 not sure if his hour long video uses this reference/associated reference page, if it does 👍
Is there a way to have entity prefab without keeping an entity in subscene?
Basically I want to have a lot of scenes
And I don't want to manually add all prefabs to them
Instead I want global prefabs
static or smth
an entity prefab is really just a regular prefab
why do you need to add them to all scenes
is this because you're destroying worlds on every scene change?
not really, it's because I have unique subscenes
and I want to contain only relevant to this exact subscene data in it
excluding anything that is common
between several subscenes
ok, nvm
it was easier than I thought
I just didn't know what blobAssetStore is
InvalidOperationException: The BlobAssetReference is not valid. Likely it has already been unloaded or released.
Hmm, any idea on this?
happens on spawning prefab
after I added physics body and shape to it
here how I spawn it and get prefab
You can't dispose the blob asset (store) until you're done with it
yep
Keep a reference, dispose in ondestroy
yeah, I wonder how to organize it
Is there an advantage to using BlobAssetReferences instead of plain structs if I don't plan on putting them in entities?
e.g. instead of a NativeHashmap<Key, StructType>, using a NativeHashmap<Key, BlobAssetReference<StructType>> ?
no
I'm guessing world space coordinates are absolutely same for entities world?
In order to create any sort of raycasts and etc I need to run system between those systems below, right?
UpdateAfter(typeof(ExportPhysicsWorld)), UpdateBefore(typeof(EndFramePhysicsSystem)
I assume physics world doesn't exist in entities world
and it just gets created as temporary step
[BurstCompile]
public static class PhysicsUtils
If I do this, does it mean that all methods in that class would be compiled with burst?
(to avoid putting attribute on all methods)
Is it safe to have a native collection containing a struct that contains a native collection, as long as all data is only ever read?
no that doesn't work unfortunately. a native collection itself contains a class DisposeSentinel ......which is, despite it's name, only used for profiler markers and to ensure the collection is being disposed in time (4 frames e.g.) but has no 'real' use.
That's odd, since it seemed to work. I had a custom Entities package that removed some safety code which blocked you from using generics in BlobAssetReferences. Everything worked, but after adding that safety feature back in it is complaining about a NativeHashmap<Key, Struct>, where the struct contains a NativeList.
I assumed it would work again if I used unsafe collections, but I thought I would ask
yeah unsafe collections would probably work,....but i've had plenty of native collections not being disposed despite thinking that i would so, if you can make it plug and play with aliases or so to have safety features when writing new code.....maybe that could work
or unity would just remove the fricking class and find a dots solution for it XD
Yeah it didn't seem to dispose correctly when I stopped playmode, but creating a bunch and disposing them again worked fine, atleast the safety system wasn't complaining.
also, i've found another 'problem' with native collections. at least in a kinda niche project of mine
1 - native collections can at max have int.MaxValue elements.
2 - that's not even true, because they can only contain int.MaxValue = <structSize> * elements elements
this makes it incredibly difficult to work withlong values and a long count in dots
or....anything really you have to do more than int.MaxValue amount of times
One thing I really have difficulty with in DOTS is nested containers of immutable data, I still have no solution that I really like
e.g. something like
struct DataContainer
{
NativeHashMap<SomeKey, SomeData> MyLookup;
}
public NativeHashMap<AnotherCoolKey, DataContainer> Data;
which isn't allowed by the safety system
if you've only got relatively few data to nest into a container, you could use a tuple, i've done that a few times
I've solved this by making everything flat and then using a int2 to tell the start and length of each nested thing
It gets annoying but it's really good for DOTS stuff
the other way which doesn't really care about linear memory layout is pointer to the unsafe container 👀
NativeHashMap<key, UnsafeHashMap<T, U>*>
if anyone has any idea how to gracefully get around the int.MaxValue limitation in dots, that would be appreciated
UnsafeUtility.Malloc uses a long although i guess you'd be rolling out custom containers
I think you can do nested containers fine with Blobassets
but then you can't change the data once its created
I have a question I don't suppose anyone knows if theres a simple burstable way of turning on and off the rendermesh
it doesn't seem to allow me to manipulate the rendermesh at all, so maybe there is another way I don't want to have to destroy and create the entity's when I just want to manipulate the rendering of them 🤔
This isn't really an issue (the immutability), but blob assets only support BlobArray, there is no e.g. BlobHashMap
This will probably be my solution, even if it's error prone. I hope they come up with something easier / safer to use in the future
can you not use your own custom struct
public struct myhasmap(int key, int somedata) etc
That's what I mentioned earlier
here
The safety system doesn't let you do that
Is there anywhere an explanation how to use BelongsTo and CollidesWith outside of fancy editor?
In code it's just uint
Hmm, ill try that later
On the topic of blobs, what happens if a component has a BlobAssetReference, and you serialize then deserialize the world?
that I do not know
Also, if you can have nativecollections inside blobs, what is the point of blobarray<T>? Since then you could just use NativeArray / NativeList...
can you use nativearrays in Blobs? 😕
I mean, you just said I could eaerlier
^
Since the blobified struct contains a nativecollection
I meant you could use structs of any types, except for unmanaged data
Then I'm back to my initial problem of not having a good solution for complex nested immutable data
You can feed them bitmasks to select layers, kinda like the layer matrix with physx
Yes you can index 50 different blob arrays to recreate your data, but its a hassle with a lot of boilerplate
how do I do that?
Need to add your layers to this asset
BelongsTo = (1 << 5),
let's say this
is that gonna make collider belong to Projectile?
I mean you can have blobarrays in blobarrays
in the struct you can i.e. say BelongsTo = (1u << yourLayer1) | (1u << yourLayer2)
and how do I define myLayer1
Yes, but then I would still need some kind of indexing scheme, unless I want to go through the entire array each time I need to find something
so simply index from 0 to 31?
it's the index of the layer, like you said
~0
wouldn't you need to do that anyway, plus blobarrays are really efficient to do that sort of thing with
~0u to *inverse all zeros , so ALL
0u would be nothing?
Well, if I had a NativeHashMap I can just give it the key and get my value
I guess you could write a helper method to search through the array 🤷
depending on the size of the list that might take longer than just going through the whole list
yes, will fill the bitmask with zeros
Maybe Ill go with that, even if it seems kind of clunky
Converting ScriptableObjects to ECS-usable data in general is something I have trouble with
belongs to Projectile (layer 5)
collides with "not player" and with "enemies"
or wait, I think that's not legal
so just want to collide with layer 1 ?
uint layer = 1 << 0; // This is 1;
// I think this looks redundant here
CollidesWith = ~layer | (1 << 1);
~layer = flip all bits, so the least endian bit is going to be 0, while every other bit is 1
| (1 << 1) = this is going to be 2, which is specified by ~layer when you bitwise OR the values
no need for help here
Just need some practice I guess
I assume it comes down to either: exluding all unwanted or gathering all wanted
Ok, this one needs help
Entity camera = GetSingletonEntity<PlayerCameraHolderTag>();
LocalToWorld ltw = EntityManager.GetComponentData<LocalToWorld>(camera);
float3 from = ltw.Position;
float3 to = UnityEngine.Camera.main.ScreenToWorldPoint(new float3(0.5f, 0.5f, 10f));
CollisionFilter filter = new CollisionFilter()
{
BelongsTo = (1 << 5),
CollidesWith = (1u << 1)
};
RaycastInput input = new RaycastInput()
{
Start = from,
End = to,
Filter = filter
};
if (collisionWorld.CastRay(input, out RaycastHit closestHit))
{
UnityEngine.Debug.Log(closestHit.Position);
}
I'm trying out simple raycast
from camera position to middle screen position
that will only hit colliders with layer "enemies"
so I get LocalToWorld of camera container entity
grab it's position
get world point from center of screen with depth of 10 units
and cast ray that belongs to projectile and collides with enemies
yet, it doesn't hit
(no debug log)
is there any obvious mistakes here?
my layers for reference
I'm wondering if the from and to positions are long enough to hit something
I'm trying them point blank
try CollidesWith = ~0 to see if it hits anything at point blank
i haven't used the physics system enough to know the caveats
I tried
it does
it hits even when I look at sky
I guess it hits player
since camera is attached to player collider
oh so if you do ~(1 << 0) - it doesn't hit the player right?
let's see
bruh, C# is funny
forces me create variable
to use ~
ok
it doesn't collide with player no
but doesn't collide with anythin
oh oh
looks like I failed at smth
when I look exactly like this
I get collisions
yea sorry don't know enough about the caveats of Unity Physics package
Both sides have to want to collide
check layers for enemies too
oh didnt see you got collisions... from the side ?
it seems like it's not dots related question, but rather screen to world question, to avoid crosspost I moved it to #archived-code-general
float3 to = UnityEngine.Camera.main.ScreenToWorldPoint(new float3(0.5f, 0.5f, 10f)); screenspace is supposed to be in pixels, not between 0 and 1, right ?
yeah...
Try Screen.width /2 ?
you're shooting half a pixel from the bottom left corner :p
oh haha nice catch
what is better approach at assigning collision filters?
rn I have demo scene full of GO Colliders
do I have to go through all of them
and switch colliders onto physics shapes?
also not particulary certain how to get mesh from probuilder into physics shape
I don't think it's even possible in editor
make a prefab ? and apply override to all
oh i see you put a bunch non-prefab
try ctrl+click each one from the hierarchy
when they have same components you can mass-edit
what about pro builder meshes tho?
hm
does conversion system uses anything else otherwise?
to apply those filters
I guess I can make authoring script
that will edit collider
lul
it appears Pro Builder has some sort of script that attaches reference of it's mesh
to Mesh Collider of GO
then you can copy it and paste into Physics Shape
xD
F, it resets
oh, nice find
I never knew it was a thing
apparently I'm not supposed to ignore them
as some core features are hardcoded on those layer indexes
IF I use helper classes ofc
oh, nvm
It's 3rd party utility class lul
Any idea if you can use Jobs/Burst without unity editor? As Mod for other unity game I mean, assuming said game has no such packages
the basic jobs are built into the unity editor so as long as it's not stripped, all the logic for executing the workers would be there
as for burst hmm not sure
the burst mod documentation says you need to call
BurstRuntime.LoadAdditionalLibrary(burstedAssembly);
i have not looked at what this method does
i think in theory you could probably replicate this layer and get it to work
Do you also happen to know whether you can implement ITriggerEventsJob through SystemBase?
I kind of really dislike syntax of implementing JobComponent systems
navigating through file is hell
you can use any job in systembase
nothing stopping you using normal jobs in there
just use
Dependency = new MyJob {}.ScheduleParallel;
i barely use entities.foreach
most of my jobs are just jobs in systembase
I mean, if there's an easier way to iterate through trigger events
similiar to Entites.foreach
ITriggerEventsJob is the only default way to do it
I see
the samples have a state version which puts events in a buffer
yeah, I remember that one
you need to add that sample system
to get stateful events
so, is that it?
You are forced to iterate through literally all trigger events?
is that even paralleled?
Are there any DOTS or ECS example projects to learn from? I look on the Unity Asset Store and all that comes up is pixel art and third-party implementations of general ECS concepts.
moetsi dots tutorial is also great to begin
I personally found it the best beginners source of info for dots
I... is this official? The name kind of makes it sound like Unity Team released this.
Unity: Owns the entire Unity Asset Store. Also Unity: provides necessary official resources via github. smh. -_-
github one is unity
I guess it's because they feel DOTS/ECS is too fluid right now to clutter up the asset store with example projects that will just be deprecated later?
dots is still alpha or smth
pre alpha really i guess