#archived-dots
1 messages Β· Page 181 of 1
Thats a ballsy move. if the backend changes from under you, that can have severe consequences
Unless you froze to a specific version of course
yeah, but better to be able to actually get feedback and improve than not being able to do it at all... our target devices are just too far away from typical gaming pcs
Mind if I ask what you are developing?
realtime warehouse visualization/monitoring frontend
What part of any visualization requires that kind of horsepower?
Are you real time rendering the whole 10 by 10 mile warehouse?
heavy lifting is in the backend, but the frontend has to run on typical manager laptops that have < 2GHz with integrated gpus that are >4 years old... and they don't want to have any impact on their other apps. we are currently down to < 13% cpu usage
Must know the exact position of all 15,000,000 bolts and washers in the warehouse!
With all due respect but that to me sounds heavily overoptimized
might be, but at least we are able to hit our performance goals consistently without having to go back and optimize after the fact. there is still a lot that is unoptimized, but moving the most critical part to DOTS has helped a lot
its easier to add more stuff later, than it is to reduce and try to optimize old code
Slightly off topic but I win todays darwin award
I am trying to debug why the heck my in script created tilemap is not rendering
I mean it cant if I do not add a tilemap renderer facepalms
And I was going over all the code if the generation of the tilemap is bugged or something and check everything in detail
I guess everyone has been there at least once π
And as I am about to give up I realize it
@neon flower ive begged on the forums for updated animation samples, to mostly deaf ears
i think ive really seen just one guy who seems to have a grasp on it, really frustrating that its kinda incomprehensible and is made worse by not having updated samples as they release newer packages
lol yeah, i wish they gave us more samples. its massive and you have to approach it somewhat blindely
ok a bit of a weird question but is there a means to execute a system if a given query does not return any entity? Say if no entity with the component "mycomponent" exists, create it." that kind of thing
Basically how do I check if no entity with a given component exists. I might be derping since I have been programming all day.
EntityQuery query = GetEntityQuery(
ComponentType.ReadOnly<PhysicsVelocity>()
);
int count = query.CalculateEntityCount();
That's the only way i know how to do it, though I'm sure there's a better way
That's more then sufficient. This is only for "initialization" logic so its okay if not too performant since its literally only called once. Thanks a bunch.
it is actually pretty performant, there is also the filterless version EntityQuery.CalculateEntityCountWithoutFiltering() which is a bit faster as it is just iterating over archetypes and summing up the length. (unless ofc your original query did not have any filters to begin with)
CalculateChunkCount may be very slightly faster (though I guess entity count probably has an early out for none). Thereβs also something called smth similar to query.ignoreOrEmptyFilter π - canβt remember exactly off the top of my head.
Maybe Sl4kers version is slightly faster - havenβt looked at source for either
Actually I think they might be pretty identical in performance. Both use Archetype lookup internally and are querying all matching archetypes for their respective Counts (entity or chunks). And both have no early out of archetypes that are empty, they iterate over all matching ones.
I am still not sure how to do what I plan to do. The idea I have is to see how well dots scales. I want to make a simple roguelike with an overworld map that in theory expands into infinity and is created as things go. That's not what I am not sure about how to implement though. My initial gut reaction would be to actually have one entity per tile but that seems that it gets excessive quick. a 1000x1000 map would already be a million entities after all.
The obvious point is that the tiles state has to be preserved which I normally would do using chunking of some kind.
do you need to have the whole world in memory at the same time ?
The rendering part is also not what I am concerned here, for that I just have a tilemap with a script that queries for the tiles that are currently visible and just use set tile.
No not necessarily. I am just not sure how I would partition or chunk it.
I need to have the state retained but do not need to have it in memory all the time.
Which probably means I have to store it somehow and load and save on the fly
so pretty much like unity does with subscenes. memory dump it out and load it once player gets closer
do we have any decent documentation on how to handle serialization and deserialization in dots?
that is also somewhat up to date?
For previous projects I did use chunks as classes and json but that does not seem to be an option here?
nah, the last time I checked it was pretty nonexistant, digging through code was the only real source of information
Yeah that is far above my paygrade I am afraid
slowly drags 3 months worth of dots project into the recycling bin
New project timeeeee
@gusty comet i think basically the only built in serialization atm is (de)serializing an entire world, tho creating a new world and moving/copying only the things you want to serialize in there is not that expensive
also ecs is pretty nice for roguelikes, same architecture is often used for non-unity roguelikes too
as for entity per tile, yea don't do that
lots of different ways to do it and i dunno if there's a 'best' one, but you could have 1 entity per chunk that each has a dynamicbuffer containing tiles
you could also store in nativearray outside ecs or on a system but i think having it on an entity is nice because it plays nice with serialization
Yeah I have used simpler ECS systems that were there mainly for the pattern before
Love2D which is using Lua has a few nice ECS systems for example
As for the tiles they literally are just data. What I planned to do in my view layer is to have an enumerator for which sprite to use and the entity just has an integer for its tile type and then update after each turn.
@hollow sorrel
yea that sounds fine but i'd still group them under chunk entities because Entity has quite a bit of overhead for things like this
entity per tile would be fine for small maps but if you're going 1000x1000 you'd see a difference between entity per tile and chunk entitities
Yeah but how would I go about that? Each tile needs to carry the three values I mentioned and potentially more.
I'm pretty sure the editor will just crash on you when you get that high
I mean I did 500x500 maps with gameobjects
so I doubt that would happen to be honest
There's a big difference between 25000 and a million
And I just mean the editor, at runtime it would probably be fine, assuming you don't run out of memory
so for example with the dynamicbuffer way you could have a bufferelement struct that holds your three values like tile type etc
Your argument still holds though I get that
oh those will never be seen in the editor
all generated through code
thats random gen
Does each tile actually need unique data, or does each tile TYPE hold unique data?
well they have as said their position, their tile type, potentially temperature, and more.
its supposed to be a survival roguelike think a smaller version of UnrealWorld
or for simpler terms think in categories of rimworld
A tile shouldn't need to know it's own position. If you store them in a buffer you can infer the position and access it in your flattened array
I am not sure I follow
You can have a buffer that just stores a tile id that points back to your actual tile prefab. Anything non-unique data can be on the prefab so your tile representation in the world is nothing but the id
There is no prefab? this is pure data
as said all my rendering layer does is acess the tiles get the tiletype and displays the corresponding sprite
My rendering layer is literally one monobehaviour that operates on a tilemap
prefab=tiletype in this case
yeah and tiletype in my one entity per tile is literally one integer per tile
yea that's good
Rendering as said is one loop that gets the players current position and has a static tilemap that then gets updated each time the player moves
so it iterates through the tiles around the player in a given radius
or that is the plan
What is the benefit of having your tiles as entities?
the idea is to have conditional as well as relational data
I can add tag components to specific tiles and operate only on those tiles with systems
which would make things like a local temperature and pressure system far easier to handle
Depends on the game I guess but in most tile games I've seen the vast majority of tiles are doing nothing but sitting around rendering. Unless you actually need to store and process a lot of per-tile data you're wasting a ton of memory by having every tile be an entity
regarding the position thing, it's like
let's say you have a dynamicbuffer (basically an array) of 100 tiles, and your tilemap has a width of 10
and you want to get a tile at position (1, 4) you know it's at mydynamicbuffer[15] and vice versa because you know the tilemap width
Better to group your tiles into chunks in a dynamic buffer or something similiar and access them through that
for infinite maps the same principle holds since your chunk would have a position and you just get the tile relative inside that chunk
don't need to allocate an extra 2 ints per tile for position
I mean if my system is feasable or not depends also on how much overhead an entity has. Python croaks at this because each struct carries a 2kb overhead
2kb yikes
An entity is literally just 2 ints. There's no overhead aside from the memory it takes up, assuming you're not foreaching over them all every frame
But with endless world games memory is something you really need to think about
As said no not every frame literally only on player input since its turn based.
that's true but looking up individual entities is pretty expensive, so if you're trying to check adjacent tiles and have to look up entity id's for that, it's gonna be relatively expensive
Yeah as said my issue is mostly me understanding the how to do that. I am used to it in an OO context where I can have my world class which is literally just an array of chunks that I can easily serialize and deserialize
And there I never had issues with performance so far.
A good chunk of my confusion mostly stems from the fact that ECS systems I used before did not take issue with having things like references.
aka you were not forced to blittable data types only.
since they concerned themselves with the design pattern primarily and only secondary with performance optimization.
And in my above example chunks are also just literally an array of tiles.
and the tiles all carry their "state" with them in the example.
i think dynamicbuffers is something to look into
it's basically the benefits of having entity per tile but less overhead
dunno if it was Sark who also used primarily dynamicbuffers for his voxel thing
You can also store the entities holding your buffers in a Hashmap and pass that between systems for fast random access
seen too many voxel implementations come by here
Yeah I am
then i prob learned my ways from you π
was it you who wrote that roguelike ecs tutorial
I am seriously a bit puzzled by all of this. I would not have expected this to be an issue in a simple 2d turn based enviroment.
As far as serialization goes Unity ECS isn't going to do you any favors right now. There's no documentation on it and info is sparse
wait you wrote a rougleike ecs tutorial?
Yeah I did
I found a few blog posts about it
mind to share the link? It might help me learn a few things
I haven't worked on it in a long time, I wouldn't be surprised if I did a lot of dumb things.
Thinking back on it I would do my console a bit differently, but it worked for the tutorial
Oh console based.
Just for the renderer
Yeah I was just not expecting that π
I can adjust my view to this I guess, so its still plenty helpful π
Thanks for sharing
Hmm seems RLTK has some issue with 2020.1.8f1
throws Library\PackageCache\com.sark.rltk_unity@81238b0a18\Runtime\RLTK\FieldOfView\Bresenham.cs(22,81): error CS0104: 'NativeHashSet<>' is an ambiguous reference between 'RLTK.NativeContainers.NativeHashSet<T>' and 'Unity.Collections.NativeHashSet<T>' and Library\PackageCache\com.sark.rltk_unity@81238b0a18\Runtime\RLTK\FieldOfView\Bresenham.cs(35,65): error CS0104: 'NativeHashSet<>' is an ambiguous reference between 'RLTK.NativeContainers.NativeHashSet<T>' and 'Unity.Collections.NativeHashSet<T>' on import
Oh, when I made it there was no built in NativeHashSet
So I was using a custom one made by Jack Dunstan
Just find wherever NativeHashSet.cs is in the project and delete it
Should fix it
Hmm I have to delete it manually it seems since you can not manipulate data from imported packages otherwise
Yeah unity doesn't like it when you change imported packages. You can just copy the repo and stick it in your project.
Does it rebuild packages if I just delete it?
Yes
oof
To do that you need to have a local copy of the package
wut now unity says the json is not valid when I try to import it from disk...
facdesks
No idea, it was a nightmare getting that set up as a package, even now I barely know how the dumb package manager works
I would say just copy the repo and delete the package related stuff and just use it as a bunch of scripts
@fair flame have you been encountering a problem where the editor freezes when you run ClientServerBootstrap.CreateServerWorld?
No matter what i do i can't seem to get around it :/
@shy pilot yes I do run into this when running it from a UI event but not when running it from a monobehaviours context menu (using the ContextMenu attribute). It has changed back and forth from working to not when upgrading netcode and editor versions, also it only appears to occur from inside the editor so I've just been working around it for now
OOH! @modest mortar coroutines work!!!
I made a void that takes a string and just runs start coroutine
and turned the host and join methods to ienumerators and it works!!!
i'll add this to the dots wiki
@violet cosmos is there a place to put bugs and workarounds for netcode?
on the wiki?
Right now there's a ECS Gotchas page. Maybe there if you can make it short and sweet
@shy pilot sorry dude, wrong person lmao
I spent so long looking at how the new UI system can work with DOTS and never thought to look at it's basic features, like being able to dynamically change text for localisation.
Diving into this damned thing to find out how to do that was a pain in comparison to getting it working with DOTS
How can you create your own system group and use it in UpdateInGroup?
smth like:
[UpdateInGroup(typeof(SimulationGroup))]
public MyGroup : ComponentSystemGroup{}```
Quick question, does AddComponentData() add the component if it doesn't exist?
yes
Great, thanks!
ok @violet cosmos i've added the note about the create workaround (maybe have a look at it to make sure i was quick enough π )
@fair flame
#archived-dots message
(pinged the wrong tom before lmao)
Did they get rid of "GetComponentDataFromEntity" from ECS?
No
It's been a couple of months since I opened my project up and it's saying "Can not resolve Symbol GetComponentDataFromEntity"
I've updated to the new version of Unity 2020
what would cause such an error
Are you doing it inside a system?
And if you haven't yet you should delete your library folder and restart unity just in case
man, tbh I don't really remember what a system is. could you point me in the right direction?
Check the pinned message in this channel
I might have to go back a few versions in my git
when do you believe they will offer a Workshop from Unity for DOTS
I know the question before that is when is DOTS going to be production ready
From what i've heard is that the Burst Compiler is stable but not production ready
and that ECS is still being updated
No definite answer, if you do some googling there's a roadmap on dots/ecs from last year. Supposedly there's more info coming, who knows when
this is the roadmap i found and it's form this past march
This is the first installment of our 2020 roadmap, Unity 2020: Core Engine & Creator Tools.
Speaker: Will Goldstone, Product Design Lead for Workflow.
We know you'll have a lot of questions about this roadmap, so we're hosting a Q&A on the Unity forum following the session. ...
there apears to be much in development
at least all the fun stuff
"fun"
Here is what is expected in 2021 posted in Aug
Unity have released a blog post detailing the future plans of Unity in 2021. From stability improvements to an increased focus on GameObject support to a new networking solution, there's a little bit here for everyone.
From what I gather DOTS is late 2021
from ECS, DOTS physics, DOTS animation, DOTS Sound, to NetCode
....2022 should be a productive year to take my project seriously...
I doubt it would be released in 2021. mid-2022 is my bet
Man, mid-22... When are the workshops and books going to be released then
I guess that give me more time to setup a paper and cardboard prototype of my game. Game test that way...
The core of ecs is in place. Most everything added from now on will just be making life easier for us
There's no harm in jumping in now and figuring out how it works
well I'm downloading prior version of my code from github that are marked as functional. Lets see if I can re-pick it up again from July
I mean I did pick dots up quickly but, I forgot it quickly as well
how goes eveyone elses experience with learning DOTS
It's like writing normal code but you have to write 10 times as much. It sure goes fast when you press the play button though
Yea, I had like 50,000 ships flying around in AR on a Samasung A31 (the lowwest level phone for AR)
it was a thing of bueaty
I've got a short video of it if your interested
OK after poking around the code is not in a system but in a monobehavior that is attached to a game object
It's code meant to initialize the level
Can't really help without more context. What source line is your error pointing to? How are you trying to use CDFE?
Are you using the latest version of ECS?
I removed the "Hybrid Renderings" package and want to add it again to make sure i have the latest version but, I can't find it even with preview packages turned on
You have to add it manually. See the wiki
Preview Packages are hidden by default now
Nothing is happening?...
yea had to click something
Welcome to Unity in 2020
source line is the following
ComponentDataFromEntity<LocalToWorld> allLocalToWorld = GetComponentDataFromEntity<LocalToWorld>(true);
what else do you guys need?
I updated to the latest version of dots and restarted the enviroment
is it ComponentDataFromEntity
or GetComponentDataFromEntity
it has a problem with the second one
GetComponentDataFromEntity
Again we really have no context for what you're doing. Are you sure you've included the namespace? If you're in a Monobehaviour, why are you calling GetComponentDataFromEntity? That's not a monobehaviour function.
Which namespace
I have the following
.
using Assets.Scripts.Data;
using Unity.Collections;
using UnityEngine;
using Unity.Transforms;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Rendering;
using UnityEngine.Rendering;
Entities. You said you're calling this from a MonoBehaviour. MonoBehavious don't have a function called 'GetComponentDataFromEntity'. If this is really the problem you're trying to solve you should take a step back and learn about the basic rules of the language
i agree. This came from a tutorial on youtube that I"ve been editing
This channel is not really the place for problems like that
it's just that I don't know what changed in dots from the last time I worked on it
It doesn't sound like a dots problem. You shouldn't be messing with dots until you're very experienced with Unity and C#
I've got over 10 years of C# experience and I"ve been working with unity since it was release for free in version 4 i believe
Okay, so when I say MonoBehaviour doesn't have a GetComponentDataFromEntity function, that should give you a hint about what you need to do, or what else you need to explain about your problem
This code is attached to a gameobject to instatiate prefabs. I create EntityArchetypes within this code
Maybe the soloution is to find a way to instatiate without having it attached to a gameobject
so I don't need to use Monobehavior
Maybe I need to seperate the logic into it's own "System" and call it from the monobehavior
Now I'm just confused. You originally said your problem was a "Cannot resolve symbol" error. I have no idea what any of that has to do with a compiler error.
this is the issue
No offense but if you can't figure out the problem from those compiler errors I have a hard time believing you have 10 years of experience
It has nothing to do with dots. Try #π»βcode-beginner
is "GetComponentDataFromEntity" part of DOTS or not?
Yes. It's a function on systems. You're attempting to call it from a MonoBehaviour, which makes no sense.
Anyone know if there is an updated https://github.com/Unity-Technologies/DOTSSample project for 2020.1 and the latest physics/netcode?
@zenith wyvern Well I recloned my project from github and didn't update to 2020. The code that was giving me the problem was not there. So it was probably something I was trying left it alone months ago.
it compiles and runs
so you were correct
It's hard getting back in the mindset of what I was thinking or trying out back then
you helped
thank you
No worries, sorry if I came off as rude
As far as it goes you're cool with me
DOTS has completely upended my thinking of programming.
I'd recommend going through the manual and samples in the pinned message before bothering with tutorials from YouTube folks. Codemonkey is great and all but his tutorials don't really show the "right" way to use ECS. The samples from unity are great and very informative
Thank you again. I'm going to need them to bring me back to the state of mind of DOTS
are we allowed to post videos here?
I'd like to show you the code when it was fully working before I completely messed it up
not code the demo
It's 1m:10s long
@zenith wyvern Reading my notes on github what I tried to do was use a Pure DOTS instatiation of entities with out prefabs. What is you opinion on using prefabas in DOTS?
does EntityManager.SetArchetype clear any dynamic buffers, even if they are in the new archetype?
It sucks. Getting a gameobject prefab to an entity prefab is annoying and way more complicated than I'm sure it will be eventually. The way they show in the hellocube samples from https://github.com/Unity-Technologies/EntityComponentSystemSamples seems to be the least painful way right now.
does EntityManager.SetArchetype clear any dynamic buffers, even if they are in the new archetype?
@calm edge Any structural change will invalidate all buffers afaik
Oh I think I misunderstood the question. No idea if it replaces already existing components with new ones
I'm "upgrading" an entity by setting it's archetype with one that has the same existing components and some new ones
Looks like it preserves the components it already has @calm edge
https://github.com/needle-mirror/com.unity.entities/blob/f0bcb0dd1b1b27418b841801c27713372ad1aefa/Unity.Entities/EntityManagerChangeArchetype.cs#L950
turns out I'm creating the base architype in two different places so getting duplicate entities π
Anybody has an idea how I could make undo/redo work with entities? Undo.RecordObject(entitiy) obviously does not work as its not an object
@pulsar jay depends what you're doing but probably should concentrate on your source gameobjects working with Undo and having them reconvert imo
yeah I dont have any source objects though. the data is coming from a scriptable object. atm it works to change the scriptable object, record it and then recreate the entities from the SO
but it would optimally work during edit and runtime so I can also use it ingame
I am afraid I will not be able to use any builtin unity solution. maybe I should build some kind of command pattern π€
your source object in this case is an SO.. undo's should work with your SO and then cause a reconvert.. no?
your source object in this case is an SO.. undo's should work with your SO and then cause a reconvert.. no?
@amber flicker yeah thats what I do atm
so.. what doesn't work?
if I would use this at runtime it would change the SO which is not intended
I would rather load from SO -> change -> (optionally) save to SO
runtime.. in editor or standalone?
both. Ideally it would be a level editor working in editor and at runtime
obviously you won't be using Undo.RecordObject at runtime with standalone... you'll need to create your own
yeah I thought so
maybe I could just record the entity state by serializing it. There should be a simple way to do that as the conversion workflow already serializes the converted entities am I right?
Oh I just found out that its possible to store reference types on shared components (https://gametorrahod.com/everything-about-isharedcomponentdata/). Is this still true? If it is I could just store my cell lookup table as an NativeHashMap on a shared component
So im working on some basic "action" system... i mark my player with a "build" component and he moves to the location. Once he arrives he should start the build process. Im a bit undecided how to track the arrival. I could either use the dots physic system and place a collider at the building stop to listen for collision events to start building. Or i could simply compare the build position and the player position to determine if he arrived. What would you go with ?
I'd go with comparing the positions :)
How do you go about reusing logic with ecs? Atm I have a Grid Object and it has a CellToWorld method. I will obviously reuse this a lot. I know that components should not have logic. But this is an example where I feel data and logic is tightly coupled for a good reason. I could also put it into a static method but I would have to pass the grid component to each method and it would lead to an even tighter coupling of all systems that use this static method
I've only touched pure ECs but having to use some GameObject conversions and only just discovered that GenerateAuthoringComponent does not work with ISharedComponentData. I assume the correct way to handle this is setup the struct and then Setup a monobehaviour with IConvertGameObjectToEntity and add my shared component onto it in the Convert method?
@loud matrix yeah you could create and add as many components and shared components as you need in you conversion method
Coolio thanks, just wanted to make sure I wasn't barking up the wrong tree and there was some default way to handle it.
@pulsar jay you shouldn't put mutating methods in component data but sounds like your case doesn't so should be fine to put it there since it's a helper function related to that specific component, alternatively you could use a static extension method in a utility class so you don't have to pass it in as param but still have it seperate (basically same thing as putting it in the struct, only difference is where your method is located)
@hollow sorrel "components should not have mutating methods" makes much more sense to me than "components should not have logic" which seems to be the the standard definition of ecs
hello i got the error but i cant find the problem solve.
Assets\Scripts\Client\Network\ClientNetworkAuthoring.cs(21,41): error CS0246: The type or namespace name 'UpdateWorldTimeSystem' could not be found (are you missing a using directive or an assembly reference?)
and the assembly has.
@radiant sentinel add Unity.Entities.Hybrid
thank you @amber flicker
so whats the deal with chunk components? is the pattern to check/add/modify all in the IJobChunk that uses the chunkdata?
@lament ermine Thanks π im gonna try both versions.
Sure :)
although really I guess I dont need a chunk component per se, I just need data per chunk. so what I really need is a number of chunks
I wonder if entity queries can tell me the number of chunks they currently select...
@tight blade I wonder if you actually want an ecs chunk or more like a tile chunk? Not sure what you're doing, just to say that you'll be wasting a lot of memory if say you put 16 tile entities in a chunk (for example)
and yes, an entity query has a CalculateChunkCount()
a tile chunk? I mean that sounds more similar to what im thinking of, but this is the first Ive heard of that
it doesn't exist π - I just mean, conceptually a different chunk than an ecs one
hahaha interesting. Yeah, you know the docs are funny about that. from the entities docs on chunk components:
For example, if you have chunks of entities that represent 3D objects that are organized by proximity, you can use a chunk component to store a collective bounding box for them.
doesn't that kind of imply some ability for authors to control the organization of chunks to some degree?
in my opinion, using chunks like that (with chunk data) is almost always going to be awkward. Either a) you waste a lot of space if you have only a small amount of data but high chunk count or b) it all works well until you want to add an extra component to an entity and then you have to reduce the number of entities per chunk. I don't know if anyone really uses chunk data in practice.
yeah. my use case is just to assist in parallelism. basically I want to perform a reduce operation on all of these entities. I cant have them all add to a global number in parallel, because there'd be race conditions
how i can set the pivot of a render mesh to rotate the center and not the left-down corner
so, instead, they all add to some chunk value, and then at the end of that I can add together all the chunks
its just a 2 step aggregation. thats my chunk data use case
if there was some kind of "IJobReduce" I'd be all over that
how i can set the pivot of a render mesh to rotate the center and not the left-down corner
@buoyant willow with a script
@buoyant willow there is a RotationPivot component, see the Entities docs regarding the Transform System for more info on all the types
the "answer" to these kinds often seems to be a bunch of flat arrays with an index you maintain. That said, any solution depends hugely on exactly what data you have and how frequently you want to manipulate it in what ways. If you have 10k tiles with a float someVal and you wanted to sum them, just do for all entities(add).Schedule(). Before you try and make everything parallel, make sure it's worth it - schedule will run on a worker.
@buoyant willow there is a RotationPivot component, see the Entities docs regarding the Transform System for more info on all the types
@safe lintel i see this but i dont know how works because i added some values but always i see the same rotation
@buoyant willow ill bet you;ll need to do the math yourself to rotate the position
you may also need a composite rotation component, there is a page detailing all the interactions of component combinations
theres some pretty useful math functions for it
@safe lintel I hate that page
@buoyant willow ill bet you;ll need to do the math yourself to rotate the position
@tight blade the problem is that when broken the entity is broken but it moves since the pivot is down to the left and not in the center
@tight blade the problem is that when broken the entity is broken but it moves since the pivot is down to the left and not in the center
@buoyant willow sorry my bad traduction xD
mmm ok I'm going to have to study it then ... thank you very much!
so try adding a CompositeRotation and RotationPivotTranslation as well as RotationPivot
that makes sense. but if you have the rotation, we can move it appropriately down and to the left like this:
that makes sense. but if you have the rotation, we can move it appropriately down and to the left like this:
@tight blade π€
itll change with your use case, but the idea there is that we capture rotated space by using math.rotate(<your rotation>, <your local coordinates>)
you could bypass the transform system entirely but its there, might as well take advantage of it.
and give them an earful on what you dislike of it, so they improve it rather than rolling your own solution π
oh, my bad. @safe lintel is probably right. if theres a built in way to do it, that might be better
Im working in physics land, where there is usually not a built in way to do it, and you need to do the math yourself
ok thanks very much!
yeah annoys me how the physics package just totally ignores the transform system
would anyone happen to know offhand if the "chunkIndex" argument to the IJobChunk's Execute method refers to a static "id" of the chunk or is it the "nth chunk of this archetype"?
@amber flicker ?
the latter I believe
ugh, thank goodness
Can we reference buffered entities ? Or is this not possible... because... they are "buffered" ?
I actually mean the buffered entities which are enqueued for getting created
what do you mean by a buffered entity
something from EntityCommandBuffer?
anyway if so yes, but with limitations, afaik as long as you are referencing it with the command buffer then it will be remapped, but if you store that reference with something other than the command buffer it wont get remapped automatically and just be an invalid entity index
@safe lintel Thanks, that was what i meant ^^ thats... sad... because i actually wanna make a component reference my buffered entity :/
well use the command buffer to set that component?
@safe lintel How do you mean that ? ^^ An existing entity should reference an buffered entity, thats what i mean.
var futureEntity = entityCommandBuffer.CreateEntity();
entityCommandBuffer.SetComponent(entity, new Parent{Value = futureEntity})
You can also add them to buffers with ecb.AppendBuffer
but if you were to just store that futureEntity somewhere that isnt touched by the command buffer, it will remain an invalid index
collisionWorld.CastRay(input, ref allHits); is causing an assertion failure since the returned Fraction of the query is more than the maxFraction.
I'm not sure how this is possible since the start and endpoints of the query are reasonable values
if you're asking if it's production-ready, it's not
but that doesn't mean you can't still do it anyway π
inserts all the hermits from this channel
it's definitely possible, but you will have to get dirty and read alot of source code when/if you're getting to the more finicky behaviors because the documentation is quite lackluster.
np
how i can set -270 of rotation (for example) in a struct "Rotation"?
you can use the RotationEulerXYZ/ZYX/XZY(or whatever they are) components
@buoyant willow quaternion.Rotate
Ok so if someone wanted to use the DOTS sample package as a starting point but use current versions of ecs/burst/etc... are we pretty much SOL?
@buoyant willow
quaternion.Rotate
@zenith wyvern yeah this is the solution
Ok so if someone wanted to use the DOTS sample package as a starting point but use current versions of ecs/burst/etc... are we pretty much SOL?
@valid haven what is sol=
?
*hit out-of luck.
I have a problem ... when using rotationtranslation when the original point (that is, subtracting the rotationtranslation) leaves the focus of the camera, the mesh disappears completely but being moved by the rotationtranslation it seems as if it disappeared before it left focus ... I don't know if I can explain
*hit out-of luck.
@valid haven yes and no .... I'm a bit of a beginner at this but there are quite a few things to implement in your game, although I don't know if it's very feasible and easy to make a game with ECS Pure
That is not what i am asking. The DOTS sample project is written for 2019.4, it wont compile with 2020.1 or 2020.2b with latest ECS packages due to the massive changes. My question is if it there is an updated version/fork floating around using the new packages/dots structure.
ohhh sorry my bad traduction π emmmm idk im learning with a videos of code monkey and and I search for them as I can
If you mean the FPS Sample then no there's no simple way to port it up. It was a massive combination of all the packages at the time just meant to show stuff off
bummer π
I somehow have a SharedComponent that is not referenced by any entity. If I use EntityManager.GetAllUniqueSharedComponentData it returns 2 sharedcomponents where there should only be one. If I iterate over all entities with this sharedcomponent (Entities.WithSharedComponentFilter(sharedComponent).ForEach((Entity entity)... it does not have any entities. How can this happen? It should be impossible for an unreferenced SharedComponent to exist as it is reference counted π€
This mystic SH also has all its values set to 0. Is there any way to see all unique SCs e.g. via Entity Debugger?
Could it be possible that just having a private field of this SC type somewhere creates an empty "instance" of the SC?
Maybe a prefab entity references the shared component
Maybe a prefab entity references the shared component
@north bay thats impossible because the grid is not part of any conversion it is only created in my custom editor script
I'm getting back to DOTS and tring to get a better grip of BlobAsset, BlobAssetStore and SubScenes.
I checked the BlobAsset scene example from the ECSSamples and tried to get some info from googling and watching some videos, but guess I haven't found the right one yet. When you allocate blobs to be presistant in the context from conversion of a subscene as done in the ECSSample, is this stored with the subscene? Is it allocated/deallocated when subscene is loaded/unloaded or is it always allocated? Any guidance is highly appriciated! π
now I am wondering if GetAllUniqueSharedComponentData just always returns a default SharedComponent by design
@mystic mountain basically yes, I believe so.. 1 sec, there's a comment in the code I can copy pasta
Im trying to implement rotation to Entity and it doesn't affect
its always rendering like with quaternion.identity
@mystic mountain I was thinking of BlobAssetStore:
/// In other words the cache is created when we enter edit mode for a given SubScene and it is released when we close edit mode.
/// And instance of this cache is exposed in <see cref="Unity.Entities.GameObjectConversionSettings"/> to allow users to query and avoid rebuilding assets.
/// During conversion process the user must rely on the <see cref="BlobAssetComputationContext{TS,TB}"/> to associate the BlobAsset with their corresponding Authoring UnityObject and to determine which ones are to compute.
/// Thread-safety: nothing is thread-safe, we assume this class is consumed through the main-thread only.
/// Calling Dispose on an instance will reset the content and dispose all BlobAssetReference object stored.```
Still waiting for more materials/info about Blobs
Im trying to implement rotation to Entity and it doesn't affect
@half jay maybe it gets overwritten by unitys internal system?
you should look at the inspector it the LTW component is set to your intended value
@half jay I assume if you log out data.rotation it's as expected - a normalized quaternion in radians? I'm personally not a big fan of setting LTW directly - out of curiosity does it work if you set Rotation instead?
@amber flicker Thanks. Yeah I saw this as well, and I'm not 100% sure of what it means, if it actually means it's what keeps track of the BlobAsset itself, I have a hard time seeing the connection of the "BlobAssetComputationContext" where the settings connects to the blobAsset.
Wish I could offer some profound understanding. I got majorly switched off blobs once I realised just how much hassle manually managing their lifetimes is. Do I really want to start reference counting? It's much better if you only use them with GameObjects in conversion - at least there's BlobAssetStore. I believe there's a post somewhere on the forums about whether they unload with subscenes or not. Will try a quick search.
Wait.. found it.
now I am wondering if GetAllUniqueSharedComponentData just always returns a default SharedComponent by design
@pulsar jay after some testing this seems to be the case. GetAllUniqueSharedComponentData always returns a default component. Even if no ISC of this type has ever been created
@mystic mountain oh? Also beware, there are issues with serializing blobs atm I think
@amber flicker Hmm ok. Yeah I looked at
https://docs.unity3d.com/Packages/com.unity.entities@0.5/api/Unity.Entities.BlobAssetComputationContext-2.html
"When the context will be disposed (typically after the conversion process is done), the store will be updated with the new associations between the BlobAsset and the UnityObject(s) that use them. "
And in the code I found
"context.AddComputedBlobAsset(settings[i].Hash, job.BlobAssets[i]);"
combined with
"context.AssociateBlobAssetWithUnityObject(hash, auth.gameObject);"
Would define the connection and reference tracking.
Now the question is if subscenes share blobs or not.
I do remember reading somewhere that there's a fixed size for the blob assets? Couldn't find that when I looked just now though. Please lmk if you find out
@amber flicker
Yes - normalized quaternion in radians. Our system a bit tricky. This Entity has parent and can't be set through Rotation and Translation components because rotation and position i have in worlds coordinates thats why im using
new LocalToWorld {Value = float4x4.TRS(worldPos, data.rotation,1)}
If you're not careful with your timings and if you don't update Rotation, the Transform system may run (using Rotation) and set the LTW after you just set it.
nothing will automatically update the Rotation component after you set the LTW - so either just do the math to work out what Rotation should be (my strong preference) or you could remove the Rotation component / look into write groups depending on what you're doing.
@amber flicker Ok so this was much harder to test than I thought. Unity doesn't seem to like deallocating the blobs. So I allocated memory in blobs, 1gig each, using hash based on allocation size = same. I had two subscenes, one with two allocations, one with one.
Before scene swap to test scene 731 MB, after scene swap 2628 MB, when hitting play 4547 MB, when changing scene to other scene 4555. x)
Yep, did some more testing with deactivating one subscene etc. And it seems that currently the blobs created are not shared between subscenes.
@mystic mountain nice one - I do wonder if it behaves the same in a build but that's a bit of a headache to check
So how should one think about this regarding resource management? How are textures and meshes stored? Should I have all visual alterations of one model in same subscene?
got a first version of my burst-compatible linq library out here: https://github.com/CareBoo/Blinq
It's got a lot of limitations because there isn't really a great alternative to delegates for Burst, but I'm working on another project that lets you codegen delegate lambdas into structs.
Cross post from forum if anyone would know how to deal with storing references to multiple entity prefabs in a good way
https://forum.unity.com/threads/where-how-to-store-reference-to-multiple-entity-prefabs-for-ghosts.987594/
@mystic mountain Unity/Topher have let us know that dots prefabs workflow is very much on the way / in development - no eta but a promise that it will feel native/natural to work with...
what comes first, the prefabs workflow or the blog post π
hover boards? π
So EntityPrefabs are different from simple prefab entities (entities with Prefab component)? Some special thing?
we kinda have them already right? hover boards, jetpacks, saw a crazy video yesterday of a plasma lightsabre!
The plasma lightsaber got spread by the almighty algorithm, so you're hardly the only one
must be getting old because i wasnt thinking "damn thats so cool" only "damn thats so dangerous!"
Then there's the guy who makes the homemade jet engines and straps them to all sorts of things. Something something child at heart and outwardly.
But to repeat my question,
EntityPrefabs are some kinda special thing distinct from entities with the Prefab component?
its some sort of workflow that i imagine has similarities to addressables
ive seen it mentioned when people ask about dots addressables and they mention the prefabs, so afaik distinct but encompassing
@tawdry tree From what I wrote EntityPrefabs is basically converted gameobject prefab to entity prefab
Aha
From what I found addressables is not compatible with subscenes?
Because if there's no special thing there, it sounds like the time to use... entities with the prefab component, referenced in a dictionary or something
(because the simple solution should be tried first)
if I needed to work with prefabs now I think I'd try either 1) a single Prefab subscene or 2) a subscene per prefab. Trying to populate your own blob array or something is just so much pain right now.
Of course it's not that hard to set up a custom solution. It's just annoying. Considering how integral prefabs are to workflows, there should be a sensible built in solution
think everyone agrees about that
what's the benefit of treating subscenes as prefabs?
Oh yeah, how to get the prefabs into the scene to begin with is a bit harder thn just storing them...
as opposed to a single subscene? Potentially easier memory management / streaming
From what I can tell it lets you set up all your conversion in the editor and stick it into a single subscene, then you can load that as a prefab
The benefit of one subscene per prefab is presumably that you can spawn in only the prefabs you need/want, when you need/want
also one major thing preventing you from using subscenes as prefabs is that assets are not shared, referencing a tree in your subscene and pasting it 1000 times in your scene means you will have that tree 1000 times in memory
Whereas one subscene with all prefabs is exceptionally easy to load, since you just load that one subscene
I think they fixed the duplication thing didn't they
@hollow sorrel yea, they have implemented it apparently - I haven't tested though
ah
Last time I tried you couldn't load a duplication of a subscene
@mystic mountain I think there's a procedural dungeon example knocking around that uses 'instances' of subscenes
I tried this spring, so might have been fixed.
i think subscenes use asset bundles internally so should mean it's for assets in general
but not sure
You're probably right
There's also a difference between using subscenes as prefabs directly, vs loading a subscene with all prefabs at load time and thus loading a bunch of entities with the Prefab component, and using those entities as the prefabs (the conversion process would need to register the prefabs in a central "database" for this to be particularly useful, though)
@tawdry tree Any examples of how to use them directly?
I don't think you'd want to instantiate a subscene...?
That's exactly what the procedural dungeon example does from what I understand
It treats the subscenes as parts of the level that get placed randomly
It's hard to know for sure since it's using a bunch of internal stuff so you can't load up the project without a bunch of fiddling around that I don't want to do
EntityManager.Instantiate(entity) will create a copy of the entity you give it - it will also remove any Prefab components. Thus, if load a prefab, convert it into an entity with the Prefab component (which stops entity queries from finding it), and store the entity ID for the prefab entity, you can freely instantiate copies of your prefab
I don't want to bother with it too much until they give us some proper examples or documentation on subscenes
In other words, what I would do is make probably just one subscene with all the prefabs I might need (or split into categories of prefabs, to split the load?).
Make sure they each have a custom converter which: 1. Adds the Prefab component to the entity 2. Saves a reference to the entity in a "database".
Then you use said "database" to grab the entities you need to EntityManager.Instatiate(entity)
How you'd group stuff depends on the game of course, and subscenes should be pretty lightweight to spawn in, so one big should be fine. The categorization is more for it being easier to work with design-time
You wouldn't necessarily need a database. You can use a static "GetPrefab" function that uses a query.GetSingleton with the prefab type included
You could, yes, but if you have a bunch of very similar prefabs that could be a pain
Even more so if you have prefabs with the same components and just different values
True, it would only work for very simple archetypes
Hmm, maybe I should try to actually make such a system, since this is all theoretical from what I know, or think I know.
You might want to wait and see how this prefab workflow thing turns out. But I guess we'd never do anything if we all just waited for the next big thing
Eh, I'm not really working with anything Unity/gamedev related, I just play around for learning/fun every now and then, and this sounds interesting enough to do so.
Hello, im using a custom mesh for a render mesh but the mesh dissapear in certain angles of a camera... im recalculatingbounds and im too using a custom bound of a 20000 of a range and the same issue appear... any solution?
Is this with Graphics.DrawMesh or something similar?
Any time that's happened to me it's from passing incorrect bounds. Double check the bounds and especially the origin point you're passing in
On the small off-chance, worth checking clipping planes too if you haven't already π
Is this with Graphics.DrawMesh or something similar?
@zenith wyvern its a rendermesh
of a entity
Hello !
I'm currently learning DOTS and i'm doing a space Invader like to train.
my spawner work but the job don't loop trought all the spawners. Just the first one. I don't realy understand why... Any ideas ?
protected override void OnStartRunning()
{
base.OnStartRunning();
alienPrefab = GameManager.manager.getAlienEntityPrefab();
entityManager = GameManager.manager.GetEntityManager();
}
protected override JobHandle OnUpdate(JobHandle inputDeps)
{
spawnTimer -= Time.DeltaTime;
Entities
.WithStructuralChanges()
.ForEach((in AlienData alienData, in SpawnerAlienData spawnerData, in Translation trans) =>
{
if (spawnTimer <= 0f)
{
spawnTimer = spawnerData.spawnRate;
alien = entityManager.Instantiate(alienPrefab);
entityManager.SetComponentData(alien, new Translation { Value = trans.Value });
speed = new float3(UnityEngine.Random.Range(-alienData.moveRange, alienData.moveRange), -alienData.speed, 0);
velocity = new PhysicsVelocity()
{
Linear = speed,
Angular = float3.zero
};
entityManager.AddComponentData(alien, velocity);
}
}).Run();
return default;
}
the spawners got AlienData struc and SpawnerAlienData sstruc too.
@karmic junco did you check in your entity debugger that you have multiple entities with these 3 components (in AlienData alienData, in SpawnerAlienData spawnerData, in Translation trans)?
@pulsar jay Yep
Well otherwise I cannot really see whats wrong with that other than the structural changes
Although it is allowed I would not be surprised if creating entities while iterating over entities could cause problems
But thats a wild guess
you could try to use EntityCommandBuffers instead and get rid of your WithStructuralChanges
this way you can also use jobs
i could maybe do a list of entities and use the buffer after the loop maybe yes
i will try thank's
there is a specific tool for delaying entity instantiation called EntityCommandBuffers. You should look it up. I am not sure if it will fix your problem but it is the recommended way of instantiating entities in a system
@karmic junco spawnTimer is part of your system that you're changing after the first loop, so after first loop it won't be 0 anymore thus the rest of the entities don't pass
most straightforward solution would be to give each spawner their own timer
(unless they're all synced up by design i guess)
yes i used a buffer but it doesn't accept addComponant so i need a list of Enity and an other one of PhysicsVelocity.
@hollow sorrel Ohh yeah i see ! Thank's !
@karmic junco spawnTimer is part of your system that you're changing after the first loop, so after first loop it won't be 0 anymore thus the rest of the entities don't pass
@hollow sorrel oh didnt catch that. Thought the spawnTimer was part of the spawnerData
Yeah that was the problem thank's a lot !
Are systems disabled based on ther ForEach Lambdas? I just tried with a test system with only Translation and Rotation. As soon as I added another Component Entities.ForEach((ref Translation translation, in Rotation rotation, in Placeable placeable) it did not show up in the entity debugger anymore
yeah if there are no chunks matching the query the system won't run
there's a dropdown in entitydebugger to show inactive systems if you want
but the system might do additional stuff besides the ForEach
I guess I'll have to use [AlwaysUpdateSystem] then?!
Can anybody tell me why my system isnt running?
{
protected override void OnUpdate()
{
Entities.WithAll<Placeable>().ForEach((ref CellPosition cellPosition) => {
Debug.Log($"Placeable: {cellPosition.Value}");
}).Schedule();
}
}```
I instantiate Entitys which have both a CellPosition and a Placeable Component. But the system is stull "not run"
Is there anything I am missing about tag components maybe?
can you check it from entity debugger and check if that system is running and/or have any queries ?
the TestSystem says "not run"
but this is one of my entities:
it definitely has a CellPosition and a Placeable
it has a prefab component - prefabs are ignored by systems by default. If you explicitly require the Prefab Tag I think it will work - if you want to run over your prefabs.
also yea alwaysupdate attribute is the way to go if it does other stuff besides just queries sry late reply
oh wow. this implicit behavior is driving me insane
so it is intended for me to first instantiate from the prefab I guess?
yes
I think you really wouldn't want systems running over prefabs by default - the Disabled tag is similar.
Agree the implicit nature of this stuff is frustrating
Is there an opposite of RequireSingletonForUpdate<Thing>() - ie do not run Update if this SingletonComponent exists?
just WithNone<> @wary anchor ?
SO far I just did a normal EntityQuery notThing = GetEntityQuery(ComponentType.Exclude<Thing>());
I think you really wouldn't want systems running over prefabs by default - the
Disabledtag is similar.
@amber flicker yeah as I was about to use it as a "placement marker" I thought I could just use the prefab and than create instances when placing it. but I'll just instance it first then
I don't mean for an Entities.Foreach, I mean as a way to stop a system running OnUpdate() entirely
@wary anchor the [ExcludeComponent] attribute? Though my pref would be for WithNone in the lambdas
@pulsar jay if you want to do it that way, I think just saying WithAll<Prefab, Placeable>() will work
Ok thx I will try that
maybe you could make an entityquery withnone<mysingleton> and requireforupdate that
might as well just check explicitly in the onupdate at that point tho
yeah I'm doing that at the moment, it works - the system is "Not Run" as expected, it's just I get 340 Entities matching that query:
just seems a bit hmmm
I assumed [RequireSingletonForUpdate] doesn't do anything more performant than adding an early out in the system like you would manually
I don't know what the difference is between a system that is not run and a system that runs but does nothing
I think they all run.. it's just whether user code gets executed or not basically
but not everything is in lambdas so excluding at that point isn't going to cover all options, and you can't check HasSingleton without also having a ref to the system it's registered to, which is blegh too
internally it just does if (query.IsEmptyIgnoreFilter) before deciding wether to run onupdate so i think performance wise it's the same if you do it yourself in onupdate
Fair enough that's good to know π
if it's constructing a query, it may even be slower than just doing ```cs
if(!EntityManager.HasComponent<Blah>()) return;
waaaait up, you can HasComponent on the EntityManager?
hang on.. what did I just type π
Ah ok, it takes an entity
when you'll have a query
You can HasComponent on a ComponentSystemBase but not the EntityManager no?
you can do either but yea, what I was saying was nonsense because at the entry of your system you won't have an entity, at best you'll have a query - which is what RequireComponent etc is checking
Ahh I need to switch to 0.14 for that
no I'm getting confused between HasComponent and HasSingleton
Mm yeah what I'm after is really just a RequireSingletonForUpdate<Thing>(false) to invert the requirement π
why not [ExcludeComponent]?
Good question. lemme read up on it π
oh right, that would apply to the Entities lambda, rather than the whole OnUpdate method
wait that's nonsense, ugh things made so much more sense when it was jobs as structs as the main way to write this stuff π
okay it's simple enough, I just define all possible states and create an EntityQuery built up from the various EntityQueryDesc for each of those that isn't the one(s) I wish to avoid. Sorted!
Mm yeah what I'm after is really just a RequireSingletonForUpdate<Thing>(false) to invert the requirement π
@wary anchor that should work
EntityQuery inverseSingletonQuery = GetEntityQuery(ComponentType.Exclude<MySingleton>());
RequireForUpdate(inverseSingletonQuery);
oh yeah I already did that before, but of course it simply returns all the entities in the world that aren't that singletoncomponent, which just seems weird.
I got around it by turning my question on its head and instead of trying to exclude a system if one singletonComponent is not present, creating singletonComponents for all possible states and enabling the system if any of the other singletonComponents are present via individual EntityQueryDescs
I could need some help here... im getting an weird exception :
And it simply does not tell me where exactly the entity gets null :/
It drives me crazy... any ideas what i could do ?
have you turned off burst as it suggests?
Yep
what's the error message with it disabled?
@amber flicker Wait... i did not notice that before. It happens in my "Destroy" systems, i should probably take a look at that one
Is there a way that queries only return entities that are not null ? One query i pass to the command buffer system contains a null entity for some reason
not afaik - you need to sanitise beforehand
Damn... I found the piece of code that throws the exception but i cant find the null entity
worst case for now you can do a for loop using EntityManager.Exists to find it
@amber flicker And what can i do once i have found it ? :/ Just delete it again ? Can i somehow check its archetype to determine where its "from" ?
you can certainly get it's archetype sure - I'd try and track it down and find out when/why it's becoming null
the other thing you can do is add an ISystemComponentData to your entities to do cleanup if need be
(it's much easier than it sounds - just change one of your ICDs to ISystem... and when your entity would be deleted, instead it remains with that component)
@amber flicker Thanks ! Well another problem is that the ecb gets executed later... i just print all entities marked for destruction when i buffer that query and none of them are null/not existant
yea.. gotta manage your timings.. guess an entity is being deleted before the ecb plays back
@amber flicker That shit is crazy... i literally only have one single line for destruction in my entire project.
Why should an entity become null when i dont delete entities anywhere except in the "DestroySystem" ?
? I'm just guessing but what I expect is going on: Your 'DoSomething' ecb system runs... adds a bunch of entities to an ecb. Then your destroysystem runs, destroying one of those entities. Then the ebc playsback at whatever time (presumably end of frame depending on what you've chosen) and the entity has already been destroyed on the main thread.
If that's not what's going on, I have no idea without stepping through your code (though I think the above is likely given your description).
@amber flicker I never delete entities by "myself" in the entire project. When i want that one entity gets deleted, i mark it with "DeleteAfter". My "DestroySystem" loops over those marked entities and adds them to the ecb for being deleted". Thats the whole story. I never delete entities by myself :/
I'm a bit... sceptical about that π .. I'm not aware of anything that automatically destroys entities unless you're using a third party event system or something?
one other thing that could be happening is you're adding an entity that was returned by an ecb.instantiate or similar - that entity will become invalid. Thinking about it @stone osprey, this seems the most likely if you're not destroying any entities.
@amber flicker Well im not creating entities via the buffer mechanics :/ So thats also not the case... No, i wrote the system myself. Its actually pretty simply, 5 lines of code. But great if you wanna iterate over entities that are getting destroyed soon ( Cleaning up ). I read the exception again and found this here :
EntityCommandBuffer was recorded in Script.Client.Environment.Entitys.Systems.DestroySystem and played back in Unity.Entities.EndInitializationEntityCommandBufferSystem.
at (wrapper managed-to-native)
Thats interessting... it says "played back in EndInitializationEntityCommandBufferSystem"
But my destruction query does not use that ecb to destroy its entities
hey, newbie using dots here
after any code change i have to wait this thing for 4- 6 seconds
is something regular or just my unity is taking so long?
The same thing happens to me too, I guess it's normal but if it can be solved it would be a great relief
as I ended up "getting used to" but hey also slows down the tests that one wants to do
Have you both enabled the experimental enter playmode options in the preferences? It makes a huge difference
great change4
Be mindful itβs not default because it doesnβt reset statics
unity animator works if I convert a gameobject to entity?
yep
unity animator works if I convert a gameobject to entity?
@keen sapphire didnt work for me :/
(for a sprite renderer)
there is animation package for entity animations, not sure if its ready to be usable for scrubs like me tho
Do we have any updates on the component disabling feature?
And burstable systems? β₯οΈ
As the docs recommend using static methods to reuse code how would I handle static methods that require an Entity query as both Entities and EntityManager are not accessible in a static method
bypassing this would be as easy as declaring a static ForEachLambdaJobDescription:
private static ForEachLambdaJobDescription StaticEntities => new ForEachLambdaJobDescription();
However I dont know if this will break anything with the code generation going on in the background and I guess it is somewhat against the intended design
@digital scarab since nobody really tracks the 48 hours, isn't that quite silly limitation?
could be just dots challenge and you'd suggest people to take 48h max for it
oh huh i thought the 48 hours was like a copypaste mistake but looks like it is intended
"make a game or prototype in 48 hours over the course of 9 days"
"You have 48 hours (non-consecutive) to make a game or prototype."
that being said, non-consecutive 48h means basically you get to work on the thing 8h per day for 6 days
(or 5.3h each day throughout the 9 days)
so I guess it's more of a guideline then as most people will not have even that time to put for this
I assume it's deliberately put that way to stand in contrast with the unhealthy crunch atmosphere of a normal 48hr jam. There's no prize and the challenge isn't to produce the most complete, most polished game.
reminds me of time gates in mobile gacha games
once you reach your daily stamina you gotta wait before continuing your jam game
pay gems to unlock except in this case the gems are irl HP
Still trying to figure out how to best find an entity by value. It works with using a query and ToComponentArray but I am wondering if I could also use a ForEach job which returns the entity... or if there is an even better way to do this
@amber flicker a few days ago you recommended to use some kind of GetSystem method to get a reference to a system. I cannot find it anymore. Could you tell me again what the method was called?
what's the issue with your current solution?
GetOrCreateSystem
it cannot be jobified and I need a reference to the EntityManager. not sure if its a great idea to wrap that into a static method. Then again I am unsure if it is a good idea to use Entities.Foreach in a static method
GetOrCreateSystem
@deft stump thx thats what I was looking for
you can't put a lambda in a static method - it needs to be in a SystemBase
so.. rather than immediately returning a particular entity, you want to do it async - so a job that relies on the resulting entity doesn't run until you've gone wide and searched for it?
I thought It might be possible to handle this with dependencies but it might be to complicated
Just keep in mind there's a cost to scheduling - make sure you're addressing a real performance concern, not a theoretical one (imo)
I am trying to figure out where to put the GetEntityFromCell method which searches for an entity with a specific CellPosition
I could either put it on the MapShared component or on a MapSystem (either static or not) or maybe a utility class?
My opinion is that this isn't worth thinking too hard about. I highly doubt whatever you write now will be there in a month.
You are probably right. Its just such a core architecture decision...
My guess is you'll almost certainly end up creating different acceleration structures and then in a few months circle back to flat arrays and managing indicies somehow. One issue with caring about cache & multithreading is the 'best solution' is always very dependent on your data and how you need to transform it. Only you are able to judge it and judging it comes with practice. This is hugely amplified if you are under very few constraints and can change the approach or concept at any point. Other people here may have a different perspective to me though - I'm just some guy who's been going dotty for a couple years π π¬ .
I see. Maybe I am coming from the object oriented approach here as I think I was trying to create an "interface" to swap out the data structure later. I thought if I just create a GetEntityFromCell method which is accessible from all systems I can for now just search for the entity and later on swap it out for a lookup in an acceleration structure without the need to refactor all of my code.
(Unsurprisingly) I feel similar to a friend of mine who wrote this post - I'd recommend a quick read but again, it's just opinion http://medium.com/@pjsdev/abstract-programmers-acada09df860
Software is just data: input, processing and then output and my best code has always been that which does the simplest thing to get the job done.
thx for the recommendation
difference between renderbounds{center and extents}?
difference between renderbounds{center and extents}?
@buoyant willow I would infer from the names that the center is the centerpoint of the bounding volume and extends are usually the distance to the border on each axis (= half the size of the bounding volume)
but I have a problem ... when creating several meshes these disappear because of the center but if I put the position in the extents they show correctly ...
maybe you could try to convert a prefab via conversion workflow and look at its converted bounds?
I am not even sure if they need to be in object or world space
the meshes are allocated in instantiated objects
this contains a mesh foreach entity
If you just create entities from converted gameobjects the renderbounds should just work
if you create them from code I would compare them to auto converted ones
i did this and for now it works: EntityManager.SetComponentData(antentity, new RenderBounds { Value = new AABB {Center = trans, Extents = new float3(4, 6, 0) + trans} });
trans is the value of translation
sure if it works. but there should also be some api to extract the render bounds from the mesh
sure if it works. but there should also be some api to extract the render bounds from the mesh
@pulsar jay If there is, I have no idea what it could be
I think its just mesh.bounds. They might be in the wrong space though. If renderBounds requires world space you would have to multiply by the entities localtoworld matrix
but the problem is not the mesh since if I only visualize the gameobject it works fine ... the problem is the render limits
How do we design easy extendable ecs workflows ? Im currently running into the following issue... Player owns an inventory, that one references to item entities. Once he kills a mob i wanna put/merge items into the inventory. Therefore i have a "AddToInventory" component and entity that gets consumed in order to add the defined item as an entity to the inventory. The problem here is that this "command" component "AddToInventory" contains hardcoded variables like : "Level, Amount...", so theres no way to customize the item getting inserted in an easy way, we couldnt easily add new stuff to that item itself, because the consumer takes care of constructing the entity by using the shipped variables. How could we design this more "flexible" ?
In my head I might think something along the lines of:
- Inventory is dynamicbuffer of items (entities)
- An item is just an entity. What an item is depends on what ICDs it has present.
- A ChangeInventory { public Entity Destination; } ICD could then be used by a system to move an entity into a dynamic buffer.
I can't say whether that kind of system exactly would be good in your particular case though.
@amber flicker Thanks ! So you mean instead of having some sort of command "AddToInventory{ level, amount, type... }" and an system which consumes this command for constructing item entities by its own to add them to the inventory we should rather take care of the construction on our own ? This would work, so we just widen the narrow hardcoded "interface" to pass in an whole entity instead
hmm.. basically my approach to these kind of things is design by subtraction. What is the minimum data you need to keep track of. In this case, an entity perhaps. Then apply the same thing to system design - what does it do - move inventory ok cool. Though couldn't this just be a PopulateDynamicBufferSystem depending on a PopulateDynamicBuffer ICD that has a target entity. Gone from Player having inventory to an entity having a buffer. That may be a step too far depending on your tastes but now this can be used to put items into a bag or populate furniture in a house or whatever you want. Dunno if that makes it any more clear what I mean.
I'm not sure what you mean by a whole entity - it's not like a gameobject - it's 2 ints - it's like holding onto a lightweight reference to your item/object.
Any way to have systems linked only to certain scenes without having to manually create them?
As far as I know, no. I've just used a singleton "key" object to allow the sysfem to run
So the RequireSingleton method (naming not exact)
FYI https://forum.unity.com/threads/psa-workaround-for-orderfirst-orderlast-not-working-in-updateingroup-attribute.988992/#post-6423715 - re OrderFirst etc and also 0.16 estimated later this month.
Does debug draw of rays still should be done with OnDrawGizmos ?
RE URP support Hybrid Renderer V2 0.10 will support lightmaps but not GI probes, 0.11 will support both https://forum.unity.com/threads/hybrid-renderer-v2-0-4-0.847546/page-9#post-6424199
@half jay #archived-dots message
I was just wondering why order first and order last didn't work just the other day lol
oh man
i've been assuming it works all this time
entitydebugger/systems view doesn't work with custom worlds so i was just flying blind
ive gotten so used to the idea of making a dots game without lightmaps, didnt expect support this soon π
(even though its not technically out and i consider it late in the greater scheme of things)
how do i use ApplyImpulse in unity physics (as in com.unity.physics)? is it similar to AddForceAtPosition in physx/regular unity physics?
similar though it needs a little more input than physx requires.
ApplyImpulse(ref this PhysicsVelocity pv, in PhysicsMass pm, in Translation t, in Rotation r, in float3 impulse, in float3 point)
just an example from my project:
ok, do i pass impulse and point the same way as in physx?
as in, are they world space?
otherVelocity.ApplyImpulse(otherMass, new Translation{ Value = localToWorld.Position}, new Rotation{ Value = new quaternion(localToWorld.Value)}, velocity.Value, rayHit.Position);
what are you doing vs what are you trying to achieve?
for any force applied over time (like many frames) you should multiple by deltatime
if this is a single-time force, then you should not multiple by deltatime
well
here's the monobehaviour code that im trying to convert from: https://hatebin.com/hwydbzbgpp
here's the system code i have right now: https://hatebin.com/vpmpnpoahm
ignore smoke and wheel mesh in monobehaviour
problem is that the physicsbody isnt affected by the impulse
personally i would remove delta and add a large multiplier or force number just to double check its working at all(if you havent done so already)
the other things are system ordering if it needs to be before or after buildphysicsworld system, which i am extremely fuzzy about, but currently i have before BuildPhysicsWorld
ok i think i need to assign the component back somehow
i decided to type in SetComponent to see if that's a thing and it is
oh yeah you need setcomponent too π
and while were at it, you should cache World.GetExistingSystem<Unity.Physics.Systems.BuildPhysicsWorld>(); in OnCreate
ok it works now
ok now what is this error
i tried to make onupdate execute on fixed update and added these attributes for that
[UpdateInGroup(typeof(FixedStepSimulationSystemGroup))]
[UpdateAfter(typeof(BuildPhysicsWorld)), UpdateBefore(typeof(StepPhysicsWorld))]
now i got this error
The previously scheduled job WRCarWheelSystem:OnUpdate_LambdaJob0 writes to the Unity.Collections.NativeArray`1[System.Int32] OnUpdate_LambdaJob0.JobData.collisionWorld.Broadphase.m_DynamicTree.BranchCount. You are trying to schedule a new job Broadphase:AllocateDynamicVsStaticNodePairs, which reads from the same Unity.Collections.NativeArray`1[System.Int32] (via AllocateDynamicVsStaticNodePairs.dynamicBranchCount). To guarantee safety, you must include WRCarWheelSystem:OnUpdate_LambdaJob0 as a dependency of the newly scheduled job.
looks like its related to raycasting
@maiden delta what part of physics are you using in that system?
setting components as well, but the error only went away after i commented out the raycasting part
https://hatebin.com/ogdyjbmjty here's my current code
it's kinda unusual to do stuff after build but before step
well i copied it from here https://github.com/Unity-Technologies/EntityComponentSystemSamples/blob/master/UnityPhysicsSamples/Assets/Demos/6. Use Cases/RaycastCar/Scripts/VehicleMechanics.cs#L109
huh weird, wonder why they do that, maybe i'm missing something about that topic then
anyway i'm guessing the part you're missing is adding a dependency on the buildphysics system, in the example they use Dependency = m_BuildPhysicsWorldSystem.GetOutputDependency();
when you swap it around it throws an out of range exception sooo
Are you combining the Input and Output dependencies correctly? @maiden delta
well, here is a common boilerplate to have system running between 2 of the physics systems:
[UpdateInGroup(typeof(FixedStepSimulationSystemGroup))]
[UpdateAfter(typeof(PhysicsSystemA))]
[UpdateBefore(typeof(PhysicsSystemB))]
public class MySystem : SystemBase
{
private PhysicsSystemA _physicsSystemA;
private PhysicsSystemB _physicsSystemB;
protected override OnCreate()
{
_physicsSystemA = World.GetExistingSystem<PhysicsSystemA>();
_physicsSystemB = World.GetExistingSystem<PhysicsSystemB>();
}
protected override OnUpdate()
{
Dependency = JobHandle.CombineDependencies(Dependency, _physicsSystemA.GetOutputDependency());
// do your stuff
_physicsSystemB.AddInputDependency(Dependency);
}
}
InvalidOperationException: Adding/removing components or changing position/rotation/velocity/collider ECS data on dynamic entities during physics step uh, how else am i supposed to do that then without cars having seizures
https://hatebin.com/thkdbkphmj what am i doing wrong? no matter what i do it's always this error or others
wait
ok fixed the code, still the same thing
the "adding/removing components" error when the raycast hits
try updating it before buildphysicsworld system
I need to bring this function to ECS/Unity Physics and I have absolutely now idea how
public static void GroundedCheckStatic (Transform obj, Vector3 globalDown, PlayerParametersAsset param, out bool isGrounded, out Vector3 groundNormal, out float groundDistance) {
int layer = 9;
isGrounded = Physics.CheckSphere(obj.position + param.physicsParameters.groundSphereYOffset * obj.up, param.physicsParameters.groundSphereRadius, 1 << layer);
if(Physics.Raycast(obj.position, -obj.up, out RaycastHit groundHit, Mathf.Infinity, 1 << layer)) {
if(groundHit.distance > param.physicsParameters.colliderHeight * 0.5f + param.physicsParameters.colliderRadius) {
groundNormal = -globalDown;
} else {
groundNormal = groundHit.normal;
}
groundDistance = groundHit.distance;
} else {
groundDistance = Mathf.Infinity;
groundNormal = -globalDown;
}
}
@foggy stream
(just clone that EntityComponentSystemSamples as is and look for the physics examples, there are bunch that do raycasting)
@safe lintel what would be the output dependency then?
so i got this error now after i added dependency to the args in Schedule
InvalidOperationException: The system WRCarWheelSystem reads Unity.Transforms.Parent via WRCarWheelSystem:OnUpdate_LambdaJob0 but that type was not assigned to the Dependency property. To ensure correct behavior of other systems, the job or a dependency must be assigned to the Dependency property before returning from the OnUpdate method.
problem is that i can't find GetOutputDependency on ParentSystem
In DOTS, Systems are always running as long as there are components that match their filter criteria. Is this really desirable? Typically a game has a concept of "scenes"; How are we supposed to transition from one "scene" to another in DOTS? I.E. a menu vs an overworld vs a level vs a cutscene. None of this is clear to me.
i think it unloads all the components, then loads gameobjects from the desired scene and converts them to entities i suppose
So there's not a "Pure Ecs" concept of grouping together systems and components? Or is that the concept of a "World"? Related, how does the renderer know which "World" to render, or is just rendering all worlds?
I'm also assuming that a "Pure ECS" approach will eventually supplant the Hybrid authoring.
@frigid onyx authoring using GameObjects is here to stay. The conclusion Unity came to (as far as I understand) is that desired authoring representation is rarely desired runtime representation so focus will be on improving the workflow and conversion process.
As for scenes etc itβs a bit more tricky to say. Some people have made systems that track and unload entities when scenes are loaded. I would hope this kind of workflow also improves over time. That said, streaming in and out subscenes takes care of entities and in theory your systems donβt run when not required so thereβs potentially not much need to disable the systems.
right, now my code works when i Run() the job, but how would i use Schedule() with it?
https://hatebin.com/ntnztyggda my code that works but is single-threaded i think
Is this the right channel for NetCode questions, or would I post those in #archived-networking ?
Youβd have more luck here than there I guess but still very few people using it here. Forums may be better.
Do you know of a decent tutorial on Subscenes? I keep seeing them referred to, but I haven't found anything that really explains them well.
Sorry for all the questions, still wrapping my head around DOTS / ECS
No problem at all. Itβs still more in the self-exploration stage including things like going through source code. Not that youβd guess that from Unityβs dots marketing a couple of years ago but thatβs the reality. The only person I know really trying to do any tutorials on yt is codemonkey - could be worth seeing if heβs done one on subscenes but youβre also welcome to ask any specific questions here ofc.
Yeah, it's actually frustrating. As a new game dev approaching Unity, 2019 is in LTS and in a number of places (like networking) they are already deprecating packages, but the new stack is still in preview. I don't want to develop my game and have to face a major refactoring in the future, I'd rather develop in DOTS/ECS from the start, and by the time I'm ready to take my game into Beta, DOTS should be out of preview. Obviously, I'm struggling with the sparse documentation right now, which seems to already be outdated. The unofficial docs made by the Discord community already seem much better.
Basically, I'm in limbo, and as a new Unity dev, that's not a fun place to be. I also expect that my game will be complex enough to warrant the new networking stack, hence why I don't just use GOs
@maiden delta what happens if you just say Dependency = Entities.ForEach().....).Schedule(Dependency)? In terms of terminology, Run is main thread, Schedule is on a single worker thread, ScheduleParallel is all worker threads possible.
@frigid onyx networking has always been a bit of a nightmare with Unity. In practice I expect 99% of people to either a) make their own solution possibly using Unity's lowest level legacy api or b) use an asset from the store like Photon, Forge, Mirror etc. I'm not up to date with netcode but if you're new to Unity, let's just say it could be some years before in it's in a state you might expect an engine to provide. That said, if you're a networking pro, you could probably think about doing a) with netcode but you'd have to explore the viability of that yourself.
got all these errors now https://hatebin.com/gmbgnjepcp
@maiden delta that looks like a pain - I haven't messed with Physics - perhaps someone else here can help. I'd also make sure you're following an example if you can find one.
My problem with the networking packages available in the store is that each has their own approach/interfaces; if I want to swap one for another later, it becomes a nightmare. NetCode's approach seems powerful, but my only concerns there are much the same as my concerns above. All of the tutorials kind of drop you into the middle of gameplay (with NetCode, connected gameplay) but don't really illustrate how to transition from a disconnected, local state (overworld, menus, etc) to a connected state on the server. Or how to spin up a server, wait for all players to connect, and then begin the gameplay. At least in the documentation I've seen, they are tech samples, but not practical / pragmatic.
I'll probably have to deep-dive into the FPS demo source.
I have opinions on these things like many π Mind me asking how exp you are re networking and games?
I've got 20 years of software development under my belt, mostly doing corporate software, and much of that in the C# stack. I'm a clean code / SOLID adherent, so wrapping my head around DOD is new to me. I'm an avid gamer, and have done some simple games myself from the ground up. Many years ago I messed around with DirectX.
I've only been messing around with Unity for about a month.
I've done some cool things, like procedurally generated courses, etc
@amber flicker If you're curious, I'll PM you some captures of what I've done so far
Sure - feel free to pm anyway - probably straying tangential to dots here
right, now my code works when i Run() the job, but how would i use Schedule() with it?
https://hatebin.com/ntnztyggda my code that works but is single-threaded i think
@maiden delta if you want to schedule something before BuildPhysicsWorld, then you need to get the OutputDependency from the EndFramePhysicsSystem, as its last frame update may be still running
Also, you want to use Time.DeltaTime, it gets overriden inside FixedSimulation already so you will get the correct one. Here is the fixed parts of your code:
// no changes above those lines
private BuildPhysicsWorld buildPhysicsWorldSystem;
private EndFramePhysicsSystem endFramePhysicsSystem;
protected override void OnCreate()
{
buildPhysicsWorldSystem = World.GetExistingSystem<BuildPhysicsWorld>();
endFramePhysicsSystem = World.GetExistingSystem<EndFramePhysicsSystem>();
}
protected override void OnUpdate()
{
Dependency = JobHandle.CombineDependencies(Dependency, endFramePhysicsSystem.GetOutputDependency());
CollisionWorld collisionWorld = buildPhysicsWorldSystem.PhysicsWorld.CollisionWorld;
float delta = Time.DeltaTime;
// do your stuff with .Schedule safely now
}
It is a little tricky to deal with the Physics right now, but once you got it all it starts to make sense
feel free to ping me if errors still shows up after those modifications, I know the pain of needing to figure it all by myself haha
so i realized that even in single thread the performance is great (50-90 fps on 121 cars in ecs and unity physics vs 3-4 fps on 101 cars in physx)
yeah, Burst is a beast even on main thread
Can an individual entity have two copies of the same component attached (IE a helicopter with two machine guns)?
I realize I'm still thinking in objects here, so, to be more "ECS": can an entity contain two BulletSpawnTags, say. Or, maybe more specific, how do you make one entity the child of another? Really I'd want to attach the "gun" entity with the BulletSpawnTag to a "helicopter" entity, right?
Still digging my way out of OOP thinking
@frigid onyx you can turn your ICD into an IBED, you can think like ICD being like a MonoBehaviour with [DisallowMultipleComponent] and the IBED being a MonoBehaviour that you can attach multiples.
btw, it is ok to go OOP with ECS, you can migrate your code to be more data-oriented as needed
@rancid geode I'm not familiar with the acronyms ICD or IBED; can you expand those for me?
IComponentData and IBufferElementData, sorry haha
If I mix the two approaches, do Entities still raise Rigidbody triggers? ie, if an entity "bullet" hits a gameobject, will the collision detection fire? (If a tree falls in the forest...)
I keep getting the impression that while rendered together, GOs and Entities exist in two different "dimensions"
Unity Physics doesn't know about Rigidbody and vice-versa, I recommend you to choose one or another (you can use Unity Physics with GO btw, by using Convert & Inject, or you can use Rigidbody with entities, by using HybridComponent or ComponentObject)
Thanks, I'll check them out
Are the
.Run(),.Schedule(), and.ScheduleParallel()methods underEntities.ForEach()just syntactic sugar to the Job System? If so, when would you need to use the more verboseIJobsyntax?
You can use the more verbose syntax if you're not using SystemBase
so you can write jobs and have them scheduled elsewhere
there's also IJobChunk, if you want per chunk logic, and IJobParallelFor/IJobParallelForTransform, which the Entities.ForEach() api wouldn't have
Entities.ForEach is just syntax sugar for IJobChunk
Job.WithCode is synstax sugar for IJob
is DOTS in a productive stage?? like is it possible to make a full game from scratch with DOTS?
not really. it is possible to make a full game, but most of DOTS is still in preview and some stuff will change
uh ok.. by productive i dont meant like publishing. i meant a game with some functionalities. all in all tnx :D
well yeah it's possible
It's possible to make a game in dots, but if you want Physics, or animations, or, well, anything beyond very simple stuff, you either need to implement it yourself or work with incomplete and/or cumbersome and/or unstable libraries/APIs
Or put differently:
DOTS itself works perfectly fine as the foundational framework for a game, but most of the components to actually make a game with that are missing or incomplete
hello all
just a quick question regarding dots and the job system
does Entities.ForEach().Schedule(); run each iteration of the foreach in parallel?
or schedule the entire foreach as a single job?
Schedule is how you do a parallelized foreach query, yeah
Oh wait
.ScheduleParallel()
thanks :)
one last question, is there an equivalent of Physics.OverlapSphere in dots?
In the new physics package, you mean?
For that, what you want is collision queries
https://docs.unity3d.com/Packages/com.unity.physics@0.5/manual/collision_queries.html
ok, thanks
hmm
what's the best way to use unity's new input system under ecs? preferably with action assets
^ same question on #π±οΈβinput-system
still no news on dots in their blog?
nope π¦
oh...
that abomination XD
probably asked a lot here, but couldn't find anything in pins
did they put dots on pause ? had to do some googling just to understand why the packages no longer appear in the package manager
No, they haven't put it on pause, they just made it harder to opt-in to preview packages in the 2020+ editor. The easiest solution I found was just to add the packages to your Packages/manifest.json. Buyer beware.
Check the first link in the pinned messages (Pin icon above). I've found the documentation coming out of the Discord community is often more useful than the official docs.
Yeah, the future is DOTS, but they are still trying working on the tech (and making it more creator-friendly). The APIs are bound to change.
@maiden delta thereβs an example in the physics samples of how to use the input system from a system base class without needing to use a MonoBehaviours
Oh torsinaβs got you coveredπ
Does anyone know how to call WithDeallocateOnJobCompletion on a native array after a CollisionEvent job execution?
with other jobs it would be a modifier but it doesn't seem to be allowed on ICollisionEventsJobs
why does unity physics behave so random with forces?
like, right now i have a car that's going in circles as if i was steering right and holding gas (didnt implement input yet) and the first time it almost flipped on the side but balanced out (because center of mass) and the second time it flipped at a different point for some reason
and now it flipped over 4 times again at an earlier point
does it have something to do with the "stateless" thing?
ok it doesn't seem to, on havok physics it's as unpredictable, probably because applylinearimpulse and applyangularimpulse is... weird i suppose
Err, are you applying your forces scaled by the physics delta time?
deltaTime vs fixedDeltaTime, pretty sure the newer physics packages are also in fixed timesteps.
Other than that, physics sim can be really owonky if things aren't configured correctly, though you'd assume the out-of-the-box config is decent.
Then again, cars, with wheel colliders and suspension joints are very complex and easy to mess up, and if you don't have some kind of suspension it's significantly worse. At least unless you use some hack to keep the car stable.
i used Unity.Core.TimeData.Time.DeltaTime provided by jobs, and i heard that updating in FixedStepSimulationSystemGroup overrides it to be equal to fixedDeltaTime
but yeah, once i began changing velocity directly without impulses, it started working great
i got this circular intercommunication going on rn, it looks cool but is probably ineffective
And how do I step the physic system EXACTLY when I want to?
don't think it's possible without changing unity physics' code Β―_(γ)_/Β―
The default world generally does its thing and I think it'd be pretty hacky to override it for manual stepping (and not a good idea), but you could have a separate world that you step on-demand. Can't say I've tried doing anything like it, nor read anything about it, so dunno how you'd go about doing it. Pretty sure it's possible, though.
That said, why do you want/need to step physics manually?
if i get on a hiatus and come back to my code i'll probably be very confused (this is how my systems communicate btw)
fixed diagram edition
Pausing the simulation (setting time speed to 0) might be part of the solution, though I'm not sure if you can step physics manually.
Two wheel drive, or does the four wheels of one car communicate to two different cars?
not two wheel drive, it's only two as an example
the grounded flag
Ah
Do you need true physics sim for the car?
If you just want it to feel decent for a racing game or something, you could look up how they've done racing games in the past, probably a bunch of simple technically-not-simulation tricks to learn from what people have done before
@olive kite WithDeallocateOnJobCompletion is an attribute you put on your (public or private) attributes on your job struct's native containers
If it's arcadey like a cart racer, you could probably just straight up move the car (and all parts π ) and turn it and whatnot "manually" with no real simulation
no, as in like, close to black box era nfs games or something
got simulation elements but its really arcade actually
"Simcade"
yeah
Like, has drifting and stuff in sharp corners?
yeah
That's a bit more complicated, but should be doable - as mentioned I encourage you to look up how those kinda games did it, you might be surprised by how simple it could be.
i already have a working prototype in regular unity code, converting it to dots rn because awful performance
Ah, if you already have working code porting should be doable
That said, a simcade racer shouldn't be particularly heavy on the CPU...?
and with 100 cars with each having 4 wheels i got 3-4 fps on a pretty alright cpu, if not old (amd a8-6500)
Oh, yeesh, if you're using that many cars, yeah
@tawdry tree too late lol i converted most of code i have to dots
π€· Should be fine if you have the habit of always using a Git repo, even for simple private projects
just need to convert the spawner and rewrite most of it lol
well, i just have two projects
that kinda counts as source control lmao
DOTS is.... tough to work with (or around, as it may be) at times, but if you're decent at the whole software engineering thing (knowing when to use patterns, how to problem solve, and how to find documentation for this f***ing obscure piece of **** library) you should be fine. Oh, but you need more patience than otherwise
Eh, I initialize local git repos for any code project beyond one file of "faster than using the calculator/a spreadsheet", that way I have history and can roll back. Branches are nice too, when I experiment with something that is likely to break everything else
You have 1 big advantage with dots because you have the source to most of it, so if you don't understand something you can always go check for yourself if you're skilled enough
That's true, but the documentation can be both lacking and arcane, and the source code even more so if you're not a seasoned programmer
Using source control even for small projects have saved my butt multiple times after I try stupid shit and then realize I deleted some key code or entire files (or in one case, nuked an entire folder without realizing)
@tawdry tree
That said, why do you want/need to step physics manually?
Server reconciliation, (returning to a snapshot of the world sent by the server and stepping it forward in time so it returns to where we were on our timeline.)
But yeah, how do we even create our own separate simulation world...
Creating a new world is stupidly simple, but then you'd need to populate it with all the systems you need including system groups, which is not so simple.
I haven't messed with worlds and can't really offer more help than that, but that sounds like the Right Way to do it. Hopefully it'll help you with search terms or more pointed questions when asking some of the people who've swam through the deep ends of DOTS.
I love the videos of DOTS spawning 198k ships... would NetCode honestly be able to keep up? I've got to imagine there's an upper limit there.
It depends on how you do the netcode?
@tawdry tree
foreach(ComponentSystemBase sys in World.DefaultGameObjectInjectionWorld.Systems) {
simulationWorld.AddSystem(sys);
}```
would this work?
And I can't find ANYTHING on google. There's so little tutorials and Unity's own demo projects seems like they've been bodged together in 5 min.
Obviously sending the positions of each ship every frame would be bonkers, but if you simulate it both client and server, and have the server just send rotating sync packets (and when big things happen), you can drastically reduce the network traffic needed. One of the things with DOTS is that it's supposed to make it possible to make deterministic code, and deterministic code needs very little network traffic to sync
In other news, I've been fighting with ECS all day, wondering why it wasn't rendering a simple cube decorated with Convert To Entity. I've finally traced it down to one of two libraries that have caused the issue and I can't wait to report this defect because I've lost an entire day on it
@zinc plinth yeah usually it would can be added to the job like: Job.WithCode(() => { }).WithDeallocateOnJobCompletion(nArray).Schedule();
but with ICollisionEventsJob it doesn't allow adding that attribute
@olive kite Tried with actual attributes?
[Attribute]
[DeallocateOnJobCompletion]
@foggy stream pretty sure World.DefaultGameObjectInjectionWorld isn't used like that. The docs are sparse as always, though...
I did find a class DefaultWorldInitialization in the docs, though, which seems to be a helper to create a default world?
@frigid onyx you sure you have hybrid renderer installed? it's needed to render the meshrenderers on entities
and you will also need a render pipeline obvs
and also some features are unsupported
in short, dots is a mess yeah
@maiden delta I finally got it. It's actually the HybridRenderer that was causing the problem.
see?
I added the ENABLE_HYBRID_RENDERER_V2 tag
ah
When you enable it, it has this awesome V2 feature where it doesn't work.
Universal RP
does it have the Hybrid Renderer V2 active, MaterialProperty component type count 52 / 128 in console?
hm
The object is stupid simple. just a default cube, clean project.
with the default material?
are you sure urp is, you know, actually properly set up?
waaaaaaaait
wait
hold on
youre using the built-in pipeline material, not urp's
When I take the setting off, it's fine. When I add the _V2 setting, it doesn't work
herm?
it's called Default-Material, which is a default built-in legacy non-scriptable etc. render pipeline
Did I not RTFM enough?
urp's default material is just called Lit
try doing it again but creating the project from the urp template
Oooh, Worlds have a method Update(), so if you can stop the simulation, you can probably use that to run ONE tick of all systems.
You'd need to set the deltatime, though, which would look something like:
var world = /*get your world, somehow*/;
//Set time
var previousTime = world.PopTime();
var deltaTime = 1f; //whatever you need, here: 1 second
var newTime = new TimeData(previousTime+deltaTime, deltaTime);
world.SetTime(newTime);
//There's also this,
//and I don't know which are corretc to use,
//so you'd need to experiment
world.PushTime(newTime);
//Run update!
world.Update();
//Hurray! Something probably happened, hopefully!
So... who were looking into this? @foggy stream ?
Source in docs:
https://docs.unity3d.com/Packages/com.unity.entities@0.14/api/Unity.Entities.World.html#Unity_Entities_World_Update
try doing it again but creating the project from the urp template
@maiden delta
π€¦ββοΈ I didn't even notice that option. Why isn't this as easy as installing the package?
I'm sure this'll be the issue.
because you have to create a settings asset, needed assets for that, and set that asset in graphics settings set set set set set set
You rock. Thank you for your help.
@tawdry tree Yes! it does work. thank you
I have the hybrid renderer package installed, and added the ENABLE_HYBRID_RENDERER_V2 define to the script define symbols, but 'Hybrid Renderer V2 active, MaterialProperty component type count X / Y' doesn't show up in my console. Am I missing something? I have URP downloaded and a URP pipeline asset in my Scriptable Asset Pipeline settings, and a normal shadergraph green shows up fine on a cube, but I can't seem to use instanced material settings
@maiden delta Following the steps on this page solved my problem, but without you pointing the right direction, I never would have found it. Thanks again. https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@8.2/manual/InstallURPIntoAProject.html
would anyone here happen to have an example of how to use collsion casts as an equivalent of OverlapSphere
@shy pilot
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static unsafe bool SphereCast (ref CollisionWorld collisionWorld, float3 position, float radius, uint mask, out float3 surfaceNormal) {
CollisionFilter filter = new CollisionFilter() {
CollidesWith = mask,
BelongsTo = ~0u,
GroupIndex = 0
};
BlobAssetReference<Collider> sphereCollider = SphereCollider.Create(new SphereGeometry() {
Center = float3.zero,
Radius = radius
}, filter);
ColliderCastInput input = new ColliderCastInput() {
Start = position,
End = position,
Collider = (Collider*)sphereCollider.GetUnsafePtr()
};
ColliderCastHit hit = new ColliderCastHit();
bool hasHit = collisionWorld.CastCollider(input, out hit);
if(hasHit) {
surfaceNormal = hit.SurfaceNormal;
} else {
surfaceNormal = float3.zero;
}
return hasHit;
}
Tell me if you need help with implementing it.
@tawdry tree
gravitySystem = new GravitySystem();
playerSystem = new PlayerSystem();
projectileSystem = new ProjectileSystem();
fixedStepSimGroup = new FixedStepSimulationSystemGroup();
simulationWorld = new World("Simulation World");
simulationWorld.AddSystem(gravitySystem);
simulationWorld.AddSystem(playerSystem);
simulationWorld.AddSystem(projectileSystem);
simulationWorld.AddSystem(fixedStepSimGroup);
World.DefaultGameObjectInjectionWorld = simulationWorld;
GameObject with the ConvertAndDestroy monobehaviour somehow don't get putted in this world. Is there a way to directly put them into the simulation world in an other way?
that looks great @foggy stream, is there any way to get it to return components on the entities that it hits?
i'm looking for a way to get nearby entities with a certain component
without having to loop through all of them
or should i just cut my losses and do that? π
@shy pilot
pw.Bodies[hit.RigidBodyIndex].Entity;
pw being your physics world.
This returns only one entity, for nearby entities, I don't know sadly.
in the GO implimentation of this system it suffered from having to loop through them all every frame but maybe the performance of burst and the jobs system can compensate for that
ok, thanks for the help STUWU :)
i'm not great with writing for optimisation by default
can i get someone's opinion on this?
so i'm making a simulation of an ecosystem
which means inevitably a creature is going to have to flee from a predator
as far as detecting predators goes, i had three ideas for how to go about it
- Run an overlapsphere for each predatory species (on a separate layer each) and if we find one run from it
- Loop through all creatures and check their species, and then their distance if they are a predator and run from it if its too close
- Wait until a predator attacks and when they do, take their entity id, and then query their position and run from it
what do you guys think will be the best approach?
How do I get this to show up for a parameter on my shadergraph?
This is my version, no dropdown arrow:
i'm not great with writing for optimisation by default
@shy pilot
I'm pretty sure they should be rebranding DOTS as "confusion by default" π
hehe
yep lmao
its not that bad really
once you get used to it
its when they dump a demo gif in the docs as the only information on a feature that makes it conufsing π
when i said that i meant i usually go with the lazy solution and don't consider the performance until after there's no going back π
i saw this as an opportunity to fix that
apparently I was looking in the wrong spot. There's a graph inspector in the top right with node settings.
Yeah itβs on top right side , I was confused at first too
@shy pilot an overlap sphere wouldnβt be bad, depends on how many total entities/ objects there are. If it is a big world with a lot of units then implement a spatial hashing system. That is super efficient
ooh, i'll have a look into it :)
Itβs a simple concept, divide the environment space into a grid, and each square of the grid is a bucket. Update the units when they move to see if they entered a neighboring bucket and place them in that bucket. Then if you need to check for nearby units you can just check the bucket and neighboring buckets for units instead of cycling through all units
Iβm sure google can explain it better π
yeah, that looks almost perfect
wouldn't that mean that two entities could be really close an not be able to see each other?
if they are in separate buckets
Yeah thatβs why you check neighboring buckets far enough to reach max distance
Itβs really good, might be overkill but thatβs what we used back when everything was single thread stuff and it worked well with tons of units
I think code monkey did a video on it , if you search zombies vs marines on YouTube in his channel
yeah. One thing i noticed about his approach is that he has a HasTarget component that he adds when the entity has a target
is it not bad practice to rapidly add and remove components or is that efficient?
It's relevant
aren't we always in the latter?
occasionally the first happens, or we wouldn't be insane enough to keep doing what we're doing
I feel like such a dumbass now. Too depressed to keep working
though I'm happy I found out what the problem was
hehe nah
the former is what others see the second is what we see
to borrow a phrase from dear Albert
Theory is when you know everything but nothing works. Practice is everything works but no one knows why. In our laboratory, theory and practice are combined: nothing works and no one knows why!
that is my favourite quote ever
hah
so I'm new to this ECS thing...are gameobjects useless now?
I wanted to turn gameobjects into entities and attach IComponent structs to them and have them work
go's are still useful
what do you do with them?
you turn them into entities, duh
oh and use them to do things that aren't really possible with entities so far, like cameras
^ cinemachine
@foggy stream I had gone to bed and couldn't answer, and it seems like you're away now, but @ me when you're back and I can discuss (assuming I have no work that must be done - I'm kinda on-call).
Setting the DefaultGameObjectInjectionWorld seems sketchy, though.
Any tips why Mesh Collider doesn't work. It didn't display with Physics debug display?
@half jay you're using the GO physics engine right?
im converting my game object into entity and setting collider myself
using unity dots physics
mmk
hmm
are you sure it supports mesh colliders like that?
shot in the dark here but could you try telling it to update after localtoworld?
or localtoparent
i remember there being problems for some people with trying to interact with stuff before behind the scenes calculations are made
you mean change order of adding components?
no
in the system this is being called from, add [UpdateAfter(typeof(LocalToWorld))]
or local to parent
i don't know if it will work, i just remember that fixing a problem for me a while ago when i was messing with either the transforms library or the physics library
Hey ho, can't find Unity.Mathematics in the Package Manager in 2020.1.9f1 does someone have a this issue too?
you need to add it manually now
@pliant orbit welcome to the club π
you add it by pressing the + in the package manager and typing the git url
in your case com.unity.mathematics
good thing I have this bookmarked
hehe
same here, different url tho
after it took me two days to figure out
i had already resorted to redownloading unity 2019 then upgrading the project π
I already did the preview thingy π