#archived-dots
1 messages ยท Page 225 of 1
I somewhat disagree with this. I'm not expecting a stable product, but I am banking on this not being a dead end , and that's what we're afraid of. We're not upset because our hot water heater isn't strong enough and the shower isn't warm -- we're worried someone shut off the hot water completely and didn't tell us, and its only going to get colder.
After messing with it for a while i would honestly not suggest anyone use Tiny until it's been intergrated better with the editor. There's almost no integration with the unity editor and it's just extremely annoying to use in general
With that being said if you want to stick to only dots stuff it's your only option. For making a 2D game in dots without Tiny you have to do a lot of annoying stuff using hybrid gameobjects
I genuinely have a growing fear that DOTS will be walked back completely in the footnote of a release in 5 years.
i would really love to use tiny if you could use it to do a game within a game
it will just be a backend optimization of a monobehaviour workflow
Thank you for your help ๐
no updates (and by "updates" i mean Unity devs telling us "here's what happening") is definitely a problem. i've even converted a couple projects back to "classic" Unity just so i could use 2021.2 because we have no news if and when DOTS will be compatible
or, like the DOTS visual scripting project, some 3rd party company will be acquired and DOTS will be merged with and become a backend feature of that
Hmm unity acquired parsec just recently
So who knows if that live link thing will be a backend of parsecs services
i dont know anything about business so please inform me if i'm wrong about this, but it seems they're doing a lot of acquiring lately and not working on what they already have
acquiring is kind of what all the companies are doing though
They changed gears a year or two ago to focus on improving the core editor. It seems like it's working, from what I hear the core editor is faster and more stable than it has been in a long time
Of course it's frightening. I still have hope
Unreal has been on a huge acquisition binge Unity has to compete
right I couldn't think of the name
superficially one could argue that youre wrong because acquisition is only adding resources, not subtracting from other work. In reality though, anyone who's ever worked in tech knows that isn't true. Acquisition drains your core resources more than project work because you have to integrate the new culture.
Well, lots of people say Unreal engine already beat Unity Engine in 3D
that said, Calabi is right. Unity has to grow grow grow right now. They have no choice at all in the matter, if they don't grow, they'll die, and now that they're publicly owned, they cant do that
Gosh, I just really wish this DOTS experiment had come to fruit and its value was proved before this period of explosive instability
it would be ridiculous and counter productive for Unity to give up with Dots now, its there one edge to compete with Unreal
Not yet it isn't. It's not a differentiator until it has market traction. The acquisitions will all be vying to demonstrate that they are the differentiator
take my word for it when i say its not a dead end
well yeah they have to finish it and prove its value
hmmm. actually I think I will. Because what I was about to say is "Right now all DOTS does is piss off established game businesses, who insist that Unity should stop trying to split its core development in half"
thats pretty much all i can say about the matter though ๐
so, given that.... actually even if DOTS was healthy, I could very well imagine that it might have to operate under fight club rules, like someone suggested
Yeah, you know what, I'm encouraged
well I'm sticking with DOTS till the end
we are using DOTS or rather a hybrid approach in production now
so im sticking with it too!
its painful at times figuring out stuff, but I don't know I like it
If they don't make any updates Unity can't compete with Unreal Engine
Yeah. All things considered, I just don't know how to develop any interest in the non DOTS approach.
you could write your own game engine lol
Fishes gotta swim, birds gotta fly, and I've gotta hate me some OOP
Which will cost a lot of time
yeah I hate OOP as well
lmao
@sour atlas Don't post memes or anything off-topic, please
it was pretty on topic so i thought it would be fine, notice taken though ๐๐
i think it is time to establish the order of DOTS knights and oath words will be "I'm sticking with DOTS and yeah, i hate OOP"
You like DOD and not so much DOTS then ^^
yeah I guess I do
unity's acquisitions for the most part recently feel like just collecting pokemon rather than any real integration into the editor
or any benefits to the end user
I think the multiplay acquisition probably has the most benefits for end users, but its only relevant to you as a dev if you need a server scaling solution for multiplayer
isnt that only a contact us to discuss solution?
no idea how their multiplay stuff integrates with dots networking tho
yea probably most likely
id agree with your assessment but so many of their recent acquisitions havent really joined the fold so to speak, they just exist as their current iterations. multiplay was a while ago and given how badly unity lacks in the networking dept im surprised nothing has really materialized in the sense of better integration or even a blog post talking up how it fits into unitys future
no idea what middle/upper management is doing there so im just patiently waiting :/
the thought of there being technical dept accrued from having to integrate new product doesnt really seem to jive with how unity appears to work. from the tidbits of what devs have said here and there its like teams dont really communicate between each other
yea for sure
im impatiently waiting and its hard not to speculate crap ๐
I kinda just want their latest collections package update to just drop
what are you looking for from collections? it got an update semi-recently
Oh i mainly want to explore the new allocators from reading Joachim's post sometime ago
ah
well 1.0 is preview now so i doubt it's coming soon http://docs.unity3d.com/Packages/com.unity.collections@1.0/changelog/CHANGELOG.html
Yea
the new Collections versions don't work with the rest of DOTS (mainly the Entities package). the last working version is 0.15 iirc
Is it not compatible? I just made a fresh ECS project on 2021.2b5
it's not supposed to be, according to Unity
https://forum.unity.com/threads/notice-on-dots-compatibility-with-unity-2021-1.1091800/
if you encounter any errors using an unsupported release, don't expect help from them
hey guys, my mesh renderer gets converted to an entity then disappears completely on play mode
i have identical settings in a separate project but the mesh does not disappear
I can see the entity with the renderer component in the entity window
it has to do with the subscene they're all in
I'd prob clear out the scene dependency cache and restart the editor
Could solve your issue with rendering @digital kestrel
oh cool, where's the dependency cache?
should be in your assets folder iirc
@coarse turtle thanks, i think it's DOTSNET asset conflicting with Rival Character Controller from the asset store
@digital kestrel any thought on DOTSNET yet ? Didnt have the chance to test it yet
I mean it's from vis2k so I assume it's awesome ๐ but just to get impressions
Hello I try to use Rigidbody 2D using Project Tiny. But for some reason the position of the sprite doesn't update in the Game View. Can someone please help me to fix it ?
Preview 0.32- DOTS Runtime & Project Tiny: Getting Started Table of contents Document Change log 4 What Is Project Tiny and DOTS Runtime? 5 System Requirements 5 For Development 5 For Runtime 6 About Linux support 6 Filing Bugs and Providing Feedback 7 Getting started: use Sample Projects 7 ...
bruh
Hello everyone!
I'm looking into this subscene component by Unity...
And I wonder: is this support navmesh agents? And if it does, how? What if I walk away from a tile, but there are AIs left there.
Maybe some of them are even chasing my player character...
Does anybody have exp with this system, any suggestion regarding my question?
(pls @me)
no it doesn't support navmesh agents at all
Well i cnat see any point of using dots when there are lots of stuff missing
well yeah that's why its in alpha and a work in progress
sad ๐ฆ
thanks for the clarification!
What's a "right way" to pass config data to a BurstCompile'd JobChunk? I can't pass reference types like class MyConfig : ScriptableData. I tried the following, all the alternatives I could think of felt clunky.
public struct TreeGrowth : IComponentData
{
public float age;
}
// Config data I want to be able to set up in editor & easily swap out
public class TreeGrowthConfig : ScriptableObject
{
public float acordDropAge = 4.0f;
public float acornDropRate = 2.0f;
}
[BurstCompile]
struct TreeGrowthJob : IJobChunk
{
// Config data to be passed at job construction.
// Gives error "Burst error BC1051: Invalid managed type"
public TreeGrowthConfig growthConfig;
public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
{
// Boilerplate to iterate thru the chunk, etc...
// Inside the "for each component in chunk" array:
float newAge = growthComponent.age + deltaTimeDays;
growthChunk[i] = new TreeGrowth { age = newAge };
if (newAge >= growthConfig.matureAge)
{
// Drop acorns using the drop rate!
}
the only way to use the job to its fullest multithreaded and with burst is to copy the data and make it local
That makes sense, so change config from a class to struct TreeGrowthConfig and pass that to each job from my TreeGrowthSystem?
And is there some community-standard way to still keep my TreeGrowthConfig easily configurable in editor? I imagine make the struct [Serializable] and expose it on a ScriptableObject or MonoBehavior that the TreeGrowthSystem then references, not sure if there's a better way.
well your using a scriptableobject so I don't think you can change it to a struct ๐ค
if your just reading the data it should be fine
Why can entities also store monobehaviors ? if i understand well you can also iterate through entities and get the monobehavior in store for that entity so what is the draw back for this ? if anything its better because you have authoring + systems to work out the behavior
Right yeah, I mean make TreeGrowthConfig a non-scriptableobj struct and stuff it inside a ScriptableObject "wrapper" that I can then edit in editor
fwiw you can use the conversion workflow to help. E.g. on conversion, create your blittable struct. Then you can declare the SO as an asset dependency via conversionSystem.DeclareAssetDependency(gameObject, scriptableObj); - it will then get converted everytime your SO changes.
Managed objects can't be used in burst/jobs, meaning any component that refers to a managed object also cannot be used in burst/jobs
so its just for the added performance right ?
because i like ecs for some aspects but the authoring is a bit hard to work out while being understandable
Yes the burst restrictions on managed objects is all about performance. If you don't care about performance you can just use hybrid components and stick to gameobjects while still using ECS systems. You would be limited to doing everything on the main thread and you would not gain any performance benefits from using ECS
Possibly still worth it for the code structure you gain from using ECS I guess
yeah I wonder it might be slightly faster than using monobehaviours ๐ค
I'm not sure, there's still a lot of performance overhead (right now) from just systems matching on queries even on the main thread
You mean stuff like GetEntityQuery is slow? Is this only a problem if you're doing it in OnUpdate()?
and is a system update loop automatically slow if you do any monobihavior work in the foreach ?
As far as I've heard it's slower than it can be and they are working on it, but it shouldn't be a bottleneck by any means
alright thanks ! @zenith wyvern
What would be the "correct" way to approach something similar to a state machine in DOTS ?
e.g in traditional states id have "stunned" and "attacking" and i dont want to be able to transition from stunned to attacking.
with DOTS my first idea would be to just use tags but that A) creates sync points and B) ill have these long chains of queries
WithAll<PlayerTag>.WithNone<StunnedTag>()
(in the example it isnt actually a long query but with lots of states you can see how this will grow larger and harder to maintain
couple of ways, the way you mentioned using tags is also valid. You can also just store an enum into a component data and perform switch cases in a system. I was also reading about how flecs handles it (another archetype based ECS written in C) and they have a special component which combines structs (which are your states) together into a linked list. The benefit of that approach was that you can write components as usual and be able to query and filter entities that are in certain states
hrm. might go with the enum approach then, but thanks!
https://ajmmertens.medium.com/why-storing-state-machines-in-ecs-is-a-bad-idea-742de7a18e59 here's the blog post if your interested in exploring it on the side
yeah it makes sense why it doesnt "make sense" in DOTS. ill check the article out, ty!
Unity made their own state machine in dots for a use case example https://github.com/Unity-Technologies/EntityComponentSystemSamples/tree/master/ECSSamples/Assets/Use Case Samples/1. State Machine AI
I'm basically just using a switch case(or If else) for states with enum in my game
You'll find a long post on the forums where people explore state machines in DOTS
yeah there's someone that has some kind of polymorphic state machine they made I think
oh yeah thats clever, ill be using that
ask me again in a month lol :P. I have little experience in networking. Overall, it's very simple to use and pretty reliable, so I would recommend it to people
@sour atlas GOAP AI might also be a solution to replace a state machine. Looks like DOTS lends more to this idea but I haven't had the time to make an actual test out of it.
after some consideration i think were just going to use ECBs and Tags, that seems like the most natural and perhaps easy approach. gonna put a nice wrapper around it and that should work :)
main argument for that being that then we dont have exclusive states but can mix states too
Does DOTS work at the moment with URP/2D renderer and HybridRenderer in 2020.3? I can't seem to get sprites drawn. The quads are drawn but without textures...
i havent tried doing that yet but i think you need the Entities.2D package
This seems to be for Project Tiny
yeah thats why i havent tried it yet either ๐
Is it just me or does Unity feel like a complete mess at the moment. I have been away for a year out of Unity and I expected some learning curve coming back to the updates, but this URP/Hybrid Renderer feels like such a mess. Even the official examples are sketchy, half working at the moment.
yea its not a wrong assessment, multiple versions of many common modules found in a game engine
if I'm interested in messing around with ECS/DOTS for the first time, is there a recommended version of Unity + DOTS packages I should use? Best tutorial/example as an entry point into the tech stack?
the samples repo in the pinned messages is the most up to date place to start
awesome, thanks
Is there an idiomatic way to spawn an entity from IJobChunk.Execute()?
typically by passing in a command buffer to your job struct
well that depends on when you need the entity, if you can defer until later than definitely a command buffer
Deferring is fine, I think I got that figured out. Now I have the same problem I was facing before: I can't pass my config data to jobs so they know how to set up the component...
Current setup is a MonoBehaviour with all the config, who then creates entities using the config data in Start(). From what I understand I can't pass that class to my job ๐
you could just parse all fields "manually" ?
not sure if i understand the problem
but
or pack your configs into a struct and pass that config struct into your job
yeah thats what i was trying to say
GameObjectEntity was deprecated how do you link a prefab to a entity now ?
just make your config data an entity and then you can query for that entity in system updates(as a singletonentity) to pass along the data for jobs
alternatively if the config data doesnt change i think blob assets are the way to go ? not sure, havent used them.
err i'll give it a shot
is there a way to reference a system ? e.g accessing a systems entity command buffer ?
sure GetorCreateExisitingSystem() I think
don't, we all forget stuff sometimes, or maybe its just me 
Can't you do GetComponentArray anymore ? I need to iterate in an update to find a matching entity stored i the component
isn't it ToComponentDataArray()
huh might be thx
(woops didn't mean to reply, deleting this in a sec ๐ )
AFAIK if I want a Burst'd system OnUpdate(), the system needs to be a struct... and to pass a CommandBuffer to my job struct I need one of the FooCommandBufferSystem objects... but I can't store object references on my system struct...?
Are you using SystemBase or ISystemBase for your systems
struct MySystem : ISystemBase
Yeah ISystemBase has limited support
Technically what you can do is create your own command buffer
and then pass that command buffer after it's scheduled to your own custom command buffer system
so that you can do playback later ๐ค (cause you can always submit the constructed command buffer to a pointer to a collection)
I haven't tried that
the struct version is super early days, you cant use updatebefore/after with it
I guess if I'm using Jobs anyway there isn't much practical benefit of the struct version's BurstCompile-ability?
i think there may be some benefits for scheduling...but can't say
honestly my class systems run quickly(under the right circumstances), performance benefits of struct equivalents doesnt really seem to be all that different
maybe if you had a lot of stuff that for some reason needs to be mainthread but cant be jobified but can be bursted you'd see some improvements but I didnt really notice anything that was a big deal. maybe also slower machines or mobile its a bigger deal as im only testing with a desktop
I can't use my EntityCommandBuffer in my IJobEntityBatch (You must call JobHandle.Complete() on the job before you can write to the Unity.Entities.EntityCommandBuffer safely.) Is the following incorrect?
// in MySystemBase.OnUpdate()
Dependency.Complete();
var commandBuffer = m_EntityCommandBufferSystem.CreateCommandBuffer();
var job = new MyJob () { /**/ };
Dependency = job.ScheduleParallel(myQuery, 1, Dependency);
Ahh, I guess I wasn't supposed to use Dependency. This works: job.ScheduleParallel(myQuery, 1).Complete();
is this SystemBase or ISystemBase?
ISystemBase -> i believe you have to call systemState.CompleteDependency() or something similar as the first call
It's a SystemBase now
oh
try yourCommandBufferSystem.AddJobHandleForProducer(Dependency)
you want the your entity command buffer system to be aware of scheduled jobs
Call that after Dependency = job.ScheduleParallel(myQuery, 1, Dependency);?
Yes
I am trying to setup a mesh using RenderMeshDescription, however when I check the entity all the settings I put in the MeshDescription are there apart from the Mesh. Somehow the mesh will not get connected to my entity. Is this a know issue?
Hi all, re-asking this question here. Was wondering if the BurstCompile decorator usage has changed (i have v. 1.4.9) or if I'm missing something, ty!
how do i attach an entity prefab in the inspector to a monobehavior that gets converted to entity(IConvertGameObjectToEntity)
i think you might have to add burst to your assembly definitions
at least last time i had a similar issue that fixed it
Having a quick question here...
I have a inventory component and several item entities.
The inventory component simply stores a list of item-entities inside it...
When i add an item, modify its amount... or remove it from the inventory... i need to check a lots of stuff and modify that item structure.
Normally a inventory would have methods like "add, get, remove"... but this is ecs... so what are common ways to do this ?
using Lists instead of Arrays
im not sure whether theres a NativeList though
i think Dynamicbuffers ?
yeah I think I would use dynamicbuffers
but generally speaking you do not use arrays for things that change in size
@sour atlas Use NativeList if you need some sort of networking/serialization... dynamicbuffers if you want the performance advantage
technically arrays are always contiguous blocks of memory and all languages that allow dynamic resizing just copy the array and assign it a larger block of memory which is slow since everything has to be copied -- this does allow for rapid iteration since theres no cache misses :)
with lists you store a reference to the next (and for double linked lists the previous) element which allows you to easily insert elements
well nativelist is local to the systems
im not sure how native lists work ๐คทโโ๏ธ
oh no i was adressing you
nativearrays/lists/queues etc can't be used on a ComponentData
Ohhhh ๐
UnsafeList is the way to goooo
by the way is there a way to check if a ECB exists ?
if (ecb != null)
Doesnt work so im a little confused ?
it might be because the ecb is a struct, I think you have to check against default instead
its because structs have to be initialised with values
isn't there an ecb.exists or something like that
Cannot apply operator '!=' to operands of type 'Unity.Entities.EntityCommandBuffer' and 'default', candidates are: bool !=(string, string) bool !=(System.Delegate, System.Delegate)
uhh i might be too deep in OOP but calling a method from a nonexistant struct doesnt work or does it ?
It does... because structs cant be null
But it doesnt make sense... because the struct wasnt initialized properly
what if i dispose of the struct ? doesnt it get gced ?
No... because structs are local.... but the content of the struct gets gced ( if theres any content to get gced like pointers and normal classes )
ahhh okay thats neat
theres ECB.isCreated
that should work.
yeah alright thanks that makes snese
okay yeah so reading through the ECB implementation that all makes a lot of sense
though the way isCreated works is funny
public bool IsCreated { get { return m_Data != null; } }
you can get the whole system
_bufferSystem.AddJobHandleForProducer(exampleSystemDep);
need to do this
just declare it public and set it when you schedule the job
ah yeah, forgot that was a thing
It's not great to have inter-system dependencies but sometimes it's the straight-forward way.
yeah it makes sense in this context since i dont want my player attacking when hes stunned and having one system wait for the status system to complete first makes sense
couldn't you just use an event system like the one Tertle posted in the forum
If you can put up with up to a frame of delay (sounds like you possibly could?) then it might be better to instead have e.g. your attack system have a WithNone<Stunned> tag requirement
I mean would that not be better for this sort of problem ๐ค
Not imo. An event paradigm can help but it's a whole bunch of code to add to do something that's very fundamental to working with systems & jobs.
his system seems pretty simple and it has no structural changes and same frame creation and destruction
like you said earlier adding dependencies between systems can be bad for instance what happens if you disable the first system or something
thatll grow unmanageable pretty quick. i thought about using an event system but it seems to directly contradict the data oriented paradigm while adding/removing tags is just the way it is intended
and the dependency is only for a small subset of systems thatll always be running anyway so i dont think there should be any issues there
though i think the way i actually want to do this is different, UpdateAfter probably makes more sense.
I mean adding removing tags is a structural change
The Windows > DOTS > Entities editor window doesn't let me check out the components on entities, and the Window > Analysis > Entity Debugger window's "All Entities" is empty. Am I doing something wrong or is there another window I can use to inspect entities?
they should show in the entity debugger, sometimes there can be a delay until things show up
I never get more than this :/
there should be a whole tab right next to it
Aha! Still, that only shows the entities but I can't view the per-entity component data. Is that possible with the current tools?
that's in the inspector
๐คฆโโ๏ธ thanks!
Burst/Jobs: Only running one chain of jobs & completing it at a time atm, so it's mostly only able to use a single thread until I restructure some other code, but I'm seeing about twice the performance with "Use Job Theads" disabled so it all runs on the main thread - anyone got any insight as to why? This is much of a difference than I'd expect
quick question that might not be entirely dots related but if i have something like this
public struct Foo : IComponentData {}
public struct Bar : Foo {}
will Bar work just like a tag ? if so is there a way to query for all tags inheriting from Foo ?
You cant inherit from structs
Try disabling the JobDebugger if you haven't already
Yeah, that's disabled
ah alright
Unless you're using .Run() that's to be expected. Also, it gets worse, the more cores you have and proportionally much worse the fewer entities you have . Schedule() is better than ScheduleParallel() though.
I think it's mostly the dependency chain resolution that takes the time.
Thanks! that's helpful to know ๐ In this case my scheduling chain is basically just A>B>C>D though ๐ค Maybe I'll play with using run for smaller loads and schedule for larger ones
In my experience you usually have to be processing >1000 entities on a high core count cpu before you take less time on the main thread scheduling a job than just processing them all with Run. So painful.
Not using ECS but processing meshes of various sizes so maybe I'll try using run for smaller ones and schedule for larger ones ๐ค Need to get them scheduling together together, at the moment it's basically calling complete on each before going onto the next
Good luck! If you process multiple meshes at once, using Schedule per mesh is another way of getting parallelism.
Thanks ๐
Anyone else hating relations between entities in ecs ? ... like imagine you are having inventory items as entities and a player entity with an inventory referencing those.
No problem... as long as you do not play around with networking or serialisation ( not the whole world ), then its a freaking nightmare. I get the feeling that an ecs entity should only be something which is not "owned" by something else. Items ( In inventory ) cant exist without an player, so it would make sense to nest them inside him.
But entities are nestable no?
Really ? If you mean this UnsafeList<Entity> it does not nest them... thats only a reference to the entity ( its index )... which as said above, is a pain ^^
Nesting is more like having all components INSIDE the entity itself... Entity{ List<Components> ...} which of course defeats the purpose of the ecs, but is great for "owned" stuff like items. So i really think that pure ecs is not that great at all and a mix between ECS and EC is the best way to go ( In case speed is not that important )
But you could create an Inventory entity, with a Dynamic buffer (for the items) on it and stick the entity onto the player no?
Or is it this referencing that is causing your issues?
Nothing wrong with creating your own unmanaged data structures ๐คทโโ๏ธ
maybe i dont understand the total scope, but is there something wrong with a dynamic buffer/list of IDs for 'owning' an entity/item as a means of nesting?
@north bay Yeah thats right ^^
@coarse turtle Its too much to explain, but the short version is that going the pure ecs road is pure pain for some certain topics/features and only makes sense in a few certain cases.
I started with dots as an ecs purist... it may work for a easy, local game. But i tried implementing everything as an entity and it its a lot of work and very complicated when it comes to relations, serialisation, networking... meanwhile im more fan of having everything in worldspace as an entity and everything else as just pure data/structs owned by those entities ( Player is entity, item just a struct and owned by that player ).
yea I can see your point, i typically don't represent everything as an entity
I do utilize a lot of blob data for look up of inventory values (although mine are just cards lol)
Feels great that im not the only one ^^ going with pure ecs actually wasted months of work finding the best structure, dealing with weird issues etc.
Whats blob data ? ๐ฎ
BlobAssets
Since card data for me is typically immutable and I have a lot of card types
pure ecs doesn't mean that you put all your data into entities ๐
I just perform a look up to grab the correct blob data per system, and cards that fall within the same category - use that blob data, fetch the values I need and perform whatever effect the card does
No ? I was told that you implement every "object" as an entity... like items, buffs, recipes or even buttons. Did i missed the point ?
Does anyone know how to add an artificial delay to a standalone player? Like this screenshot of the editor, but standalone
On windows https://jagt.github.io/clumsy/download
Data oriented design means to choose the best tool for your data
It's not about some random dogmas on how to do stuff
Well said! I recommend this video to anyone interested in data-oriented design: https://www.youtube.com/watch?v=rX0ItVEVjHc
http://www.cppcon.org
Presentation Slides, PDFs, Source Code and other presenter materials are available at: https://github.com/CppCon/CppCon2014
The transformation of data is the only purpose of any program. Common approaches in C++ which are antithetical to this goal will be presented in the context of a performance-critical domain (cons...
Thank you!
Someone posted a website a little while ago about how thinking of entity's as objects isn't really dots
It's about optimal structures for a tic tac toe game
You shouldn't really need to think about entity's at all, they are just a side effect you might sometimes need to access
Do queries get other entities from separate worlds than the world the queries are run in
no
When using HybridRendererV2, does it make sense to apply the DisabledRendering component to entities (to hide off screen entities) even though HybridRenderer applies Frustrum Culling?
is there any way of copying an EntityCommandBuffer ?
why do you need a copy of a specific command buffer
basically im writing a wrapper for component setting/unsetting and since theres no BeginUpdate or LateUpdate i kind of need an intermediary buffer to write to
I have no clue what any of that means ๐
but arent buffers copys anyway there structs that you create when you need them
well its entirely possible im misung the systems at hand, let me illustrate what i mean
actually i think i know how i can do this
thanks
xd
PresentationSystemGroup is effectively your 'late update', because that system group runs in PostLateUpdate
no thats not what i mean, i need e.g LateUpdate to run after the Systems Update function if that makes more sense
oh
you can pretty much inject your own loops using this also if you ever need to: https://docs.unity3d.com/ScriptReference/LowLevel.PlayerLoop.SetPlayerLoop.html
when scheduling IJobFor - I need to pass in the array length when scheduling - if my array is a list produced from a job run previously, how can I schedule them together without completing the array that resizes it first? I'm passing in the list with AsDeferredJobArray, but is there any way to schedule it referencing that array for length?
IJobParallelForDefer doesn't seem to be compatible with the latest collections package & I'm not sure if that's actually what I want anyway (or is this what I want?)
uhh im not sure i understand correctly what do you mean by "completing the array that resizes it first"
The job, sorry!
well if its an array the lenght is fixed anyway
First job adds stuff to list, passes it into new job that loops over list
but its a list you are converting to an array, correct ?
List passed in as an array, yeah
wait, passed in or converting ?
because passing a list in place of an array wont work
Passed in via AsDeferredJobArray
You should use IJobParallelForDefer instead of IJobParallelFor and pass list to field as deferred array and as argument to Schedule
https://forum.unity.com/threads/deferredjobarray-with-ijobparallelforfilter.780836/
๐คทโโ๏ธ
alternatively it might be worth considering whether you need a list in the first place ๐
What if I don't want it done in parallel though ๐ค
why wouldnt you want it done in parallel ?
Order dependant result
hrm. you could use multiple arrays you merge/multiple lists depending on what exact order dependency you have
Basically some elements will be removed, some will be added, but needs to all be in correct order (processing meshes where indexing etc is important)
Slicing meshes repeatedly with a variable amount of cut planes done sequentially
Where due to triangles being split, the mesh can actually get larger or smaller
(since you might either remove a tri or turn that triangle into a tri and a quad)
well theoretically you can compute the maximum number of vertices and use that as the maximum array size and then manipulate in place and just remove all elements that fit a specific (e.g being null or of a null equivalent) criteria and THEN generate the triangles
because im fairly certain both of these tasks can be run in parallel and if you are manipulating large amounts of meshes thats going to be exponentially faster than operating on a single list
Max vertices is insanely large compared to the probable actual vert count (worst case cut would split every triangle into three, but in actuality they generally get smaller)
you could assume a certain max size ๐
not the maximum theoretical size just one thats usually going to be large enough
and if you notice it isnt
you resize the array
its going to be slower than a list in the cases where the size isnt large enough but it is bound to be faster in every standard case
But then if I have to resize get back to the original issue - how do I schedule an ijobfor of the new size before knowing it?
do jobs allow for the unsafe keyword ?
if so i think you could pass a pointer to a size variable and change the value to the appropriate one inside the job
It's more a problem with scheduling the job than the job itself
Since scheduling it needs a fixed size (before any of the chain has kicked off)
i forgot the jobs dont run immediately.
uh well
you could check if the passed size matches the actual size inside the second job and if it doesnt reschedule ?
I guess I could not use a for job and do the loop inside of the job based off the list length, but it feels like I'm missing something here
it might not be a generic approach but finding a generic solution is nonsensical as the most common problem needs to be solved, not every problem
personally id suggest
JobA writes to array with usually large enough size
if not large enough resize array in fixed increments
JobB then generates the triangles
checks if given size matches actual size
if not cancel job and reschedule in fixed size increments
sure the wort case scenario is going to be slow
but the most common cases are going to be lightning fast
Basically, I've already got the jobs setup for doing it for a single plane, then I can complete on that, pass the data back in for next plane, but I could do this all without completing between each of there was a way to schedule for the list size
but there isnt without forcing a sync point
Which the parallel deferred one does
there is with arrays
But I don't want it in parallel
then use a sync point
no way around that
other than scheduling for a size thats definitely going to be larger and just not doing anything when out of bounds
I mean, I could do it fine just without using the for-job, I was wondering if there was a solution without doing the loop manually
personally i cant think of one off the top of my head, sorry
again, id use the array approach!
that said
if you are not going to operate on large amounts of data it doesnt matter anyway
Oh yeah I'm running this on insane amount of data ๐คฃ
if you havent already go watch this talk
its really really good
and the most important thing to me is "dont solve for a generic problem, solve for the most common one"
theres probably going to be a better approach than the array one i mentioned, but id probably use that
its pretty easy to use anyway ^
I'm not solving a generic problem, this is the exact use case
Yes, that is the requirement.
and for any resize operation
More like the entire scene ๐
yeah but most of the operations are going to be inside certain specifications e.g its not going to be more than say 64k verts per mesh
on avarage that is
so why not exploit that and employ the most optimal solution for the avarage problem and use a suboptimal one for the others
Again, my problem isn't the big picture, I have all of that working except for this one scheduling issue
yes but that issue is unsolveable without a sync point
except it's not, because IJobParallelForDefer does it
i think that just defers until the list is being done written to
Yes - the list is done written to when the job is started (it's dependent on the previous job), just not when it's scheduled
well then just use IJobParallelForDefer ? i forgot what the initial issue was ๐
Because I don't want it to be done in parallel! ๐
I just want an... IJobForDefer I guess?
which doesn't seem to exist, making me think I'm missing something obvious
maybe schedule on one thread only ?
even then - I can't schedule it at all since the fixed size needs to be passed into the schedule function
wait doesnt IJobForDefer not allow to specify the amount of threads to use ?
IJobForDefer doesn't exist
I could pass in a max int batch size into IJobParallelForDefer I guess... but I can't use IJobParallelForDefer because it's not compatible with the latest collections package
yeah sorry i meant IJobparallelfordefer
ahhhh
okay now were getting there lol
uhhh
downgrade your collections package ?
can't, need some of the features in 1.0
i hate to say it but then you probably need to use a different approach ๐
whats the error
youre saying its not compatible but whats the actual error
various stuff in IJobParallelForDefer
if you import both the latest versions of jobs & collections packages
ah so its just the typical descriptive DOTS errors
or - any version of the jobs package and collections v1
yeah, since they're not... uh, supporting ECS for a while
(not that i'm using ECS)
you can try importing both versions of the package and change their namespaces to reflect that ?
again though, I don't even want to use IJobParallelForDefer
Just unsure if I can schedule an IJobFor with a non-fixed size
Why would you need IJobFor if you aren't going to do any parallel work?
dont think you can
So, I was under the impression it had vectorization advantages over having the loop inside of an IJob
you could make a job that waits for the first job to complete and then schedules the second job
but if there's not - I can just move the loop inside of the job
since at that point the size is known!
DOTS is just the 10th circle of hell
sure, that's what I'm doing - but i IJobFor needs the size to loop over when scheduled - I don't want to have to complete and go back to the main thread to then schedule it
Uhh I would highly doubt that
no thats now what i mean
Interesting - if there's no performance advantage to IJobFor over having the loop inside of it... that solves my problem ๐
you create a job that waits for the first job to be done and THEN Schedules a third job which is the job you want to schedule right now with the loop size since you already know it at that point
with BURST there are advantages iirc
yeah, that's where I'm unsure
pretty sure it depends on your loop
but if it's just moving where the loop is, the result code might be equivalent pre-bursting?
You can always inspect the Burst Inspector to see what your benefits are
Burst Inspector makes it pretty easy to see what the asm would be per line
I don't think there is a difference tbh
But as @coarse turtle said the Burst Inspector is your friend
hope this makes sense
sadly the documentation doesn't have any clear explanation if it does / doesn't, and I'm struggling to find any information elsewhere ๐
It even gives you little messages telling you how the auto vectorizer doesn't understand anything
but yeah, making both versions and checking in the job inspector and comparing the optimized code is a great idea
i still think you should try to parallelize it though, that way itll for sure be faster
again - can't parallelize it due to the nature of the work being performed
(but I'm still making use of all cores anyway since I'm running the job chain on multiple meshes)
oh fairs
Thanks all - there (probably) not being an advantage for IJobFor over IJob if you're not parallelizing is what I was likely missing
I'll do some tests and check what the inspector says ๐
im pretty sure BURST optimizes for loops but it doesnt understand all of them
i think that was mentioned at the Unite talk on burst
also again, does anyone know if theres a way to copy an entity command buffer ?
I'm not aware of a way besides modifying source code and adding it yourself
You need to copy all the command chains over and allocate new safety handles
Yea, since internally the command chains are pretty much a linked list
128 linked lists + a main thread one ๐
??
i think ?
i couldnt figure out a way to do it otherwise
well
actually i could just ... add a different type of command buffer ....
You can modify source code as much as you want
Copy the package over into your projects package directory and you are good to go
yeah, just copy the files for that package out of /library/projectcache into /packages/ and you can edit it easily ๐
I had to do it for a few packages just to make them compatible with eachother ๐
asked on the forums, maybe one of the gigabrain DOTS people knows a way to do it otherwise ill have to write it myself
which is a hassle.
uh
that doesnt work
package is readonly
^
you might have to change the settings in Preferences > External Tools > Generate .csproj files for: aswell to include embedded packages
more info here: https://docs.unity3d.com/Manual/upm-embed.html
already got that enabled
might be that the actual folder is just marked as readonly, might have to turn that off manually for some ides?
nope if i change anything it complains about the checksum being incorrect and then reverts my changes
what folder did you move the package to?
you definitely moved it out of packagecache and into the packages folder (at same level as assets folder?)
gotta move it on disk, not in unity itself
(as it'll show both those directories as "Packages")
move the folder for your package from <Project>/Library/PackageCache to <Project>/Packages/
and now i can edit them ?
yeah ๐
whats the directory you moved it to
<Project>/Packages/
and you used the file system to move that, not unity project outline?
yup
nvm i was just being a moron and dont actually need this.
i forgot functions could return things
anyone faced a need to remap shared value which contains Entity?
i have CreatedFrom ISCD in my project and this component contains Entity field which is not remapped after moving to another world
anyone tried to use asmdefs with DOTS?
seems like it's unsupported, I just get a InvalidOperationException: type registry is not initialized when I run
I'm using asmdefs with dots and all goes ok (in build too)
public static void Foo(EntityCommandBuffer buffer = null)
{
EntityCommandBuffer buffer ??= <non null value>
}
how do i do something like this ? ECBs are non nullable and im not quite sure how this should be done
anyone able to open DOTS-based projects with Unity 2020.3.16f1? im trying to update a project from .15f2 but it always gets stuck at "Importing". i've tried deleting the Library folder, and even some other unnecessary (probably) folders, like obj, Logs, and Temp
might just have to downgrade
https://docs.unity.cn/Packages/com.unity.entities@0.10/api/Unity.Entities.EntityCommandBuffer.html
ECB is a struct, which makes it a value type, like int or float, you can not assign null to it, however,
C# gives you an option to use null with value types: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types
public static void Foo(EntityCommandBuffer buffer = default)
{
if (!buffer.IsCreated)
{
//whatever
}
}
Would this work ?
ECB is a struct, which makes it a value type, like int or float, you can not assign null to it, however,
yeah i know that ^
public static void Foo(EntityCommandBuffer**?** buffer = null), I havent worked (or ever) with nullable types but this might work ๐ง
EntityCommandBuffer buffer;
if (bufferPassed.HasValue)
{
buffer = Utils.InitialiseEntityCommandBuffer<T>(dependency, world);
}
else
{
buffer = bufferPassed.Value;
}
meh
doesnt seem very clean
i think it might be better to use a method override that takes it as a non optional argument.
iscreated should work
ah thats good to know
public static void Foo(EntityCommandBuffer? buffer = null)
{
EntityCommandBuffer buffer ??= <non null value>
}
is this correct ?
looks like my issue might be with the OS ๐ฌ tried 2020.3.15f2 and still no luck. the only thing i've changed since then is updating the OS version
TIL: System state components are not serialized. Cool. In docs you can read that such components can be used to implement reactive system, but when you need to make save you need to dance with it a little more. I understand that name "system state" means that (and it mentioned in docs) it holds system's state. But that black magic is just annoying. No word about such behaviour of serialization was found by me.
what's the current most common way to name IBufferElementData? Sometimes I find myself naming them after the elements (e.g. CharacterInventoryElement), other times just after the thing (e.g. CharacterInventory) and other times as if they were the list/buffer (e.g. CharacterInventoryBuffer). I can't seem to find something I'm happy with
always with 'Element'
that feels most in line with C# naming convention
I always name them CharacterInventoryBuffer, I guess its not convention but I try and name them after what they are so it's easier to remember
the problem with naming Buffer for me is that when you write inventoryBuffer.Add(new CharacterInventoryBuffer {...}) looks like you add new buffer to buffer
yeah I sometimes purposefully miss spell stuff to avoid that, like I'll write Buffa instead or something
thats a terrible idea
my var naming conventions are a mess/all over the place tbh I should probably stick to some convention ๐
youll end up hating yourself over that when working on something for a longer time
How do you get the entity of a prefab on instantiate ? you used to only be able to just add GameObjectEntity script to the prefab and get the entity variable it stores is it still the good way to do it ?
Thats the new workflow yeah but i need to get the entity on creation this workflow creates the entity but you can't get it on creation
not sure what you mean you need to get it on creation
If you use an IDeclareReferencedPrefabs script you can get the entity that will be created from the prefab via conversionSystem.GetPrimaryEntity(prefabGameObject)
You can use the entity reference in place or store it to refer to later
oh i see i'll try it thx
Is there a way to spawn systems / componentsystemgroups in a specific world by default
I have a package that uses dots but spawns everything in the default world
when I need it in a client world
I just move entities to their respective worlds
so they spawn into the default world which is an empty world for me (only systems I have are systems which move entities into their correct worlds)
@coarse turtle i might do that in the future. For now, I'm going to check the system's namespace and see if it matches my package's namespace, in which case i'll just autoassign it to that world
My player, mobs and other entities are... ecs entities.
I do not want to implement inventory items as ecs entities, because i need to avoid relations between entities as much as possible ( a pain to save, serialise and network ). So i thought about implementing those items as something like this instead NestedEntity{ List<object> components; }
But on the other side... i really want that some of my items execute logic every frame... how would you deal with this ?
is it not necessary anymore to add this tag post 1.4.x version ? nvm i had a missing assembly def
Is there a DOTS Physics equivalent to Rigidbody.AddRelativeForce? I feel like I'm missing something obvious here - I just want my first-person player to move in the forward direction based on which way they're facing.
have u seen Unity.Physics.Extensions ?
Yeah, I've been using ApplyLinearImpulse and it moves my player in world space.
I'm fairly certain I just need to convert a direction from XZ inputs into a relative direction, but I can't find a consistent answer among the forums about doing that.
I've tried various things so my code is a mess but this is my code that specifically moves the player:
Basically if a player presses W, the movementInput.x goes from 0 to 1. Regardless of which way the player is facing, that movementInput data should be used to move the player in relative/local space -- eg. mouse controls looking (covered elsewhere), WASD controls moving.
To rotate a vector you multiply it by the rotation, so in your example that would be: math.mul(playerRot.Value, movementInput)
As long as playerRot.Value is a quaternion which I can't tell from your example
I had to edit the code my brain is still asleep..
You absolute legend, @north bay , that works! Cleaned up movement code:
i might be using it the wrong way but i cant figure out a way to use an EntityCommandBuffer in a GameObjectConversionSystem as those dont have a Dependency to pass into the EntityCommandBufferSystem
Do you have a command buffer system in a gameobject conversion world?
im calling GetOrCreateSystem on it
DstEntityManager.World.GetOrCreateSystem<BeginSimulationEntityCommandBufferSystem>();
well im thinking why do you need a command buffer system in a gameobject conversion world?
I'm not really sure what your set up is either
the whole picture is unfortunately more complicated ๐
however the conversion world doesnt even show up in the debugger
huh. this is stranger than expected
it seems like the stack trace just gets interrupted midway
wait ... do i have to have "convert to entity" checked
ah fucks sake lmao
anyone know of a good solution for behavior trees
@digital kestrel https://github.com/quabug/EntitiesBT
@digital kestrel looks simple right? ๐
why would i use DynamicBuffer over NativeList ? e.g what are the use cases for DynamicBuffers ?
Nativelists are local to systems, Dynamicbuffers are persistent lists you can store and easily get and set from any systems
also you can store relationships between entitys/data which you can't really do with nativearrays
!warn 449620283008090112 Don't be obnoxious and ping random people. If you're not here to participate in the discussions, don't post.
guy#8804 has been warned.
?
Should the ECS manage the loading and filling of UI objects with data ? Quick example...
I want to display an item on the ground... im using the hybrid approach ( selfmade one )... so i have a "ItemOnGround" gameobject and a item ecs entity which stores the data.
The "ItemOnGround" gameobject is spawned in by a system... however that gameobject is pretty generic, it should be used for all kind of items... like wood, goldcoins, a sword. So the icon in it should change accordingly to what type that item entity is.
I found two ways of doing that... the typical MVVM pattern : Script on ItemOnGround Gameobject which reads the item entity and loads the fitting icon
And the ECS way... FillItemSystem, which basically iterates over all newly created ItemOnGround gameobjects to load the icon in the ecs system.
Which one would you choose and why ?
Sorry for that long question but i hope someone understands my question ^^ Its basically : Should i load in a icon by using a script on a gameobject which reads the entity or should a system load that icon instead ?
@stone osprey The ECS one for me is more applicable because all your project logic is written in the same syntax and relations between gameobjects and entities are simple as entities contains all data and systems do all your custom logic. So you can expect the same approaches in your code whatever feature it is.
Thanks ^^ Yeah thats a good point... Would actually look like this.
Entities.ForEach((ref Entity entity, ref Item item, GameObject go) => {
var spriteID = item.icon;
var loadedSprite = LoadSpriteByIDOrWhatEver(spriteID);
var spriteRenderer = go.GetComponentInChildren<SpriteRenderer>();
spriteRenderer.sprite = loadedSprite;
}).With<NewlySpawned>.WithoutBurst().Run();
Are there any advantages when i just implement that ui logic in monobehaviours and attach them to the item gameobject itself ? Or are there disadvantages ?
Because i actually heard somewhere that its not such a good idea to let an ecs control such ui like logic
Why wouldn't it be a good idea? ๐ค
i can just theorize because i have not touched UI with dots, but one of advantage of using classic mono is full OOP support with is helpful with such mutable logic as UI view.
But for me it is not ideal because in that case mono component must know about entities. It is good, when they can use queries, but sometimes you want to cache entity on mono component and for me it leads to unable to load game as just chunks of entities, i need also to reload all my UI components
No idea ^^ but it probably targeted the use of ECS in UI's like Screens with Buttons and stuff... there it would make sense to stick with traditional stuff... its a little bit too complicated too represent all UI elements and ECS entities.
But in this case we talk about sprites in our game world... so its probably a good idea ๐
@frosty siren Thanks, i think i will just use typical OOP structures for UI like screens, but ecs for everything inside the game world itself. I think thats the best workflow ^^
Just a thought but if you go with all these systems, you probably want to be pretty careful with your system ordering in order to avoid making it harder to do anything in parallel with other systems without unwanted sync points. Pretty easy to do in the simple case by associating all such systems in a component system group.
It'll be largely based on the kind of UI you end up implementing. But still wholly possible to use data oriented design approach with UI (there was a mozilla rust talk about UI & data oriented design can't exactly find it). But I also found that using something more declarative such as immediate mode guis naturally work with ecs
also what Timboc said about you'll want to group systems in a systemgroup to avoid unnecessary sync points
Thanks ! Im gonna keep that in mind ๐
Totally... but i think in the current state its faster to just use MVVM or similar OOP based patterns which make use of the default UI components. Otherwhise you would need to reinvent the wheel, translating the current UI solution to something ecs like ^^ Atleast for my project a bit too much work...
the rust talk with UI was primary for a retained mode UI - if I find it I'll link you to it, since it does provide some insights
https://www.youtube.com/watch?v=4YTfxresvS8 here you go
This video was recorded during the Bay Area Rust Meetup in San Francisco, CA, USA on June 28, 2018.
https://www.meetup.com/Rust-Bay-Area/events/251073767/
Raph Levien presented an overview of his new framework for creating a GUI in Rust. He uses data oriented design principles and ideas derived from entity component systems in order to create ...
Thanks ! Im gonna take a look at that ๐
Does anyone's shader cache just break randomly when using Hybrid Renderer V2?
i often get HDRP/Lit shader not compatible with hybrid renderer V2 after I already fixed it the day before (by deleting and rebuilding my Library / ShaderCache folder)
isnt hybrid renderer in preview
not ready for production
you can report bugs, but dont expect it to work all the time
Should using multiple Entities.ForEach's (not nested) be discouraged in a single OnUpdate?
no, sometimes you need to query from multiple archetypes
Is there Animator in ECS?
I tried to use Rig Component and Animation Graph which in Animation preview package but I couldn't make them work....
Is there anyone available who knows which versions of packages should be used with 2020.2.2f1?
I get the following error: "Library\PackageCache\com.unity.test-framework@1.1.29\UnityEditor.TestRunner\TestLaunchers\PlayerLauncher.cs(269,34): error CS0117: 'BuildTarget' does not contain a definition for 'GameCoreXboxSeries'"
If I back up to an earlier version of the test framework, Burst then gets the same error 3x
So try 1.1.20 / 1.1.22
You should also be able to uninstall and reinstall from Package Manager, it should only go up to latest compatible verified version I assume
same thing for Burst, check from Package Manager or this link I provided
Could need some advice...
My server is not dots based... also not c# based, just plain java.
So my server sends a packet to my client... that packet basically contains an entity for my unity ecs to spawn in or even update... looks like this
Entity{
id, opcode
components{
Health{ hp: 10 },
Attack{ damage: 10}, ...
}
}
I receive it and deserialize it using a selfwritten serializer.
The problem is that the deserialization causes huge amount of garbage... because well it creates new nativelists/unsafelists/fixedstrings or boxes them to objects. I wanted to keep the serialisation clean and easy to expand. But this is pretty bad for the performance when the server sends like 200 entities.
How would you deserialize such an incoming packet and convert it into an ecs entity ?
this might be worth checking out
Thanks ! But i think i cant apply this here because i need to deserialize a single entity... not a whole world
just move that single entity to the world then
not sure how well this performs though
Yeah but... uhm... how should i move an non existing entity into a world ? I receive a packet and need to deserialize this into a entity ^^
You just have to try to minimize the allocations where you can. If you're receiving 200 entities in a single frame, that means you can allocate a single native list for 200 entities at once, instatiate it and loop through the list deserializing each entitity one at a time
Are there any patterns for this kind of task ? This actually sounds like a lot of spagetthi like code ^^ because the components ( which are structs ) also require a own deserialisation and because we dont know which entity owns which components a lot of boxing will occur
I'm not sure how the deserilalizer wouldn't know which components belong to an entity, from the example you posted you can clearly see what components are a part of that entity
And if there are patterns I don't know them at least, tehre's a few people here who have a lot of experience with networking, I imagine they might know better
Thats right... im probably still too much in that OOP stuff involved... i do not have that much networking experience but most people explained me the workflow like this...
- Server packs its data into a POJO/POCO Class
- Server translates this class into a packet format and sends it
- Client receives that packet, transforms its back into its POJO/POCO Class form
- Client uses that packet to apply it somewhere... like transforming it into an entity
So step 3 is where the most garbage is created... for example when our poco looks like this
Entity{ int id, List<Object> components... }
Our deserializer would box our deserialized struct components to objects...
Applying this poco to an ecs is however a easy task and should not cause that much garbage
Yes that definitely looks like it would cause a heck of a lot of garbage
@karmic basin Thank you. I hadn't previously found that page, and it'll be useful forever.
Oh wow forever haha. You're welcome, happy coding !
Well, you can change versions right there on the page, so I guess "forever" until that itself changes lmao
Yup, this or the end of the Internets, whichever comes first ^^
Maybe you could re-write the de-serializer to create less garbage. Have it generate nativelists and unmanaged types instead of managed lists and objects
Thats a good idea ^^ the main problem is the boxing i guess... atleast thats what my deep profiling told me.
But does a Entity{ int id, NativeList<object> components } even work ? I guess i would need pointers then... but pointers pin the struct on the heap i guess which is similar to boxing ๐ฎ
I don't think you can't have a native list of objects, no. The idea would be to replace object with structs or native containers of unmanaged types if possible
If you want to get rid of GC you need to ditch the managed objects
Hmm... i dont know how that would look like ^^ could you give a quick example ?
Or use pooling I guess
No, I'm not going to write a deserializer for you, I don't even know what yours looks like. If you understand what causes boxing and GC, then you should be able to examine your deserializer and start making changes. Replace new calls with pooling or replace the generation of managed objects with unmanaged types
Nah thats not what i meant ๐ I just wanted to know if you mean either something like this...
Entity{ int id, Health h, Attack a, ... for every component which exists }
Or some other way i cant imagine yet.
If you don't understand what causes boxing and GC then you need to do some reading so you understand it better
if you serialize it into a byte array and know the struct you can technically just stream the byte array back into memory and reinterpret it back to your struct ๐
well you're just pinning a struct to native memory here. Boxing would mean that a value type would be converted into an object type which wraps the value type
Well thats interessting... so something like this Map<Type, byte array> ? Therefore we could cast the byte array back to its original form ?
Oh so pinning and boxing is different ?
Yes pinning and boxing are different, one is not subjected to the garbage collector and cannot be moved while the other is subjected to the garbage collector and can be moved in order to 'defrag' memory
technically yes, the problem with Map<Type, byte[]> is that you will probably not know the type in compile time. If you have a byte[], you will likely need to convert the byte[] to a byte* and then convert that pointer to a T* ptr as long as its blittable, otherwise you'll need to do some marshalling and such
the unfortunate side is that these are specific solutions and if you're looking for a more generic and performant solution, you'll probably need to narrow down your data types/scope
or what Sark said, do some sort of object pooling to reduce the GC load
You might be able to find more specific help in #archived-networking, just don't mention entities or they'll send you back here, hahah
It doesn't seem like a dots specific problem though, trying to reduce GC on yoru deserializer
Yea, you can probably take a look at some text de/serializers like SharpYaml or SharpToml by xoofx on Github to see how he attempts to reduce GC Load (the guy also works on the Burst team)
Thanks ! Well probably the pinning is the best solution for this... shouldnt cause that much garbage but. wait... event for storing a List<void*> we would need to know the type on compile type to a fuck... ok i guess pooling is the best solution so far
has anyone tried reloading a scene and the subscenes associated with the scene? I've noticed that some entities just don't get reloaded for some reason ๐ค
I guess loading it manually worked if anyone had a similar issue
What's the appropriate way to access SharedComponentData in an IJobEntityBatch? GetNativeArray() doesn't accept SharedComponentTypeHandle, and GetSharedComponentData() requires an EntityManager reference which makes me think it isn't appropriate in the job?
My intention is to pass a Mesh reference to the job so it can update a RenderMesh component. I can't pass references to burst-compiled batch jobs so I figured using SharedComponentData was the way to go.
Yeah that's not going to work either, if anything you can update a RenderMesh's mesh by filling in temporary buffers with vertex/index data and then on the main thread apply that to the mesh. Or potentially you can update mesh data using unity's low level mesh api
Sorry, "update" was the wrong word. I'm new-ing an entity and I need to set the initial mesh/material on the entity's RenderMesh, like so:
// MyIJobEntityBatch.Execute()
var entity = commandBuffer.CreateEntity(myArchetype);
commandBuffer.SetComponent(entity, new Translation() { /**/ });
commandBuffer.SetComponent(entity, new Scale() { /**/ });
commandBuffer.SetSharedComponent(entity, new RenderMesh { mesh = I_NEED_A_MESH, material = I_NEED_A_MATERIAL });
yea dont think you can do that from a bursted job. You might be able to do it in a non bursted job? Haven't tried
Wait sorry, dont think it can work in a non bursted job, believe shared components live outside the chunks and are mapped by indices. I dont remember how to easily grab everything via index with SharedComponents
Okay. How about this: my bursted job really just needs to pick a random location for the new entity; if I can pass something like a resizable array of new locations from the job to the system, the system could do the entity spawning/mesh setting using those locations. No shared component stuff needed, system can just store a Mesh reference.
How do I pass my list of locations from the job to the system?
keep a persistent native container like a NativeList<T>, fill it, on the start of the next frame, read from that native container, iterate and spawn
deallocate the nativelist when you destroy the system
if you need it filled from multiple threads instead of a native list, take a look at NativeStreams instead (or really just have per thread containers)
Ah, I think I remember those. Can't find explanatory documentation anywhere about 'em (just auto-generated API stuff), do you remember where you learned about that?
NativeList/Streams?
I'd look through Unity's Collection tests
Okay uhhh, not sure what I changed but suddenly my system's OnUpdate() isn't called and it doesn't show up in the Entity Debugger, but OnCreate and OnDestroy are stilled called at the start/stop (respectively) of play-in-editor? Signature is still protected override void OnUpdate(), is there some secret "disable systems" button I pressed somewhere?
Does your EntityQuery still selects results ?
Wait it should still show up in Entity debugger
With a run time of zero
Yes there's a way to disable but you would be aware of it (Enabled = false in create or update)
Maybe you moved it to another system group and don't see it anymore where you expect
Or another World ?
Uhm.... git diff ? :D :D :D
Not using groups or anything, if I turn on "Show inactive systems" in the Entity Debugger I can see it with the reported main thread ms of "not run"
In this panel do you see a checkbox unchecked ?
Not in front of computer cant check myself
I mean a checkbox in front of this system, presumably to make it active/inactive
Itโs checked
Erf alright
You could still put the Always Update attribute
But if your Query doesnt match any entity it wont do much anyway
Did you put a CalculateCount () on your Query to make sure ?
Otherwise I don't see why with info you provided but maybe I forgot something
Tell me when you find I'm triggered :)
Oh shoot you know what? I moved my "spawn the initial N entities" into Update because I need to spawn more over time and I didn't want the dupkicate code. Crap.
Adding [AlwaysUpdateSystem] fixed it. Thanks!
Nice ๐
Can't figure out why my capsule MeshRenderer's aren't visible? As you can see, mesh isn't null, scale > 0, and it's supposed to be near origin. Code looks like:
// MySystemBase.OnCreate()
treeArchetype = EntityManager.CreateArchetype(
typeof(TreeGrowth), typeof(Translation), typeof(Scale), typeof(Rotation),
typeof(LocalToWorld), typeof(RenderMesh));
// MySystemBase.OnUpdate()
var entity = EntityManager.CreateEntity(treeArchetype);
EntityManager.SetComponentData(entity, new TreeGrowth() { /**/ });
EntityManager.SetComponentData(entity, new Translation() { Value = position });
EntityManager.SetComponentData(entity, new Rotation() { Value = Quaternion.identity });
EntityManager.SetComponentData(entity, new Scale() { Value = /**/ });
EntityManager.SetSharedComponentData(entity, new RenderMesh { mesh = treeConfig.treeMesh, material = treeConfig.treeMaterial });
EntityManager.SetName(entity, $"Tree_{treeIdx++}");
How do I find a good batch number for scheduling parallel jobs? 128 takes a lot longer than 32 for me. For really large job counts, do I need a higher batch count?
Batch size should generally be chosen depending on the amount of work performed in the job. A simple job, for example adding a couple of Vector3 to each other should probably have a batch size of 32 to 128. However if the work performed is very expensive then it is best to use a small batch size, for expensive work a batch size of 1 is totally fine. IJobParallelFor performs work stealing using atomic operations. Batch sizes can be small but they are not for free.
If you have a very large amount of jobs, it's probably better to not use schedule parallel at all
Since the scheduling / thread switching overhead will be very large
If I use an EntityCommandBuffer to create an entity inside a job, but I need to save the entity inside e.g. a NativeHashmap, how would I go about doing that? Since the entity value is only valid after playback is called. Is there a way to "convert" the deferred entity id to the one that it is post-playback?
I think the entity id should be valid, if you get the entity id from the command buffer and then use that for the hashmap then it should work ๐ค
Nope, the entity id supplied by EntityCommandBuffer.CreateEntity is "deferred"
meaning it isn't valid until you call Playback
which will re-write all entity ids the buffer changes refer to
The error you get if you try it is this one: ArgumentException: All entities created using EntityCommandBuffer.CreateEntity must be realized via playback(). One of the entities is still deferred (Index: -2).
I thought it did work I thought I used it before and it worked
As you can see it uses a negative index internally to "defer" them
how are you using it exactly
you need a RenderBounds component too.
EntityCommandBuffer.CreatEntity
save it to a multihashmap
use it
after playback was called
I mean how are getting the entity from the createntity
It's the return value
maybe if you use a nativearray<entity> instead perhaps and use ECB.instantiate
Why would that make difference
ECB.instantiate just copies an entity instead of creating a new one
The entity value returned is still deferred
I'm thinking maybe that is how I did it before ๐ค
๐ค
can you not just maybe create a bunch of entity's before the job
I don't know how many to create before the job
Also this needs to be pretty efficient
I mean ecb.instantiate isn't really that efficient to be honest
?
its creating a job which has overhead in of itself either multi threaded or single and then playing the commands back on the main thread at a sync point
How else am I going to create entities in a job...
its double the work and much longer than just instantiating with the EntityManager
personally I wouldn't
??????
I dont even know if I need any entities to begin with
The job checks that
It's a very compute heavy operation
I can't just "do it on the main thread"
entity's have to be created on the main thread anyway
you could just do the calculations part in the job get that result out of the job to instantiate the number and whatever else with the EntityManager
Then how am I going to cache a bunch of additional information that belongs to the entity
I can't make any changes without an ECB
I would need to allocate multiple native collections for components and stuff, making it hugely complicated
For potentially no performance gain
ok maybe it is better to use an ECB in your case I don't know the specifics of what your doing
ECB is literally made for creating entities in jobs, I assume unity knows what they are doing and optimize it accodringly
I mean it's used in case you want to defer things to specific sync points on the main thread
I need a sync point no matter what
it doesn't mean its the best performance or always appropriate
Since I am creating entities
Doesn't matter if its an entitymanager or an ecb
The only argument that could be made is the way ECB.playback works, whether or not it batches entities
The other thing I'm not a fan of is I haven't found a good way to schedule the main-thread access after scheduling my job.
Since I would need to create another system that runs at that point, then creates the entities or does whatever
(Similar to how the barrier systems work)
yeah that's why I don't really like commandbuffers
Command buffers avoid that
since the barriersystems already exist
e.g. EndSimulationEntityCommandBufferSystem
yeah I mean if you use that CB then it will schedule it so you should have the entity's by the next frame
Well yeah, it will just do ECB.playback whenever the system runs
What I meant earlier, is I don't like the extra systems I need to create to do this manually, without entity command buffers
Since I would need a second system that runs at the end of the simulation step to manually create my entities
you mean it will do the playback at the end of the SimulationGroup
EndSimulationEntityCommandBufferSystem is just a normal system
it will run at some point and call ECB.playback on all ECBs that were registered to it after the jobhandles added with AddJobHandleForProducer have completed
Although I guess it probably calls Complete on those handles
it won't run at some point the name basically tells you when it will run which is at the end of the SimulationGroup which is the main systems group
by "some point" I mean depending on the system
e.g. EndOfSimulation, EndOfPhysics, etc
ok yeah
I'm not stupid ๐
just checking... joke ๐
Unity also uses ECBs internally for their stuff, so I assume it is fine to use them
It just seems like a big code bloat to never use them if you use a lot of jobs
its more code to use ecbs surely
Why would it be more?
If I don't use them and create entities manually, I need an entire second system that runs at my requested sync point
e.g. (BeginSimulation -> System that Schedules Jobs) -> (EndSimulation -> System that Creates Entities Manually)
yeah I don't know I would just use one system and a for loop or something
But then how am I going to schedule compute heavy work that decides which entities get spawned...
compute heavy are you using the gpu?
No, it's just multithreaded jobs that are computationally demanding
yeah I mean if you can't get the entity from ecb.createntity then it makes it kind of difficult
Yes I think for this I will have to go your route of manually creating the entities in another system later in the frame
I just did a test with an ecb creating and adding components and it worked for me
its probably only specific actions that are allowed
I'm trying to put the entity into a nativearray I'm getting a ton of errors
NativeArray<Entity> archent = new NativeArray<Entity>(1, Allocator.TempJob);
var ecb = endsimcombufferest.CreateCommandBuffer();
Job.WithCode(() =>
{
var tempent = ecb.CreateEntity();
ecb.AddComponent<CurrentShelveTarget>(tempent);
archent[0] = tempent;
}).Schedule();
this.CompleteDependency();
archent.Dispose();```
I did that and it seems to work no errors
but maybe that's not quite right I don't know
the entity's values were -1:0
You are using the ecb to add the value, that works fine
It doesn't work if you cache the return value of CreateEntity
ECB internally remaps the required indices when running playback
But since the cache isn't remapped, the entity value is still deferred (index < 0)
Just write to it
Make sure to create a local copy of the collection struct before, since you can't directly pass it into the job (e.g. with Job.WithCode / Entities.ForEach)
e.g.
private NativeHashmap _hashMap;
...
...
var hashmap = _hashmap;
Job.WithCode(() =>
{
//modify hashmap here
hashmap.Add(...);
}
yeah I'm not sure how you are using it I put the nativearray entity into a public Entity testent and it still seemed to work ๐คทโโ๏ธ
e.g.
var entity = ECB.CreateEntity();
cache.Add(entity);
...
EntityManager.AddComponentData(cache[0], ...);
Would not work
Since the entity passed to entitymanager doesn't exist
I see can't you just do ecb.setcomponent
Yes, I am just illustrating the issue
The above isn't what I have a problem with
I need to cache the entities since I need to keep track of them
That's probably what I am going to do
I'm not saying this is impossible
That's why I just asked originally whether or not it is possible to get the non-deferred value post-playback
There are always workarounds
no yeah I was curious whether it was possible too
I don't think it is tbh
Maybe they could add an overload to playback that returns an entity remap info array, similar to how world serialization works
Which could be used to remap entity values
_renderChunks = new NativeMultiHashMap<int, Entity>().AsParallelWriter();
SpatialMap spatialMap = new SpatialMap()
{
RenderChunks = _renderChunks,
Entities = entities,
Translations = translations,
ChunkCount = _chunkCount,
InvChunkCount = 1.0f / _chunkCount,
Bounds = _bounds
};
InvalidOperationException: The UNKNOWN_OBJECT_TYPE SpatialMap.RenderChunks has not been assigned or constructed. All containers must be valid when scheduling a job.
Im a little confused ?
ah fair enough
Also I'm not sure if you can dispose a parallelwriter
You probably need to cache the actual hashmap to dispose it once the job completes
Use RenderMeshUtility to create your renderable entity. Then you can change the mesh if needed
Are there any good quad tree for dots use out there?
I need to be able to map entities to an int2 and find them quickly (and ideally space efficiently)
at what point is it not a good idea anymore to just use a NativeHashmap?
anyone else get stuck loading a DOTS project at this bit?
Start importing Packages/com.unity.collections/Unity.Collections/FixedList.tt using Guid(f16da17e34bf5f149a196c3f6b32e37f) Importer(-1,00000000000000000000000000000000)
Unity always hangs and i have to force quit. i've tried deleting the Library folder and everything :/
Perhaps remove package from the list of packages to force project error and open project with Ignore errors options?
having some performance trouble after setting collider data for for the PhysicsCollider
๐ฅ
I'm pretty stoked! I finally got my research caliber networking system working. Now back to dots. Can I ask a question? Oh I just did. I meant to say,"How do you shut off rendering for an entity only? How do you shut off everything on an entity completely including collision and scripts?" Thanks in advance, remember if I make it big, anyone who helps me: track me down and demand my shoes, my clothes and my motorcycle, and I'll get you probably something better.
Oh disabled component
sweet learned the search function in discord is better than google for ECS/DOTS
yes, Disabled for entities and DisableRendering for the Hybrid renderer
Much thanks Mr.K, I never left, I just had to really intense coding on networking.
is it possible to raycast to non collider objects [means objects without any collider] with jobs / burst?
How would you know where the ray is supposed to hit without a collider
i tried this many times ago ... [https://assetstore.unity.com/packages/tools/physics/super-raycast-91154]
working without any colliders ...
but its too old ... and too slow :]
Question about setting IComponentData from Monobehavior: https://hatebin.com/mljmyhkvmt
Trying to set IComponentData on a gameobject.
I could just wait til it is an entity, but I'd have to make a script to hold the data til it becomes an entity.
Oh I already have my gameobjects becoming entities.
I was just looking to set their IComponentData properly.
Is there any way to set IComponentData via script on the Intantiated GameObject before it becomes an Entity, or do I have to make a work around temporary script to feed the variables directly into the entity.
I can do both, but the former would be cleaner than the later.
i think you should just use the game object conversion utility
I do.
You're talking about convert to entity?
Yeah, I have everything working. I just was asking if there is a Design Pattern standardized way of doing it.
Or we just in wild west, hack it until it works, cuz I mean I can get this working, nothing holding me back.
Since you can set IComponentData in the Hiearchy /Scene manually...On the game objects.
I assumed you could do it in script too. Or am I wrong?
I guess I might be trying to be OCD is properly formatted code. Wicky Wicky Wild West Style it is.
if you want to change the data on a monobehavior you need to have a monobehavior component attached to it
// Authoring component
class FooAuthoring : MonoBehaviour
{
public float Value;
}
// Runtime component
struct Foo : IComponentData
{
public float SquaredValue;
}
// Conversion system, running in the conversion world
class FooConversion : GameObjectConversionSystem
{
protected override void OnUpdate()
{
// Iterate over all authoring components of type FooAuthoring
Entities.ForEach((FooAuthoring input) =>
{
// Get the destination world entity associated with the authoring GameObject
var entity = GetPrimaryEntity(input);
// Do the conversion and add the ECS component
DstEntityManager.AddComponentData(entity, new Foo
{
SquaredValue = input.Value * input.Value
});
});
}
}
something like this.
Yes I do this.
I think I wanted my code to be too neat and streamlined, assuming the script could do the same thing the scene can. DOTS/ECS is very Wild West.
Hahaha, my funny bug of the month: https://www.youtube.com/watch?v=PJh611IyAFg
Dear community: name my videos. Leave a suggested name in comment.
You can also come to like the only positive zone of the Internet I know: www.twitch.tv/VGMCrazyJim The Bro Zone Layer. (temp)
The #1 video gamer who ever lived with proof! I just missed tourneys due to life problems(college for Starcraft thinking my email invite to Korea was a ...
I'm close to object pooled lasers from the resource folder in a generic one size fits all resource loading and object pooling solution. Should have it done by 7 tonight. Then tomorrow, maybe some online multiplayer battling in and possibly drone enemies(mobs commonly called in mmos).
nope, i think conversion systems are the only way.
though i havent used dots a lot yet. maybe there is a way
Object allocation: parameters array 'requiredComponents' creation
[NotBurstCompatible] public EntityQuery CreateEntityQuery(params ComponentType[] requiredComponents)
in struct EntityManager
do i need to dispose of the ComponentType array ? i dont think so but id rather know for sure.
I'm not sure what you mean here. By disposing that - do you mean you want to dispose it manually or let the garbage collector collect it because the latter would happen
if its gced thats all i want to know
ive been having strange issues with memory leaks, thought maybe this was the cause.
A managed array wouldn't cause a memory leak
yeah i just wasnt sure whether there was some weirdness going on since its inside a system.
//Query all Entities that can be rendered
EntityQuery query = EntityManager.CreateEntityQuery(typeof(RenderData), typeof(Translation));
NativeArray<RenderData> renderDataArray = query.ToComponentDataArray<RenderData>(Allocator.TempJob);
//clean dynamic render chunks
_renderChunksDynamic.Clear();
//Schedule mapping job
SpatialMapJob spatialMapJob = new SpatialMapJob
{
Bounds = _bounds,
ChunkCount = RenderSettings.ChunkCount,
InvChunkCount = 1.0f / RenderSettings.ChunkCount,
RenderDataArray = renderDataArray,
RenderChunksDynamicWriter = _renderChunksDynamicWriter,
RenderChunksStaticWriter = _renderChunksStaticWriter,
RenderChunksStaticLookup = _renderChunksStaticLookup,
RenderChunksStaticLookupWriter = _renderChunksStaticLookupWriter
};
JobHandle spatialMapJobHandle = spatialMapJob.Schedule(renderDataArray.Length, 64);
spatialMapJobHandle.Complete();
query.Dispose();
renderDataArray.Dispose();
speaking of weirdness apparantly the renderData array is never disposed ?
A Native Collection has not been disposed, resulting in a memory leak. Allocated from:
Unity.Collections.NativeArray`1:.ctor(Int32, Allocator, NativeArrayOptions)
Unity.Entities.ChunkIterationUtility:CreateComponentDataArray(Allocator, ComponentTypeHandle`1, Int32, EntityQuery) (at Library\PackageCache\com.unity.entities@0.17.0-preview.42\Unity.Entities\Iterators\ChunkIterationUtility.cs:604)
Unity.Entities.EntityQueryImpl:ToComponentDataArray(Allocator, EntityQuery) (at Library\PackageCache\com.unity.entities@0.17.0-preview.42\Unity.Entities\Iterators\EntityQuery.cs:675)
Unity.Entities.EntityQuery:ToComponentDataArray(Allocator) (at Library\PackageCache\com.unity.entities@0.17.0-preview.42\Unity.Entities\Iterators\EntityQuery.cs:1489)
Ambition.Rendering.RenderSystem:OnUpdate() (at Assets\Ambition\Rendering\RenderSystem.cs:115)
Unity.Entities.SystemBase:Update() (at Library\PackageCache\com.unity.entities@0.17.0-preview.42\Unity.Entities\SystemBase.cs:400)
Unity.Entities.ComponentSystemGroup:UpdateAllSystems() (at Library\PackageCache\com.unity.entities@0.17.0-preview.42\Unity.Entities\ComponentSystemGroup.cs:472)
Unity.Entities.ComponentSystemGroup:OnUpdate() (at Library\PackageCache\com.unity.entities@0.17.0-preview.42\Unity.Entities\ComponentSystemGroup.cs:417)
Unity.Entities.ComponentSystem:Update() (at Library\PackageCache\com.unity.entities@0.17.0-preview.42\Unity.Entities\ComponentSystem.cs:114)
Unity.Entities.DummyDelegateWrapper:TriggerUpdate() (at Library\PackageCache\com.unity.entities@0.17.0-preview.42\Unity.Entities\ScriptBehaviourUpdateOrder.cs:333)
Ambition.Rendering.RenderSystem:OnUpdate() (at Assets\Ambition\Rendering\RenderSystem.cs:115)
line 115 is the line where the renderData array is assigned.
From what I can see from that code I don't think it should be leaking. It would leak if your job was throwing an exception
It sounds like there's another issue that you're not catching. It doesn't make sense that allocating a native container then disposing it causes a leak
If you allocate and there's any other error then will leak. So you need to figure out what's happening between allocation and disposal that's causing that
Also keep in mind that leak warning can be delayed by a frame
Because it's catching the issue after you've stopped playing
it seems im not allocating a hashmap properly
So the editor might not catch up
yeah I can get errors like that sometimes from other problems
_renderChunksDynamic = new NativeMultiHashMap<int, RenderData>();
_renderChunksStatic = new NativeMultiHashMap<int, RenderData>();
_renderChunksStaticLookup = new NativeHashMap<RenderData, bool>();
these seem to be gced ?
im not sure how i can make these use a persistent allocator
its like something else is interfering with the disposal
Native containers don't get garbage collected. And you're not passing in the lifetime specifiers
how do i pass them a lifetime specifier ? rider only generates a capacity field
ah, right. had the same issue yesterday. forgot i need to pass the capacity to be able to pass the allocator. i think.
yeah now it works. thanks!
how do we read a locally captured dynamic / native buffer in an entities.foreach lambda job? I get errors saying I'm writing to it in the foreach lambda when I'm not and marked it as "readonly"
Can you show the code?
next issue
InvalidOperationException: The writeable Unity.Collections.NativeHashMap`2[Ambition.Rendering.RenderData,System.Boolean] SpatialMapJob.RenderChunksStaticLookupWriter is the same Unity.Collections.NativeHashMap`2[Ambition.Rendering.RenderData,System.Boolean] as SpatialMapJob.RenderChunksStaticLookup, two containers may not be the same (aliasing).
what exactly does this mean ? im figuring it has to do with the way im implementing IEquateable for the RenderData component ?
From the error it sounds like "StaticLookup" and "StaticLookupWriter" both point to the same native container?
they shouldnt but maybe i fucked up
If not try putting the [NoAlias] attribute on all the native containers in your job struct
I don't understand aliasing very well, I just know it doesn't like when you pass multiple native containers of the same type to jobs sometimes
But I think it's only an actual problem if they're the same native container
[ClientWorld]
[UpdateInGroup(typeof(FixedStepSimulationSystemGroup))]
public class BuildingHUDProcessInputSystem : SystemBase
{
BeginInitializationEntityCommandBufferSystem _beginInitializationEntityCommandBufferSystem;
protected override void OnCreate()
{
_beginInitializationEntityCommandBufferSystem = World.GetOrCreateSystem<BeginInitializationEntityCommandBufferSystem>();
}
protected override void OnUpdate()
{
Entity craftingMenuEntity = GetSingletonEntity<CraftingMenuComponent>();
DynamicBuffer<HUDToBuildingSpawnVisualizerBufferElement> buttonToHUDInputArray = GetBuffer<HUDToBuildingSpawnVisualizerBufferElement>(craftingMenuEntity);
EntityCommandBuffer commandBuffer = _beginInitializationEntityCommandBufferSystem.CreateCommandBuffer();
Entities
.WithReadOnly(buttonToHUDInputArray)
.ForEach((Entity entity, in HUDInputComponent input) =>
{
int buttonID = input.buttonID;
HUDToBuildingSpawnVisualizerBufferElement bufferElement = buttonToHUDInputArray[buttonID];
Debug.Log("[CraftingInputSystem]: Processing button press");
if (bufferElement.prefab != Entity.Null)
{
commandBuffer.Instantiate(bufferElement.prefab);
Debug.Log("[CraftingInputSystem]: Instantiating CraftingBufferElement Prefab");
}
else
Debug.Log("[CraftingInputSystem]: has null entity prefab. Unable to Spawn");
commandBuffer.DestroyEntity(entity);
}).Schedule();
_beginInitializationEntityCommandBufferSystem.AddJobHandleForProducer(this.Dependency);
}
}
error
The previously scheduled job BuildingHUDMenuSystem:OnUpdate_LambdaJob0 writes to the BufferTypeHandle<HUDToBuildingSpawnVisualizerComponent> OnUpdate_LambdaJob0.JobData.buttonToHUDInputArray. You must call JobHandle.Complete() on the job
Ahh right, I think the issue is that GetBuffer will retrieve your buffer as read-write. So even though you use AsReadOnly the buffer is retrieved as read-write originally. Try using GetBufferFromEntity instead, where you can pass read-only as an argument https://docs.unity3d.com/Packages/com.unity.entities@0.17/api/Unity.Entities.SystemBase.GetBufferFromEntity.html
I mentioned this on the forums and I think I even made a bug report about it and was ignored so I assume it's by design
Also heads up you might run into some incredibly hard to track down dependency issues from retrieving your dynamic buffer on the main thread
You should prefer to retrieve it in your job if possible by passing in the owning entity and using BFE/GetBuffer inside the job
what's BFE?
BufferFromEntity
Nice, well if that's a reasonable jumping in point for an unrelated question... anyone know how CompositeScale works? thats a new thing to me
or, perhaps ill present this as a general strategy question if someone can answer in broad strokes. I'm working on what you might call a "Pinnochio's Nose Problem"
I have an entity made up of a few primitive shapes (pinnochio's head), and one of those shapes needs to change scale (pinnochio's nose) when data on the entity changes (pinnochio_lies++)
anyone have any ideas? do I need to create the nose as a linked entity of some sort?
okay so i have a design problem:
previously i had a RenderData Component set up like this :
public int Frame;
public int FrameCount;
public int MaterialIndex;
public float Depth;
public int Priority;
public Directions Direction;
public RenderFlags RenderFlags;
public float2 Position;
now this i cant do since i want to have RenderFlags and Material on shared components so i can query for specific values.
so now i have it set up like this.
RenderMaterialData => Material
RenderFlagsData => Render flags
RenderAnimationData => Total frames, current Frame, anim speed
RenderDirectionData => characters are 8 directional
RenderTranslationData => Where to draw, and at what depth
however now i cant just store the entire struct as the draw data in my hashmap : private NativeMultiHashMap<int, RenderData> _renderChunksDynamic; - this is what i had earlier
ideally id like a hash map with multiple different type values per key but that doesnt work. do i need a struct to combine all the different components again ? D:
i could just have multiple component arrays and have the hash map hold the indices for each value but that seems suboptimal.
What does this error signify? I'm not sure what part of my code is causing it since it only tells me the system file errors: https://hatebin.com/pybebztraj
looks like theres a missing reference somewhere where you are using AddComponentObject
ty
Turned out to be a missing script
I tracked down the null in official unity: EntityManagerChangeAchetype the part where it checks for nulls, I put a breakpoint.
yeah the error messages could be a bit more precise
Can i use Dynamicbuffers outside of them being attached to an entity ?
e.g
StaticRenderPass = new DynamicBuffer<RenderElement>();
not sure but why not use a nativearray/list?
i had assumed since buffers have a fixed size theyre contiguous blocks of memory like arrays
whereas lists just point to the next adress
unless thats wrong
i could use an array and resize manually i guess.
Buffers have a "fixed size" in which they will fit inside a chunk. Beyond that size they will be allocated on the heap, but are allowed to keep growing
No. A native list is pretty much identical to a nativearray except they do the work of resizing it automatically under the hood
oh. then ill make my life easy and use a list
There are probably cases where a native array will be optimized better by burst but probably not worth worrying about
NativeList.AsArray() does not require me to Dispose of the array, right ?
They both point to the same memory. If you disposed the array you'd be disposing the list
I figured this out by the way. I hadn't realized that GetComponent<> was something you could do without entity manager / in burst/parallel
Anyone know how to update materials from systems? Do I need to hybrid stuff for that? Is this kind of an open problem?
If you're using hybrid renderer you would update it through the RenderMesh component
I probably should have specified, I mean per-instance material parameters. Does that affect that answer? is it still RenderMesh? (I'm looking it up now, you don't necessarily need to answer if that is what you meant)
hmm, it seems like RenderMesh would only be if I were updating the material for all instances, or swapping out the material entirely on this entity, no?
For per-instance you need to update whatever component is tracking what you want https://docs.unity3d.com/Packages/com.unity.rendering.hybrid@0.8/manual/index.html#built-in-material-property-overrides-v2-only
So to change an entity's material color you change that entity's BaseColor component
hrm.. it mentions custom variables but only for stuff made in Shader Graph
Yes, hybrid renderer only supports shadergraph
wait, but hybrid renderer is a requirement of ECS
I have the hybrid renderer, but not Shader Graph. Shader Graph comes with the universal render pipeline stuff, I had thought
Yes, built-in rendering isn't supporting by the current version of hybrid renderer
... I didn't even think shader graph stuff worked all that well with the version of unity that ECS runs well on
It will only support URP/HDRP
I'm confused, how do I have entities installed without shader graph then? isnt the hybrid renderer a dependency of ECS?
No, you don't need to use the hybrid renderer with ECS
You could just use hybrid components with normal MeshRenderers and whatever
huh. well, interesting. Lol, I literally spent the day learning how to write shader code today in order to port a shader I had made in shader graph into my ECS project -- because I thought shader graph and ECS did not play nicely together
Sorry to tell you but you can't use those shaders with the hybrid renderer
Which is unfortunate because as far as I know there's no simple way to write shader graph shaders yet
You're not alone in thinking URP/HDRP/ShaderGraph does not seem well integrated right now, so it's unfortunate that it's all hybrid renderer supports
But that's what they chose to do
I mean that doesn't seem to be true. I have a material that I wrote in HLSL, and I have it on my entity, and it does correctly manipulate the vertices in play mode
so is it just that it will fail if I attempt to build the project or something?
You're probably running v1 of the hybrid renderer I would assume
I don't think that supports the material overrides, which v2 does
To use v2 you need to go into preferences and set a special define https://docs.unity3d.com/Packages/com.unity.rendering.hybrid@0.8/manual/index.html#using-hybrid-renderer-v2
so this is not a package version thing, this is some kind of feature switch thing? where even though I have the latest package version, I'm not using "v2"?
Exactly
and when you say hybrid renderer only support shader graph, you mean that v2 only supports shader graph
well ain't that something
Yup. And the last hybrid renderer release was a little over a year ago. So who knows what's next
i believe you can get around not using shader graph as long as the shader features are set, since you'll generally see in the URP shader source: #if DOTS_INSTANCING (for v2)
huh.. interesting. well, time to push this stuff up to source control because I can 100% guarantee I will brick this project during this sequence of changing renderers and trying to hack these shaders to work
seems to happen every time I try to bring shader graph and entities into the mix in the same project
anyone have any (superstitious or otherwise) belief in a particular version of unity that works best for hybrid v2 and ECS? should I do the 2020.3.16f1? Or should I go back to 2020.2.x because that's the latest version mentioned by the hybrid renderer v2 docs?
guess Ill go with the .3.16f1... you know, for the "long term support"
https://forum.unity.com/threads/notice-on-dots-compatibility-with-unity-2021-1.1091800/ Anything before 2021 should be fine
bleh anxious for updates
anxious about not getting them or anxious about dealing with them when they arrive?
woooh, cool. successfully using the hybrid renderer v2! and I know I was successful, because now nothing in my project renders at all
I don't even... what is supposed to be happening here?
are there some special v2 materials im supposed to be using? I was assuming they would automatically replace the existing shaders
nope, even deleting everything in the scene, creating a cube and attaching a convert to entity script results in nothing being rendered
Make sure you have all the necessary urp rendering assets. And on the assets try enabling or disabling srp batching, I remember that caused some issue back when I was messing with it
And make sure the assets are set up in the rendering settings in your project settings
Once you have all that set up make sure your cube is using the right shadergraph material - should be "lit" by default
I think
haaa, damn it. deleted my assets and recreated the HDRP asset from scratch during an earlier debugging step
and never dragged that bad boy into the graphics pipeline asset settings
is there a way to tell if a given entity has a component? something like entity.has_component<Position>() returning bool
I am trying to call JobHandle.Complete() inside editor [not play mode] and it throwing me this error, any idea why that is?
and yes it works in play mode, just would like to see the effect while editing aswell
It works fine for me with a simple job outside of playmode
Yeah, I am just trying to await the handle inside a async, which I guess changes thread id and just errors out
Item laying on the ground is an entity... my player is also an entity...
My player wants to pickup that item on the ground, so he should walk to it first... I can already detect when he presses "pickup".
I have no clue how i should model that pickup process... would you consider to implement this as an component on the player ?
PickUp{ Entity itemOnGround } and a PickUpItemSystem{} which makes the player with that component move to the item for picking it up ? Or how would you implement this ?
I would assume the player is responsible for his own movement and this system doesnt railroad him (unless cutscene or point&click game ?). I would do it like with gameobjects, but using the dots physics system or distance check if you dont use it. Display a prompt to the player when inside item trigger area, player presses key input, add to inventory, remove from scene, and so on.
So a component if you need to hold pickup data else than the item itself, but it's more about the system, right ?
So you mean the pickup logic should be in the button press rather than in a system ? Yes its kinda point and click ๐ Like player klicks on item, popup appears, pickup is pressed, player should move there to pick it up. But the player is still able to controll his own movement by double clicking somewhere else.
Not in the Button press neither :p
I didnt think much about it but first idea is to have a pickup System
Alright so yeah movement also :)
Ah alright, thanks ๐
So PickUp{ Entity item } with a System that pickups that item once it was reached/collided.
But one problem is... when the player decided to interrupt that action by double clicking somewhere else... the component stays :p
Yep you need actions that are able to cancel others
Like a simpleMove can interrupt a goToAndPickup
Depends on how you built those actions :)
Does this also work in an ECS ? ๐ฎ i just cant imagine how this would look like ^^
surely the action would be so fast that you wouldn't have time to cancel it