#archived-dots
1 messages · Page 245 of 1
this +1
RequireForUpdate is helpful because it prevents whole OnUpdate() run not only single .ForEach()
Hey all! What's the recommended way to store a list that's meant to be accessible and modified by a system? I tried creating a NativeList in OnCreate, but I'm getting the following error: Burst error BC1042: The managed class type Unity.Collections.NativeList1<Unity.Entities.Entity>* is not supported. Loading from a non-readonly static field RockMine.C4.Agents.NavigationDijkstraPathingSystem._navigationQualityGroupEntities is not supported. Do I need to create a dummy entity with a DynamicBuffer to store this data? Or is there a simpler way?
It's perfectly fine to use NativeList in Systems, not sure why you're getting an error really? 🤔
public class SomeSystem : SystemBase
{
private NativeList<Entity> _entities;
protected override void OnCreate()
{
_entities = new NativeList<Entity>(16, Allocator.Persistent);
}
protected override void OnDestroy()
{
_entities.Dispose();
}
}
welp, now this weird bug persists even in build
ok, small question: does anyone have experience in rust? if so, what is the c# equivalent to usize?
not familiar with rust but is that just the size of int?
no. at least i don't think so
usize is platform dependent
interesting graphic style you have going on here 🤣
So on 64 bit machines believe it should be a 64 bit uint
The IntPtr type is designed to be an integer whose size is platform-specific. That is, an instance of this type is expected to be 32-bits on 32-bit hardware and operating systems, and 64-bits on 64-bit hardware and operating systems.
so is IntPtr
is it not equiv?
Should be equivalent
the thing is, i want to convert some rust code and in there it's let tmp = someNumber as usize which....doesn't make much sense when IntPtr.Size is an int value
Could treat it as a 32 bit uint if you know the upper and lower bounds of the whatever the rust side is doing?
yeah i've just cast it to long since i'm on a 64 bit machine, so i guess it should be fine. but i was just curious about usize
what is somenumber anyway
or should i use ulong?
just some seed number which gets converted from long to double and back a lot
is it being converted or just reinterpreted?
Oh, maybe stick with ulong if you don't wanna lose bytes during the conversion from 64 to 32 bit?
e.g. 1 line is index[3] = (iseed as f64 / F32 * SOLIDS.len() as f64) as usize;
Yea I guess ulong would make sense
i'm not really converting anything to 32 bit since almost everything in that code uses i64 which is a long i guess
but yeah, maybe i'll change these things to ulong. i literally have no experience in rust so, it's been a bit of guesswork and googling
Yea id probably just stick with ulong.
Yeah, it's strange. I wonder if it's because in my case _entities is static? From my understanding, methods called inside OnUpdate need to be static, right? At least I'm getting the following error if they're not static: error DC0002: Entities.ForEach Lambda expression invokes 'GoalBufferUpdate' on a NavigationDijkstraPathingSystem which is a reference type. This is only allowed with .WithoutBurst() and .Run(). In order for it to be accessible from within other methods, _entities needs to be either static or passed as an argument to the methods called in OnUpdate. When it's static I get the error in my original question. When I pass it as an argument I get the following error: error DC0001: Entities.ForEach Lambda expression uses field '_navigationQualityGroupEntities 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(). I have no idea what else to try, honestly.
@verbal pewter i feel like you're doing something like this
protected override OnUpdate()
{
Job.WithCode(() => {
var entity = _entities[0]
}```
you can't access the list in that scope
protected override OnUpdate()
{
var entities = _entities;
Job.WithCode(() => {
var entity = entities[0]
}
is what you need to do
Oh really? Let me give that a try.
Yep, that seemed to have fixed it! What a completely unintuitive thing to have to do. Anyways, thank you!
i always felt this is the problem with new people learning entities and their first experience being entities.foreach/job.withcode
it completely hides what's going on under the hood
for any new dev i need to teach it's the last thing i show them and by this time these quirks all make sense
Yeah, fair enough
but yeah, not really any fault of your own. it's just how it's presented these days in both the manual and most online tutorials
and there are a lot of quirks you have to hurdle across which makes starting with entities a huge pain for many people
For sure
like a quick question, i'm not sure of your experience so maybe this is obvious to you but do you know that Entities.ForEach/Job.WithCode isn't actually real code, it's just a stub and the whole thing is code generated under the hood?
hi. is it possible to view the generated code?
@lusty pewter
when they change to source generators (hopefully) that'll be much more nicer too
so it generates me an IJobChunk job which is superseded by IJobEntityBatch according to the docs?🧐
preview is preview
good point
thank you btw. been working too long with Entities.ForEach without knowing this
it will generate IJobEntityBatch in 0.50
the docs for EntityCommandBuffer.AddComponent(EntityQuery, ComponentType) state that "The query is performed at playback time, not when the method is called.". does anyone by chance now if this is guaranteed to be before or after any other changes are executed?
Not sure what you mean? If you enqueue multiple commands they will be executed in the order you enqueued them
heads up the behavior for this is changing in 0.50
currently it executes at the time the command buffer plays back, so the entities it could be used on are different to when it's called
so the EntityQuery is handled the same way as any other recorded change? i usually use EntityCommandBuffer.AddComponent(Entity, ComponentType) to record changes and not the EntityQuery version
from memory, in 0.50 it will on the spot query all entities it could match then store them in the buffer
this is much slower but much more predictable
so if i have changes in the buffer that generate entities that match the query they will be changed as well?
if they were passed to the buffer (or another buffer) before you call this method
then yes they will also be affected (currently)
in 0.50 they will not
i see. thank you very much.
did unity announce this as a behavior change? is there a list of known changes for 0.50?
i'm pretty certain a dev posted this on the forums otherwise i've said something i shouldn't 😅
it was just a random post in one of the longer threads so i cbf finding the source
if someone asks i tell them i didn't read anything 😉
didn't read what?
here we go: https://forum.unity.com/threads/question-with-ecb-removecomponent-t-entityquery.1209505/#post-7725696
It turns out that the EntityCommandBuffer commands which evaluate their EntityQuery targets at playback time are problematic for many reasons; this is one of them. We've removed them internally for the next DOTS release; going forward, the EntityCommandBuffer.*ForEntityQuery() variants will be the only way to target queries with ECB commands. These variants evaluate the provided query at command-recording time, and serialize the list of matching entities. This can be slower than the alternative for queries matching a large number of entities, but provides a much more predictable (and less error-prone) experience.
I actually just wondered
what if
instead of changing archetypes of certain entity
you'll create new entity of your wanted archetype instead and just copy all values over to it from old entity. and then remove it.
Like do it all yourself.
Is it gonna be as slow as changing archetype or?
it's a structural change just like adding or removing a component which is slow
ah
So I did this and I'm kinda stuck again cus I'm not sure WHY this is happening:
I had a path creator system in my assets that I used a while ago and decided to reuse for this, since it seemed to be along the same line of thought. It's really simple and normal gameObjects simply follow the path by just attaching a script that is already inported with the Asset
Using this I make a path, turned it into an entity, attached the entity to the main spawn system as a prefab and attached the follower code to the bees
but for some reason it's not working
I checked that the path is spawning and the code is correct as well as converted to an entity but I'm not sure what I'm doing wrong?

Is reading from NativeStream is fast as from NativeArray?
no
nothing can really be as fast as reading a native array, it's pretty much direct memory access
but nativestream allows parallel writing and reading which is a huge benefit
how to overcome the limit of arguments in the Entities ForEach method
@hollow jolt
https://docs.unity3d.com/Packages/com.unity.entities@0.17/manual/ecs_entities_foreach.html the section "custom delegates" should explain this
that's nice , thanks
How would you handle a projectile that gets stuck in the enemy when hit? If you just parent the projectile to the entity the parent component will become invalid and trigger an error as soon as the enemy is being destroyed.
destroy the projectile as well
so you mean crawling through children of the enemy and check each one if it has a component of type projectile and destroy it?
there is a foreach that runs on each entity with an enemy and a dead component. so I would then have to check each of its children for any projectile components. Or do you have any better idea?
i thought you parented it to the enemy? just get it from the children component and destroy the projectile. also, if you have parented the entities correctly, it should automatically destroy the projectile
afaik destroyEntity does not destroy children but only entities in a linked entity group
I don't suppose anyone can tell if I've got the thinking of the below code correctly
if (!TempRecordEventBool.boolVal && currRobstate.currrobstat != RobotState.PackingShopping && currTillat.floatVal == 0)
{
return;
}```
if put inside a job that means it should exit the job straight away if any of the above statements are true correct
is it possible to not schedule the job instead of doing checks inside it?
not really I've tried that way and can't get it to work
althought thinking about it I could just surround the whole job within the If(TempRecordEvent.Bool) code 🤔
not that I know of
not using any unsafe code*
if you need arrays outside systems then you use DynamicBuffers
as far as I know you shouldn't keep any data in systems so how should I keep i.e. native hash map?
there's no rule against it you can keep data in systems if you want
it can just be a bit more hassle to get it when you need it
yeah but rules are made to be broken and sometimes you've just gotta do what works
I mean DOTS is still really new and people are still figuring out all the rules and supposed correct ways to use it
maybe dots but DOD or ECS exists for a long time
but seems DOTS has only DB to contain arraylike data
seems reasonable to while thinking about entities like i.e. units
but it's strange to keep my map as a dynamic buffer
especially when restricted to single thread write
I know I already recently asked this, but I forgot my follow up, so here it is again:
Is StepPhysicsWorld incredibly slow for anyone else? Even with a single physics entity it takes up like 6 ms
This is with all safety features turned off
Burst on
Using normal unity physics
Hello guys,
After many test with AsyncGPU, i have last question.
Who is more efficient for no loose frame.
Step one with sync or
Step two with async ?
What's the best practices recommendation for cases where you need to have settings accessible and changeable within jobs? As an example, I'd like to keep track of a simulationStep value that gets updated every step. This needs to be settable at the start of the program running since it's going to be saved between play sessions. I was hoping to create a static class with static values, but it seems that Burst can only access static values that are also marked as readonly. My only thought is to create an entity that will have a SettingsData component on it. Then it would be accessed/modified in the same way as any other component. Is there a better way to go about this?
I assume direct static property is faster than any singleton entity component, or?
not relevant to question above
It's actually kind of relevant to my question hahah, I didn't know about singleton entities. That's probably what we're meant to use for settings shared across the project. But as far as I can tell this can't be used in cases where you'd want settings to be a list (or DynamicBuffer, I guess). Still seems like creating an entity to store all the data and DynamicBuffers representing your settings is the way to go.
afaik if you want your settings to be changable from withing a job, singleton entities are the way to go. there are some convenience methods to work with singleton entities. for example "getSingleton" and "getSingletonEntity" in SystemBase
Ahhhhh thanks for mentioning GetSingletonEntity, learning all kinds of things tonight. That should let me get DynamicBuffers as well.
and if you to use your singleton as update requirement use RequireSingletonForUpdate()
Can you clarify what you mean by "update requirement"? Is that a way to ensure there are no updates unless the singleton exists?
are you using Entities.ForEach to schedule your jobs?
What is the array equivalent for use inside an Entities.ForEach? I have an array with 3 items that does not need to be added to. I can't use array or any ienumerable as it's not burst compatible
NativeArray
You can also specify .WithReadOnly() in the Entities.ForEach
you can use https://docs.unity3d.com/Packages/com.unity.entities@0.9/api/Unity.Entities.ComponentSystemBase.html#Unity_Entities_ComponentSystemBase_RequireForUpdate_Unity_Entities_EntityQuery_ to add new entityQueries as condition when to schedule your job
didn't find the docs section i wanted. i'll send a better link later
Fantastic! Can you also tell me the dictionary equivalent?
NativeHashMap
Thanks for the link, I think I understand. Along with that I was looking at GetSingletonEntity a bit closer. It looks like that's part of ComponentSystemBase, so it can't be called from a MonoBehavior, for example. In the case of needing to be able to set a simulationStep value at the start of the program, it seems like you'd need to: 1) Create the entity in the MonoBehavior, 2) Add the component to the entity in the MonoBehavior, 3) In the OnCreate method of a system, get the entity, get the component data from the entity, and set that component data as a singleton. Does that sound right?
Edvard, you should be looking more at the conversion workflow: https://docs.unity3d.com/Packages/com.unity.entities@0.17/manual/conversion.html
Thanks, will do!
Also, the singleton exists on merit as being the only instance of that component. SetSingleton updates the VALUE of the component data that is the only one of its kind. You do not designate a componentdata AS a singleton
Okay, makes sense, thank you
can anyone help answer this?
honestly, we have no idea what you're really doing with that except that it seems like you're trying to reuse a Monobehaviour script that was applied to each bee GO and wondering why it's not working in a entities environment. There are myriad possible reasons for this.

well yes, but no. There's only 1 bee prefab, which is spawned as many times as I want (I can put in a number for how many I want to spawn in the inspector through a Spawn system script: ||https://pastebin.com/kCgq6cwF||)
I also do the exact same thing to spawn the track and so I assumed that since bot were entities, they would just follow the code after it immediately. But yeah, I guess not
I mean, do you have a system managing the bees locomotion? I understand that you're generating a path somehow, but what's moving the bees around it?
oh yes, I do
||https://pastebin.com/uxAQu68J||
So, the path follower monobehaviour has no affect on entities
I'm just grabbing the prefab and slotting it in
ooooh
a core tenet of ecs is that processing is not affixed to data
you need a SystemBase, or ISystemBase, that iterates through your bees if you want them to follow the path
damn ain't ever been taught about this 
you got any videos you recommend to watch to understand this then?
np, good luck
dumb question, but is there an easy way to find if a nativeArray contains a particular element? .contains() or .indexOf() doesn't seem burst compatible - if there's a resource I can refer to of the list of possible burst compatible methods I can run that'd be even better
are you trying to use linq versions of contains/indexof?
NativeArrayExtensions contains burst safe versions of Contains, IndexOf etc
your type must implement IEquatable<T>
/// Determines whether an element is in the native array.
/// </summary>
/// <typeparam name="T">The type of values in the array.</typeparam>
/// <typeparam name="U">The value type.</typeparam>
/// <param name="array">Array to perform search.</param>
/// <param name="value">The value to locate.</param>
/// <returns>True, if element is found.</returns>
[BurstCompatible(GenericTypeArguments = new [] { typeof(int), typeof(int) })]
public static bool Contains<T, U>(this NativeArray<T> array, U value) where T : struct, IEquatable<U>
{
return IndexOf<T, U>(array.GetUnsafeReadOnlyPtr(), array.Length, value) != -1;
}
/// <summary>
/// Searches for the specified element in native array.
/// </summary>
/// <typeparam name="T">The type of values in the array.</typeparam>
/// <typeparam name="U">The value type.</typeparam>
/// <param name="array">Array to perform search.</param>
/// <param name="value">The value to locate.</param>
/// <returns>The zero-based index of the first occurrence element if found, otherwise returns -1.</returns>
[BurstCompatible(GenericTypeArguments = new [] { typeof(int), typeof(int) })]
public static int IndexOf<T, U>(this NativeArray<T> array, U value) where T : struct, IEquatable<U>
{
return IndexOf<T, U>(array.GetUnsafeReadOnlyPtr(), array.Length, value);
}```
Hello, i was wondering where the best place is to see the current progress on DOTS to a fully stable release
ah thanks, i haven't come across this one yet
ok so. im trying to learn how to use DOTS and one thing i'd like to do is within Entities.ForEach I would like to be able to reference other entities as the input. Like, I have a bunch of entities with a Block component that has a coordinates component and I would like to, within a foreach for one block, access the coordinates of other blocks
is that possible?
you'll need to stash the other Block entities in a container and then read them in the job
There's ComponentDataFromEntity, which you can use for the look up once you have the entities
ok, so with the Entities.Foreach I would interatively store the blocks in a big list and then work on that list
That's the basic idea if you want to reference other blocks while iterating. Pretty sure there are better optimal ways if anything.
Hey there, I'm trying to learn DOTS however I have this problem: whenever there is a PhysicsBody I get an IndexOutOfRangeException. It is the same whether it is a RigidBody being converted, or whether it is a PhysicsBody from the beginning.
This is the complete error I'm getting on apparently every frame
IndexOutOfRangeException: Index 0 is out of range of '0' Length.
Unity.Collections.NativeArray`1[T].FailOutOfRangeError (System.Int32 index) (at <d3b66f0ad4e34a55b6ef91ab84878193>:0)
Unity.Collections.NativeArray`1[T].CheckElementReadAccess (System.Int32 index) (at <d3b66f0ad4e34a55b6ef91ab84878193>:0)
Unity.Collections.NativeArray`1[T].get_Item (System.Int32 index) (at <d3b66f0ad4e34a55b6ef91ab84878193>:0)
Unity.Physics.Broadphase+DynamicVsDynamicFindOverlappingPairsJob.Execute (System.Int32 index) (at Library/PackageCache/com.unity.physics@0.6.0-preview.3/Unity.Physics/Collision/World/Broadphase.cs:1052)
Unity.Jobs.IJobParallelForDeferExtensions+JobParallelForDeferProducer`1[T].Execute (T& jobData, System.IntPtr additionalPtr, System.IntPtr bufferRangePatchData, Unity.Jobs.LowLevel.Unsafe.JobRanges& ranges, System.Int32 jobIndex) (at Library/PackageCache/com.unity.jobs@0.8.0-preview.23/Unity.Jobs/IJobParallelForDefer.cs:62)
Removing the RigidBody or PhysicsBody makes it disappear
I think the error is misleading. Do you have declared a NativeArray somewhere that you forgot to instantiate by any chance ?
Nope, I haven’t done any code yet
100% blank project with a converted rigidbody ?
@rotund token btw why EventSystem : EventSystemBase and not say just EventSystem : SystemBase when eventsystem itself doesnt contain anything ? Ive noticed this paradigm in unity's own class usage
because you can implement more than 1 eventsystembase
FixedEventSystem : EventSystemBase
MyCustomEventSystem : EventSystemBase
ah right
(and you can optionally implement them in different ways implementing a variety of virtual members)
Yup, well I used the URP template but I deleted almost everything except the URP config stuff
Unity 2020.3.26f1
Entities 0.17
Physics 0.6
yeah probs an editor derp if zero code 🙂
Well I restarted the editor and tried with Burst enabled and disabled and it’s the same @karmic basin @safe lintel
How do I implement IEquatable on enums/strings? I have an array of enums(or strings) which I want to do a contains check on
first of all, get far far away from strings when working with dots
Uhm... unless there's something wrong with 2020.3.26f1 + these packages versions, I don't see... I mean you have zero code, right ? sooooo... maybe regenerating project files could help
second: that's not possible currently in c#. you have to encapsulate the type in one type you created and then implement IEquatable in the type you've written
Still no luck
can you screenshot the inspector of your object ?
Here's the GameObject and it's converted entity
Hey guys! I just figured out Unity with gameobjects/mono won't allow me to do what I was hoping to almost certainly. Which means either I move to Unreal, or DOTS. I'm going to give DOTS a serious try, but where do you start? Does anyone know any tutorials or resources/projects for:
- DOTS physics (rigidbody equivalent, raycasting, overlapsphere equivalent, checking collisions, translating objects)
- DOTS networking (basic rpc-like functionality, replication and synching)
- DOTS character controllers, camera controls, etc.
I have a huge grind ahead of me to learn these, but if you could point me to stuff it would be a lot easier. I already know there's a TPS project on github which I plan on studying, but the more of these the merrier
Inititally I had a Collider and a Rigidbody but that also gave me the error, so I changed added the PhysisBody and PhysicsShape instead, same result
ok so simple capsule with physics components... I don't know man. If you can reproduce form a blank project it's worth a bug report
@shrewd lion so you want to learn the kitchen sink, pinned messages has links to all of that(samples repos has character collider example)
Yeah Unity does the conversion for you from RB + collider so yeah same result
@pearl laurel if this is really an empty project, could toss it on github(without the library folder) for us to take a look at. have you tried opening the physics samples?
@shrewd lion you could also consider an intermediate solution between mono and DOTS, which is mono + Jobs
thanks, I'll check them out
I'll try it again on a new new project, I'm using the URP template but I delete everything except the URP config stuff (and some other stuff I'm not sure if I should delete, but no scripts are left in the project)
Unfortunately, I'm going to need a huge amount of entities with whatever is the ECS equivalent of mesh colliders (physics body?), and afaik GameObjects cannot collide or interact with those
@pearl laurel honestly none of that should matter, and ive setup dozens of mini projects with physics to repro bugs etc.
@shrewd lion tbh unreal might be better suited to your needs at the end of the day given how experimental and unfinished dots is
Probably, but I mean c++ is a pain in the ass to deal with, plus I'd have to learn everything from scratch anyway. Afaik you can't have many AActor objects in the scene either, which means I'd somehow have to modify the entire Unreal physics system to suit my project
That should be doable since I have the source but man.... not something I would look forward to
I'll still try to create a new project but that'll take a while, so this is the original project
@karmic basin @safe lintel
https://github.com/Agent5S/physics-bug-reproduction
Again an empty project, didn't even add the DOTS editor this time, same thing
I have never filed a bug before, so how should I go about it
🤔
help>report a bug. just opening it after installing the latest editor
Thanks, I'm doing that now
yeah getting that error. hmm
oh
unity 2020.3.26 is broken (and unity 2021.2.8f1)
broke deferred job arrays
I already contacted Unity, the fix is to edit the collections package and change AsDeferredJobArray allocator to Invalid from None
What do you think
(i'm literally telling you what's wrong)
either edit the collections package or downgrade to unity 2020.3.25
😵💫
how do I do that?
- go into YOURPROJECTLibrary/PackageCache/
- copy com.unity.collections@0.15.0-preview.21 into YOURPROJECT/Packages/
- open com.unity.collections@0.15.0-preview.21\Unity.Collections\NativeList.cs
- change line 599 from Allocator.None to Allocator.Invalid
Let me know if it fixes it, I haven't confirmed the fix on 2020.3.26 yet only 2021.2.8
@rotund token @pearl laurel dunno about that because im looking at my actual dots project and its working with collections 0.15.0.p21 with physics
admittedly im still on 2020.3.25 though for the editor
yeah im not 100% certain physics is broken with this, i only know for certain netcode is broken
but yes the bug was only introduced in 2020.3.26
but TransformIncrementalConversionSystem uses AsDeferredJobArray so I believe the entire Entities package is broken
if you check changelog
it's this line that broke it in 2020.3.26
Kernel: Fixed an issue where low bit set in NativeArray buffer pointer assumes NativeArray is created by NativeList.AsDeferredJobArray which is not always the case. In some cases NativeArray can be created by NativeArray.GetSubArray, where pointer would have lowest bit set for odd byte aligned offset. (1294627)
sadly ive only gotten one response back from the qa team on some of the bugs ive submitted since dots went dark, and that was "is the bug still affecting you?" so cant say im really pleased about how qa and dots team work currently
qa is useless for dots
as long as its reproducible, it should get to the dots team though right?
sure
anyway unity is should be fixing this in the next collections package but well since entities don't support new collection packages I suspect this fix will be required to use entities for any new version of 2020.3 and 2021.2 until 0.50 comes up
cool, none to invalid does fix it
can also confirm
@rotund token @safe lintel Thanks for helping
Though I wonder how long til I encounter the same thing just with another part on the same file

just pray for 0.50 to arrive soon
I wonder when will unity consider Pure DOTS?
based on this reply https://forum.unity.com/threads/dots-development-status-and-next-milestones-december-2021.1209727/page-7#post-7815696
It seems not any time soon.
i imagine when there's a 1:1 conversion substitute of everything
I'm kind of hoping the tooling for converting and declaring that an entity is a part of a world is better since they look like they're sticking w/ the conversion workflow.
netcode gave some good insight in how multiworld setup works but wasn't really enough 🤔
seems like they consider pure dots is when theres no reference to anything unityengine
What on earth does the error Entities.ForEach Lambda expression uses field 'blocks 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() mean
are you doing something like
protected override OnUpdate()
{
Entities.ForEach(() => { var test = blocks;}).Schedule();
} ```
as the error states, you need to do this
protected override OnUpdate()
{
var myBlocks = blocks;
Entities.ForEach(() => { var test = myBlocks; }).Schedule();
} ```
it's telling me that the error is in this chunk here
protected override void OnUpdate()
{
//initialize lists
m_vertices = new NativeArray<Vector3>(24 * DataLUTs.chunkSize * DataLUTs.chunkSize * DataLUTs.chunkSize, Allocator.Temp);
that's not possible because there's no Entities.ForEach there 😅
thats why i was so confused
Entities.ForEach((ref Block block) =>
{
blocks.Add(new BlockData
{
type = block.type,
coords = block.coordinates
});
}).Schedule();```
this is the foreach
what is Block
[Serializable]
public struct Block : IComponentData
{
public FixedString32 type; //must be less than 32 characters
[ReadOnly]
public int3 coordinates;
}
private struct BlockData
{
public FixedString32 type;
public int3 coords;
}
what do you mean
i can see blocks in your job
where is it stored
(be easier if you just posted the full onupdate or system code)
protected override void OnUpdate()
{
//initialize lists
m_vertices = new NativeArray<Vector3>(24 * DataLUTs.chunkSize * DataLUTs.chunkSize * DataLUTs.chunkSize, Allocator.Temp);
m_triangles = new NativeArray<int>(36 * DataLUTs.chunkSize * DataLUTs.chunkSize * DataLUTs.chunkSize, Allocator.Temp);
m_uvs = new NativeArray<Vector2>(24 * DataLUTs.chunkSize * DataLUTs.chunkSize * DataLUTs.chunkSize, Allocator.Temp);
blocks = new NativeList<BlockData>(Allocator.Temp);
m_vertexIndex = 0;
m_triangleIndex = 0;
//build list of blocks
Entities.ForEach((ref Block block) =>
{
blocks.Add(new BlockData
{
type = block.type,
coords = block.coordinates
});
}).Schedule();
//loop through blocks
foreach (var b in blocks)
{
if (IsSolid(b.coords)) //if this is a solid block to render (not air)
{
for (int side = 0; side < 6; side++) //draw sides
{
DrawSide(side, b.coords);
}
}
}
//create mesh
m_mesh = new Mesh
{
vertices = m_vertices.ToArray(),
uv = m_uvs.ToArray(),
triangles = m_triangles.ToArray(),
};
// do calculations
m_mesh.RecalculateNormals(); // normals
m_mesh.RecalculateBounds(); // for occluding
// set mesh as mesh
//gameObject.GetComponent<MeshFilter>().mesh = m_mesh;
//EntityManager entityManager = World.Active.EntityManager;
//Entities.ForEach()
// dispose of arrays
m_vertices.Dispose();
m_triangles.Dispose();
m_uvs.Dispose();
blocks.Dispose();
}
it's this exact issue i posted here
you need a local copy
otherwise the entire system gets brought into the job (which is not allowed for obvious reasons)
if you're code was simply
var blocks = new NativeList<BlockData>(Allocator.Temp);
it'd work
also this should be allocator TempJob not Temp as you're passing it into a job
ok cool, that fixed the errors. Nothing like learning a new coding paradigm to make you feel like an idiot, hahah. I'd like to use m_mesh to set the mesh of one particular entity- how would I do that. Would I simply Foreach an entity with a component unique to that particular mesh, and then just, set the mesh?
@rotund token can a render component’s mesh be assigned after creation of the entity?
Yes
Ok cool
last question:
//create mesh
var m_mesh = new Mesh
{
vertices = m_vertices.ToArray(),
uv = m_uvs.ToArray(),
triangles = m_triangles.ToArray(),
};
// do calculations
m_mesh.RecalculateNormals(); // normals
m_mesh.RecalculateBounds(); // for occluding
// set mesh as mesh on VoxelChunk types
Entities.ForEach((ref RenderMesh r, in VoxelChunk v) =>
{
r.mesh = m_mesh;
}).Schedule();
Entities.ForEach Lambda expression captures a non-value type 'm_mesh'. This is only allowed with .WithoutBurst() and .Run() what on earth does it want from me here.
so how do i do this. do i have to use blobs instead
or do i just call the foreach with .WithoutBurst()
you'll have to use Run() instead of Schedule() as well
also from memory you're going to get in trouble for doing a r.mesh = m_mesh here
what do i do instead
don't pass it in by ref
r.mesh = m_mesh;
EntityManager.SetSharedComponent(entity, r);
the more performant way would be to re-use the mesh and not create/set a new one though
so i would do a EntityManager entityManager = World.Active.EntityManager; although last time i did that it yelled at me that World didnt have a .Active
where does entity come from here
add it to the foreach query
(also use .WithStructuralChanges() so you can use entitymanager)
no you're in a system, you have direct access to EntityManager
// set mesh as mesh on VoxelChunk types
Entities.ForEach((ref RenderMesh r, in VoxelChunk v) =>
{
r.mesh = m_mesh;
EntityManager.SetSharedComponent(entity, r);
}).Run().WithoutBurst();
what... order do i do things in. thank you for your patience i started learning DOTS [looks at watch] two days ago
also that
before or after WithoutBurst
}).Run().WithStructuralChanges(); do i really call it like this? it tells me I can't use . on a void function
waity, you sure Cannot assign to a member of variable 'in RenderMesh' because it is a readonly variable Entities.ForEach((Entity entity, in RenderMesh r, in VoxelChunk v)
var copy = r;
copy.mesh = m_mesh;
just do that
(though do note i have no 'in' on my rendermesh on the code i posted)
im doing in because it tells me i cant use it with ref
yes hence i had no ref or in
oh is that what they meant by use value
okay
ok thank you the errors have left. Now i just have to spawn an archetype
Is there a way to figure out what commands are being run in an EntityCommandBufferSystem?
can i safely get a gameObject from a static list inside a job when i pass in the index of that static list via [readonly] nativearray<int>?
you can only access gameObjects in a job if you disable burst, which will make it way slower. so you can access it anyway but you need to disable burst to do that. doesn't matter how you access the game object
@finite remnant All the information in a GameObject is bad for performance. Should figure out what you need from a GameObject and just grab that at some point
im trying to get a script from a gameobject. sry. will this be different then?
What are you trying to get from the script?
Cause the idea behind ECS is that you have components which are just data
and then you have systems that operate on that data
just some locations to do some vector3.distance/float3 calculations
So you want to step back and figure out what data you need
if you can you should move that data to ecs components
You need to be specific in the data you a grabbing
so do you want a position of the game object?
Do you want a position that is set once?
i cant use ecs, because im running v2021. im trying to use jobs without ecs to do some multithreading
Do you want a position that is always updating
Oh I see
Well throwing ECS out, what you need is an array of whatever data you need
yap
you mean nativearray?
thats my approach 😄
And so you need some code that loads the data in the NativeArray
and then you load the data in the Job
So you need to figure out how you are going to find the relevant data
if you wanna do it stupidly simple, make two native arrays, one as a key and one as the value
and then just for loop through it. Once you find the one you want boom you have the data
Burst makes this so fast doing fancy look ups is usually not that important
Just don't load a gameobject into the native array, that will be horrible for performance and memory
but im not sure if i an set values of a monobehaviour via job. is that possible or also blocked by safety sys?
plus you can't really do that since NativeArrays need to be a struct
No that won't work
you can't pass things in and out like regular OOP
damn
You need read code, job code and write code if you want to go between the two
so i need to stop the mainthread anyway right?
yes to write information to the gameobject monobehavior you will need to do it on the mainthread
ok thank you!!! that are some really helpful infos!!
i saw a video from codemonkey where he was using this for transforming a bunch of objects. this could at least be used for transforming my car ai. i guess i would need to store all the informations of the cars in arrays inside a single script, rather than having a script on each car for transforming. like: float[] speed; transform[]positions; etc and then pass that in via nativearrays.....
Yes, aligned arrays are best. So index 55 of each Native Array is associated with the same gameobject. So you only pass the information you need into a job.
Unfortunately, looks like the list is internal or private at best. You could write your own override to a custom ECBsystem that keeps track of each command alongside adding it to the buffer
Yeah I found the same
Has anybody made an editor script or tool that will dump a selected Entity hierarchy ( selected in the Entities inspector ) as gameobjects into the scene, for debug purposes?
Seems it would be really useful, i find myself creating gameobjects and manually entering position to Entity positions for various reasons
I think that's what the BatchRendererGroup API is supposed to do, since you can pass in a 'clickable object'
but still experimental
huh, what namespace is that under
will have a look thanks
hmm i think this just takes an existing gameobject and creates batch renders from it
ah nevermind
what i mean is - say you have an Entity selected in the jobs Entities inspector, i'd like to be able to convert that into a gameobject and inject it into the scene
just a basic gameobject with pos/rot/scale tbh, for debug purposes
yea I think you'd have to roll your own. Have a system reads the translation/rotation/scale that you can manipulate and then apply it back to the entity. I think the difficult thing is when you have transformations being applied back to the game object (e.g. you have a system that animates the scale of an entity). It doesn't really give you much window room to apply your transformation I think.
yeah just looking into whether it's possible to reference the entities inspector and get the selected entity from it
i've written basic editor scripts but never tried to poll an inspector other than just, get selected object(s)
Yea I'm not really sure. I haven't looked into the entitydebugger inspector yet to give better insight
use case would basically be - hit pause, click entity in inspector, hit a shortcut or menu item and it dumps a static gameobject with pos/rot
do they have changed the syntax for jobs (currently using 2021) ? i cant find ijobparalellfor with intelisense
hi, I wanted to know how to use coroutines in ECS, is it done the same way?
do i need to add some namespace, or something?
you don't use coroutines in ecs.
it's in Unity.Jobs
so how would I do a while loop?
while (condition)
{
}
normal
why would it be unsupported?
because i cant find it inside the manual/api
so I don't have to create a coroutine for it??? oh shit den
@finite remnant or are you looking for IJobParallelForTransform?
sry i meant IJobParallelForTransforms
that's in UnityEngine.Jobs
and yes i cant find it in the api
ahhhh thanks mindstyler now i see
you never have to create a coroutine to have a while loop
not even in monobehaviours
you dont have to, but how will you delay the iteration to the next frame in update(), so you dont cause stackoverload?
that was never the question. the question was how to create a while loop
but i guess if the the execution of the loop is taking less time than the frame its no problem...
exactly
also: don't ever do coroutines. but especially not in dots
coroutines have been superseded by async / await a long time ago
i feel you!^^ coroutines are killing my fps
but theres one single thing that i dont understand about async: can is start a bunch of tasks and cancel them with cancelationtoken after 2 seconds? or is async/await made for running the whole time while an object is active?
of course you can just cancel them anytime
can i use burst with all android devices, or do i need to use neon?
yo boss, why is my while loop crashing, I've set the default timer to be returned to Default Timer which is 5. It's meant to make an object move at a random z axis then change every 5 seconds
That while loop will never break because it is always above zero.
Your if statement resets the whole loop to above zero before it can be completed
Also that while loop doesn't do what you think it does. It won't move it incrementally.

Remove the while loop. You'll have greater success. A while loop is the same as a for loop. It stops everything to complete.
wait why not? the random range sets the direction, speed sets the speed and delta time makes sure it does it in real time
Except that loop doesn't break until the condition is met.
You have no break. While loops happen right at that instant. So you are just reducing the timer in one frame
Just remove the while loop and it should work
oh aight
that's also not what you asked
Error: IL2CPP error (no further information about what managed code was being converted is available)
Great :[
How do I debug this?
The only additional info in the error message is: System.AggregateException: One or more errors occurred. (Value cannot be null. (Parameter 'definition')) ---> System.ArgumentNullException: Value cannot be null. (Parameter 'definition')
https://forum.unity.com/threads/unity-jobs-and-static-variables.534719/ so im wondering how i can prevent a job from changing a static variable that may was deleted. this thread says i should copy the values from the job to native array and change it in monobehaviour. but this wouldnt work with IJobParallelforTransform
Is there a way to disable the ECS completely temporary and turn it back on later? If not, I'll have to disable all entities I want to render with a tag on being able to enable em later.
I assume you can just destroy world
and not create new one
but that's not disabl
that's literally destruction of everything that exists
The problem I have is this: Scene loading doesn't work
Subscene works in editor, but not live compile
how so?
So I have to do work around for my own personal set up.
Sec, no one on this forum could help me before, but I'll link u
Starfighter MMORPG engine test launch imminent next few days. Can you help me figure out why my subscene ain't loading?
StarfighterGeneral.com Bloopers, Bugs and Outtakes: https://www.youtube.com/playlist?list=PLOQ-J23AJUfSCeuHkKQtL1Al70iAWnbSO
Been #1 in the world at every online ladder video game I played even the highest skill games Star...
I'm a boss at doing work arounds. I like the challenge of getting stuff done when I don't have techs others have.
I'll just add tags to everything that isn't disabled, + disabled tags. Then when I want to turn em on, I look for the one tag and take it and disabled off. Ez pz
If you can figure that scene thing, more power to you, most said it was a unity bug, but maybe I didn't subscene right.
Thank you for being interested to help. The willingness of random people to help is the one thing the Internet still has right in this weird age.
Fortunately I was smart enough to dodge that one
Hey there. I want to know generally what is the recommended way of handling branching logic with DOTS. AFAIK if we are talking about something like a = condition ? x : y as long as x and y are simple variables then there is no branching. But what if I want to do something more complex, I can just put the branching logic inside my system's job and that would work, but the preferred way is supposedly adding a component of either type a or b and letting system a or b process that. However isn't deciding which component to add (or not to add) branching already, which means I'd still get a misprediction half the time (assuming a 50/50 split). What is the difference between just executing the logic on the spot? And isn't the overhead of modifying the archetype of the entities just cancelling any gains I might get.
I guess the answer is "if you only have a few components use an if, otherwise add a new component" but I'd like some elaboration
afaik structural changes can only be done on main thread
so you still want to use buffer
and it means your branching is irrelevant
Input is by[ .foreach] or [entity Queries] before output via EntityCommandBuffer
I didn't understand any of that 🙃
I'm saying, that if your logic is about adding components
you'll pass that job to buffer system
the best way to do states like this, imo, is to have a component with a bool inside.
and 2 systems process the if and the else separately
///psuedo-code
//System A
Entity.ForEach() =>
{
if (ComponentA.Flag)
{
//process
}
};
//System B
Entity.ForEach() =>
{
if (!ComponentA.Flag)
{
//process
}
};
for flipping them on and off, you can flip them inside those systems.
or have another system do the flipping for you under some conditions.
I'll have to read up on that then
Anyone here super-familiar with Burst FunctionPointers? I'm trying to refactor out a bunch of switch statements (like switch(biomeID) { case Mountain: return MountainBiome.Generate3D(...); ... }), and thought this pattern would be perfect:
[BurstCompile]
public static class MountainBiome {
public static readonly BiomeGenDefinition GEN_DEFINITION = new BiomeGenDefinition() {
Generate2D = BurstCompiler.CompileFunctionPointer<Biomes.Generate2DDelegate>(Generate2D),
Generate3D = BurstCompiler.CompileFunctionPointer<Biomes.Generate3DDelegate>(Generate3D),
GetTerrainBlock = BurstCompiler.CompileFunctionPointer<Biomes.GetTerrainBlockDelegate>(GetTerrainBlock),
GetProspectiveFeatures = NullBiome.GEN_DEFINITION.GetProspectiveFeatures,
LiquidType = BlockID.LiquidWater,
UndergroundBiomeID = BiomeID.SurfaceLayerUnderground
};
[BurstCompile]
[AOT.MonoPInvokeCallback(typeof(Biomes.Generate2DDelegate))]
private static void Generate2D(double2 pos, long seed, /*...*/) {
fullColumnBufferProxy.HeightMin = BASE_HEIGHT;
fullColumnBufferProxy.HeightMax = BASE_HEIGHT + NOISE_AMPLITUDE_1 + NOISE_AMPLITUDE_2 + NOISE_AMPLITUDE_3;
}
[BurstCompile]
[AOT.MonoPInvokeCallback(typeof(Biomes.Generate3DDelegate))]
private static float Generate3D(double3 pos, long seed, /*...*/)) {
// ...
Then I only need one switch statement method that returns a readonly ref to the BiomeGenDefinition instance.
I'm getting errors such as the following, though:
Burst error BC1064: Unsupported parameter
Unity.Mathematics.double2posin functionMountainBiome.Generate2D(Unity.Mathematics.double2 pos, long seed, float naturalHeight, ref Biomes.BiomeHeightRangeAndColumnBuffer1<Biomes.ColumnBufferProxy> fullColumnBufferProxy)`: structs cannot be passed to or returned from external functions in burst. To fix this issue, use a reference or pointer.
Is there any way to "mark" a FunctionPointer (I guess it would be on BurstCompileAttribute actually) as Burst-internal only, so I can avoid this type of issue? I would prefer not to have to move all my function parameters into a boilerplate reference-passed struct, if at all possible.
Thanks!
I am sort of new in this, but wouldn't using an extra byte here just for that go against data oriented design?
*extra byte per component
still probably will be faster to just make another loop xD
it is. and believe me I cringe at this solution.
plus the fact we just put branching in a system which hurts Burst
but right now, that's what Unity has done in their demos. so I guess you can call it recommend-ish.
until Unity introduces enable/disable component, it's the best way
I see
oh, so Burst doesn't like ifs?
there's a talk about smell-checking what burst like and what doesn't.
https://www.youtube.com/watch?v=BpwvXkoFcp8
This session addresses how we are expanding the scope of the Burst Compiler to enable even the most demanding, hand-coded engine and gameplay problems to be expressed in HPC# via direct CPU intrinsics. Andreas shares the reasoning and use cases; as well as discussing implementation challenges, debugging, and performance along with comparisons to...
My take away here is, when dealing with complex branching,
the CPU has to drop the instruction and load in the new one.
and Burst doesn't like those since it relies on patterns in the code to SIMD it.
another great talk about CPU caching
https://www.youtube.com/watch?v=WDIkqP4JbkE
code::dive conference 2014 - Nokia Wrocław
http://codedive.pl/
Why I wish Unity.Mathematics had a hardware-matched vector type like System.Numerics does, heh
Ah they discuss it at 35:39
how can i get job index inside a job and how can i get maximum job index in current machine? What i've found is [NativeSetThreadIndex] and JobsUtility.MaxJobThreadCount, and the last returns 128
okay so. I have this code here:
protected override void OnUpdate()
{
//initialize lists
m_vertices = new NativeArray<Vector3>(24 * DataLUTs.chunkSize * DataLUTs.chunkSize * DataLUTs.chunkSize, Allocator.Temp);
m_triangles = new NativeArray<int>(36 * DataLUTs.chunkSize * DataLUTs.chunkSize * DataLUTs.chunkSize, Allocator.Temp);
m_uvs = new NativeArray<Vector2>(24 * DataLUTs.chunkSize * DataLUTs.chunkSize * DataLUTs.chunkSize, Allocator.Temp);
var blocks = new NativeList<BlockData>(Allocator.TempJob);
m_vertexIndex = 0;
m_triangleIndex = 0;
//build list of blocks
Entities.ForEach((ref Block block) =>
{
blocks.Add(new BlockData
{
type = block.type,
coords = block.coordinates
});
}).Schedule();
//loop through blocks
foreach (var b in blocks)
{
if (IsSolid(b.coords, blocks)) //if this is a solid block to render (not air)
{
for (int side = 0; side < 6; side++) //draw sides
{
DrawSide(side, b.coords, blocks);
}
}
}
//create mesh
var m_mesh = new Mesh
{
vertices = m_vertices.ToArray(),
uv = m_uvs.ToArray(),
triangles = m_triangles.ToArray(),
};
// do calculations
m_mesh.RecalculateNormals(); // normals
m_mesh.RecalculateBounds(); // for occluding
// set mesh as mesh on VoxelChunk types
Entities.ForEach((Entity entity, RenderMesh r, in VoxelChunk v) =>
{
r.mesh = m_mesh;
EntityManager.SetSharedComponentData(entity, r);
}).WithStructuralChanges().Run();
// dispose of arrays
m_vertices.Dispose();
m_triangles.Dispose();
m_uvs.Dispose();
blocks.Dispose();
}
and apparentyl the list blocks is causing a memory leak
where should I dispose the list blocks to stop the memory leak
first you're scheduling a job, which may not be completed by the time you read blocks in your foreach loop. And yes you should schedule the disposal of the blocks native array. (blocks.Dispose(someJobHandle)).
.Schedule() returns a job handle right? So i could just go JobHandle FindBlocks = Entities.ForEach((ref Block block) => and then call FindBlocks.Complete() to stop it until it finishes
Yea
im very new to DOTS so bear with me
yea all good
And can I dispose of the Blocks list at the end as normal if I do that
yea
JobHandle FindBlocks = Entities.ForEach((ref Block block) =>
{
blocks.Add(new BlockData
{
type = block.type,
coords = block.coordinates
});
}).Schedule();
FindBlocks.Complete();
it says that Entities.Foreach.Schedule is a void function and doesnt return a jobhandle?
might be your IDE, does it compile in the editor?
my IDE is having csharp issues i need to figure out, unity says this, and the error is right after FindBlocks =
oh I can think 2 things since I don't typically use the lambda foreach (so I'll need to check the codegen later).
But try this first
JobHandle FirstBlocks = Entities.ForEach((...) => { }).Schedule(Dependency);
FirstBlocks.Complete();
The second option is (which I need to double check):
Entities.ForEach((...) => {}).Schedule();
Dependency.Complete() // Dependency is a SystemBase class variable you can access
okay, the first one works. I just need to somehow... get my code to actually do what its supposed to, and then not run all of this in an update loop and lag out my computer. thank you!
Okay I think the second option should just work as intended
ok question how do i make it so that a system only fires when i want. can I only do calculations in update or can i make my own function and call it from somehwere
or do i have to add a flag
systems only ever update when you want them
systems react to data, if you've provided data it will update
if you don't want a system to update, don't provide it data!
hmm okay so the problem is that as im spawning 16^3 data points its doing the whole rigamarole each time, so i have to figure out how to stop it from doing that until im ready
also the mesh never actually appears but thats a separate issue
you can use RequireForUpdate/RequireSingletonForUpdate
to limit when systems will update
or just early out on a query etc
so i could query for a tag component, hm
hey, how do I make materials for the hybrid renderer, because my mesh is green for.... some reason
using hybrid v2 btw
what is a valid transformaccess? can i use this to check if a gameobject is destroyed/deactivated?https://docs.unity3d.com/2022.1/Documentation/ScriptReference/Jobs.TransformAccess-isValid.html
just normal materials. make sure to enable gpu instancing on the materials (which really should be enabled by default in unity)
hm. I did that ...
do you have any special material or smth?
Hmm, I'm trying to install URP
I basically followed guide on how to upgrade built in render into URP and then how to install Hybrid Renderer V2
and this results in instant 999+ errors
upon creating entities
In empty world - no errors
Entities dynamically created ?
yeah
ANyway disable Burst, you'll get more verbose stack
yup from main toolbar
yup
you want to play your project without burst, so you can track back the error
Hmm probs something wrong with editor/packages versions
can you regenerate project files / delete Library folder ?
just to be sure nothing is cached
also do you use git ? to quickly check if nothing was bumped on your behalf during the update
SOrry just giving ideas
no
but safe to delete anything inside
your next opening of the editor will just be way slower as it regen everyhting
Multiple worlds ?
Im not sure then. My best guess is still versions conflict 🤷♂️
But HR should be good with URP 9+ and editor 2020+
so annoying unity hides all "experimental" packages tho
hard to debug version conflict
actually you can dig through them inside the packageCache
weird part is that all stack trace leads to physics
I think it just stumble upon the first NativeArray it found
well I double checked
all packages
are up to date
AND are automatically assigned as dependencies
in the first place
2021
oh I can't tell then, didn't switch yet
eventually i would try to downgrade collections package manually to a previous version (if I'm out of options)
Other than that, I'll let someone else bring his light on the topic 🙂
yeah same stuff, version mismatch
oh man
need to find the right combination I guess
stay on 0.15
it's hell to get back to previous version
ecs specifically say it requires collection 0.15
any tip what exactly?
"com.unity.collections": "0.15.0",
like this?
or?
yes, but my situation was much worse
it was stuck on 0.17 a few month ago
and since then I forgot how I did it, let me check my old messages
read the messages around here
I edit manifest directly so
"com.unity.collections": "0.15.0-preview.21",
it's kind of like this to me
but my experience is that this doesn't update the actual package
read the link
it's shows how to see all version
let me fire up unity
I think I'm confusing both myself and you
bruh, I read whole thread and it's just complains about removed preview packages feature
😐
there's no way to see all packages in Unity 2021
could you send me manifest.json?
unity keeps loading wrong version of collections for me
I probably made a mistake or smth
pretty sure back in september i tried to change the manifest and did nothing
this should help you
this is how i finally solved my problem, by downgrading the package through the package manager
after showing the hidden option
yep, they started hidding that button after an update
it messed up a lot of things
finally
I resolved it
it was job package
that was forcing newer collections version
ye, let it mature a little, heard 1.0 is coming (p.s. i will hop back on to dots when 1.0 comes out)
do you have hybrid renderer installed
oh nvm, i saw you message
rn I'll try to just install all versions same as yours
the problem is with the physics package
from what i can gather from the error
havent followed too closely @vagrant lotus @rustic rain but it looks like a bug introduced in the editor and the fix is here https://forum.unity.com/threads/2021-2-8f1-broke-asdeferredjobarray-and-deferred-jobs.1225635/#post-7815393 thanks to tertle
yep, that fixed it
thank you
I got interesting point on my other bug tho:
If I don't run game with game scene, all materials in that scene are broken
Yet, if I load that game scene, change it to other scene and then go back to that same scene again - all materials work fine.
Any idea what can it be?
not sure, you switching materials at runtime or something?
can't take too much credit, just asked unity dev for a fix and passed it on
can you ask em for a 0.50 release estimation? 😉
i couldn't tell you anyway
no, just spawn prefabs
Irrelevant question:
Is it absolutely sure that all monos run BEFORE systems?
I checked several rn with logs
and it looks like mono run before systems, but I'm not sure if that will behave like this 100% times
i wouldn't rely on it
better to look at this: https://docs.unity3d.com/ScriptReference/LowLevel.PlayerLoop.GetCurrentPlayerLoop.html
I think it's about system order
between systems
not monos
monobehaviours depending on the message callback update in various places I know in PostLateUpdate they're called at the end
i can tell you the order of some things is also different in builds vs editor
SEO doesn't affect systems, only MB
Assuming system loop uses Default Time
This is where monobehaviours update. You can inject your own delegate right before all monobehaviour's update loop.
i would imply this means there is something wrong with our architecture
there is
it's hybrid
I want to keep everything related to gameplay in ECS
while everything about game managing (as app) in OOP
that violates tertle's rule #3
3. Do not access entities from game object world. Inject references into game object world from entity world (Systems -> GameObjects)
but I'm not trying to
I just need to set certain static fields before systems can use them
in any way
the rule basically says, game object world should never access anything ecs related which is what you're doing with game management
anyway they're just my rules, not forced ideas
but the whole point of them is to avoid issues like you're having
funny
new input system design just doesn't fit DOTS
xD
or maybe I'm just unable to find the balance
i have no issue with it
the only thing that bothers me is there is no asset for mapping groups
so i have to string look it up
no asset for mapping groups?
action maps
each action map has a collection of actions
actions have an InputActionReference
so you can put them on assets for conversion etc
but action maps do not
just a little annoyance i have with IS atm
still kinda don't get what you can't do kek
it bothers me its called InputSystem but its not an ecs system
it's event driven system
public class BuildInputConfig : IComponentData
{
public InputActionReference Select1;
public InputActionReference Select2;
public InputActionReference Destroy;
public InputActionReference Place;
public InputActionReference Rotate;
}```
I want to store a referenced to InputActionMapReference
so i can disable/enable groups of actions when i change state
oh
wdym data driven?
if a designer comes in and decides to change the input action for menu
renames it, BackButton
does your code break
yeah
and that's the problem
now it's not an issue if you're the only one working on the project etc
but if i'm writing a library for a large team i shouldn't be able to break the application changing data
my designers/artists should be free to change data how they please without having to find a free programmer to update the code and put up a pull request etc
the larger the team, the worse this becomes
yeah, I see what you mean here
anyway that's why i want a reference to mapping
so i don't have to hardcode FindMapping(string)
but I feel like player input actions is not smth designers or artist should freely change at all
why would a programmer setup action mappings?
i would argue only a designer should set this up
by mapping you mean creating new action and etc or?
there's been a prototype for dots input of the input system on the input system github. 2 times actually. 1 prototype and 1 a bit more fleshed out. hasn't received any further update since. but that's probably gonna resume once 1.0 drops
i simply provide an empty field call InputActionReference - they can pass whatever they want into it
my code will work with whatever binding they choose
well keybinds are fine not to be hardcoded, but creating new actions, just by designers seems weird
how can you even make it work, he'll create new action, but what system will catch it up?
yeah, input registers, events trigger. But what is game feedback?
i simply provide a set of fields for actions
its up to design to map to them how they want
they can re-use existing actions
a lot of them time the same action can be bound to multiple in game things
sometimes they want to split it off
so a new keybinding can be created
actions and action maps directly map to options screen for keybindings etc
so its important they can control, change, rename etc
but it's still same thing, but with extra steps
it's not though
I mean, can't you just create such maps references yourself?
if you don't generate C# class
you can give to team certain maps like actions
and that would be your references
oh i can just pass in a string
and it works
it's just an annoyance because strings are prone to errors
and if someone renames an action map group
it breaks all the data
whereas if you rename an asset (which actions are)
it will propagate for all settings
and actions / actionmap naming is important because it's used to auto generate options and keybindings
so its quite common to rename them
i just don't like anything prone to breaking. if i have 3 devs and 2 designers all changing input settings in different pull requests
i don't want anything to break when they all merge
it's just a minor annoyance of the inputsystem atm that's all, i'll live with it. way more discussion than required about it.
apart from that i've found a pattern for using IS with entities and am pretty happy with it
Command Pattern
Is there a way in jobs to schedule IJobParallelForBatch with 1 batch per thread?
you don't care about threads in jobs. the work stealing will change things around anyway
i want use NativeStream with 128 forEachCount, so i need 1 batch per thread
or understanding of how to pick minIndicesPerJobCount properly
what i'm worry about is somewhere i saw that 64 is good number for small amounts of work, so knowing my minIndicesPerJobCount i can create NativeStream with Length/BatchSize, and then knowing startIndex in job i can calculate what index of NativeStream it belong. But with array length growing grows NativeStreams' forEachCount
So I'm looking at the netcode package and I'm wondering where in the conversion pipeline the ghost entities are brought into their designated worlds (Server/Client). I see the GhostAuthoringConvesrion system which handles majority of the work, but it seems like everything is using DstEntityManager so I imagine that the entities are going to whatever the DefaultGameObjectInjectionWorld is.
Anyone have any clues that can point me in the right direction? 👀
you mean where netcode instantiates ghosts sent from server?
Yea
if so it's just GhostSpawnSystem
predicted ghosts spawn line 96
interpolated line 75 (but delayed)
cool I'll take a look tomorrow morning - I'm trying to emulate something like that 👍
hey can i dispose a persistant nativearray after i used it a second time for another job?
also: why do i need to restart editor all the time when i edit a script with burst turned on?
Does anyone know why my DynamicBuffer extension method isn't working when the DynamicBuffer value is a property? If I assign the property to a temporary variable in a method, I can then use the extension method on that temporary variable. But, when I try to use the extension method on a DynamicBuffer property it throws an error saying it does not contain a definition. Any thoughts?
EDIT: this can be ignored, I was being dumb.
Hi, are UnityEvents comparable with ecs authoring. I'm aware it doesn't fully make sense with how ecs works but it's also a big part of my prefab workflow so it would be great if I can still use UnityEvents in the inspector
well you can't use them on ecs, but you can still use them with ecs i guess
of course.
you don't
@haughty rampart if i change some values in inside a job (the struct is not perfect in that case), i always get internal error somehow. i think its because the jobs havent been completed because of faulty code-> nativearrays dont get disposed and this somehow causes internal compiler error and i need to restart unity
can i complete my jobs somehow if i get error in runtime ?
it should not throw a compilation error with this. there's something other faulty
no
damn
you wouldn't want to
ok
Hey, where can I find out which unity systems are/aren't currently compatible with ECS
So I'm going to work with a DynamicBuffer to store an array in a singleton entity. Is there a way for me to allocate a certain amount of memory to it in the heap at run-time? (I want to be able to initialize the 'array' to different sizes depending on other stuff in the code) I'm worried about the performance of appending a few thousand elements to a dynamicBuffer rather than something like initializing an array and then going through its indices.
That is actually perfect, I have no idea how I missed this but ty lots
Hi! Need a bit of help. I have a Camera that I want to follow the player race car but I have an issue:
- If I put it inside the subscene, is converted correctly but the Camera component does not work.
- If Ieave it in the root, the Camera component exists, as well as the ArenaCameraTransformComp but my systems cannot see that entity in the World.
How can I have a camera functionality while the World can see it and I can update the position?
[UpdateBefore( typeof(TransformSystemGroup))]
[UpdateAfter(typeof(AdvanceActorSpeedSystem))]
public class CameraFollowPlayerSystem : SystemBase
{
/// <inheritdoc />
protected override void OnCreate()
{
RequireSingletonForUpdate<ArenaCameraTransformComp>();
RequireSingletonForUpdate<ArenaPlayerComp>();
}
/// <inheritdoc />
protected override void OnUpdate()
{
Entity camera = GetSingletonEntity<ArenaCameraTransformComp>();
Entity player = GetSingletonEntity<ArenaPlayerComp>();
var playerPos = EntityManager.GetComponentData<Translation>( player ).Value;
EntityManager.SetComponentData( camera, new Translation{Value = playerPos} );
}
}
- If I put it inside the subscene, is converted correctly but the Camera component does not work.
Put HYBRID_ENTITIES_CAMERA_CONVERSION in your defines
@rotund token I also had to put ENABLE_HYBRID_RENDERER_V2 before, are there other defines I must-have in there? I plan to have physics stuff happening if that matters
// Camera conversion is disabled by default, because Unity Editor loses track of the main camera if it's put into a subscene
Entities.ForEach((Camera camera) =>
{
AddHybridComponent(camera);
});```
the reasoning why it's not enabled by default
Also thanks a lot for your help all over the forums and discord @rotund token , you're a strong pillar of the community
@rotund token the ArenaCameraTransformComp is in the root of that GO, while the Camera itself is somewhere deeper in it's grandchildren
Strangely, if I activate that subscene, it works :/
just to confirm, you are auto loading the subscene? also did you reimport the subscene after adding the define?
I was under the impression adding the subscene (not activated) will suffice. Am I to understand that I have to activate them at runtime?
if you don't activate the subscene nothing in the subscene will be loaded, including the camera
So basically, subscenes are a hybrid between a regular scene and a prefab?
if I have two entites that each have a PhysicsCollider entity component, and those components have the same Serialized Hash value, does that mean the collider is the same on both Entities?
and is that a bad thing? i think I noticed when you EntityManager.Instantiate(entity) on an entity that has a PhysicsCollider component, it produces a new entity with the same Serialized Hash
someone I work with seemed very surprised to see two entities that each had PhysicsCollider components that had identical Serialized Hash values and I've been scratching my head over it all weekend
example
or perhaps that Serialized Hash is just a reference string to a BlobAsset?
should i render say 4 million spriterenderers using dots, or 256 tilemaps
Probably 256 dynamic meshes 😄
rendering as 256 tilemaps it works at 400fps, but loading as you pan is a bit slow
Hey people on Unity discord, how's dots doing these days? I thinking of starting my next project in it (i tried out ECS like two years back)
It's a slow burn. Check the forum for the update on ECS .5 and ECS 1.0
As for just DOTS in general, Burst is the best as is the job system
0.50 😉
Lol what??
0.5 and 0.50 are not the same version
anyway, other than that, your answer is accurate
I was just nitpicking
🤓
If I'm doing raycasting for a character controller, is there a better way to detect the closest hit besides iterating through all DistanceHit from CalculateDistance? There is a version that returns the closest hit, but I don't see a way to ignore the collider that is being cast from, meaning the closest collider would most likely be the entity itself...
If that happens you could still offset the origin of the cast (in the PointDistanceInput) or ignore the entity layer (in the Filter struct)
can also use a custom collector to ignore the casting entity @misty wedge
Hey everyone. I am trying to learn and redo my idea in DOTS. I have an array of gameobjects that I want to define as the spawnable elements in my level. I am having trouble describing that in components. Does anyone have any helpful links and/or videos?
- the official ECS samples will teach you how to Instantiate from converted prefabs through monobehaviour authoring
- in the netcode package you store all ghosts (network-aware spawnables) by registering your prefabs to a buffer, you could get inspiration from it
I explained it badly but 99% sure you'll find it useful
and for netcode I don't remember the component name, something like GhostPrefabCollection or close :p
can somebody tell me why this job wont run?
public struct JobLODTransforms : IJobParallelForTransform
{
public Vector3 pointOfView;
public float lodDist;
public NativeList<int> occluded;
public void Execute(int index, TransformAccess transform)
{
Vector3 diff = transform.position - pointOfView;
if (diff.sqrMagnitude > lodDist)
{
occluded.Add(index);
}
}
}
i keep getting an error that say: InvalidOperationException: JobLODTransforms.occluded is not declared [ReadOnly] in a IJobParallelFor job. The container does not support parallel writing. Please use a more suitable container type.
error tells you everything you need to know
you're writing to NativeList<int> in parallel
when the container does not support parallel writing
but it does when i'm using IJob
IJob is not parallel
oh, that makes a lot of difference, what data structure can i use to fill a list in parallel or is impossible in the current version?
nativelist has a parallelwriter version but it can't be resized so you need to know max capacity beforehand
also it's a bit slow
but if you aren't using it a lot it's fine
nativelist.asparallelwriter()
alternatively a nativequeue is probably your best bet
(again use asparallelwriter but it can be resized)
thanks, whereś more documentation about job compatibility between job types and usable structs?
no container by default is supported in parallel
most have a parallel version
but they have various limitations etc
as for documentation, the best source is honestly the source code. Unity for the most part has done a really good job documenting everything.
So I've had this problem before using ECS where my object wouldn't render. I remember adding the hybrid renderer. Even now, my object gets converted, but I dont see it in the scene/game view.
I turned off hybrid V2, and it worked /shrug
Is it possible to have dynamic animations in dots/ecs?
You're asking the wrong question.
The answer to any question starting with, Is it possible ...? is Yes
You're a developer, you can do anything with enough time.
The question you probably want to ask is, how much effort is X? or how painful implementing Y is?
Yeah alright, that's true. Let me revise my question - How painful is it to implement dynamic animations using the unity ecs packages we have at the moment?
Is there an easy way I can find a specific Entity within a MonoBehaviour script
This is my code but unity is not having it
EntityManager entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
EntityQuery rawQuery = entityManager.CreateEntityQuery(typeof(ParsedRawsData));
rawQuery.SetFilter(new ParsedRawsData { General.id = GetNameFromHash(id) });
NativeList<Entity> rawDataArr = entityManager.GetAllEntities(Allocator.Temp);
if (Array.Exists<Entity>(rawDataArr.AsArray(), r => entityManager.GetComponentData<ParsedRawsData>(r).General.id == GetNameFromHash(id))) //inefficient but the only way I could get this to work
//searches the array of entities and find the one that has an ID matching the one corresponding to the hash and also is a ParsedRawData
{
return entityManager.GetComponentData<ParsedRawsData>(Array.Find<Entity>(rawDataArr.AsArray(), r => entityManager.GetComponentData<ParsedRawsData>(r).General.id == GetNameFromHash(id)));
}
@whole inlet what do you mean by a dynamic animation?
perhaps im using the wrong term, sorry about that. I'm looking to see if anyone has done animation where you can have a character model run in a certain direction, but then have the upper body face a programmatically defined direction (eg. face cursor). So part of a rigged model has it's animation dynamically defined.
blended animations?
Fairly certain the dots sample demo showcases that @whole inlet
Thanks for the suggestion, I looked it up and although it's not quite what I'm after, it's good to know ECS has this, I was able to find an example of this in the sample projects.
I found a Brackeys tutorial that described the effect I'm after, it's called "Animation Rigging". @safe lintel do you know if there is an example of this in the sample projects? I took a look around and couldn't find any
Is there any way to order systems like UpdateAfterIfExists? I have a system that should run after UpdateWorldTimeSystem. But the other system might not exist. E.g. while running in edit mode. Using UpdateAfter leads to Unity spamming warnings about invalid UpdateAfter.
I've seen some in the forums use a monobehaviour in the scene to create and organise the systems maybe that will help?
Yeah I know that you could basically sort the systems yourself but that means doing everything manually afaik 😕
yeah but that's kind of one of the strengths of systems being able to create and order them yourself more easily than monobehaviours
Is there a way to instantiate entities with proper name?
so in debugger
you'd see those names
You need to set the Entity name via the entity manager. IIRC it is a pain in the butt
Probably not. The entity naming is only for debugging. In a game you would never see that so they didn't put any work into making it fast or jobs safe
@whole inlet animation samples repo has some ik manipulation examples, imo you could go pretty deep here but its not nearly as user friendly as the animation rigging package is
thing is, it only happens with this component in stack trace
ooooh
wait
I get what you mean
yea
yup
that was it
hmm
Using deltaTime in fixedStep
I think I'm doing smth wrong here
any tip if I even should use deltaTime for fixed step?
Yeah, it's overriden for you with a fixed timestep
Do you capture it when you use it inside a Job ?
Should capture first, then we'll see if that works 😛
I figured it's because it uses rigid body
and I multiply velocity by delta time
kek
erf ^^
I have struggles to copy data from one DynamicBuffer to another DynamicBuffer on another entity. In the vsdebugger, all the data is set correctly, but in the entity debugger, my entities buffers are length 0 with no entries. Is there a correct way of copying the data? (couldn't get CopyFrom() to work as well)
I tried entitymanager.getbuffer and dynamicbuffer.add, but these are structural changes, so I used ecb, now I am here after several different attempts having a foreach and ecb.AppendToBuffer. finally no compile errors/runtime errors, but yet no data in the buffers
probably I can't see the forest for the trees. (I am running the things in an async void, because I have to wait for an asyncoperation to finish, idk if that is causing troubles?)
Hey, is this possible?
I'm pretty sure I'm doing smth wrong, why render thread can be 12ms in this scene
You can do something like
destBuffer.ResizeUninitialized(capacity);
UnsafeUtility.MemCpy(dest.GetUnsafePtr(), sourceBuffer.GetUnsafePtr(), UnsafeUtility.SizeOf<T>() * capacity);
I forget if DynamicBuffer has a copy method you can use, but that's the raw way which works.
Get the world and create a query via World.EntityManager and search in your query?
var eq= World.DefaultGameObjectInjectionWorld.EntityManager.CreateQuery(...);
var entities = eq.ToEntityArray(...); // <- Is a NativeArray of entities
Yeah I’ve been trying to do that, I’ve got this code but it’s terribly broken
like it doesn't work?
what happens when you remove the filter?
Like I get all sorts of errors
what kind of errors?
I’m away from my computer right now but stuff like EntityQuery doesn’t have method SetFilter, struct isn’t serializable, etc. is there anything fundamentally wrong with my code though
not that I can really tell. If it doesn't find the entity what happens?
Well if it doesn’t it creates the entity but that wasn’t code that was relevant to the issue
I can’t actually run the project because of the compiler errors. I’ll look into it more after work
Indeed no SetFilter() method https://docs.unity3d.com/Packages/com.unity.entities@0.17/api/Unity.Entities.EntityQuery.html#methods
maybe youre looking for addsharedcomponentfilter?
oof, I built this scene just to see how much overhead Unity has
almost 10 times more fps
Unity itself actually doesn't have that much
If you turn off jobs debugger, safety but also switch from debug to release mode (and play maximised) you'll be within 10% of a build
Good to tell your qa, design this
Editor going from debug to release can doubled your fps
Been a while since I checked the training samples but Entities has been moved to 0.50 in that repo
Gonna see if I can notice anything different
seems like the few scripts there are just monobehaviours
Oh yea, that repo seems very new. Not much work done. I'm taking a look at this one:
Also 0.50 but with slightly more work
Only thing I dont recognize that well is in authoring, particularly IDeclareReferencedPrefabs. I dont use the conversion system so it could already be an existing feature or custom in this repo
Looks to be a way to prevent game objects from being culled when referenced as a property in a component of an entity rather than a direct hybrid component. Maybe
But otherwise, yea. Nothing that jumps out as particularly breaking change. Leads me more to believe that something has changed significantly on the job struct side. Burst is going to be updated as soon as DOTS is released. Last I heard from burst is that they got their next package update fixing a lot of the annoying Burst Inspector bugs from 1.7.0 pre-1 already packaged and bowtied largely tested and ready for release and just waiting for DOTS to ship... sometime in the next month or so.
The fact that Burst isnt iterating on major version number indicates that there should be no breaking changes on the job struct though. Nothing...
At least I think
IDeclareReferencedPrefabs has been there for some time, it converts the gameobject into an entity prefab
are nativehashmaps blittable
I think once Unity gets rid of the DisposelSentinel they will be (not sure if it's in the latest collections package). But an alternative would be UnsafeHashMap<T, K>
but that is debug build tho
with log console and etc
but did you enable script debugging
debug builds don't have it on by default
that's the primary thing that changes in the editor going from debug to release, it disables script debugging