#archived-dots
1 messages Β· Page 141 of 1
In which update group should I put a JobComponentSystem that creates a job of type ITriggerEventsJob (it checks for physics)
between StepPhysics and EndFramePhysics i believe
Ok
Hello DOTS community! I'm currently learning this whole DOTS world and I want to use it for a voxel-based game. I'd like to validate some assumptions and decisions with people who have more experience working with DOTS. The topic is kinda long so I made a forum post and wanted to signal boost it here.
https://forum.unity.com/threads/designing-a-voxel-structure-around-ecs.883537/
Any comment, opinion, advice is welcome π
@bronze valley a couple of people here have done various experiments with dots & voxels so will be able to give you much more useful feedback. I'm commenting mostly so you don't feel ignored π - in my opinion 1) There's no need to have an entity per voxel - entities are low overhead but they are an overhead nevertheless, 2) Something like a voxel array per chunk sounds fine to me - there may be more complex strategies for optimisation (like periodically flattening to a giant 1d array?) but I've never done anything with voxels, 3) It's unlikely anyone can tell you straight away what the best architecture is. I understand it's annoying to program things multiple ways but performance will depend a lot on what data sits where, how often which parts are accessed etc. Fwiw I would recommend not over-complicating it to start with - something like what you suggest sounds basically fine to me. It's usually not that time consuming to e.g. change chunks to be filtered by shared components to checking a components value. E.g. re concerns of constraining the size of your voxel array - yes, if you can keep everything in cache, it's faster. But that might not be your bottleneck and ultimately you may end up packing data or storing some of it as blobs or who knows... Just some thoughts. I'm sure more experienced people will step in at some point.
are you sure it's been removed? I still get it I think
and i can not use it on my project
@amber flicker thanks for the reply!
Yes after reading some more about memory fundamentals I concluded 1 voxel = 1 entity is a no-go.
On the other hand, separating voxels into components makes working with them much easier. Maybe in the future I will try to have a doble representation: array of data for "cold" chunks and single entities for "hot ones". Then when a chunk hasn't been touched in a while I "pack" it again. IDK, may work but that's for the future.
You're right about not overcomplicating. I'm gonna try this idea as-is and see how it goes.
Thanks!
@radiant sentinel read it again - that says to use IConvertGameObjectToEntity as the old proxy components have been depreciated
@bronze valley glhf!
if you are already using IConvertGameObjectToEntity it doesn't look like you need to change anything...?
using Unity.Entities; ?
@amber flicker yes
which package version of entities?
@amber flicker lastest Version 0.10.0 p6
works fine for me - perhaps an issue with your environment?
ok i will restart my unity
could also try adding public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem) { throw new NotImplementedException(); } to the body, saving and seeing if it compiles
ihave an error on interface
do you have asmdefs in your project?
? what
assembly definition files - if you don't know what they are then it's probably not the issue - think you can probably search for their existence if you type t:asmdef in the project window if you want to check
Is there a way to destroy an entity and all the children easily? Or I have to get all the children and destroy them 1 by 1?
I am using an ECB
LinkedEntityGroup
there is a buffer called "LinkedEntity" or smth, entities that are linked like this destroyed all at once when you destroy the 'parent'
Unity auto adds this on prefabs
God, a day into writing a AI system in ECS and I'm tempted to drop DOTs for a few years. Found some "resources2 on the topic that are just hilariously bad but praised no end just for existing.
Ok thanks
anyone know if physics collider CalculateDistance returns a negative if its inside the collider?
I am making an authoring to automatically link (LinkedEntityGroup) all the children of a GameObject to the GameObject with this Authoring script.
How can I get all the children (GameObject) from an authoring component? If a child has already been converted, will I miss it in the list of children?
@mint iron pretty sure it does, using it for my cc
hi, why i cant define icomponentdata as structure
@mint iron I'm using MaxDistance = 0 on ColliderDistanceInput, and then simply moving out with normal * - distance
i have not changed code, it is package code
@wide fiber it's both. class and struct. Class for storing managed data per entity
yes i know, but i cant make struct with icomp.. interface
@storm ravine ah ok
@wide fiber @storm ravine look at this refer
really? its struct and i don't want convert to string :/
why unity want kill me with upgrades
Sorry, IComponentData Is an interface, not a struct* (I know the difference between interface, struct and class but I got confused)
What are you trying to do?
i want add my component to an entity
my component is struct and i cant add struct to entity
@mystic mountain thanks, i am trying to do point contains tests on colliders that are not loaded in the physics system. and of course DistanceQueries class is private, FML
@wide fiber yes i know that but its not work because it is struct not a class
today i have presentation and i cant believe this. i should be die or present some damaged packages
The packages are fine, you're using the wrong function overload
does this code compile?
So I switched from JobSystem to SystemBase and after changing OnUpdate in the Systems I get this weird error at runtime:
InvalidProgramException: Invalid IL code in Ioe.Systems.CollisionSystem/Ioe.Systems.<>c__DisplayClass_OnUpdate_LambdaJob1:OriginalLambdaBody (Unity.Transforms.Translation&,Ioe.Components.EnemyComponent&): IL_0008: stfld 0x0400000c
I can provide the trace if you would like..
Switched to latest preview for Entities and HybridRenderer
@stiff skiff wrong overload? i have not changed entities package source code, but it is different from my last project
@radiant sentinel does your code compile?
@warped trail yes , function is different from last versions, i have degraded package but it is different at new package too, i have cleared cache and my appdata packages to re download, but it is different :/
@storm ravine
@radiant sentinel change it to dstManager.AddComponentData<MovementData>(entity, new MovementData());
Itβs not required
I think it is
The function has an overload for T : class , so you might have to enforce the type like this
AddComponentData will work and work without explicit generic type declaration if you put struct
the problem fixed, i have copied my last project packages cache to new one but i know this problem happen for other one, i think they changed source code
@stiff skiff yes but its not true because you cant add class to jobs
You're not adding class to jobs
you're adding a component to an entity
which, since more recent versions, can be a class instead of a struct
public bool AddComponentData<T>(Entity entity, T componentData) where T : struct, IComponentData
public static void AddComponentData<T>(this EntityManager manager, Entity entity, T componentData) where T : class, IComponentData
These both exist now
@stiff skiff its mean i can implement componentData as class?
The latter being behind an #if !UNITY_DISABLE_MANAGED_COMPONENTS
You can implement icd as class
yes you can, but you can't use it in jobs π
@wide fiber yes i know that but its not work because it is struct not a class
@radiant sentinel I've read you've fixed the problem but it should work both with class and structs
You can't use it in jobs, and a lot of the API's dont actually support them
If a raycast starts inside a collider, will that collider be considered?
oops, its mean rider cant detect where : struct overload
if his code compiles then it is problem with ideπ
Its a bit of a weird thing, because normally overloading a function on generic type isn't supported. But it seems to work through making an an extension method
pricebase is struct?
Yes
π ok thanks
thank you
I'm very tempted to write my entire prototype in monobehaviours just to see how it actually performs without DOTs, but god am I deep on the sunk cost fallacy right now. I don't think I could handle it running fine without DOTs.
I've been doing some testing any it seems like the new Shadow Caster 2D component from the URP 2D renderer stuff doesn't work in GameObject to Entity conversion yet, does anyone know when that will work?
@storm ravine Is there no 2D physics with ECS at the moment? What is a work around?
@storm ravine would write his own 2D physics engine
probably π hes written everything else
lmao
Well I wrote not completely 2D, it's 2.5D π
I ended up figuring out my issue. Luckily trying any and all approaches ended up working out π€£
Main collisions in XZ space (unit-unit, unit-building, unit-environment)
But height counts
for arrows
So I should write my own physics engine then?
stones from catapults etc.
So I should write my own physics engine then?
@grim walrus Depends
if you fine with that (collision not so hard thing in 2D)
All depends on what you wan't
only hard body collision - elementary, but if you need water physics in 2D, springs, soft body collision and etc. I will be a bit harder (but not imposible ofcourse)
@storm ravine I only need hard body collision
I need networking so I can't use Tiny
But hard body collision you can implement yourself
I've been planning on using Mirror for networking
hard body collision itself - simple thing, write your BVH implementation and that's all π Or
You can use Unity DOTS Physics for BVH
What's BVH π
ECS itself should
not sure about jobs, you can read forum, I remember couple of threads about that
Ok
I'm pretty sure browser hardware acceleration can't be threaded.
Would be easy to test though
it cant
webasm cant do muiltithreading
there are some tihngs that would allow for it, but the model is restrictive to a huge degree, so its worthless for games
its multithreading its more akin to something like forking a side-process on windows/linux
@grim walrus I messed around with DOTS physics a bit and found that I can do 2D by restricting the degrees of freedom, velocities and positions of all objects so that they stick to a 2D plane. It's kind of hacky but seems to work with simple cases. To restrict all objects to the XY plane I set up the Inertia Tensor to this:
@grim walrus Further I have a "Physics2dSystem" which makes sure that there is no (numerically induced) drift in the restricted axes: https://pastebin.com/pHjrBHwf
webasm cant do muiltithreading
@vagrant surge https://developers.google.com/web/updates/2018/10/wasm-threads
Anyone here ever tried combining DOTS with any AR platform yet?
As a newbie, that's make me curious tbh :3
Just recreated my quick little test in Game objects and ... yeah ok so it does need ECS. I think I need to break out the whiteboard to plan out how to make GOAP ish style AI.
@loud matrix What are you trying to test
I was just testing 1000 entities / 1000 game objects with full motion flight controls as a stress test, in the end only one will be doing the flight with all the rest AI controlled but their logic will be more complex so it was just me seeing if I really did need ECS for this game idea.
And hoooo boy will I
whatever floats your goap!
How long have you been sitting on that one?
just came up with it now π
@loud matrix Sounds good. I've seen even low numbers seem to benefit from ECS, and i much prefer its programming model.
Have you figured out how to do AI in ECS, I prototyped it a while ago but was more of a job/task system
I'm still trying to work out how, not in the best head space the last few days (weeks, month or even year) π π π π so I'm not really able to focus on it properly. I might just build more of the framework around the game and come back to agent AI later
Well if schedule parallel I would imagine a mutex or a thread safe dictionary?
but then you can't use refs
so nvm
ughgugh
I did have some ideas around storing a array of possible components on my agents and a list of their data and have a master agent system decide what one to kick into action at a given time. But not really thought it through further than that.
ah that's neat
to somewhat emulate GOAP
so regular Run() then have a par system fire after the "master"
that has just updated some component data
@loud matrix Have you seen unitys new AI Planner? that is meant to be DOTS compatiable in a few magic unity months
Not heard of it at all, they released much info on it?
Na theres not much, a gameobject preview (https://forum.unity.com/forums/ai-navigation-previews.122/)
@dawn badge Why do you think you need a thread safe dictionary? What are you trying to do?
Also theres the Native Collections which can be wirtten to via threads (Native Hash Map is a dictionary)
yea NativeCollections is what I thought of
but like I said nvm since you can't pass refs from Mono objects into a par job
but maybe coroutines can be utilized and a mutex wait after the ForEach
again what are you trying to do? Can you remove the monobehaviour? covert into components?
storing information about locations on a grid to cast rays
yea so far a small generic list seems to be plenty fast
yea, have a public native list in your "gather/find locations" system
yea might swap to native list. Do I have to worry about destroying the native list? the size will always be the same, I'll just choose when to render
and your raycast system get that system and then loop over them
yea you do, in the system on create you make the list and set its size, then in on destory call dispose
World.GetExistingSystem<SYSTEM>()
also see the CommandBufferSystems (EndSimulationCommandBufferSystem) 2 secs ill find the doc
I just currently have a single Mono sharing a few things between systems but if I can grab info from other systems and schedule par jobs I will get much better perf
oh great thank you so much this gives me hope
I really need to learn more use cases for GetExistingSystem
are you generating the whole level?
Yes
So im planning on a fog of war system(s) 2 systems will be gathering all data up into mutihashmaps<POS,LIST<ENTITIES>> and then another will be depending on those
@dawn badge No just randomly placing stuff
cool that works too
I'm using 3D physics for 2D shapes though for now
But I'm going to need to make my own physics engine soon
ah that is neat @ocean tundra
I only need circle colliders
Any resources for learning how to code that would be welcome
Oh a circle collision is quite simple for 2D
@grim walrus Circle colliders are just distance checks π
private static bool isColliding(float aX, float aY, float bX, float bY) {
var radius = 1f;
var deltaX = aX - bX;
var deltaY = aY - bY;
return ((deltaX * deltaX) + (deltaY * deltaY)) <= (radius * radius);
}
oh very nice
you can pass in a different radius if you would like (I am about to have to for fireballs and such)
but this works so well and is very simple once you learn it
Just adding the physics engine and tying it to a single entity ate up 1/2 my fps, so i decided I'll just make my own very basic one
of course if all you need are circle colliders π
yea like half my frame time is physics π¦
and all im currently using it for is mouse pick raycasts
The physics package seems to need a lot more work, I just need basic gravity free impact collisions (that would be damped anyway to stop players doing 360s) and basic raycasting so it's way more than I actually need.
2D or 3D?
2D you can probs do it, 3D might end up with the same perf because math lol
Yea but i would rather use it now and suffer the performance pain and be able to easy update to latest. As im sure its being worked on
yea that's fair, full control is full control
3D for me, but I'll be chucking the game world up so should be light weight
yea im 3d too, i guess it wouldnt be that hard to chunk the physics as we can make our own physics worlds and step them as we like
the advantage I have is my objects will generally be 10km away from each other :p
Thats actually a really good idea, especially if you can figure out if a chunk needs a update and only update then. Does physics already have a static collider list that dosnt update?
not sure, I was having so may issues with the performance and just getting a version that worked with my other packages I thought I'd rather have the control
@loud matrix wow 10 k is HUGE
Space sim game, I still need to decide what factor i need to scale the numbers up by to not fry the transform component
Very cool, another optmization is you could split into a few different worlds based on distance and update those at different ticks
EG i have Server and Client, my server world updates every 200ms and the client world every update
I did not know you could do that, I was gonna split them for loading only as it would take a player days real world to travel between systems
yea theres something like (DefaulWorldCreate.CreateWorld)
then you can loop over all the sysetms it finds, setup any values you need
finally you call world.Update whenever you want it to tick
the worst part is it dosnt yet show correctly in the entity debugger π¦ so i dont see my systems, just my entities)
I'll have to keep that in mind for once I get AI working
I may just do a full simulation of the solar systems orbital mechanics till i work out AI, somehow that will be a lot easier.
Have each planet auto generate the Lagrange points and generate the worlds there :p
players of a retro style space sim will appreciate the slightly elliptical orbits that play out in real time
this is such a dumb question but with
ref Translation translation
Can I flip the texture using this or do I need to figure that out in:
Graphics.DrawMesh
@dawn badge Theres a scale component somehwere, i think you could flip the scale in that
but your drawing manually with Graphics Draw?
nvm i think I can with var rotation = Quaternion.identity; and just do Quaternion.Euler(0, 180, 0);
yep
What are you flipping the texture for?
walking left vs. right lol
ahh
not sure if drawing manually, if your drawing using the localtoworld matrix then i think the scale or rotation should effect it
or I could just load in a different one..
I would just a have a lot of repeating assets lol
Modifying scale may introduce issues later down the road, so you'd likely be better off modifying the Material component
You can draw with LocalToWorld?
yea thats a good point, you could probably use a custom shader and pass in a property
why am I learning all of this rn
how ... how are you drawing without it?
π i spotted it in the fourms
I to am a god damned idiot who decided DOTs was a good place to start π
and you can take that matrix value and pass it into graphics.draw
oh I don't have "sprites"
In that case Modify the Material in the RenderMesh coponent
ok makes sense
theres a better way,, but i cant find it :/
got it
oh i think it requires the hybrid renderer
I should have it
I'll check that out after seeing if I can do Par jobs with the fact that I can pull in other system data
but if your rendering with graphics.draw it probably dosnt get the same magic
@dawn badge also see this (https://docs.unity3d.com/Packages/com.unity.entities@0.10/manual/ecs_job_dependencies.html)
if you have systems depending on the ouput of other systems
yea, Unfortuanlly that only effects when OnUpdate is called, it dosnt do anything to dependancies
oh within the block.. interesting
and even tho a job is scheduled after another one if theres no dependancy it will try to run at the same time, even if they are using the same data
I'm getting this in console
InvalidOperationException: object is not initialized or has already been destroyed
It is gone now for no reason
oh..
Don't know why it got there in the first place
maybe depending on how many objects something is not created on time?
Dunno
I don't htink so
Project Settings > Editor
i get that exception all the time, but only on my 2nd play
somewhere im not cleaning up correctly between plays
if i change code it causes domain reload and everything is fine
@ocean tundra Should I check either of those?
@ocean tundra Sometimes but now I'm not getting it anymore
hmmm if your not getting it on your 2nd or after run its probably something else
Now I'm getting it again
every time you press play, stop and play again?
π¦ not sure sorry, when i was getting that i was able to reproduce every time
@ocean tundra Quick question, how do you get a rigidbody to work with ECS?
I didnt, i use Unity.Physics
@ocean tundra
not super performant
just tested it, go 10,000 entities colliding at 150FPS
If that's not performant, I don't know what is
oh wow,, ill admit i havnt really tested it very hard
Wait actually 20000
na build should be WAYYYYY better
Editor has a bunch of safety checks to catch us dumb devs making a mistake π
@grim walrus are you trying a build? I'd be interested in how many you can get
ENABLE_UNITY_COLLECTIONS_CHECKS is our lord and savior 
@ocean tundra I'm targetting WebGL, checking now
I didnt realise web gl was a valid target, thought there was threading issue there?
I'm getting this
Failed running /home/elnu/Documents/Unity/2019.3.12f1/Editor/Data/il2cpp/build/deploy/net471/il2cpp.exe --convert-to-cpp --dotnetprofile="unityaot" --compile-cpp --libil2cpp-static --platform="WebGL" --architecture="EmscriptenJavaScript" --configuration="Release" --outputpath="/home/elnu/Documents/Unity projects/gunna.io/Assets /../Temp/StagingArea/Data/Native/build.bc"
Maybe it is because I'm on linux...?
I didn't think that ECS worked on webgl
I just havn't read/heard anything about it. and havnt looked into it
but based on what i know of the job system and burst im unsure they can run in a browser
I would love to be proved wrong π
@ocean tundra Tested it earlier
I got an entity with the DOTS physics system to fall in Webgl
So I'd say that's a success
Also-
Can you get a normal GameObject to interact with DOTS physics?
Or would you have to go via an entity
Another question-
What's the state of networking in Unity tiny?
Is it possible/planned?
hi! Recently installed the DOTSSample pack and have been trying to set up a capture point. I noticed that there is a sample CapturePoint prefab and some corresponding code but I haven't been able to get it working.
I set game mode to 'assault', registered the prefab in the PrefabAssetRegistry, and generated ghost code but the point does not appear to respond in-game.
also tried to see if I could retrieve the entity with this code in the GameModeAssault.cs:
but it returns 0.
any ideas? has anyone successfully implemented capture points?
Can you get a normal GameObject to interact with DOTS physics?
@grim walrus I don't think normal GameObjects interact with DOTS physics.. why are you using a normal GameObject?
@ocean tundra I think DOTS for Web uses Burst compiler (and maybe other tools) to generate wasm / WebAssembly, no javascript
but based on what i know of the job system and burst im unsure they can run in a browser
@ocean tundra yes it works, unity Tiny should support burst on the web (I don't know how jobs are managed but ok)
official word from a Unity dev that they recommend using project tiny for DOTS on Web and that Hybrid renderer/ GPU instancing should hypothetically work on Chrome and Firefox because they support WebGL 2.. but won't work on Safari because they don't or didnt support WebGL 2 at the time of writing only 1 though I know Apple is finally working on adding WebGL 2 support (several years late.)
Is a class called "InputSystem" available in dots? I've seen it in a tiny project, I didn't know that there is an input class for DOTS (I was using old Input)
Input System is not related to DOTS iirc, itβs a separate package.
Ah ok
Anybody here is using unity Tiny?
Do you know if I can directly use some DOTS code inside a unity Tiny project?
I've seen a few videos on YT and instead of for example:
Time.DeltaTime
they use:
World.TinyEnvironment().FrameDeltaTime```
It would be cooler if I could use the systems that I am using inside my DOTS project also in a Unity Tiny project, I don't want to change all these little things
you can use Time.DeltaTime in Tiny
but you can't use anything from UnityEngine
and InputSystem is Tiny's stuff
Ok ty
oh, and you can't use it in editorπ
When will we get an entity editor in Unity DOTS?
Like in Unity Tiny, I can directly create entities, not GameObjects that then will be converted to entities (the current version of DOTS)
soon
ok
Not soon
@wide fiber you mean the OLD unity tiny with dots mode that got scrapped already?
and yeah, not soon at all
Ah ok
So to use pure ECS the only way is by writing code?
No editor to make things easier?
no
New platforms package
### Added
- New component `ClassicCodeStrippingOptions`, exposes Classic's StripEngineCode and ManagedStrippingLevel values.
- New class `RunTargetBase`, can be used to specify deploy targets for pipelines.
### Changed
- Updated `com.unity.properties` package version to `1.2.0-preview`.
- Updated `com.unity.properties.ui` package version to `1.2.0-preview`.
- Updated `com.unity.serialization` package version to `1.2.0-preview`.
- Classic build pipelines will pick development players when ClassicBuildProfile Configuration is set to Debug or Development.
### Removed
- Removed obsolete class `BuildSettings`.
- Removed obsolete interfaces `IBuildSettingsComponent` and `IRunStep`.
- Removed obsolete properties `flags`, `description` and `category` on class `BuildStepAttribute`, as well as the nested `Flags` enum.
- Removed obsolete property `BuildSettings` on class `BuildPipelineResult` and `RunStepResult`.
- Removed obsolete property `Scenes` on class `SceneList`.
currently they want you to use the conversion workflow
:(
if you want "pure" as in no gameobjects on final build, look for recent tiny examples
they have different systems for Tiny 2D and Tiny 3D
Can I use
MyRaycastHit.entity
Instead of:
physicsWorldSystem.Bodies[MyRaycastHit.RigidbodyIndex].Entity
does RaycastHitResult have a field "entity" ?
i think it only gives you RigidbodyIndex, it doesnt give you Entity
Btw, i kinda hit a point where.. i fail to see how to improve my game, like what to do, what kind of mechanics i should implement etc..
i am kinda sad rn
Yes, it has an Entity field that "returns" an entity type (it is a Get, not a function but ok)
yeah, I'll just revert back...
0.4 works fine for me π
I think it fails for me since it can't autoupgrade the properties package
it's pretty common with PM
something else got the dependency with lower version installed before
RaycastHit indeed has Entity field, i guess its much better to just to use it instead thru RigidbodyIndex
I can try forcing both properties and serialiation I suppose
i have never seen that Entity property before, is it a new thing π€
it's just pain to upgrade when you have tons of manually installed things on your manifest
@opaque ledge ok
I also see that my verbose project name was on that screenshot π
I usually keep things simple, but then add more things to the name if I have variants per Unity versions or different renderers
and yeah, after updating these manually, I got it to launch the editor:
"com.unity.properties": "1.2.0-preview",
"com.unity.serialization": "1.2.0-preview",```
do note that I have platforms.windows installed here, it installs platforms and platforms.desktop as well
the build conf asset thing didn't seem to work anymore on platforms 0.3 anymore without the windows package
talking of builds
is there any easy way to get the build logs?
I have a faint memory they exist somewhere but I can't find anything obvious just by looking around
I kinda miss that from unreal and basically every other game engine
hmm, there was a new api about build stuff, i kinda forgot tho
So is it safe to upgrade "Platforms" to 0.4?
oh wait, it does output these to editor.log
I'd just love to have these on build dir directly
or in project folder somewhere
it works for me @wide fiber
@opaque ledge ah, thanks. I see that there's a package named "Build Report Inspector" on PM
oh yeah π
I think the editor log with full logging enabled still gives more of the data I wanted
the report inspector just gives the highlights basically
well, and what files made it to the build etc
So to use pure ECS the only way is by writing code?
@wide fiber Conversion Workflow, Subscenes IS pure DOTS. It's authoring, that you using GO for authoring doesn't make it "not pure"
Ok
I am trying to get the float2 relative to entity rotation.
I've found on internet that I should multiply the vector by the rotation in eulers, but I don't know how to get the eulers from a quaternion
there is a math.forward() function that gives you forward vector of a quaternion, maybe that can help ?
I'll check
i checked the Entity Property btw, it indeed works, so no need for RigidbodyIndex
https://twitter.com/aras_p/status/1258030236219985922 ooh this is interesting π
we'd get disposable ref structs in C# 8
Looks like @khyperia, @lucasmeijer and some others have just landed C# 8 support for Unity 2020.2 a12. \o/
Sorry I am making a 2d game and math.forward doesn't work..
Basically I have a float2 that holds the position of a point. I have set the float2 to (2, 0), so it is at the right of my player.
If my player rotates, I want to also "rotate" the float2, so it should be always at the right of the player, I don't want it to be static
does the player just flip between left and right for the forward?
like in a classic spriterenderer?
/// Rotate <paramref name="point"/> around <paramref name="rotationCenter"/> by <paramref name="degree"/>
/// </summary>
/// <param name="point">Point for rotation</param>
/// <param name="rotationCenter">Point around which <paramref name="point"/> will be rotated</param>
/// <param name="degree">Rotation degrees amount</param>
/// <returns>Rotated point position</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float2 GetRotatedPoint(this float2 point, float2 rotationCenter, float degree)
{
float radians = math.radians(-degree);
float2 distance = point - rotationCenter;
return new float2(math.cos(radians) * distance.x - math.sin(radians) * distance.y + rotationCenter.x,
math.sin(radians) * distance.x + math.cos(radians) * distance.y + rotationCenter.y);
}
Oh I see, you might want to just rotate the point along a pivot
What eizenhorn posted works π
Ok ty
What eizenhorn posted works π
@coarse turtle Of course it works
Anyone have any thoughts or ideas how to handle states in the DOTS world? I saw that the DOTSSample used child entities as "abilities" where one is the death state, not sure if it's the approach I want to go with.
its probably useful to approach it from how the data needs to be used, if you need to iterate on every ability when they exist, they could be either a separate entity or just a component on the parent. A factor would be if you wanted to be able to bulk delete the entities versus being forced to add/remove the component (because you can't delete the parent), and also the cost of linking/updating the parent/child relationship. Having a seperate entity means you're not splitting your main objects' into two archetypes - depends if you want that to happen. @storm ravine thoughts?
First of all, which genre?
@mint iron Hmm I see. Something like first person, action crew game.
But I'm thinking of having it on all sorts of things that can spawn/despawn be broken etc.
Not just on the player, as they have in DOTS Sample.
There is 3 approaches which I use in RTS. One case is component on entity like tag for state - Dead unit, Hungry unit etc, Building affected by some modifier (like food produce boost). Second is component with enum state, for example pathfinding status. And both - when component itself it's state and has substate in enums. Third independent entity which has "reference" to parent\child entities (depends on case it can be component or buffer)
Hmm, I see. And those three variants are three different contexts? You can't have variant 1 interact with variant 3?
its just different ways of coding it, with their own bonus-cons
you can also store a component with a function pointer
enum state is absolute fastest to toggle, for example
but its slightly slower to iterate as it iterates all and has the switch
Hmm, I see. And those three variants are three different contexts? You can't have variant 1 interact with variant 3?
@mystic mountain Well 1 and 2 can coexist as I mentioned
All depends on data
how often you change it
which archetypes size
HOW you change that data (batches or not)
And of course on context
For example if I have Hungry state for unit, it doesn't make sense store it on different entity π
but abilities are not stored in player in DOTS sampleπ€
Because this exact entity Hungry and if I will do something with that entity (like lowering speed as example) I'll doo it exact on same entity because it's marked as "Hey I AM Hungry, process me, a have every thing about me)
but abilities are not stored in player in DOTS sampleπ€
@warped trail I speak about exact context mentioned above
because dots sample is kinda crappy in so many ways
also in ecs networking, adding and removing components is not supported
so child entities are neccesary for a lot of things
the key point there i think is that, if its on the same entity you will have easy access to the other needed data when the state changes.
yup. But on the case of abilities, not even that much
they can be fairly atomic, in a way
Yes they can
plus you have multiple of them, so you cant put it as component
Same like a weapon
plus you have multiple of them, so you cant put it as component
@vagrant surge why so, buffers exact for that π
but buffers arent as flexible
We using buffers for stacking buffs\debuffs π
yeah if i had 15 weapon types, 15 movement types, 10 whatever else types, and tried to add/remove each as a component it would be a nasty fragmented mess
of course if you can have your ability state as an union... then you good
but buffers arent as flexible
@vagrant surge what you mean by that? π
If you have same ability and doesn't matter you have 2 or 3 this ability on entity, it's still same ability, and buffers cover that case π
If they different in their base - well it will be different abilities
With different type π
would that be like an FSM state component with union fields for each? like awareness component, might have a type enum and 3 fields that union different structs and those contain the actual behavior (Alerted, Idle etc) and switch on the type in component to pick the right one?
@storm ravine mostly commenting about separated abilities
of different kinds
so i was mostly thinking of more of a "AbilitySystemComponent" type of thing,where it holds array of all abilities affecting the entity
Well that not flexible for me π You exclude query filtering at that point (huge reason for me against that), you always work with that array when you only need for example operate on specific ability π For me that approach feels much OOP with inheritance and interfaces when you have, for example, IAbility and different abilities implement that π
something i have seen was to use function pointers
but
you have a general "MovementState"component or similar
and it has a literal virtual void update(entity ID this)
and then grabs the data needed from components
movementstate comp is basically a pute interface
And that is OOP way which you truing to mimic in DOD π But of course no one can stop you and it valid and can be used with function pointers
yeah thas basically OOP on top of the ecs
Well conclusion of all top posts @mystic mountain analyse your data, choose what you will do with that data and try appropriate approach for you π
yes that very "common" answer
But its as its is π
All depends
and in DOD land that depends very valuable, because it's data driven and data defines what can do π
definitely. You have all this choices on how to do it, vs the "typical" oop state pattern, so just select whatever works best for your use case
If you have some, not so big, amount of "abilities" my personal recommendation - use components as tag\storage for data state (Dead, Hungry, etc.), I tied some sort of one component which store simple states (simple enums before function pointers ages, for different citizen states, like builder, porter, woodcutter etc.) and in the end I dropped that and decided use defined type for different citizen work states and code become much "cleaner" and intuitive, and feels like real data flow. Plus more built in helpers like filtering\change filtering and querying which is very big boost, nothing can be faster in processing performance than not processing things π For big amount of abilities\states, maybe much convenient for you be function pointers approach. All up to you (no up to data)
so now you have components like WoordCutterJob that has all the state regarding the job of the npc ?
(couldn't completly understand what you said)
Not exactly, but close, I have system which search targets for every worker types in parallel (like woodcutters searching trees and dirtywood storage), and depends on current substate (i mentioned them above), that substates very atomic like HaveResource\Haven't (and in veeery rare cases that can be enum flag) which exist or not in association to current entity (one more bonus, you can operate on different independent states in parallel without concurrency, because it's absolutely different data subset which not aliasing with each other) decide - Search Tree or Storage, that all. Same for storages. It can be one object - Storage, but depends on type of resource (different components - WoodStorage, StoneStorage etc.) it will be included in query for woodcutters of for miners etc.
With that way as I mentioned above we can reduce processing of many things, in addition with any spatial portioning it become very fast and intuitive to process.
@vagrant surge something like this you were referring to? https://gist.github.com/jeffvella/57da54567c7127be4fff7e124a97f5f8
This is approach to which I rewrote our citizens and resources systems when we decided (month ago) rewrite game core and use addressables and completely remove all old roots which was from before-DOTS ages when we started developing that game.
@wide fiber I need to get networking to work, I am using Mirror
I was going to make the player objects GameObjects so they could network/ use input
But then again I need to network my entities too
@storm ravine Cool thanks! (thanks all who put in their input)
Maybe I should just not take it as such a finished product, but in the DOTS Sample they seem to take little regard to not using causing sync points by playbacking entitybuffer outside of the set sync points of begin/end. I've currently tried to only use the set syncpoitns + 1, causing workarounds with how I handle stuff etc, I thought this was more or less a hard rule for perf?
it depends on how ham you go. The sync points harm multithreading, but if your game code goes fast enough with 1 core, thats not even a problem
@grim walrus ah ok.. I don't know, I've never used networking "seriously", so yeah
@bold pebble Hey, your Physics2dSystem is giving me errors
I'm getting
Assets\Scripts\Physics2DSystem.cs(22,72): error CS1061: 'quaternion' does not contain a definition for 'ToEuler' and no accessible extension method 'ToEuler' accepting a first argument of type 'quaternion' could be found (are you missing a using directive or an assembly reference?)
Assets\Scripts\Physics2DSystem.cs(23,15): error CS0023: Operator '.' cannot be applied to operand of type 'void'
Not sure what is the issue
What's the preferred way of handling procedural meshes in DOTS? I don't think using RenderMesh is appropriate since it's Shared, and all the meshes would be unique...
currently I do a managed ComponentData with a Mesh field in it
and temporary buffers to do all my mesh vertex manipulations
how do you managed ComponentData?
class MeshContainer : IComponentData, IEquatable<MeshContainer> { public Mesh m; public bool Equals(MeshContainer other) { ... } public override int GetHashCode() { ... } }
oh what I thought IComponentData could only be a struct
they introduced managed component datas sometime ago - they cant be accessed by jobs tho
still that should work for me, thanks
I don't suppose anyone knows why a physics object would not be displayed, when using Dynamic or Kinematic(I'm pretty sure its not falling through the floor, and I do have the hybrid renderer) π€
Did you remember to put something on it to render?
yeah I think so, it renders when its static just not with the others
Did you try and and check the position of the object in the inspector?
Is Vector2 the best way of storing vectors in a IComponentData?
See if it's moving at a gazzilion miles an hour for some reason?
float2 @grim walrus
Practically identical but it uses the mathematics package
@tardy locust What's the advantage of that?
I am pretty sure it's better packed
But I could be wrong. Either way, float2-4 instead of vector2-4
it doesn't appear to be flying around all values are normal
It should also be said that your components (like transform and whatnot) are using these structs
not vectors
@tardy locust Ok noob question here
@pliant pike Hm. And you are sure this only happens when you apply the physics? What if you remove that component?
What is the GetComponent equivalent in ECS?
Er
Or am I thinking about this wrong
You should have an entity already
And then you get the data, from that entity
Which is to say, your entity is just a number. The engine then goes and fetches all data that's tied to that entity
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Transforms;
public class InputSystem : SystemBase
{
protected override void OnUpdate()
{
float deltaTime = Time.DeltaTime;
Entities.ForEach((ref InputComponent inputComponent) =>
{
});
}
}
Here's what I have
How do I apply the data in the inputComponent to the transform component?
Well this will automatically look for InputComponents and then you process the reference to those
Well
You could just do
Do I have to put some other value into the ForEach?
ref InputComponent inputComponent, ref Transform transform
This way you get all entities that have both components on them
I think maybe because it was because the physics objects were a subobject of an empty object
they were going haywire it just didn't show for some reason
Right
Also what's the difference between .Schedule(), .ScheduleParallel(), and .Run()?
To execute a ForEach construction, you have three options:
ScheduleParallel() -- schedules the work to be done in parallel using the C# Job system. Each parallel job instance processes at least one chunk of entities at a time. In other words, if all the selected entities are in the same chunk, then only one job instance is spawned.
Schedule() -- schedules the work to be done in a single job (no matter how many entities are selected).
Run() -- evaluates the entity query and invokes the lambda function for each selected entity immediately on the main thread. Calling Run() completes the system Dependency JobHandle before running, blocking the main thread, if necessary, while it waits for those jobs to finish.```
Is anyone else getting this error spamming their console after finishing running after updating to b8? InvalidOperationException: object is not initialized or has already been destroyed Unity.Entities.ComponentSystemBase.CheckedState () (at Library/PackageCache/com.unity.entities@0.10.0-preview.6/Unity.Entities/ComponentSystemBase.cs:333)
@winter depot I was getting that error randomly the other day too
It happens randomly, couldn't figure out why. It wasn't preventing anything from running though
As for .Schedule(), .ScheduleParallel(), and .Run() I think I understand better now
But what are the use cases for each of them?
Does it depend on priority...?
Performance i think
So it would change depending on if you have only a few/a lot of a certain Component to iterate through?
Schedule as much as possiable and if you have loads of entities use schedule parallel
Ok
it usually is based on the complexity of the job
Wait I thought parallel does single if it only needs
I only use Run when i have to have something on the main thread or im interacting with classes
sometimes I forget to put parallel
So player object use .Schedule(), and if you have thousands of world objects use .ScheduleParallel()?
if your job is simple enough and might have a lot parallel
I always .ScheduleParallel()
So I should use .ScheduleParallel() for everything...?
If you can I would say yes
if you can yes, it wont hurt anything
Alright then I'll do that. Thanks for the help
yea that makes sense, I guess i need to change all mine now π
But unless its 100% pure ecs you will need WithoutBurst().Run() for things
yeah your gonna run into lots of cases where you need Run()
yea its super annoying
@low tangle Wait so I should use .Run() if there are a lot of something?
also, some job chains you might be hashing, then using that data 1:1 with a small pool of entities
I'm still rather confused
Run is main thread
Only thing not ECS in my project is UI
think monobehaviour stuff
Do parallel
let me make a example
Now I'm getting this
...\Assets\Scripts\InputSystem.cs(12,9): error DC0023: Entities.ForEach uses managed IComponentData InputComponent&. This is only supported when using .WithoutBurst() and .Run().
if your job is simple enough run is faster than scheduling even a single worker job
When doing parallel
so thats a case where you are forced to use Run. inside that code your calling a class somewhere
unless your n is high enough
like everything in ecs it depends
you want to be building in habits for success though
not over analyzing every single system for max performance
This is my code
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Transforms;
public class InputSystem : SystemBase
{
protected override void OnUpdate()
{
float deltaTime = Time.DeltaTime;
Entities.ForEach((ref InputComponent inputComponent, ref Translation translation) =>
{
translation.Value.x += inputComponent.input.x;
translation.Value.y += inputComponent.input.y;
}).ScheduleParallel();
}
}
What am I doing wrong?
Show us InputComponent
pretty sure it will be public class InputComponent : IComponentData
I'm so used to classes I automatically wrote class haha
and also if your not changing anything in InputComponent (its readonly) change ref to in
using Unity.Entities;
using Unity.Mathematics;
[GenerateAuthoringComponent]
public struct InputComponent : IComponentData
{
public float2 input;
}
So this is better?
yup
and when changing ref's to in's i think in's go last
if your using vs that is
yeah it goes managed, ref, in, no keywords iirc
if it red squiggles just move it
ez
do entitydebugger timings only include main thread? or how long the jobs took across all threads
and if so is there a way to check how long it took across all threads
trying to make debug tool for how long entire world took to update including all threads
Oops forgot to multiply by deltaTime that's why it was going so fast lol
entitydebugger shows only main thread
the profiler somehow manages to get the job run times tho
hmm
@hollow sorrel i would be very interested in the answer when you figure it out. i have a few custom worlds and getting individual timings would be great
they dont
not till the new one comes out
heres that simple contrived example
struct MyPlayerInput : IComponentData
{
public float H;
public float V;
public float MoveSpeed;
}
struct MoveForward : IComponentData
{
public float2 Value;
}
struct MyPosition : IComponentData
{
public float2 Value;
public float Rotation;
}
class TestExampleSystemFactoryWorkerSystem : SystemBase
{
protected override void OnUpdate()
{
//there will only ever be one in my game
Entities
.ForEach((Entity ent, ref MyPosition pos, ref MyPlayerInput input) =>
{
float deltaX = math.clamp(input.H, -1, 1) * Time.DeltaTime * input.MoveSpeed;
float deltaY = math.clamp(input.V, -1, 1) * Time.DeltaTime * input.MoveSpeed;
pos.Value += new float2 { x = deltaX, y = deltaY };
}).Run();
//there will be anywhere from 1k -> 100k
Entities
.ForEach((Entity ent, ref MyPosition pos, ref MoveForward forward) =>
{
pos.Value += forward.Value * Time.DeltaTime;
}).ScheduleParallel();
}
}
since there is only ever one player, it makes more 'sense' to .Run() it
and since there is 1000 - 10000 of the other entities you would want to ScheduleParallel() it
which you can do because this is a very simple foreach
gotta remember to not overcomplicate examples
One more noob question.
Structs cannot have their values changed after being created, right?
they can have them changed
might be thinking of const? or readonly?
they are value types if thats something you've heard of
Hi guys, I was wondering if someone could tell what is the good reason for using blobassets over simple entity+cdfe<readonly> for immutable data?
@low tangle It was just because VS glitched
gotcha
I think the use case for blobassets are things that will NEVER change, like animation data
For some reason the struct parameters weren't coming up
Also is using Input.GetAxis the way to get input in ECS?
Or is there a whole new way
thats the most basic way thats totally fine to use
@low tangle That
is weird because it gives me errors
using UnityEngine;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
public class InputSystem : SystemBase
{
protected override void OnUpdate()
{
float deltaTime = Time.DeltaTime;
Entities.ForEach((ref InputComponent inputComponent, ref Translation translation) =>
{
inputComponent.input.x = Input.GetAxisRaw("Horizontal");
inputComponent.input.y = Input.GetAxisRaw("Vertical");
translation.Value.x += inputComponent.input.x * deltaTime;
translation.Value.y += inputComponent.input.y * deltaTime;
}).ScheduleParallel();
}
}
ah
just like you did the deltaTime?
you have to do that for most things you need to bring into ecs
...Assets\Scripts\InputSystem.cs(14,13): Burst error BC1033: Loading a managed string literal is not supported
Oooh
so cache the Input.Get's above into floats
yep
Just curious, why?
you need to think of the ForEach inside code as a totally different world
it might run on the main thread, or any number of other threads
so to make it simpler unity's compiler asks you to make it into a local variable, so they can be sure you don't modify it somewhere else while it runs.
You should Run for main threaded work which can't be done on worker threads. If code can be processed on worker thread better is use Schedule (if it can't be parallelized) because of freeing worker thread, and not interrupt dependency chain for readers, if that code can be parallelized without RC and memory aliasing - choose ScheduleParallel
this also allows them to copy it simpler to the other threads when you use Schedule() it
thats the wordy technical reason to use run vrs s or sp yeah
Are you talking to me? All this stuff about threads is going right over my head π
Yes it is
alright
But after that worker threads and all that I was a bit lost
yeah dont worry
Yeay! My ECS movement worked!
eizenhorn has been doing this since ecs came out
he knows all the internals and what not
Now time to test to see if it works on WebGL

Not ECS but just Job system, has anyone checked on multithread related things on mobile?
Hi guys, I was wondering if someone could tell what is the good reason for using blobassets over simple entity+cdfe<readonly> for immutable data?
@eager jungle Because of memory. Blobs stored in preallocated memory block (200mb per scene) and not consume your chunks memory. Your BlobAssetReference in simple words - just pointer (fixed 8byte size) to some piece of that memory, thus instead of store all that data on entity and reduce count of entities in chunk (because that data will take it size from chunk memory per entity) you just store pointer to that memory. It's just excluding data duplication, reduce memory usage, freeing chunks for important things
both work on android fine @lusty otter
Sure, but I meant more about ScheduleParallel vs Run stuffs.
same reasons you would use either
Scheduling overhead, and generally how many worker threads we have.
its the same as pc, number of cores - 1
My job stuffs isn't very expensive and I start to think maybe do some optimizations on that, rather than always do schedule parallel I'll just do run for low count jobs.
and again, the scheduling overhead is part of the job system unity wrote so other than os quirks (its linux) its going to be the same
@lusty otter you can limit the # of worker threads if you choose to, I wrote an option to do that on mobile
yeah theres that one static count you can set
psuong after using the managed ComponentData for the mesh, how do you get the render system to pick up on it?
@coarse turtle Can you limit the number of worker threads per World?
@opaque escarp You can use BatchRendererGroup or Graphics.CommandBuffer to issue instructions to render things on screen
ty
I'm not looking to limit the worker threads, just wondering if there's a "simple rule of thumb" that I can do to determine ScheduleParallel vs Run.
thanks @storm ravine. Not sure to get the data duplication thing though. If we create only one entity holding the data, and this single entity is being referenced everywhere it is needed (like the blobasset reference would be), is that really a problem? is that really different?
thanks @storm ravine. Not sure to get the data duplication thing though. If we create only one entity holding the data, and this single entity is being referenced everywhere it is needed (like the blobasset reference would be), is that really a problem? is that really different?
@eager jungle That entity will take whole chunk - 16kb
again its pretty much the same as pc, except intuitively since we have more lower powered cores on mobile I'd assume you would want to be more multi core happy
@ocean tundra what @low tangle said
since your going for a slow vsync and idle the rest of the time, divide and finish the work faster
@storm ravine that makes a lot more sense now, thank you
Does it cause more energy consumption, as in battery dies faster?
basically rush to idle
well if your not vsynced sure
but why you want to crank out 1000fps on mobile is beyond me
Both iOS and Android force vsync afaik.
You can't even go beyond it even if you tried.
pretty sure android unity let me
but your probably right
either way, basically what I said before
vsync idle should be the majority of your games cpu time
Hmm okay, so I guess no point in looking into this and just let it run on multi core.
Is anyone using multiple Worlds OR breaking up processing across frames (eg ComponentSystemGroup1 runs on odd frames and ComponentSystemGroup2 runs on even frames)?
We using multiple worlds for saving\loading game, for creating big amount of entities on worker thread (EcxlusiveEntityTransaction)
noticed this popped up in entities 9
gonna have to pull up my other words again now that I can actually transfer small amounts easy
Any issues? Thats not my exact usecase tho, I'm wanting to break apart my server world into server core (this is all the network communication, Unity.transport. and that sort of stuff) which runs every frame, and my server simulation worlds (these are simulating the rts stuff, units/battles/buildings all the goodness) and it runs every 200ms but offset so they dont all run at the same time (as there can be many of these)
for my server updates I threw them all into a fixedupdate utility recently
I'm in the middle of a update to the core server loop right now though
yea i currently just have my whole server world ticking inside fixed update
its new in ecs 8 iirc
7 actually
its much cleaner than the overloading the group method
Ooo very nice
that would blow up and spit out some stupid leaks and callstacks for errors
well you still have to tick the world but
you can tick it every frame
and only get a hz you set
yeah, but I already wrote that ages ago in my game
well, no issues then π
im also not using NetCode
but I still feel they should have it out of the box
the only thing I really dislike about the multi world stuff is that you can't really dupe the unity scene
im just not using scenes
need the physics scene loaded for my server world
π
UGC is all old unity physics that I can't really convert 100% of the time
i've been lucky so far and dont have any old unity stuff
yeah, keep it that way if you can
but when i want effects im sure ill need to learn how to merge
I have to do so much animation and ik stuff I'm always stuck in old unity
yea i just have T pose units atm π
waiting untill unity.animation works
looks so bad tho
with the game object conversion pipeline, can we attach a old monobehavior/gameobject?
pretty sure you can
You can override GameObjectConversionSystem
and add monobehaviors there if you need to π€
though I imagine you can use IConvertGameObjectToEntity in a MonoBehaviour too
I just allways use EntityManager.AddComponentObject()
when i last tried that it didnt copy/instanate component objects
tho that was many versions ago
so does that warning of experimental feature still apply to companion gameobjects now(i mean experimental on top of everything being preview already)
are you using them in DINO @storm ravine ?
Yes, for camera for example
For PostProcessingLayer and AudioListener
For UI bridge
hmm ok
Sweet
one last weird question
I'm instantiating my prefab, then converting it to a entity and cleaning up the gameobject. I also add the Prefab tag to the new entities. Any idea if that would work with those companion Gameobjects?
Was just reading that cause I got curious π
Looks like 5argon answered it
It will work and will instantiates with prefabs
Sweet, thanks for the link
I'm getting this weird error

Unexpected exception System.InvalidOperationException: Unable to find type `PlayerMovementSystem+<>c__DisplayClass_OnUpdate_LambdaJob0` from assembly `Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
It isn't preventing anything from working
But it happens regardless
turn burst off and see what it says
@ocean tundra That crashed Unity π
@ocean tundra
using Unity.Entities;
using Unity.Transforms;
public class PlayerMovementSystem : SystemBase
{
protected override void OnUpdate()
{
float deltaTime = Time.DeltaTime;
Entities.ForEach((ref InputComponent inputComponent, ref StatsComponent statsComponent, ref Translation translation) =>
{
translation.Value.x += inputComponent.input.x * statsComponent.movementSpeed * deltaTime;
translation.Value.y += inputComponent.input.y * statsComponent.movementSpeed * deltaTime;
}).ScheduleParallel();
}
}
hmmm apart form ref instead of in it looks ok
@ocean tundra Wait what is the deal with ref and in
maybe schedule instead? how many entities is this expected to effect?
1 entity
ref = ReadWrite, in = ReadOnly
input component and statsComponent are only read, so you get a little pref boost if you make those in
and it dosnt update the change version under the hood
in (read only) components go last π
Hi guys, I haven't been keeping up with the dots news for a long while now, I was wondering is UI work possible using dots now or do I still have to make a "hybrid" app using dots for all game mechanics but traditional unity UI?
do you know of any links (guides/documentation/addons) that could help me get started? @ocean tundra
Not really, i just read everything i can from https://forum.unity.com/forums/ui-toolkit.178/
thanks a ton, I'll study it too
but you can still use all the existing UI stuff
it will probably be easier
I just figure im so deep in beta/previews with Entities it dosnt hurt to add more π
u mean just use them the normal way i'm used to?
yup
ah gotcha
should i be aware of any complications arising from trying to make the two methods work together?
thanks you too
is there any way to add a DynamicBuffer to a chunk, in the same way you add ChunkComponentData?
@ocean tundra Switching ref to in fixed it so far, thanks for the help!
@ocean tundra Also I can't see anything for Physics Body in Unity.Physics. Is that Unity.Physics.RigidBody?
its not called rigidbody any more
umm i think its PhyiscsCollider and PhysicsVolisity
Ahhh I see
cause evil
For example
PhysicsVelocity
using Unity.Entities;
using Unity.Mathematics;
namespace Unity.Physics
{
public struct PhysicsVelocity : IComponentData
{
public float3 Linear;
public float3 Angular;
}
}
Is this the way we are supposed to do things now?!?
oh no thats because its public
In normal scripts public variables don't have to be capitalized π€
c# conding standards are public = CapEveryWord
private = notCapFirst or _notCapFirst
theres no requirment
you do as you like
fields vrs properties
but unity are trying to follow c# standards a bit better now
yep
monobehavure is old and evil
So in a normal MonoBehaviour you should do MyPublicVariable not myPublicVariable?
This is news to me
no i follow c# super hard
i never public anything
useing private _varibaleName
if it needs to be in the inspector is use [SerializeField]
if it needs to be seen/used via another scirpt i use public Property {get {retun thing;}}
but im still figuring out public Sysems, so far i just use public FieldName;
you can do whatever you like π
Ok thanks for the explanation
just dont use properties in ecs components
properties and data hiding sucks public everything :^)
π lots of people like that
we like him because he speaks the truth
its my c# roots not liking it π but with DOTS everything public works
and is needed
Hmm - with the hybrid companion gameobjects workflow it's cool that data from entities are copied to the gameObject but is there a way to do the opposite (go -> entity), especially for the TRS matrix? π€
https://gametorrahod.com/game-object-conversion-and-subscene/ O didn't see 5argon had a blog back a few months ago about this workflow
CopyTransformFromGameobject
simply make an authoring component and add that component
Hmm let me check if that's still on the entity
@opaque ledge what do you mean by authoring component?
You can find it in create menu in assets, ECS -> Authoring Component, its basically a monobehaviour that implements IConvertToEntity interface, which will be run when your gameobject is being converted to entity
ah thanks! im just now starting with ecs and im trying to take in as much info as i can
saw a couple of his videos back when ecs was still brand new
things have come a long way since then and that's why im trying to get into it
back then finding readable documentation, easy to understand turotrials etc was pretty hectic for me
so i took a break from it
yep, its in much better shape now, you can also check ecs manual, good info there as well, less practical ofc
thanks for reminding me of him
ah - I guess the companion workflow rejects usage of the CopyTransformFromGameObjectSystem π€
well companion works from Entity -> Go tho π
Yea lol
Well it's not much of a big issue for me, I can always change the logic from entity -> go instead of go -> entity for a few monobehaviors lol
what is your usage case ?
I still had some old rigidbody2d I haven't converted yet - been pushing it off
so it just lazily handled some physics for me π
ah okay π
is there a way to order a job to complete last (in ecs world), without adding dependencies to all other jobs before it?
trying to check how long it takes to complete a world update, i guess total job time isn't doable but total sequential time would be nice too
so if i know when the final job is done i could get the time difference from that
You could add them to a component system group and check how much that system takes in profiler-timeline
that only shows main thread time
Maybe profiler analyzer - I think it can read other job threads and can give you a general overview (also maybe the performance testing package might help not sure if it would π€ )
i think profiler analyzer would still show individual job duration on the other threads
trying to get a grouped time
i guess manual job order goes against the whole idea of having a job system
you could put ProfileMarkers inside every burst job, but that would only give you the internal time minus scheduling etc.
ya but also that'd be a lot of work
i guess could call .complete on every system after world.update and see how long it takes when actually profiling
would just be more convenient if there was another way that's not blocking
Why is bool2 even a thing?
If I try myFloat2 == float2.zero I get this bool2 thing
It is really annoying
Vector2 never does this
math.all(bool2)
Ok thanks
but also
@grim walrus you probably shouldnt be doing float == 0, its easy to get little rounding errors to make that false
instead something like math.abs(value) < 0.000001
but maybe DOTS is different??
@ocean tundra I'm doing it with Input.GetAxisRaw, I've been using == 0 with that for ages no problem
I think its when your doing some maths to the number first, then comparing to 0
Rider just always gives me the error π
Ah
@ocean tundra Is there any way to lock rotation/position on specific axes in the physics body?
Or does one need to make a new System for that
umm i havnt done it, but i saw someone else doing it a few days ago
Oh ok
i think there was some setting somewhere they ticked
in one of the physics components
the authoring ones
yup
to get started its probably the way to go
long term depending on your needs, you could implement a c# physics engine or just colliders
or wait for unity physics 2d
but i think that will be awhile
Any thoughts on resources for making a super basic physics engine?
unfortunately not sorry
Oh ok
π€·ββοΈ
yea dont know sorry
i would use that compainion thing with rigidbody2ds
for now
as it gets you started quickly
and slowly start to research the options
and when you start actually hitting unity's limits then you implement
@ocean tundra One more question (please let me know if I'm being annoying for asking so many questions)
using UnityEngine;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
public class FaceMouseSystem : SystemBase
{
protected override void OnUpdate()
{
Camera mainCamera = Camera.main;
Vector3 target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Entities.ForEach((ref Rotation rotation, in FaceMouseComponent faceMouseComponent, in Translation translation) =>
{
float angle = math.atan2(target.y - translation.Value.y, target.x - translation.Value.x) * Mathf.Rad2Deg;
rotation.Value = quaternion.Euler(new float3(0, 0, angle));
}).ScheduleParallel();
}
}
I'm trying to get a point to mouse System to work
It rotates, but it rotates way too fast.
Any ideas why this isn't working?
what you probably want is to rotate over time
instead of immediately applying the angle
so some kind of interpolation between the current rotation and the target rotation
@coarse turtle I should have been a bit more clear
The rotation simply doesn't work
It overshoots
For example, if I move my mouse only a little bit it tolerates around 360 degrees multiple times
is this like a first person camera?
@coarse turtle 2D top down
oh alright
I'd imagine the angle is just too large, and if you want the camera to face the direction of where your mouse click hits, you want to take the angle between the camera's forward and some position
you're taking the angle between the target position and translation of some entity π€ not sure what that is
@coarse turtle I'm not rotating the camera, I want to rotate the player toward the mouse