#archived-dots
1 messages · Page 192 of 1
Firing events isnt a good solution, because there plenty of players, mobs that have weapons equiped and each event would iterate over all of them. Second solution is to mark all inventory items if the player attacks... but that doesnt feel right
Like spawning something, or applying velocity on the hit target... plenty of different stuff @deft stump
Never thought that its so hard to find a good solution for such an "easy" feature
@stone osprey This is what I ended up doing in my roguelike. A bit different than what I described to you. It's flexible and avoids structural changes https://hatebin.com/rqwzpzqtaw
Could be missing something in the long run but it works well now
So when an entity attacks it just adds to the other entity's "DefendBuffer". Other systems can effect the buffer before it gets resolved in that system
@zenith wyvern Thanks ! 🙂 But how exactly do you involve items ? Im using a pretty similar system for the combat calculation. But i cant find a good way to connect the player and his items. Like notifying the items that the player attacks for spawning a damage event ( Which then gets resolved like in your example )... because the player is its own entity and the weapons/items are also entities...
Like player presses attack -> Player gets marked as attacking -> Now involve items for firing damage events, spawning stuff or whatever
I would say any time it equips an item that effects combat it should add a component onto the entity that can be queried whenever it wants to initiate combat
Thats what i cant find a nice solution for
@zenith wyvern Could you describe this a bit further ? Player already references his items and the item gets references the player... but how do i actually tell the items "oh your player attacked... now do stuff ? "
If you have a sword that poisons your target whenever you attack, when you equip the sword you would add an "ApplyPoisonInCombat" component to the equipping entity. Then you can do something like
Attacker
Entities.ForEach((CombatAttackBuffer attack, ApplyPoisonInCombat poison)=>
AddComponent(attack.target(poison)));
Defender
Entities.ForEach((CombatDefendBuffer defend, ApplyPoisonInCombat poison)=> etc
I haven't gotten to items yet but that's what I plan on doing, no idea if it will work
Ahhh... So we simply transfer some of the components to the player once he equips the item. Thats actually the best idea i have seen so far. The only problem i see is to add item effects... Like one item addint "PhysicalDamage (100)" and theres a second equiped item that adds "PhysicalDamage(50)"... The same problem when we unequip the item
Just sum the bonus on a single "Damage" component, or use a buffer.
Well thats a option i havent thought of ^^ thanks... That could work :) thats probably a little disadvantage of an ecs, would be a bit easier to solve in oop
I'm not sure but my intial feeling would be to avoid trying to come up with some kind of "generic" system for applying the item bonuses to the character. If your items can do a lot of wacky things then it's going to be a fool's errand trying to come up with some fancy system for applying the effects, just write straightforward systems for every different kind of item on how it applies it's affect to the equipping character
@zenith wyvern Hmmm... any idea hoe this could look like ? ^^ like Entities.ForEach(weapon, equiped, physicaldamage) => apply physical damage component to player ?
Seems reasonable to me
so in the same way, whenever an item is unequipped, you iterate through each entity to check if there is a unequip flag present and remove the component ?
is there a way for me to download these docs for offline viewing somewhere? https://docs.unity3d.com/Packages/com.unity.entities@0.9/manual/index.html
or is it just save each page manually
I would probably use SystemStateComponents rather than a flag
But you wouldn't need to I don't think. If you're unequipping the item you should already have a direct link to the entity it's equipped on so you just remove the component directly
@stone osprey
Totally agree with you on the lack of examples, but since you've been asking a few questions on this for few days, I think you might be still thinking about ECS from a kind of OOP way.
Even though data layout is an important consideration/motivation for ECS, when you're actually designing things, IMO you should start with the systems—the behavior you want to happen—and work backwards. When you've got an idea for a system, let that tell you what data it needs to work. Once you've got a mental picture of a few related systems, that should at least hint at how the data should be stored (Which data should be components? Which entities should get these components? Et cetera)
"The problem is that the player and his weapon are seperate entities... The inventory items should get notified about the attack to deal damage or to execute unique logic."
Like this kind of statement is pretty object-oriented.
Just as an example, for an inventory system, do a player's items actually need to be entities? Well, it depends. Consumable items often won't have any unique data (every Super Potion heals for 50% or something), so one option for their inventory representation could be a simple struct Consumable { int itemID; int inventoryCount }, with the consumable inventory being a DynamicBuffer<Consumable> component. The entire table of consumable item effects and their sprites could be stored separately and loaded by the relevant systems. Weapons could be stored in a similar way or maybe not. If you want things like customizable attachments, tweak-able stats, or durability, then having loads of weapon entities can make sense. Entities/components are a way to store individualized data.
There are no hard rules saying the group of systems that implement combat should care whether the necessary data is on the player or weapon entities. If your game was just projectile weapons, the player's primary weapon entity might only need to hold components that tell you how much ammo it has and what kind of projectile it spawns.
Then some combination of systems could:
- read players input and write some "Command" component
- check this Command component
- if the command is to fire, use some data about the player's weapon to queue the spawn of a projectile
- check existing projectile entities
- did they collide with any player entities?
- for each hit check hostility between the player who fired the projectile and the player who got hit
- if the shooter was hostile, add an element to the hit player's "ModifyHealth" buffer
- queue the deletion of all projectiles that hit something
- spawn/delete queued projectiles
I'm currently trying to figure out why my app starts so slow. (4 second black screen after unity splash on a good device, 8 seconds black screen after unity splash on a shitty device):
15:54:55.350 I SwappyCommon: Swappy version 1.3
15:54:55.351 I SwappyCommon: SDK version = 30
≈ 3.5 seconds of no logs
15:54:58.964 E Unity : Unable to find lib_burst_0_0
15:54:58.965 E Unity : Unable to find _burst_0_0
≈0.5 seconds of no logs
15:54:59.370 W Unity : Earliest log statement I can squeeze into any of my code is here
The burst statement looks somewhat suspicious, but it's not actually unable to find burst (game runs just fine). Anyone has already dug into what might be happening in that ≈3.5 seconds downtime.
Any good Unity ECS alternatives until DOTS is production ready?
I've looked into Entitas but the code gen is quite the turn off.
Uh, someone might have a more proper feedback, but on a standalone c# server project I'm using Leopotam.Ecs but I've modified and updated it to match the project.
What have you changed? I looked into it and it seems like it's version of the "Archetype" or "Group" is very limited.
syntax of the filters, changed the names of most of the terms, to match the unity ones (their names seem to 'fit' better)
added the multi threaded example they had there
the thing with this project was performance wasn't key, its just to be mostly good, but similar pattern to the my game's logic
the games all running on UECS though, if you don't double down on everything being in ecs (like rendering, animation, subscenes) you can already do a lot yourself
UECS?
everyone is hesitant to suggest building on it, because you're going to get stuck, and your going to have to finish things yourself. if you decide that you can deal with that, you can.
what drew you to it in the first place?
performance, the design, new shiny tech, tired of oop?
Looking to try my hand at a turn-based Roguelite. The sheer amount of data and modularity made me look into options.
what kind of visuals, classic text? tile? 3d?
Well Roguelite in a progression sense, less so replicating actual Rogue.
If you want a better way of visualizing it.
Then the closest thing is probably Slay the Spire.
example helps, sorry I had to do a quick playtest with users to test a build
Hm I see
mixed 2d/3d
I don't want to be your only source of advice, but I'd say to do at the minimum the visuals on that with classic unity gameobjects, animations
now the meat could be ecs logic, with lots of EntityManager.AddComponentObjects() or the hybrid version these days (I'm little out dated on latest hybrid stuff) for the tie into rendering
but theres no real easy way to slice it, your gonna have to weight running two different kinds of architecture in the same project, which even if good is extra complexity
are you sure you can't just focus on the game logic and do it in the classic monobehaviour, manager, singleton approach that works?
@rancid shell
Is there a way to wait for subscenes to load in before I run a specific system?
@deft stump in 0.17 (which still isn't out yet i think?) you could put your system in ProcessAfterLoadGroup which specifically runs after a subscene is loaded
other than that not sure
well it already exists just is not set as public until 0.17
if you need it now you could modify the package and add a public there
haven't tried it yet but seems like it should work, group gets updated by unity's system manually as soon as a subscene finishes loading
Ya my current idea is to just have a pure ECS framework handling all the logic, and then a bunch of monobehaviour views that follow along. I proooobably could go the classic route, but I really do want to be expandable.
expandable is premature optimization in disguise
make the design of the game, then make only what you need to get that done
changing code after the fact, and reworking systems isn't as hard as we are conditioned to believe. The key thing is if its designed well, you can understand it, given time, and that means you can pick and pull it back apart and put it back together. keep the scope and complexity to just exactly what the game needs and you wont have as large of a mental burden to do so for any one piece
make the game, not a general framework for making your kind of game.
hey all, im trying to build the tiny 3D template with very little knowledge of DOTS (other than a broad understanding). Im getting a series of errors though. Im building from a build config file within the project, in particular the Wasm build config.
Build Wasm failed after 4.30s.
[ ] Require frontend run. artifacts\tundra_tiny3d-wasm_ehs.dag.json does not exist yet
[ ] Require frontend run. tundra_buildprogram.dag no longer valid. directory contents changed: ../PackageCache/com.unity.dots.runtime@0.31.0-preview.24/bee~/BuildProgramBuildProgramSources
[ ] Require frontend run. buildprogram_buildprogram.dag no longer valid. directory contents changed: .
[ 0s] Freezing buildprogram_buildprogram.dag.json into .dag (.dag file didn't exist)
*** buildprogrambuildprogram build success (0.06 seconds), 0 items updated, 7 evaluated
[ 0s] Freezing tundra_buildprogram.dag.json into .dag (.dag file didn't exist)
*** buildprogram build success (0.09 seconds), 0 items updated, 13 evaluated
error: Value cannot be null.
Parameter name: executableStringFor (System.ArgumentNullException)
at Bee.Core.Backend.AddAction
at Bee.NativeProgramSupport.CLikeCompiler.SetupInvocation
at Bee.NativeProgramSupport.NativeProgram.SetupObjectFilesAndSetupBuiltNativeProgram
at Bee.NativeProgramSupport.NativeProgram.SetupSpecificConfigurationImpl
Advice appreciated 🙂
Turns out i needed community + a bunch of new addons 😛
Good that you got it figured out but Id recommend starting with the normal ECS samples before jumping into tiny. The entity debugger helps a lot while learning, and you can't use it in tiny
Thanks for the advice 🙂 Tiny is a core component in the end product, but I will probs take your advice and create another ECS project to test things in. The project goal is pretty simple, just an interactable UI that can send commands to a server.
Nothing I havent done in normal pipe before, ECS makes it a challenge though 🙂
Hrmmm other than RayCastCommand, what other classic-Physics API that uses Jobs?
How can i create a function which i can call in the Lambda expression that uses ScheduleParallel?
Does dots have its own gitignore or is the regular unity gitignore enough?
i believe regular unity gitignore is enough
Hey again all, I think I might be following an outdated tutorial (not a hard thing to do when working on preview stuff).
Im using 'ConvertToEntity' on a prefab, and its creating the entity and removing it from heirarchy, but its also disappearing from my screen, when tutorial says it should still be there.
Has something changed in this part of the workflow?
Is this still tiny, or hybrid renderer? For hybrid renderer you need to double check the hybrid renderer package is actually installed, and as of the latest version you need to disable srp batching in the srp configuration assets
hybrid renderer
It was the SRP batching you legend 🙂
Theres an hour of googling that mentioned SRP exactly zero times :
Yeah it seems to be a fun hidden change in the latest version(s)
Its really the hardest part of keeping up with all the new stuff. And all the official tutorials dont mention them because they're from 3+ versions ago
Well every aspect of dots is in different stages of Not Ready. Hybrid renderer is more Not Ready than most unfortunately, which is kinda weird since reindering stuff is like....important
Just a bit...
Im okay with it all being not ready, just wish there was more up to date documentation on the not readiness
Its understandably a preview package
You and me both
Does dots have helper functions for quaternions? Struggling to find a replacement for monobehaviours LookAt()
you can use quaternion.LookRotation(direction, up) to figure out the rotation for a similar effect to transform.LookAt(...)
but... mentioning it now, you won't find quaternion to euler very easily - think there's a version in physics (I think) or else in the forums else via Quaternion if need be or else you may be able to use e.g. EulerZYX instead of Rotation depending on your use-case. Most use-cases don't *actually need it but sometimes you just do.
Thanks 👍
is the best way to get all entities in an area to run world.overlapaabb? is there one that is sphere based instead?
is that essentially PointDistanceInput?
Quick question is there a way to destroy the original gameobjects when you're converting a whole scene using
GameObjectConversionUtility.ConvertScene(activeScene, settings);
(kinda like the convert & destroy option on the convert component)
maybe it wasn't such a straight forward question
anybody has some ressource that can explain me how ComponentDataFromEntity<Type T> works within SystemBase?
i just get Debugs with InvalidOperationException: <>c__DisplayClass_OnUpdate_LambdaJob1.JobData.seekerTarget is not declared [ReadOnly] in a IJobParallelFor job. The container does not support parallel writing. Please use a more suitable container type.
witch makes no sense at all because i dont write to it
jobs can't determine whether you are actually writing into a container, if you don't declare ComponentDataFromEntity<T> as readonly in a lambda foreach or a job struct, then by default it's assumed that you "may" be writing/updating a value @crystal helm
// Lambda
var some_data = GetComponentDataFromEntity<T>();
Entities.ForEach((...) => {}).WithReadOnly(some_data).Schedule(...);
// Job struct
struct SomeJob : IJob {
[ReadOnly]
public ComponentDataFromEntity<T> SomeData;
public void Execute() { ... }
}
uh, thats helpful, thank you ill try it right now :3
.WithReadOnly() takes only one agument... wtf
You can call it multiple times
yay, it doenst throw debugs, but it doesnt work >.< fml
So there’s not a way to ‘destroy’ the scene objects when using ConvertScene ?
Are there any good resources for UI use with ECS? I have a base understanding of ECS flow for normal play systems (locomotion, data change, etc), but not sure whether I can use normal monobehaviour for UI, or if I need to use some new esoteric implementation
I don't think there's any resources or tutorial really. You can use managed components with ChangeFilters to make a pretty easy self-updating UI https://forum.unity.com/threads/dots-and-ui.1018159/#post-6598195
Someone also made a pure ECS UI on the forums a long time ago, no idea if they've kept it up to date
I've made some more progress with that attempt at raycasting I was doing the other day - I actually managed to write something to an int array! But it's slow and doesn't really work. Can someone tell me what I should do with this job/arrays?
This is the job struct:
`
[BurstCompile]
public struct LineJob : IJobFor
{
[ReadOnly]
public TileAddress2 start;
[ReadOnly]
public NativeArray<TileAddress2> endTiles;
[ReadOnly]
public NativeArray<TileAddress2> addresses;
[NativeDisableParallelForRestriction]
public NativeArray<int> visibility;
public void Execute(int index)
{
Bresenham.LineUntilBlockedFlatGroupParallel(visibility, addresses, start, endTiles[index]);
}
}`
hmm. my last message was removed
job.Run(40); does this compile? haven't seen .run used with params before
ahyea cuz ijobfor my bad
i was just doing it to make sure it worked before I set it to parallel
ya that's fine
but I'm (knowingly, to some degree) fucking up the memory management here
what did you mean with doesn't really work
I just don't know the right way to do things
well, two things: it runs really slow, and it gave the wrong output. it looked like it wasn't completely iterating over the toprow[index] bit
ah, how do you set it to jobs - change main thread to one of the worker threads?
Change .run to .schedule. I just want to verify this is actually the thing that's running slow
As for not getting expected results - not really clear to me what should be happening from the code. Just looks like a bunch of magic numbers out of context
yeah, the logic's happening in a third function, which I was holding off pasting to avoid spam 😄
okay, added it to the end here: https://hatebin.com/fiadjwrzgp
And the profiler
I changed run to schedule
but I don't see it in the profiler
is this what you mean?
Change the hierarchy tab to timeline
Include the main thread part
this is with .schedule?
yes. I'm definitely doing something wrong. Many somethings, most likely.
I think schedule can still choose to use the main thread if it's not already busy
does this look right?
the native arrays i'm using are, incidentally, very very large. that might be part of the problem
Probably. With my pathfinding I found it started to slow WAY down with maps > 1000 * 1000. I would say verify your algorithm outside of jobs and burst in isolation, step through on a smaller map and make sure it's doing what you expect
For performance do deep profiling and dig down in the hierarchy view to see what's slowing down, that only helps so much though since you can't do it with Burst on
so, the visibility int[] IS 1000x1000. but I thought if i was just writing to random parts of it (only about a 100 or so, in the end) it would be fine
You can use Unity's performance testing package to do more fine grained profiling on self contained burst functions. It's a slow and annoying process though
am I allowed to be writing to a native array inside a job like that?
I'm not worried about concurrency issues because they're all writing the same thing (for now)
If it's single threaded you're safe to write to whatever index you want. If you're running in a parallel job Unity will restrict you to the index they pass in unless you disable safety checks
yeah I added that line to the job struct
Oh, I see. Well it's only okay as long as you are 100% sure you're never writing to the same index from any two invocations of the execute function
well - I might be, but with the same value
Writing or reading
does .... is that bad?
Yes
I don't know enough about multithreading to know exactly what it will do, I just know it's bad. There's a reason they put so many safety checks in to stop you from doing it
haha yeah, very true
okay. I think I might go back and check out some more of your roguelike visibility stuff before I try this again
but hey, I got closer this time!
at least it actually compiled and ran 😄
do you mind telling me some of the results you were getting with your fov/LOS checks? specifically, what ms per frame was dedicated to that with your 1000 visibility mappers, and what was their max line of sight?
I'd really like to get similar performance and I don't think I'm going to be able to do it without jobs
I'm going to pass out atm. I should be able to check tomorrow before work
I want a system to take in a mesh, but i cant since a mesh isnt blittable. Is there any workaround?
you can use managed ICDs to store a mesh there and run an Entities.ForEach Withoutburst
Thanks :)
I have a similar question. Well the same question. Which is... what? What did you say about the ICDs and the things? I'm dumb. Actually... here is my question.
It seems like in Unity.Rendering, mesh data is stored in a RenderMesh component
So, if something has a RenderMesh component, how in the heck fire do I update the mesh field inside the RenderMesh component?
Is there a Pure ECS way to do that?
in Entities foreach is there an extension method to get a number of entities it found?
@deft stump I think so let me check my examples
@deft stump EntityQuery?
CalculateEntityCount()
I mean EQ should do it. But in a way, I'll be essentially EQ'ing twice.
1 for CalculateCount.
and another in Entities.ForEach
I wanted to avoid that
I'm new to ECS, its my best guess. The EQ should be used inside the foreach no?
.WithStoreEntityQueryInField(ref MyEQ)
Doesn't that return and store the resulting EQ from ForEach?
Yes that stores the query into a field of choice
Yes the query is valid to get the entity count from even before the foreach lambda where you ref it
@low tangle thanks for clearing that up
No problem
well if there's no extension method I'll just IJobChunk it or something.
NativeList<float3> Vertices = new NativeList<float3>(Allocator.Persistent);
NativeList<int> Triangles = new NativeList<int>(Allocator.Persistent);
MeshData result = new MeshData
{
Vertices = Vertices, //native list
Triangles = Triangles //native list
};
return result;
Any clue why these might get deallocated?
My only guess is because there inside a struct...
Nevermind. I think its referencing the original thats been deallocated.
Reading through code in com.unity.mathematics, specifically random.cs... either I'm missing something here or this code is whacked:
/// <summary>Returns a uniformly random int value in the interval [0, max).</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int NextInt(int max)
{
CheckNextIntMax(max);
return (int)((NextState() * (ulong)max) >> 32);
}```
NextState() seems to return a pseudo-random 32-bit value (uint) which is then multiplied by max into a ulong, presumably to attempt to prevent an overflow, and then right-shifted 32 bits. So, if NextState() happens to return something small (let's say 1 for now) and max is something small (let's say 5) then you get a ulong with a value of 5 which is 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 01001. Now, if you right-shift this by 32 bits, you are left with 0. So, while technically true that it returns a random int value in the range of [0, max) it seems that's mostly because for the first 4 billion some odd possible values, it will simply always return 0. Or am I missing something?
So that’s a no then?
@neon pewter so my take on this is the odds of getting such a low number are very low.
Long/int = 9223372036854775808 / 2147483647 = 4294967298
Ok that calcation doesn't make any sense. But imagine every bit being random 0/1, you're only taking half the bits away
I mean, look at the bit array you made. What are the odds of having so many consecutive zeroes if the number is truly random ;)
@last lintel This is with ~2500 monsters, in the editor with safety checks on in the current version of my game. All the monsters in this test have a visibility range of 5.
Also I convoluted a test where monsters are doing FOV checks every couple of frames. Normally my game is turn based so the FOV checks only run when an entity moves
where's the proper place to learn unity ecs? the unity manual? are youtube videos about it outdated?
The manual and github samples are the only things kept up to date-ish ATM
ok
Also fun GIF of monsters trying to wander around an incredibly cramped dungeon:
Funny how the scaled version of that GIF looks a lot emptier
Let's say you want to generate a random number between 0 and 2, inclusive. You would pass 2 as the value of max. That means that the NextState() call would have to return something higher than half the maximum value of a uint in order to return any positive value at all. However, if the number is truly random, you would expect that 50% of the time, it will return half the value of uint or less. For all such values, the final result would be 0. Thus, the distribution of random numbers from consecutive calls to NextInt(int max) would be roughly 50% => 0, 25% => 1, 25% => 2 assuming the bounding equation were actually correct. And that's not even a uniform random distribution. If you want to pick between 0 and 1, as far as I can tell, it will always return 0 as 1 times any value of uint will never exceed 32 bits and if you shift it right 32 bits, it will always fill it with 0.
Again, this is assuming that the bounding algorithm were in fact correct. If the random value (RV) returned were anything other than 1, then the equation (RV * Max) >> 32 is never going to return a value bounded on the upper end by the number Max (it will, but not in the expected interpretation in terms of random number generation). If you break out a programming calculator and inspect what happens to the bits when you take integer max and multiply it by (for example, 9 as the max value) then shift it right 32 bits, you get 4. If you take integer max and subtract any number from it (go mono-sequentially incrementing) you will see the resulting value is always 4 for small values. At some point, you hit a large enough value being subtracted that you can generate 3, then 2, then 1, and then the remaining set of integer max returns 0 always. Never can you get the algorithm to generate 5, 6, 7, 8, or 9.
You could also easily test the function with your input set that you think will cause the issue
figuring it out academically is totally fine too though
fwiw I haven't had any issues with random, other than forgetting to init it sometimes which gives you zeros till you do
Well, that's why I assumed I must be missing something. But the more I look at the code and crunch numbers on the calculator, the more I'm convinced it's just plain wrong. 🙂
if it does turn out to be that way, make sure you post on the forms with your findings. unity would be very happy to fix it I'm sure
The only mathematical operation I am aware of to generate a uniform random distribution bounded by a range is using a modulo operator, not a multiplication.
I believe it should be (RV % Max) + 1
that would indeed generate a value in the range [0, Max)
However, modulo operators are pretty heavy
A more performance friendly way is probably to generate a random double in the traditional 0.0 - 1.0 range and then multiply by max.
Anyone have strong knowledge of the RenderMesh component? I can't figure out if there is a way to use SetSharedComponentData to set the { mesh } field of the RenderMesh component
is this possible?
Entities.WithStructuralChanges().ForEach((Entity e, RenderMesh renderMesh)=>
{
renderMesh.mesh = new Mesh();
EntityManager.SetSharedComponentData(e, renderMesh);
}).Run();
Hey all, I'm finding that I have to create separate methods for use with burst and without, and I'd like to find more ways of reusing code. Are there any best practices guides or articles about this? It's a bit frustrating to have to create one version for an editor script, and one for an entity system.
for example I have two methods that do the same thing: public static void GetTerrainHeightData(TerrainBounds area, int resolution, TerrainSettings terrainSettings, IEnumerable<TerrainLayer> layers, Action<int, int, float> setValue) and public static void GetTerrainHeightData(TerrainBounds area, int resolution, TerrainSettings terrainSettings, NativeArray<TerrainLayer> layers, DynamicBuffer<float> buffer)
if it works with burst then it also works with not-burst
the non-burst one would be redundant
but in your example if they actually need different params, makes sense to have two seperate methods, but call one from the other
Maybe the question should be how do I use DynamicBuffers outside of a system then?
I'm using the first to update a color array for use in a texture, and the second one updates a dynamic buffer.
if you can get away with nativearray you can just use .asnativearray for the dynamicbuffer
but if it's a C# array vs a nativearray then yea makes sense to have seperate implementation
if it's a long method you could extract the part that's specific and still reuse method for the rest
I'm trying to separate out as much as I can, but for some there's not much difference between them except for one allows for a reference type to be used.
But thanks anyway.
yea
well in case of arrays nativecollections are allocated in a different way from C# arrays/lists so they're not interchangeable
but you could for example in method 1 pass in a nativearray, copy that into a C# array and pass it into method 2
or vice versa
extra copy doesn't matter much if it's in editor
That might add more issues as far as managing the native array lifetime. Good idea though. I think I'll live with the code duplication for a bit.
So I checked out these two articles, and you're right that the Unity.Mathematics method is biased.
But apparently, whether you do a modulo operation or multiply the range by a random [0, 1) floating point value, the distribution would still be biased.
https://www.pcg-random.org/posts/bounded-rands.html
https://ericlippert.com/2013/12/16/how-much-bias-is-introduced-by-the-remainder-technique/
The problem is that there's no guarantee that max divides the random uint32 evenly. You'll probably have one bucket with fewer numbers than the rest.
The only thing you can do to remove bias is to just try again whenever you get a number in that bucket.
while(true)
{
// RAND_MAX = 2^32 - 1 or 2^64 - 1
if (NextState() < RAND_MAX - RAND_MAX % max)
return state % max;
}
The first article has cheaper variants of this method that use fewer modulo operations or none at all. The biased integer multiplication method that Unity.Mathematics uses is the fastest. That said, the documentation should definitely warn that the bounded generator is not uniform (and maybe provide an unbiased generator).
I have a custom GameObjectConversionSystem, and it runs on entities that are converted by the Convert Behaviours (e.g. GameObject with ConvertToEntity, or GameObjects in Subscenes that are Open for Editing).
Problem is, as soon as I close the scene (converting it), that doesn't run the necessary system, or at least a part of it (so things like collider tags are never applied).
Strangely enough, its output does show up in the subscene conversion log, but the output of that log glitches so I am not sure that it is recent (i added a timestamp and it seems to not be appropriately recent).
What do i need to do this to execute for Subscenes as well?
public class BubbleGroupConversionSystem : GameObjectConversionSystem
{
protected override void OnUpdate()
{
Entities
.ForEach(
(BubbleAuthoring input) =>
{
var entity = GetPrimaryEntity(input);
var bubble_id = DstEntityManager.GetComponentData<Bubble>(entity).id;
var bubble_data = DstEntityManager.GetComponentData<BubbleData>(entity);
//... instanceContent is intended to be a prefab some day, that didn't work
//... but right now it's a gameobject that is a sibling in the hierarchy, which is also acceptable to me
foreach (Transform t in input.instanceContent.transform)
{
var linked = GetPrimaryEntity(t);
Debug.Log($" + Contained Entity {linked} - {t.name}");
// -- This seems to happen?
DstEntityManager.AddSharedComponentData(linked, new BubbleGroup() {id = bubble_data.id});
// ... snip ...
//-- this doesn't seem to happen in subscene, but is fine in GameObject Conversion
if (t.GetComponent<PhysicsShapeAuthoring>())
{
DstEntityManager.AddComponentData(linked, new PhysicsCustomTags() {Value = bubble_data.id});
}
}
}
);
}
}
Yes, the whole system ONLY runs if I hit play and the Subscene is open.
How do i get it to run for a subscene?
if you debug and put a breakpoint at var entity does it stop at the point?
(with the subscene closed)
actually
not sure how you debug subscene editor conversion but im wondering if its an ordering issue at play
The system seems to run actually, just that one query doesn't.
It picks up entities that are not from the subscene fine.
but it shouldn't just run on playmode.
the entities I see ARE the right entities, they just have this particular conversion step not applied to them.
hmm
Together our discord discriminators would break discord, but with the minimum effort. I like that.
it sounds like that GameObjectConversionSystem isn't being used to convert the entities @warm panther
It is.
Breakpoint triggers when the scene is open and I click play.
It doesn't when I close it (and the entities get converted then)
One thing I need to test though...
Yes it runs only when I click play.
I see, don't gameobjectconversionsystems run in the editor though, I mean I thought they run before you press play
The entire system.
It should run in the editor, whenever entities are converted.
(my intuitive expectation)
they are put into a subscene in the mean time and then moved to the main scene when the program loads
that's how I remember it anyway when I came up against similar problems
The entities are in the default world.
Which is fine, but I can't run a ConversionSystem for a subscene and I wonder what I need to do instead, it's much nicer to have a conversion system than to have monobehaviours on a few thousand entities. So strange.
does ConversionSystems even work for subscenes 😕
I mean I used them for monobehaviours but not subscenes as they are already converted
But it should.
Well.
Log: BubbleGroupConversionSystem
Log: 2021-01-04T17:19:06.2363917+01:00 Converting Bubble 10 - Sphere Volume
Log: + Contained Entity Entity(2:1) - Moon
Log: (is physical)
Log: + Contained Entity Entity(9:1) - Isotope Exchange
Log: (is physical)
Log: + Contained Entity Entity(3:1) - Cube (01)
Log: (is physical)
Log: + Contained Entity Entity(10:1) - Power Plant
Log: (is physical)
Log: + Contained Entity Entity(4:1) - Cube (03)
Log: (is physical)
Weirdest part tho...
The conversion log shows the right actions.
(the isphysical is when the component is added that is missing)
So it DOES run. But doesn't hit the breakpoint (ehhh?)
are you sure it runs though
No that output doesnt come from that step.
It comes from playmode.
Weird.
No it's from reimporting the subscene
Interesting.
It doesn't hit the breakpoint.
I never trust anything
Healthy mindset after 2020 😄
Adding more printfs...
Log: BubbleGroupConversionSystem
Log: 2021-01-04T17:28:05.0801887+01:00 Converting Bubble 10 - Sphere Volume
Log: Playmode <color=cyan>False</color>
Log: + Contained Entity Entity(2:1) - Moon
Log: (is physical)
Well.
It's not playing.
And when I enter playmode, it clearly is.
So I wonder what is missing.
yea that's weird
The subscene will only run conversion under certain circumstances right? Like if an authoring version changes
I've barely messed with subscenes but this confusion is definitely consistent with my limited experience
It runs exactly when I expect it to, when the subscene is closed and serialized (or reimported)
Loading the data into my world (editor) gives me entities that also have the right components and values.
The only thing I can't verify is the physicscollider
Because Unity just neeeeeds to obfuscate these as much as possible, ikr?
oh I don't think breakpoints work in ConversionSystems
@warm panther did you add the ConverterVersion attribute and is updating it after each script change that you want to reflect on existing subscenes?
No. Not yet. That script changes all the time. I should probably use current time as the version.
like I said unless you somehow run them manually at run time they are run before the program is run
The scene is actually in correct state. I now need to check what happens when these entities are loaded.
If you don't use it, it will only fully reconvert if you clear that sub-scene cache
I believe that in the most recent release there is a an option to clear the sub scenes caches
I remember seeing something like that
It's just the COLLIDERS that seem to not work.
have you tried checking the worlds there should be a subscene where the converted entities are in stasis
Yep.
That's what I'm doing, the entities are there. Bare numbered entities, because who needs names, but I identified one of them.
And that thing has everything it needs.
But the collider doesn't work but the object is entirely opaque.
Weird.
so you want them to be converted but they are missing certain components?
maybe a conflict somewhere
just a thought maybe the primary entity doesn't exist 🤔
It exists.
The log shows everything correct. So actualyl the code executes.
I am now investigating the colliders.
are you sure though
It's almost certainly the custom tags on the colliders at this stage.
Yes the stuff wouldn't be there if it weren't converted.
And the components I THOUGHT were absent aren't absent.
Just hidden under layers of unsorted entities.
(these things are like eels)
but if they are in a subcsene then they are already auto converted
Yes and that auto conversion I can see, properly, in the subscene's conversion log.
But the mesh colliders don't work.
I'll try a sphere collider.
Just to make sure it's not the mesh.
maybe I'm wrong in this case but I came up against the problem before where I had to add blob to an entity in a conversion system but I though the entity existed but it didn't so I had to use a monobehaviour and convert that first
And I don't think you can do sub scene and game object conversion system at the same time on the same game objects
Yes the collider is dead, even if I disable my custom filtering, it no longer interacts.
You can, you gotta. 🙂 That's no longer the problem, my problem now is that some of my colliders cease working.
do you have any other code modifying colliders in your project?
to be precise, none of the subscene colliders work.
I don't modify colliders, I only set PhysicsCustomTags components on objects and disable BodyPairs in a job based on that. I just uncommented that code to rule it out, and it doesn't cause it.
Ok getting closer...
Change is good.
Ok, the collider doesn't get scaled.
In Subscene workflow vs. gameobject conversion workflow.
Not exactly though.
Oddly enough box colliders also break.
The mesh collider breaks if the object isn't scaled 1/1/1
position plays nor ole.
I thought the collider was left in the middle but it is somewhere 😄
Maybe I can display it with physics debug.
getting curious
Physics debug says it's there, in the expected size.
Nope. They're all there, they just don't collide.
Huh.
But they DO collide if the object is scaled 1/1/1 but isn't one of the small boxes.
Have you tried adding a scale component I don't think it gets auto added, I know you used to have to add non uniform scale manually
It's a uniform scale.
But it could be read as nonuniform by a very jittery CPU 😛
16.4/16.4/16.4
The mesh is scaled correctly.
On the entity.
And the collider is also there.
Physics Debug can draw it so it definitely exists.
I'll check its collision filter.
If I find out how.
Because fuck these opaque collider objects.
select collider edges if you don't want opaque
By opaque I mean data you can't look into.
The only thing the DOTS editor exposes is the hash of the collider asset.
I am taking apart my culling system because that's where I can most easily see which colliders matter.
(it's a visuals only culling system but I can get the colliders there in the volume where the gameobjects close to the player are)
Well. Getting closer.
("Value" is the actual field that matters here tho)
found a composite collider that was empty.
But weird.
need to reduce this to the minimum case
Interesting.
Anyone knows why this isn't working? the changes on nrOfAliveRobots doesn't get saved, like im working on a copy of it. Im new to dots so its probably something basic
If I add my player to the Same subscene, it collides.
If I add it to another subscene, same behaviour as if it were outside just as a converted gameobject.
You need to write the componentdata back in this case.
you're working with a struct - a value type - so add allSpawnRobotData[parentGoliathData.goliath] = spawnRobotData;
Thank you, that fixed it :D related question, is there a version of GetComponentDataFromEntity for managed component data?
Don't think so. Similar to SharedComponentData you just need to re-set it through EntityManager if you ever need to change it.
Man, it would really, really, really, really help if we could have something like entity names.
I'm this close to writing a hashmap.
(in converted subscenes, that is)
It doesn't even display FixedString128 it seems.
Huh, it does, but you need to unfold.
NonUniformScale ... is kinda weird on these meshcolliders.
Okay that's a conversion bug.
If I scale it to 1/1/1, it works, as does the collider.
If I place the player object in the subscene, it, too, gets a NonUniformScale component; and with that scale, it will collide, also with the larger collider (16.4) Oddly enough, this only happened once.

can you browse pages of buffers using the dots editor?
i cant remember if that ever worked but I had to uninstall it to properly inspect a buffer that had more than 5 or so entries
It's a mess but yes I generally can.
perf of dots editor also seems impressively slow, but then again might just be me
So it appears to be an issue with the NonUniformScale on some meshes, but in fact; i have a bunch of boxes and SOME of em work and others don't.
This is pretty interesting now.
But that DOTS inspector has me crosseyed.
and I'd love to filter by a sharedcomponentdata value
This doesn't collide...
this does.
Authoring stage of both. Right one collides.
@warm panther what does your Point Of Interest Authoring do (or its conversion system)? (as this and the mesh's material are only visible difference there)
It sets a simple IComponentData that contains an enum and 2 FixedStrings.
And a bool.
These are only read by a UI behaviour.
The entities that come out of this are structured exactly the same (other than for that IComponentData.
I am now at the point where I suspect it may be a chunking issue or something.
I'll try to make the two objects as equal as possible and see where it stops being broken.
public struct PointOfInterest : IComponentData
{
public FixedString128 label;
public FixedString512 detail;
public PoI icon;
public bool announce;
}
public class PointOfInterestAuthoring : MonoBehaviour, IConvertGameObjectToEntity
{
public bool announce = false;
[Required]
public string label;
[TextArea]
public string detail;
public PoI icon;
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
dstManager.AddComponentData(entity, new PointOfInterest()
{
label = label,
detail = detail,
icon = icon,
announce = announce
});
}
}
}
This does nothing fancy.
Ok it's not the material so I removed the authoring component.
Now it seems to collide, test pending.
(ongoing I mean)
Okay. It is that component, or what I do with it. Weird.
If I don't add the component, it collides.
Whaaa.
this is beyond strange, lol
Even the colliders are the same hash
So it seems I may not properly be processing chunks.
because if the archetype changes, even with as little as a tag, they won't collide.
BUT... they are different from the player anyhow.
So... what gives.
So I'll disable my collision magic stuff.
Nope. Ot
It's not that.
Just wondering if you add the icd’s in the after conversion phase whether you still see the same thing
Or tag them at runtime for that matter
I can try that.
And will also try to use the ui to remove the ICD
should be easy to code
so I can fly there, click the PoI, and try to collide.
that's one thing I desperately want from the DOTS editor.
Adding / editing ICD at runtime.
OK. I fly through the immaterial object to see collision fail.
Then I click the PoI, ICD gets removed. Collision works. (at this point remotely expected)
Unexpected: Collision then works for all other PoIs, even with the ICD still on them..

Gonna look at the chunk lay out...
literally this click should only move two entities in memory though
On the plus side, thanks for that idea, I'm gonna build some debug tools for my UI out of that. Yay, entities identifiable!
That's the chunk they're in before the click...
Then that one entity is moved to this chunk (which holds 3 others, which are the debug cubes that worked)
The chunk it was removed from looks like this now
What's the number in the corner at the top right?
Only one entity was moved in the chunk, I guess the last one.
Tfw you're onion-skinning chunk infos -.-
What do these 2 bars mean? Any ideas?
I clicked one of the earlier entities and it kept moving the right bar, but one entity made the left bar move.
Now the bars are orange. ...
the chunk info is a mystery box filled with encrypted information that scholars have been studying for years
but yea the 2 bars mean you have 2 chunks, one full and the other one has a few entities (horizontal = entity count)
Wait so this is 3 chunks?
Makes sense, there's 3 SICDs that differ (from meshes)
so I wonder if this chunk reordering can be triggered.
as a workaround at least 😄
So one thing I do is move all entities in that "Bubble" into one BubbleGroup, setting a SICD.
(well that happens before)
so when I enter the bubble with the player entity, all the system does is set or remove DisableRendering appropriately
and it definitely does that.
so a mere structural change doesn't seem to be enough.
Newest theory: The static physics bodies don't get updated in BuildPhysicsWorld if only their custom physics tags value changes.
Or just not updated.
Because I haven't seen an invalid value come up in the collision checks (I think)
I added a PhysicsBody to one of the buildings and it works if that is Dynamic or Kinematic.
Doesn't work if it's static, which I tried before.
(no, I'm not moving anything)
(but actually moving would help, ironically)
Yup 100% repro now.
what a waste of 6 hours. And by waste I mean I appreciate the learning opportunity, thank you Unity DOTS.
Interesting.
if (PhysicsWorld.NumStaticBodies != previousStaticBodyCount)
{
HaveStaticBodiesChanged[0] = 1;
}
Interesting, interesting.
public int NumStaticBodies => Broadphase.NumStaticBodies;
I don't see how these queries are affected by other components but... they are.
I think it's the fact that I change some other components, that moves the bodies out of their chunks; causing something in Physics to silently fail, but not rebuilding that part of the Broadphase ever. I don't understand why it needs to be rebuilt though... but this is their test.
// Make a job to test for changes
int numChunks;
using (NativeArray<ArchetypeChunk> chunks = StaticEntityGroup.CreateArchetypeChunkArray(Allocator.TempJob))
{
numChunks = chunks.Length;
}
var chunksHaveChanges = new NativeArray<int>(numChunks, Allocator.TempJob);
staticBodiesCheckHandle = new Jobs.CheckStaticBodyChangesJob
{
LocalToWorldType = localToWorldType,
ParentType = parentType,
PositionType = positionType,
RotationType = rotationType,
PhysicsColliderType = physicsColliderType,
ChunkHasChangesOutput = chunksHaveChanges,
m_LastSystemVersion = LastSystemVersion
}.Schedule(StaticEntityGroup, Dependency);
staticBodiesCheckHandle = new Jobs.CheckStaticBodyChangesReduceJob
{
ChunkHasChangesOutput = chunksHaveChanges,
Result = HaveStaticBodiesChanged
}.Schedule(staticBodiesCheckHandle);
}
public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
{
bool didChunkChange =
chunk.DidChange(LocalToWorldType, m_LastSystemVersion) ||
chunk.DidChange(PositionType, m_LastSystemVersion) ||
chunk.DidChange(RotationType, m_LastSystemVersion) ||
chunk.DidChange(PhysicsColliderType, m_LastSystemVersion) ||
chunk.DidOrderChange(m_LastSystemVersion);
ChunkHasChangesOutput[chunkIndex] = didChunkChange ? 1 : 0;
}
So yeah. This doesn't realize I've drastically changed the physics world.
But why does it realize this later.
So I need to move just a single static body at application start and this will work. Something to try tomorrow.
this is why I'm not using Unity.Physics 
@warm panther if you didn't know, entity names are editor build-only
The pins and channel description explain everything.
exactly same i was gooing to ask here now
Is it possible to move game objects between two subscenes?
I have a game where I want to use an ECS trigger system to cause the camera and player to move to the next 'level'. At first it seemed like subscenes would be the way to go for this (even though I don't especially expect performance issues), it seems appropriate to use subscenes. If I can get my level exit entity to point to the main camera entity whilst authoring this problem is easy, but it seems that's not an option if I want to use subscenes, so is there a way to make it so my system can find the main camera and move it each time the trigger is called, or to find the camera when the game starts and have access to it each time the trigger happens?
Sorry if this is super simple stuff or covered elsewhere
@fading nest so you're asking to move an entity to another scene?
why not just move/copy-paste it's data instead
Well since it's a camera I believe it has to stay as a game object, no?
I have tried creating a MainCamera component and using this to update the MainCamera entity's translation component, but this doesn't seem to update the transform of the MainCamera gameObject. Should I expect it to? Do I have to create a system for handling this myself?
How are you attaching the gameobject to the entity? ConvertAndInject?
Or adding a hybrid component
I was doing convert and inject
I've now added the deprecated Copy Transform To Game Object Proxy and I have warnings but it works 😅
incidentally when I get a Translation component for an entity it appears to be local to parent, I assume there's some way to get a local to world translation, but I can't see anything but the raw local translation on the component itself
I guess I get the translation of the parent and add that?
to get the local to world translation you can grab the LocalToWorld matrix and access the Position property, it will return a float3 in world space
that's the easiest way, but your way can also work
are there any current tutorials or tips on where to start using ECS/DOTS? Most stuff from 2019/2020 is outdated as it seems
I dont think there is many if at all up to date tutorials, there's codemonkey but his tutorials are a bit out of date I think he uses JobComponent instead of the latter SystemBase now, but if you use them with the info in the pinned messages up top you should be able to get somewhere
thanks @pliant pike
this is also a good tutorial just replace JobCompSys with SystemBase
https://www.youtube.com/watch?v=a9AUXNFBWt4
In this workshop style video we walk through an example project created by Unity Evangelist Mike Geig on how to script a Pong style game using Unity's Data Oriented Tech Stack (DOTS) including the Entity Component System (ECS). This video covers the latest syntax in Unity 2019.3.0f1 and Entities package version 0.3.0-preview.4
You can download ...
Ah perfect thanks!
@fading nest Use AddHybrid from conversionsystem, it will make a hidden gameobject and manage the lifetime for you (based on the entity created as well)
it also supports automatically copying the l2w to the hidden gameobject's transform component
aka updating the translate will magically move the transform of the camera in your case
tested as of yesterday on a new 2020.2 ecs project
Also I've been trying to get back caught up with the latest ecs stuff, and I really gotta say the new conversion stuff is much much better than before
I can't yet do complex IK & skeletal animation though hybrid, but everything else seems quite a bit more tolerable
I'm in a bit of a pickle for that stuff anyways
to get access to the hidden gameobject, you just need to find one of the hybrid components and use the object field to jump to it
which is copyed from the LTW <- Translation on the entity
If you add the gameobject's transform with hybrid, it will ignore the l2w on the entity
so I wouldn't do that, also heres a lazy way to add all components to a entity, for quickly testing what you can get away with
internal static void ConvertEverything(this MonoBehaviour self, GameObjectConversionSystem conversionSystem)
{
var allComponents = self.gameObject.GetComponents(typeof(Component));
foreach (var cmp in allComponents)
{
switch (cmp)
{
case ConvertToEntity _:
case IConvertGameObjectToEntity _:
case Transform _:
break;
default:
conversionSystem.AddHybridComponent(cmp);
break;
}
}
}
its a static extension, but you could just copy paste the body into your IConvertGameObjectToEntity and call it 'ConvertEverything'
thanks I will look into this
So I sort of want to start a fps project. How integrated with the rest of unity is dots atm. Like will I be able to use cinemachine for example? How are animations and IK ? Im guessing that finalik is not usable
you'll be able to use cinemachine with hybrid dots. Just have a targetGO sync up with the entity.
I'm not too sure on animations and IK though. someone else can answer that, probably.
I haven't used dots animation myself but seeing other people talk about it it sounds extremely rough right now
it was, and I think its in a much better state now. but I haven't finished assessing it
I'd imagine though that conversion of anything other than one set of animations will work right now
and it will take awhile to fill in the gaps of ways you might want to animate things before your usecase finally fits
if you are willing to take on the fact that, hey I might have to do a custom solution, and or a hybrid one (utilizing monobehaviour solutions where needed) then you could start one
well Im mainly looking at dots because of the enemy idea I have haha. I want them to be essentially made out of voxels that you shoot out and they die when you destroy them like that.
Should be doable but it I think it would be very complicated if you want them to actually use physics. I wouldn't recommend it for a first dive into dots
I don't mean the physics itself would be complicated, but working with dots and unity physics is
I thought thats what the Physics and Havok package is for
Yeah it would certainly work and probably perform great, it's just a lot to tackle for a first project. Using the Unity.Physics package is very annoying right now - in my opinion
well I might just give it a try this weekend and see how it goes haha. If you ask me the procedural animations are going to be the biggest obstacle in this one.
@mild ledge cant use finalik with dots animation. you can do ik stuff(not sure the extents though as I personally dont use it) but you will need to deal learn dataflowgraph, which is what the animation package uses - this is what a directional controller setup looks like https://github.com/Unity-Technologies/Unity.Animation.Samples/blob/master/UnityAnimationHDRPExamples/Assets/Scenes/Advanced/AnimationController/AnimationControllerGraph.cs
(also cant use the animation rigging package with dots animation)
hmm interesting. Thanks for the repo share will check it out. I however dont plan to have 10000 enemies. I plan to have a few enemies but they are made of 10000 parts. So I will have to make entities follow a regular animation I think. At this point it's all in my head and I have not yet done my research.
yeah id say mecanim would be far a better choice for that scenario atm
perhaps there is a easy way to chain entities to a normal bone transform. I hope haha
that boiler plate 😬
i laugh at people complaining that systembase foreach etc is too much boilerplate, animation/dfg system takes it to a whole new level
I'm sure this will improve massively, esp with editor tooling... but .. ```[UpdateBefore(typeof(DefaultAnimationSystemGroup))]
public class AnimationControllerSystem : SampleSystemBase<
AnimationControllerSetup,
AnimationControllerData,
ProcessDefaultAnimationGraph
what is that ugly complex generic inheritance doing in my shiny dod? 🤣
part of it is so they can reuse that base system functionality for every single example, but it def adds to the cognitive complexity of just unraveling the examples to try to understand them
Since Rendermesh is a shared component, does that mean i can't modify a specific entities mesh?
you can modify it (by changing the shared component data) - it will just then sit in a different chunk
Hmm, when i modify one of them it affects all. Testing it by setting all vertices of a mesh to Vector3.zero, which makes every entity that uses a copy of that mesh to disappear. Instead of just the mesh i called it on
Since im using Unitys standard cube mesh, even when i spawn new cubes from the editor outside of play mode, they're invisible
Yeah, it is a shared component
Meaning it's state is shared between entities
If you want one of them to have a new mesh you need to call EntityManager.SetSharedComponentData and pass in a new RenderMesh with your new mesh on it
But as Timboc pointed out - keep in mind you're creating a new chunk when you do that
As for wrecking the standard cube mesh, I assume that would fix itself if you restart unity
And theres no workaround? Gonna have to modify a bunch of meshes
Workaround for what?
Workaround so they don't have to create a new chunk.Is it possible to have each mesh in its own chunk at the start so new chunks dont have to be created and copied over in runtime?
Not if you're using hybrid renderer. By definition the value of a shared component determines what chunk it's in. In the case of a rendermesh, your mesh is one of those values.
So if you change it, it changes the chunk
Welp, lets hope it doesn't get too expensive 😬 Thanks for the help
Any news on the dots roadmap?
they are stacking on blog posts people want to see
they archived Graphics repo (basically removed public SRP development on git) little over week ago, then some while later wrote a forum post (thread now locked) where they said they'll explain it better on upcoming post
ugh what the hell
Hey y'all, new here, I'm on a project that has started to move towards ECS, and we're in the process of converting a lot of prefabs (like hundreds) into subscenes. We obviously want to automate this as much as possible.
So my question is: how do I save a subscene with an editor script? None of the documentation I can see has a command for it. Do I use the SceneManagement stuff?
I don't think I can cast a subscene as a scene, not sure how to interact with subscenes in the code
fuck me I think I just create a new scene, put the stuff I want to in it, then save it normally, then plug the scene into the subscene component as a sceneasset.
I think.
Will update with results for posterity
ok so it's 2021. i'm new to Unity but have spent a couple of months studying c#.
how's DOT's going for Unity so far? If I wanted to make what is mostly a flash-card learning app using Unity, could I do it all in DOT? it wouldn't require the performance, but I'm going to make the app regardless and would like to just use it as a good excuse to start learning DOTs since that's where Unity is going.
i have a few hours of experience making a UI desktop app in Unity
from 2019 version
stopped doing it because the app itself didn't have a bright future as far as usefullness goes, but also because i let myself get frusterated with it. I was basically making a notepad editor app and it just bothered me that copy and paste was a pain, TMP was flawed for this purpose and had some bugs i noticed.
current goal is to make a flash-card app for mobile and maybe webGL for learning japanese. lots of apps exist like that already, but none of them do exactly what I want. so i'll make it myself, and in and of itself should be a small project (relatively)
also super simple since it'll be mostly just UI stuff.
Same question, how's DOT's going for Unity so far.. because the new networking tech is not EAC compatible and there still not a stable package for DOTS
last time i check animations and particles were a mess with DOTS
I wouldn't try to make anything in dots if you're not very familiar with it and you're on a deadline.
There is very little/no support for mobile and web in dots right now. Project Tiny does support web, but it's still very alpha.
@lean cedar If you have the time and patience I would say try cloning the Project Tiny 2D sample project and messing around, you could probably make what you want from that.
Jobs and Burst are stable. Everything else is probably years away.
Based on the on their current progress anyways
Well jobs and burst are stable , but you can't use it with the unity api anyways
In some cases you can. A lot of unity api interfaces with native containers, and there are things like TransformAccessArray for moving gameobjects in jobs
But it definitely has a long way to go
yeah, that is what i think
everything feels experimental
and it seems to me Unity is in no hurry to develop
i guess until the competition has something similar stable
They're a big company. Last year they made a very large and very public pivot away from experimental stuff to try and focus on fixing the inummerable bugs in the core engine. It makes sense that dots development would slow down
so it's really nothing more than a dream right now? what can i expect to use it for at the moment?
The core is solid. People are making stuff with it. Just don't expect it to be easy, that's all
And expect some bugs here and there
If you're only worried about performance you should just try to learn the job system and burst and see if you can integrate that. If you want to try some very shiny new tech and are feeling brave than you can go all in and try ECS as well
Question how does a System onUpdate compare to a Mono onUpdate (number of calls)?
By default it's called once per frame as long as it matches it's required queries
If the system has no entities to match against it won't be called
@zenith wyvern thanks for that. I'm investigating a memory leak and i just started with ECS. Aline, the package I'm using seems to support ecs but used in a foreach i get a giant memory leak and huge cpu spikes. Theres a note about NativeSetClassTypeToNullOnScheduleAttribute which seems to only support jobs. I'm using the package inside a foreach so im wordering if this is the issue (I don't know if under the hood ForEach is still a job I know it replaced a old method)
If you're using a SystemBase then yeah a ForEach gets compiled into an IJobChunk during codgen
In the menu DOTS->Dots Compiler will show you what it gets compiled into
DOTS still has a long way to go before being production ready, but it's still worth using if you value performance. vanilla c# is just horribly slow compared to DOTS
*sometimes 🙃
I wish cinemachine could get the jobs + burst treatment
it's still running in mainthread coroutine blueegh :puke:
oh? I thought they did a big thing about how it could support many thousands of cameras with burst now
really? afaik, there's no post about it
remembering something from over a year ago - could well be wrong
might have been from this talk maybe? https://youtu.be/TtD-ywes5oQ?t=2043
https://blogs.unity3d.com/2019/12/23/the-most-wonderful-realtime-of-the-year/
His demo includes the goods on Technocrane filmic camera rigs, a CM 3.0 DOTS preview (with support for tens of thousands of active cameras)
so Cinemachine 3.0, which isn't out yet, is DOTS based
yikes, still not out? that was 2019...
yup. current latest is 2.7.1
yikes
Do you actually need the Jobs package if you only want to use IJob and/or IJobParallelFor? I noticed that I can use those without the Jobs package, but does it bring some other benefits?
I did a test. And indeed you can run ijob without the jobs package
So assuming there is a default jobs package preinstalled. The question remains. What version of jobs is the default running on?
@fair stirrup late reply but i'm also using aline + dots and haven't noticed any leaks, can you post some code?
@hollow sorrel Sure. I was going by the sample code. It was using a job.
CommandBuilder drawingBuilder = DrawingManager.GetBuilder();
drawingBuilder.Preallocate(100 * 100 * 400);
Entities
.ForEach((Entity entity, ref MyComponent Data) =>
{
drawingBuilder.WireBox(Data.position, 1f, new Color(0, 0, 0, 0.2f));
}).Run();
drawingBuilder.Dispose()
hmm
seems like that should be fine
how are you checking for memory leaks/spikes?
just tried that code as well and don't see issues other than some gc alloc from an editor-only assert
@hollow sorrel I get a jump into gig's of memory however i should note I'm booting my world in the editor (I'm creating mesh assets and using aline for visualizing data.).
Where do you see the gc alloc ?
@fair stirrup profiler hierarchy view shows gc alloc per method
you might be seeing gc alloc being the increase before it gets collected
but if you're creating mesh assets then that sounds like the more likely culprit, especially in ECS i've found it's really easy to create leaks with meshes
creating a Mesh and never destroying it also, so if you're not cleaning up in editor then it'll slowly increase each time
@hollow sorrel haven't started creating meshes yet. I simply added 8 empty entities then tryed visualizing there positions.
Soon as drawingBuilder.WireBox(Data.position, 1f, new Color(0, 0, 0, 0.2f)); is added i go from 0 to 8gb of memory alloc
then my editor just crashes.
I suspect its the rate at which the call happens and the buildup.
hmmm
causes it seems exponential based on the number of Entities.ForEach
Ill post some screens of the profiler when i get a chance.
@hollow sorrel did you test that in a SystemBase?
yea
what does cpu profiler hierarchy view say about those spikes?
Thats GC right?
The memory graph shows the Object Count goes up, so something is leaking
Do you know how to view your allocations in the Timeline view?
yea seems like
code snippet from above prob isn't the issue here
is it possible to view allocations in timeline view?
Yes
enable the Call Stacks at the top of the graph, and then check the pink blocks in the timeline view
every pink block is a gc alloc
oo that's good to know
Yeah its the bright pink blocks, just zoom in and click on them and see what's doing the alloc
So you can probably ignore the Dispose Sentinels. Thats because you have the safety system enabled
you might want to disable it and check again
Is navmeshagent usable in dots?
@stiff skiff
You have to disable the safety system before trying again
This is the allocation safety system, which checks if you leak native allocations
Oops think i disabled the burst ones
Yeah its a bit oddly located / named
sorry new to ecs is that NativeDisableContainerSafetyRestrictionAttribute?
No its should be a menu option in the editor
Let me see if I can get you a screenshot
It's under Jobs -> Leak Detection -> Off
Ah i had full stack
Yeah full stack is the worst
and should only be used if you have a leak and need to debug it
On gives you those "Something leaked, fix it" warnings
Yeah i did in some previous testing
But I usually just leave it Off entirely
When i was first getting around manged objects
@stiff skiff disabled it. Should i just be looking at the call stack?
Dis it disabled, look at a fresh profile again
it now shouldn't show the allocations for the sentinels
so have a look at the other allocations you have every frame, and click to see what causes them
Yup, now just go through them all and see which one might be leaking
Thats a Native allocation
Also that's massive xD
4MB
Is it doing that every frame?
But a Native Alloc shouldn't cause GC
Do you still have the GC spikes with the leak detection off?
Those fall under others not gc.
Oooooooh....
ok so i dunno when i should and shouldn't try to use DOTS in my project, but would it be a good idea to start practicing and using DOD in my project even today, even if I might not use DOTS?
That still looks like GC time
prob trying to gc that 4mb
Neh
That 4MB Is allocated outside of GC'd memory
GC only applies to heap allocated memory through new etc
wonder if its from grabing position from the entity.
I'd say take your time and learn a bit more about memory and allocation in C# to resolve this issue
you can also learn some more tools such as the new memory profiler in the package manager
Hey all! What's the current status of dots with webGL? Last I checked DOTS wasn't working for standard webGL builds, it had to go through tiny. However, tiny is still quite a way behind on features so I was wondering if they had decided to fix whatever was stopping webGL working w/ 'standard' DOTS
doubt theres any real changes since you last checked.
So as promised, the way to do this is basically as I hypothesized. You add a new scene, move the stuff you want to be in your new subscene into it, save this new scene, then load it as a sceneasset and plug that into the Subscene.SceneAsset field... pretty obvious once I realized that Subscenes are just scenes plugged into the Subscene component, but hey, if anyone found it as unintuitive as I did... here ya go.
I couldn't find the thread now, but I saw a guy on the forums who apparently was successfully using dots in a (non tiny) webgl build. I tried it myself and at first it seemed to work but as I went further things just seemed to break randomly. So no idea how he did it.
Actually now that I think about it maybe he was only targeting mobile
I remember last time I tried it coughed up a load of errors relating to out of memory, etc
When I tried it I was able to run it and it even rendered something with the hybrid renderer but when I tried to run custom systems it just completely broke
yeah for me it runs for like half a second then locks up
I get Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value 1342177280, (2) compile with -s ALLOW_MEMORY_GROWTH=1 which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0
Hey guys do we have any news on dots navigation?
Is there an easy way to get the position of a child entity in a system?
i guess ComponentDataFromEntity<LocalToWorld> would have to be passed into the job?
Or you can just use GetComponent in SystemBase
why do I have to use tempjob on a job.run?
You guys probably get this a lot, but what's a good starting point for DOTS? Long time Unity dev here, from v3.5 but I was a kid back then
Nvm found the pinned post, sorry
welp. I just solved my issue by just... disabling the safety restriction.
Like... Job.Run is current frame, I don't need to allocate it for 3 more.
Anybody here working with addressables yet? Any best practices? E.g. how make the system wait for the asset to be loaded...
Anyone had success with NavMeshQuery? Managed to get a list of polygons through the begin/update/end findpath but i don't understand how to convert that into an actual path
What's wrong with generating meshes straight to ECS? It looks like they don't receive lighting data
MonoBehavior equivalent and the cube converted with "Convert to entity" look fine.
isnt this set of properties enough?
@acoustic spire I believe in RenderMesh there's a variable for receiving lights
Not sure
nope. It duplicates some from MeshRenderer and playing it changes nothing
If compare the auto-converted cube and the black entity, the cube entity has this property set and the black doesn't. Idk where that even comes from.
yea, conversion adds a load of stuff that's hdrp & urp specific so creating meshes at runtime is a bit painful
Sad. But can I generate the mesh on start in MonoBehavior and convert it to entity after? Maybe by adding "Convert to entity" component in runtime
I don't know of any "recommended" way to do this yet. One option is to use an existing converted object and replace the mesh (updating bounds etc as needed). Another is to better understand what that other data is (by going through the source code). Or else yea, conversion at runtime is still possible but from previous conversions had, we know Unity are quite keen to encourage people not to do that (partly because it's very slow) - so future support is fairly uncertain.
rather than adding a ConvertToEntity monobehaviour you'd probably call GameObjectConversionUtility.Convert (or smth)
I guess that's some arguments for shader. But both options make sense. Thanks for advice
No problem. If you have specific questions regarding runtime mesh generation, the dots forum may be a slightly better place. Good luck 👍
If I have a cell and need to get data from neighbouring cells what would be the best way to do it?
I'm tempted to just pre store neigboring data in a dynamic buffer on that cell
its not memory optimal but should be processor optimal
I create a struct with all the entities that hold neighbouring cells at I pass into the job. Then use GetBuffer/BFE to get the data if needed
Just try to structure the job so it uses BFE/GetComponent as little as possible
so basically what I was saying but your prestoring the entities
Yeah in a Hashmap or just get them in a query
getbuffer and getcomponent is not quite optimal though
I might just store the whole data
Well in my case I only need to call it once per neighbour. Then I do a lot of operations on the actual array, so the GetBuffer call is not too bad in that case
yeah fair enough, I had a job before where I literally halved its time taken when putting a buffer into a nativearray
yeah but then again I would have to store/copy a load of useless data maybe I'll check to see what is faster, storing the entities or the whole data 🤔
Hey does anyone have much experience working with triggers in dots?
I had a game which was working before and relied onTriggerEnter/Exit to perform some actions (is a button pressed, can I pick up an object). So far I only know how to get any current collisions using ITriggerEventsJob but it would be nice to have a CollisionStart CollisionEnd event. Does anyone know of something like this?
Thanks
@fading nest theres an example for stateful triggers in the samples repo https://github.com/Unity-Technologies/EntityComponentSystemSamples/blob/459cbce0a4f3759fa89a46afd595766164c38bbf/UnityPhysicsSamples/Assets/Demos/2. Setup/2d. Events/2d1. Triggers/Scripts/DynamicBufferTriggerEventAuthoring.cs
its kind of a hacky workaround though, you should def pester them in the dots physics forums if it doesnt fit your needs because they are quite open to feedback
Ah this looks useful, thanks very much 😊 . I will do re: pestering, seems like a super important feature
How are you guys handling animations and particles?, exist a good tutorial about it?
only samples for animation, particles dont exist for dots unless you are using tiny
tiny?
see the pinned message for more info pertaining to tiny
oh lol , thanks
When should i use which commandbuffersystem? I find 8 different ones but no documentation on how they differ from eachother
@next latch I would recommend just choosing one and sticking to it as long as there is no reason to use a specific one
I try to make structural changes at the beginning of the frame but there are no guidelines on that as far as I know
Thanks :)
its really when you want your changes to happen, so for some might be at the end of a frame, others at the beginning, maybe you want it in the middle after a specific system.
Still struggling... lets say we have items and a inventory. There stats like speed, health, attack speed, physical damage and several other ones... now we want to influence our stats by the items that are in our inventory. Any idea how we could realize this in an ecs ? :/ Havent found an example for such a typical rpg case yet... Played around with the thought of an stats component that stores object values. But then we always iterate over all entities with stats, even if we just wanna iterate over those with attack damage for example.
Or we stick with components... like Speed, PhysicalDamage, Health... but then i have no clue how seperate item entities could effect them properly
The biggest problem is to find a way to add/remove buffs in a composition based system.... Lets say we have an player Entity{ Player, BasePhysicalDamage{10}, BaseHealth{100}, Inventory{item entitys}} and an item in his inventory Entity{Item, PhyicalDamageBuff{5}, SpeedBuff{10}, HealthBuff{10}} how do we combine them now if the player references such an item in his inventory ?
There is no standard solution for a buff/demerit system. Off the top of my head, I can think of 3 ways to do this in ECS.
1) Have a different component for each type of buff.
Pros
Structs can be tailored to the type of buff.
Cons
Requires adding/removing components often, which is a poor fit for an archetypal ECS. May perform worse.
Probably a lot of boilerplate involved in writing systems (a system per buff).
2) Have a single dynamic buffer component that can represent most/all buffs.
Pros
No need to add/remove components, so it plays nice with an archetypal ECS.
New types of buffs can be added with no performance loss.
Cons
Possible worse cache utilization depending on system implementation.
All buffs are forced to share a common structure.
3) Have buffs be entities themselves.
Pros
Entity archetypes can be tailored to the type of buff.
Different buff archetypes can share components. You can have a system on all buffs with a Cooldown component.
Cons
Requires extra bookkeeping. Entities need to know which buffs they have applied. Buffs may need to know which entity they belong to.
i'm having trouble generating a simple sphere collider in unity.physics. i can add a collider to an entity, but how do i create the collider itself? creating a new collider, i dont see any way to set its type for example, since its read only.
nvm i figured it out.
On closer inspection I would still say it suits my needs but seems pretty hacky
Could you go the other way, have the item component point to an owner entity?
Then a system could loop through all items updating their owners appropriately?
@stone osprey I would just use a dynamic buffer of items, no need for items to be entities if they exist only to be stats buffs
‘I've seen the release team talking recently as if January 18 is still the target for 0.17, but I can't guarantee if that target will be hit or if the plan might change.’ https://forum.unity.com/threads/entities-0-17-changelog.1020202/#post-6701305
Do i need to crate a new Collider if i want to scale its radius at runtime?
the unity ecs physics package uses blobassets as colliders (check out PhysicsCollider, you'll see a BlobAssetReference<Collider> there)
BlobAssets are immutable containers of data. means you can't change them. you would need to create a new collider-blob and assign it to your entities physicsCollider component
as far as i know, the colliders scale is multiplied by the entities LocalToWorld scale, so in theory you could just change the scale of the entity, which is far simpler (and performant)
But maybe you need a NonUnfiformScale component on your entity, and change scale there
so if i just use the normal primitive sphere, no matter what the scaling is. if i later add a sphere collider with a radius of 0.5. it should have the same size as the sphere?
it's been some months i last had to touch ecs physics, but to my understanding, your collider should have half the size of your sphere then, when using 0.5f. If you test that, please let us know it that assessement was true or not 🙂
you can visually debug physics with PhysicsDebugDisplay added to your scene (don't forget to convert to entity on it)
ah. that would be the next questions ^^
I've changed my mind. I prefer this method overall actually
the way I found to do triggers before seems pretty grim, adding a 'deals with triggers' authoring component and having all systems look the same: looping through entities that meet a certain criteria is very nice
@visual juniper the primtive sphere has a radius of 0.5, so they have the same size if using a radius of 0.5 for collider.
unfortunately i does not seem to scale the collider in any way if i change the sphere scale afterwards.
and you added the collider by code runtime ? can you share your code ?
this is just for the collider creation:
SphereGeometry sphere = new SphereGeometry();
sphere.Center = float3.zero;
sphere.Radius = 0.5f;
BlobAssetReference<Collider> spCollider = Unity.Physics.SphereCollider.Create(sphere);
ecb.AddComponent(entity, new PhysicsCollider { Value = spCollider } );
and for scale i use the Scale componentData.
anything you're waiting for from 0.17?
burstable systems is the main thing for me - involves a lot of refactoring I guess and I'm massively crossing my fingers that it helps with perf
😭
here's what the changelog was going to be in case you haven't seen it: https://forum.unity.com/threads/entities-0-17-changelog.1020202/
@mighty remnant sorry, since i can't identify an error in your setup right now, it seems like my assumptions where wrong 😦
@mighty remnant but i guess you could still test now wether the colliders scale changes when you change scale of the scale component now at runtime
* `Unity.Transforms` systems now use `IJobEntityBatch` instead of `IJobChunk`. Expect modest performance gains due to the new job type's lower scheduling overhead, depending on the workload size. - does this imply that IJobEntityBatch uses ISystemBase or something? Has anyone used IJobEntityBatch? Should it now be preferred over IJobChunk?
@visual juniper the only way i found is from the unity examples:
https://github.com/Unity-Technologies/EntityComponentSystemSamples/blob/master/UnityPhysicsSamples/Assets/Demos/5. Modify/Scripts/ChangeSphereColliderRadiusAuthoring.cs
it uses unsafe code. dont know what that means exactly and if it is a good idea ^^
what do you mean by burstable systems? the code in systems can already be bursted no?
the updates themselves - ISystemBase interface for making struct based systems that allow Burst compiling main thread update
No need to cross your fingers. The performance gain is crazy. You can already use them in 0.16 but you gotta do a lot of hacky stuff and you can't schedule jobs from them
wait really?
I thought it wouldn't do much because main thread update is just job scheduling and all the work should be done on bursted jobs
I'm just taking a quick look now and it looks like with 0.16 IJobEntityBatch is actually superior to IJobChunk? How am I just finding out about this
I don't even know what IJobEntityBatch is
is there an example how to use burst on main thread?
How would it be more performant than IJobChunk which directly executes on chunks?
I think because it's backed by ISystemBase? Though not sure
You basically use BurstComiler.CompileFunctionPointer<T>(function) to compile your function. Then you can call it from anywhere
I see
I sadly couldn't find a quick sample online to show you
IJobEntityBatch shouldn't be faster, it's just a way to process a specific batch of entities, while IJobChunk processes all of them
(which matches the components)
Looks like IJobEntityBatch also executes on chunks huh
yea, maybe it's no faster in general
yes, because they work the same. the difference is IJobEntityBatch limits the resulting batches, less possible batches means less overhead
same execution speed
I can also no longer build using IJobEntityBatch 😒
@mighty remnant thanks for the reference, it makes actually sense. So what we can deduct :
- collider 'scale' is not affected by entity scale
Unsafe means you have to use a pointer (memoryaddress) to access the actual blobdata and change the radius. (they are only meant to be immutable, but you CAN change them).
And it comes at the cost of having a unique collider-blob per entity (usually all same prefabs would share a collider blobasset)
what do you mean?
swapping out an IJobChunk for an IJobEntityBatch and when trying to build it errors out on:
at Unity.Entities.EntityComponentStore.ThrowIfEntitiesPerWorldIsTooHigh(Unity.Entities.EntityComponentStore* this, long newValue)``` - guessing it's the kind of thing fixed in 0.17
Ah okay I think I get it now.
Each chunk is split into multiple batches that can be processed concurrently by IJobEntityBatch.
I could really use a diagram to get my head around it - esp vs IJobChunk
From what I understand the big difference is that IJobChunk can only split the processing on a chunk basis where IJobEntityBatch also splits each chunk multiple times
I could completely be wrong but I thought it was more of the opposite - rather than a new job per chunk, instead it batches chunks together for a job?
that's what I understand too
{
var job = new BatchedChaserSystemJob();
job.PositionTypeHandleAccessor = this.GetComponentTypeHandle<Translation>(false);
job.TargetTypeHandleAccessor = this.GetComponentTypeHandle<Target>(true);
job.EntityPositions = this.GetComponentDataFromEntity<LocalToWorld>(true);
job.deltaTime = this.Time.DeltaTime;
int batchesPerChunk = 4; // Partition each chunk into this many batches. Each batch will be processed concurrently.
this.Dependency = job.ScheduleParallel(query, batchesPerChunk, this.Dependency);
}```
This is from their sample
hmm why would that be faster?
well, for one thing you can potentially exploit more of your CPU cores because more batches
if you have less chunks than CPU threads
Gotcha. Sounds like it makes the most sense in the case where you can fit many entities in a chunk.
Expect modest performance gains due to the new job type's lower scheduling overhead, depending on the workload size. - I'm confused why it would have a lower scheduling overhead in this case?
Hmm maybe some JobSystem internal stuff
Wouldn't it be better if IJobEntityBatch would batch on entity count instead of x times per chunk
X times per chunks sound kinda weird when you have 4 entities inside a chunk or smth
because which limits the resulting batches to an input
it doesn't have to figure out the batches, you have to give it
interesting
I think I'm slowly understanding.
thanks for your help & patience @odd ridge - I kinda hope this isn't what their more optimised version of scheduling will mean..?
my guess is, if you do on entity count, you get unbalanced batches
you don't have to hardcode batchesPerCount, you could calculate the entity count and the chunk count, then decide based on that how many batches you'd like to do 🙂 (which is then basically you deciding how many entities there will be per batch)
Turns out those were just warnings and what was actually stopping the build was the entity debugger window being open 😒
good to know
why would having the debugger open even prevent a build. sounds like the kind of mistakes i would make 😏
ikr... with both entity debugger windows I also regularly experience a bug with creating & destroying entities at edit-time
wish there was a idiot proof method of saving entities at edit time, would love to make some entity editor tools to facilitate level editing for my project
anyone updated to 2021 with their dots project?
Does it have a pause button without Entities?
Because the Entities package actually uses a hack to allow it to overwrite the render (and logic) for the start/pause/stop buttons to add that "link" button
Using several undocumented features 😅
that big empty void where you cant add your own buttons unlike say any other 3d program really vexes me
You can use the same hack to put your own buttons there
yeah gonna have to look into it. though im not fond of using hacks(despite dots...) and the other hacks ive looked at for doing this were eventually made obsolete with newer versions
@deft stump ah I see what you mean. the menu options for it are still there so theoretically you could use hotkeys or the dropdown menu but i guess its been a low priority for them..
Whats the difference of havoc physics vs unity physics?
havok is a stateful simulation, and can have things like stable stacks of objects(table with items on it), doing the same with unity physics needs hacks or it will eventually jitter out. havok is also supposed to be faster
havok also costs money if you use pro
well not if you use pro but if you earn over the threshold that requires you to use unity pro
well you interact with it through the same api. different use cases. unity physics allows you to make major changes to the source if you desire, havok is a closed license so you need to contact them about licensing if you want source to it.
quick question. WriteGroups are the reason why the localToParent matrix updates if i change the Translation or?
is there a github for the Unity.Transforms package?
what role are playing the CompositeScale/Rotation classes?
How do I change the velocity of a rigidbody converted into an entity?
And use methods like AddTorque?
It’s just at instantiation that I want to set those values.
@mighty remnant the entities documents have a whole section on the Transform System
@wicked stone you can set the linear or angular velocity via the PhysicsVelocity component, there is a helper class somewhere in the physics system that allows you to also specify inputs in conjunction with the mass but i cant remember what its called exactly, something like physics extentions. the physics samples has examples of it in use somewhere
Thank you :)
Turns out, though, that I should probably fix instantiating first before playing with physics because the prefab that I’m cloning doesn’t seem to be instantiating correctly. I can see it in the Entity Debugger, but I can’t visually see it in the Scene view.
Do you have any idea why this could be? I’m using the first method CodeMonkey shows in this video: https://youtu.be/pk-C_h0WJZs
✅ Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=pk-C_h0WJZs
Let's check out how we can build Game Object Prefabs and Convert them into Entity Prefabs that we can then Instantiate.
Unity DOTS / ECS Tutorials
https://www.youtube.com/playlist?list=PLzDRvYVwl53s40yP5RQXitbT--IRcHqba
Getting Started with ECS
https:/...
are you creating your entity from code?
i also assume you have the hybrid renderer installed
Yep, and I have the hybrid renderer installed.
Also, I’m instantiating it once, but there seems to be a bunch of them in the Entity Debugger... is that normal?
double check you are also adding all the same components (like worldrenderbounds) that would get added automatically if you had used conversion
id expect there to be a prefab entity and an instantiated entity if you were only expecting one in the debugger
Sorry, I’m really new to DOTS.
How do I check this?
And by “a bunch”, I mean 6 entities with the same name (the name of my prefab)
There’s also “WorldTime”
oh just looking through the tutorial hes using conversion not actually creating the entity from code. i had a misconception about your problem so ignore the worldrenderbounds bit
yeah there are some additional entities, worldtime, afaik some subscene stuff if you are using them
That tutorial is 11 months old, so maybe some of it is outdated? And that’s why my object can’t be seen?
could be outdated, the part where it features using blobassetstore seems a little unnecessary
Yeah, but I’m only doing the first part
He mentions many different ways to instantiate in his video, so I’m using the first way
can you post the code youre using? im also assuming the translation value of whatever your instantiating is within where you are expecting it to be
Sure, wait a sec
This is the script I use to instantiate:
https://hatebin.com/gizvzibsli
This is the script that I have attached to a game object with the "Convert to Entity" component:
https://hatebin.com/mlorhuqnnd
It's pretty much identical to the code from CodeMonkey's video.
@safe lintel Also, I have other game objects in my scene, so it isn’t completely blank, if that changes anything.
well shouldnt be anything wrong with it, just gave the code a test and it works
hm so you are sure the system runs and creates the entity, its just not rendering but it shows in the entity debugger?
Yep, it shows up in the Entity Debugger
Lemme get screenshots of the prefab and the debugger
This is the prefab, it doesn't have any children
This is the prefab entity component game object
And there's the Entity Debugger
is there a groundplane to catch the dice?
In the form of a game object, yes
But the entity doesn’t even spawn, it isn’t visible
which entity doesnt spawn
Sorry, I meant it gets instantiated, but it isn’t visible
Is there any way I could double click on the entity to show me where it is in the Scene view? Like you can do for game objects in the Hierarchy
wait is an unconverted gameobject supposed to be catching this entity? if you put a simple plane in the scene(and convert it to an entity) below where it spawns, does it catch it?
I just added a “Convert to Entity” component to my plane game object, and when I hit Play, it disappeared.
Do you have to make any modifications to the project settings to “activate” the Hybrid renderer? I installed it, but it doesn’t seem to be working.
dots physics doesnt interact with gameobject physics
Maybe check if it has a renderer (or some other variant of that name) component?
it might be that the renderer didn't get converted properly.
what does your package manifest look like?
Sorry, how do I check that?
And by the way, I’m using the Universal RP.
type in com.unity.rendering.hybrid in the box
ok its in there
no
so if you just make a new scene, and add a cube and convert it to entity its invisible?
Yep.
I removed the Rigidbody and Collider to see if that’ll change anything, but it doesn’t
I found a Unity forums page with a lot of people having a similar issue, and the solution seems to be this:
Where exactly do I put this in my code?
thats only applicable if you arent using conversion
try enabling or disabling srp batcher in the urp settings
Alright
@safe lintel I have no idea what the SRP batcher is, but disabling it worked!
Is it bad to keep it disabled?
ok i think i had this a while ago
i am assuming you also dont have ENABLE_HYBRID_RENDERER_V2 in your scripting defines(in the player settings) right?
No
anyway, srp batcher is one of the new things thats supposed to improve performance almost for free, but with old hybrid renderer v1 the two arent compatible.
if you ever enable that define to use hybrid renderer v2(which is kinda recommended in all future stuff for dots) you will need to reenable the srp batcher
Seems like something a lot of people would be having issues with unless it was clearly stated somewhere
Alright, well I’ll enable it then
well yeah it should be documented but this is like how it is for dots land 😅 undocumented and most things are simple but super obscure. anyway given v1 is deprecated and wont get future updates i dont think they will do anything about that quirk
Alright, well at least that’s fixed
Now the dice is in the air, not moving at all, despite having a rigidbody that should be using gravity, but eh, one issue at a time... lol
yeah one step at a time
Why does ComponentSystem force you to implement OnUpdate()? And is OnStartRunning() the entity-version of Start()?
OnStartRunning is basically OnEnable (in Monobehaviour)
Alright
you should use SystemBase instead of both JobComponentSystem and ComponentSystem
the latter will be deprecated, and SystemBase does the functionality of both other system types
That’s great advice! Thank you :)
@safe lintel Using SystemBase instead of ComponentSystem gives me an error saying Every Entities.ForEach statement needs to end with a .Schedule(), .ScheduleParallel() or .Run invocationWhich of these three should I choose?
depends on your workload.
is it "light" enough that you don't need another thread? then .Run().
is your Entitie.ForEach processing many different chunks? the .ScheduleParallel().
Alright, thanks
Yet another question:
How do I reload everything, including all of the entities (because reloading the current scene doesn’t work)? So it would have the same effect as if you closed the executable and re-opened it.
hi, what is this garbage generated by entities and is it part and parcel of the ECS/DOTS or have I initialised the world or EM wrong somehow?
@last lintel is that every frame? that system shouldn't be doing anything if no scenes are being loaded/unloaded
@last lintel try turning off leak detection/safety
I'm seeing some unusual scaling when I rotate an entity that is a child. rotation is the only thing that changes but you can see that it scales as well:
I'm assuming it is due to the scale of the parent item. Any idea how to prevent this?
Just checking you’re not directly manipulating LocalToWorld?
@amber flicker correct, I am not. I am directly modifying the Rotation component
In that case it sounds like a bug to me? But I haven’t seen that happen..
I have also tried converting to local rotation before applying but seems to be the same
chances are it's a mistake from me, I have struggled with rotations in the past
any way i can define a foreach, that i can directly access a variable? for example if i have Entites.ForEach((ref Translation pos) => {});, it would be nice that i dont need to write pos.value but have the value directly in a variable. know what i mean?^^ the code looks realy strange sometimes with all those .Value.
ref var value = ref pos.Value;
is there a better shorthand for these entity command buffers?
and if I use .schedule, is the normal pattern to get the endwhateverecbsystem and add the commands/dependency there? or is there a better shorthand for that too?
@zenith wyvern am I allowed to ping you for your wisdom?
I don't mind - there's no better shorthand as far as I know
cool thanks a bunch 😄
And yes if you're scheduling you should use the commandbuffersystems as barriers otherwise you're just forcing a sync point in the middle of your frame
👍 appreciate it
If you’re rotating a child inside an entity that has a non-uniform scale then it might actually be correct I suppose?
@amber flicker Yeah, that's kind of what I was thinking too. If i want to take a world rotation and apply it to the child, I am assuming it needs to be converted by multiplying the inverse local to world matrix, so that's what I'm doing. Does that sound correct?
Is there a way I can lock a NativeList? I need to search (and if not found, add) a value from it, but now there are race conditions so the searching may not find the value if it was added during the search. (Using IJobParallelFor)
Fyi the .Rotation property of localtoworld is straight up wrong if you have a scale applied to that entity so I’d try and avoid scales on parents or else maths is gunna take more working out I guess.
why would it be wrong?
transform system should take scale into account assuming you are ordering stuff correctly?
Specifically the ltw .rotation property that decomposes the matrix. Only correct if uniform scale or even 1,1,1 I think.
The transform system handles things properly afaik 👍
so say you wanted a child entity to hold a constant world space rotation, call it targetRotation, would you assign the rotation component as: rotation.Value = math.mul(math.inverse(localToWorld.Value), targetRotation.value); ?
Yes, it's every frame, and no scenes are being loaded or unloaded