#archived-dots
1 messages ยท Page 213 of 1
eventually ( greater then 1000 systems) systems can have performance issues, but by the time you hit that Unity will have optimised them again
i really dont know if that's a compliment xD
and, if i were a guy who dont listen and still uses OOP, i would ask "but how recicler calls spawner job?"....then your answer will be "add a tag to_create and the spawner will take care of it". right?
yup
and finally....about the collider issues
iiuc, using authoring my tiles will have collider properly set (already have), same as my cars
but im failing to catch the collision events
To use a practical example, I separate out bullet movement, enemy-bullet collision, and bullet bounds checking into separate systems; I could make them one giant system, but that's both less reusable (what if I create more bullet types in the future?) and less performant (Unity can more easily fit many tiny systems into idle blocks of CPU time than it can fit fewer numbers of giant systems)
i think we all agree dots is a great idea
so...both border tiles and cars have:
EntityManager.AddComponentData(car, new PhysicsCollider {
Value = BoxCollider.Create(new BoxGeometry {
Center = new float3(0.5f, 0.5f, 0.5f),
Orientation = quaternion.identity,
Size = new float3(1f, 1f, 1f)
})
});
but i haven't been able to set a filter, neither to use PhysicsWorld.CollisionWorld or World.CalculateDistance....internet is full of examples, but none of them want to run on my computer (something tells me the issue is sit between chair and keyboard)
at a guess putting center at 0.5 will offset the collider from translation
yea so querys are annoying
just add this to code?
[AddComponentMenu("DOTS/Physics/Physics Debug Display")]
[DisallowMultipleComponent]
[HelpURL("https://docs.unity3d.com/Packages/com.unity.physics@0.6/api/Unity.Physics.Authoring.PhysicsDebugDisplayAuthoring.html")]
public sealed class PhysicsDebugDisplayAuthoring : MonoBehaviour, IConvertGameObjectToEntity
damn mudblood xD
Is it possible to do stuff like run compute shaders from jobs, or call things like https://docs.unity3d.com/ScriptReference/Graphics.DrawMeshInstancedIndirect.html
this morning or yesterday when dealing with meses i saw something...hold a sec
Where would I look for more info on that?
inside hybrid renderer somewhere
at a guess find any systems inside this group InstancedRenderMeshBatchGroup
"Hybrid Renderer is not a render pipeline: it is a system that collects the data necessary for rendering ECS entities, and sends this data to Unity's existing rendering architecture."
its called something something batch ๐
I'm actually researching this right now, looking for the most optimal way to render chunks of terrain after generating the verts, normals etc in ECS
Seems like a waste to have a pool of Mesh objects to abuse, which is what I did aaages ago
maybe...
has alot of gameobject usages
sorry, i guess dig into hybrid renderer and see what that is doing
ive heard that Hybrid renderer should now be 'on par' with game objects for rendering dynamic meshs
since you cant actualy use any batchs (each chunk will have a unique mesh) im not sure you would get much performance by rendering manually
pst, @ocean tundra do you name your components...RoadComponent...TileComponent....~Component? ? ~Data? Nothing at all?...most of mines are tags...
na i just name them what they are
eg Health
i do sometimes end tags with Tag ๐
thx...i share you pov
Yeah, I'm just annoyed about it ๐
and all my systems end with System
i would focus batching for everything else ingame, eg trees would be great batched
there is also a DisableRenderering component
as Disabled will prevent the whole entity from being processed in any system
iiuc, it's much cheaper to recycle an object/entity/whatever than destroying+creating a new one...the same way clone or instantiate is also less memory consuming
with that in mind, i though a recycler system would make sense, but at the end, recycler would only handle entities with "to-recycle" tag, and at most it would add "to-create" tag
so, in the end, recycling is simpler if it add "to-create" tag and the same system that creates, recycles (recycle=set new color and new position...remember we are talking about cars moving from left to right
and the resetting of data could end up quite complex
i mean...cars[i]=new car(...)
as im not using nativearrays or anything similar, i dont have to dispose anything...
gc would take car
well...if recycler deletes the entity, freeing cars[x]
should i be checking cars.length to create? that sucks
only calling destory entity will trigger a entity cleanup
and even then
a cleanup is not like it was in MB
pretty sure theres no preformance cost
it would be much better to make something like new system({...}).run();, but i dont know if thats how this works
so, to sum up...my systembase are invoked running onupdate by engine
if i want a task to be run...is IJob the way to do it?
create a new entity
and for a simple job just use Job.WithCode
the way your creating entities wont work in a job
cant use shared components in a job
and from memory you were setting those up manually
need a prefab instead
tomorrow ill go to prefab+job
(when switching to authoring)
so...Job.withcode().run or something like that is the way to invoke running a code snippet once?
(not like systembase onupdate with does it every frame)
i didnt understood these 2 lines
everything in dots happens in onupdate
also you can still just do stuff in onupdate
in your case of creating a entity just do that normally
Entitymangaer.create.....
you dont need a job
yes, but i dont want to duplicate the code between systems
so recycler has to call spawner
systems shouldnt call eachother
then recycler must die xD
instead create 'trigger' entities to make systems work
elaborate...NOW!
or when further along use the EventSystem on the forms
im lost here
no, noo, noooo
things like requiresingletonforupdate
you said 2 things, please, lets analyze
and has singleton
whats that
when further along use the EventSystem on the forms
?
As the original post is a bit outdated now I've moved it to here
The project and documentation can be found here:...
honestly you dont need it
but i want to learn it ๐
is this like the message queue between systems someone talk about a while ago?
but essentially is a ecs-based event-"handler", right?
yea
i would say broker/message queue
ok...and apart from that, you also suggested using requiresingletonforupdate
which seems is something to ensure onupdate is only run on certain conditions
right?
yea that will prevent a systems onupdate running unless the singleton exists
already onupdate will only run if your entity querys has at least 1 entity
so this is a extra rule on that
but there might be cases where this applies...
kind of triggering a system
and is based on creating an entity?
or a component?
component
but you probably want to be safe about it
and create a entity too
makes cleanup easier
just destory the entity when system is done
do you have an example at hand?...
notreally
em.createentity()
em.addcomponent<yourtriggercomponent>(entity)
inside your system
requireforupdate<yourtriggercomponent>()
END of onupdate
em.destoryEntity(getsingletonentity<yourtriggercomponent>())
public class my: SystemBase
{
protected override void OnCreate()
{
RequireSingletonForUpdate<whatever>();
}
protected override void OnUpdate()
{
Debug.Log(GetSingleton<whatever>().Value);
}
}
by end you mean last line of onupdate, right?
yea
how many years have u been messing with ecs? xD
too many
i started looking at it around when it was announced
but wayyy too complicated then
maybe last year or the year before got into it properly
around when Entities.Foreach got released
and physics
god it was tough to use without physics
manually writing colliders ๐
at this moment 0.17, right? when u think it will be 1.0?
well...although i merely touched not even scratched the surface, seems quite powerful, with a steady learning curve...
(does it make sense to create a new URP project or nowadays is still better to create a 3d "classic" one?)
the core DOTS is starting to stabilize, but all the edge bits are still a mess
Physics - working but still tough to use
Animation - broken mess
Pathfinding - NA
Sound - very early alpha, super mess
UI - Na , prototype in Tiny
2d - NA, prototype in Type
Netcode - working for specific case, but still alpha
Other awesome unity features
Timeline - NA
Cinemachine - NA
VR/XR - NA
Particals/VFX - NA
....
i don think they will 1.0 untill most of the core gameplay bits work and many of the side unity features are compatible, at least in late previews
yea URP is the way
does that mean if i want to play a sound ill need an hybrid GO to play it?
ok...well...enough chatting for now...going to fix this recycling thing
thanks, as usual!
@night venture loads of questions you ask are answered in the official manual. I suggest you read it 100% at least once.
theres technically a dots timeline package
its never been mentioned at all by any staff so take that for what its worth ๐
๐ im sure it will be great to use
ok...having an issue creating from prefab using authoring and, as usual, multiple code implementations differ...
there's something i dont understand:
using this code (which seems outdated as it complains)
Entities.ForEach((ref Car car) => {
Entity c = EntityManager.Instantiate(car.prefab);
EntityManager.SetComponentData(c, new Translation {
Value = new Unity.Mathematics.float3(0f, 0.5f, 0f)
});
}).Run();
where's the prefab (called on my asset myPrefab) linked?
it even has (kinda working) samples @ocean tundra ๐
i mean...i understand gameobject are destroyed and converted to entities, even than authoring+entity allow to drag&drop the prefab to an empty gameobject on scene (which works properly as i can see on inspector)
but im not able to undesrtand where's the asset loaded linked to the new entity.
your prefab is just a regular entity about with a Prefab component tag so it isnt visible by other systems be default
so prefabs are entities?
yup
yes, the prefab tag means systems by default ignore it, in a similar manner they ignore entities with the Disabled tag
even i didnt expect the spanish inquisition, that doesnt explain how it's magically loaded, as im not typing "myprefab" anywhere...
well its not magically loaded, there are lots of conversion systems that create it for you behind the hood
hold on...i think i understood the ugly trick....
its creating an instance of a running entity! u bloody bast**d
that's why the foreach!
aaand...the other example also...i got it. its creating a GO, setting a component which references the prefab, and then cloning
As EntityManager.Instantiate(MyPrefab) being MyPrefab a GameObject loaded via Resources.Load is deprecated,
- what's the most straightforward way to create an entity around a prefab?
- can I archetype a prefab?
if possible, I don't want a entities.foreach/existing object to clone, please
nope as i thought you were talking.
only if an entity is using the asset/prefab, it's created as an entity
in other words: i cant attach a component "CarPrefab" to a prefab in order to select it with entities.
They demonstrate it in the samples https://github.com/Unity-Technologies/EntityComponentSystemSamples/tree/master/ECSSamples/Assets/HelloCube/5. SpawnFromEntity
if a gameobject using the prefab+component linking to the prefab, yep
but thats creating an entity "copying" another entity
This sample demonstrates a different way to spawn Entities and Components using a Prefab GameObject.
a gameobject that exists on scene
is not loading resources, but cloning from another entity
*or converting a gameobject to entity
That is how you're meant to work with prefab gameobjects in ECS. You use the conversion system to convert your gameobject prefab into an entity prefab, either with ConvertToEntity or using subscenes, then go from there.
Technically you could load a gameobject prefab at runtime then convert it but it won't be supported in the future.
imho, it would make sense to have prefab as archetypes
Can you explain what you mean by that?
having a Gameobject with a component added which is setting a prefab (static) variable in order to clone it (essentially what they are doing), seems quite a looparound instead of:
A) converting the gameobject loaded by resources.load (now deprecated)
B) attaching a component to a prefab, in order to have it as an tagged entity I can use (without having a gameobject on scene)
C) when creating an entity, being able to add a prefab in the archetype (as a "set of components", which, essentially is what it is)
You can kind of do that with what exists, you create "authoring" scripts via IConvertGameObjectToEntity with values you want to be able to tweak in the editor. You can add those as needed to your prefab and they will convert into components on the resulting Entity prefab as you'd expect. And there's nothing stopping you from adding components to your prefab entity at runtime either
The only thing missing is loading them dynamically. It seems like something a lot of people want, supposedly Unity is working on a better workflow for handling the editor data->runtime pipeline for ECS specifically
Create a singleton prefab 'container' with all your prefabs
adding prefab2entity conversion script doesn't work when attached to prefab, as it not "loaded" into the scene. neither a tag or any other thing, as the asset is not loaded (cause is not used). so far, seems the empty gameobject is the common way to go, although imho, it sucks
It does work. If you follow the workflow layed out in the sample I linked above, you can add monobehavior authoring scripts to your prefab and they work exactly how you'd expect
a system which loads all the assets used in a dictionary to use them later? sounds too ugly for the job.
i have been playing with those all day, but ok, ill review again and give it a try. but, they are cloning from a game object, afaik
If you follow the example exactly it will work
Don't try to take shortcuts, just download the sample, look at every step and pay attention to what's happening in the spawner conversion script
I use that workflow to author monsters, items and even elements of my map generation via prefabs in the editor. It works great once you understand it
yes, but u have GO on the editor
that code is getting a GO.prefab as a parameter to create an entity with that prefab
prefab are assets, unless loaded/used on scene, arent created as entities
no matter if you attach then "convert to dots" or whatever, thet aren't loaded, so cant be used
we can discuss line by line if you find it useful
The only scene reference required is the one on whatever will end up with your prefab entity.
Like in my game, the only gameobject in my scene is the "map" that gets converted to an entity. The conversion script for that map references all the prefabs that will be used during map generation, and uses the IDeclareReferencedPrefabs exactly how it's used in the example
More or less
either your map has a component with a public field to link to the prefab or theres an object with it (empty object or not). otherwise is not possible the asset being loaded
hence, cannot be converted
Yes, it's a public field on the conversion script
then...you are "CLONING" the prefab from an existing entity
and, what im looking for its a way not to clone, but to load asset as part/component of an entity
ie: authoring is great, but only through code, you learn how it really works
I'm not sure what you mean by that....you need a canonical entity to instantiate from in the first place. Otherwise what are you instantiating
that's what is all about...i dont want to instantiate, but to "create" from scratch
i can do it with shapes, but i haven't been able to do it with prefabs
what, btw, gives me an idea...
I'm not sure what you mean by that
resources.load() as entity
That would require an editor representation of an entity. That's the whole point of conversion, there is no editor representation of an entity, we're meant to author gameobjects in the editor then convert to entities
a prefab is a set of components, hence, that would give u an entity, with a bunch of components, including mesh, rendere...and so on
and no, it doesnt require an editor rep of an entity, as im coding and its done at runtime
entity, with a bunch of components, including mesh, rendere...and so on Which is exactly what you get when you follow the conversion workflow I originally linked
but you are using the editor
and im noooot
...but you're talking about Resources.Load and Prefabs. How is that not using the editor?
really?
Alright I surrender, I guess I just don't get what you're trying to do. Good luck brother
ill say it crystal clear
on an empty world, without any object on scene (but camera)
create a system, which OnCreate, creates a single entity from an asset/prefab.
and, my dear friend, seems that was possible before the deprecation of intantiate(resources.load(prefab) as gameobject)
@night venture alternatives to resources.load are using addressables package or like said above make your own prefab container
addressables are constrained to gameobjects which it seems like hes trying to avoid
Ok so im adapting the Boid sample to my networking as a POC
But im still a bit unskilled with Subscenes/conversion
So I have the Boid Spawners, which reference the boid 'prefab'
I've added my authoring component to that prefab, and now i want to extend my conversion system to detect if the entity is a prefab or not, to setup network instantiating
Any idea how to tell if the target is a prefab from a GameObjectConversionSystem?
I feel the conversion workflow doc has had a update,, nice
According to the steps my system will run before the prefab tag is added ๐ฆ
well theres no 'nice' way to do it via entities, but i was able to use PrefabUtility.IsAnyPrefabInstanceRoot
next up, is there any subscene ID i could get ๐
yourScene.SceneGUID ?
Can't you plug your conversion in one of the systemgroups executed later ? I mean they sure do it for their companion conversions, you could be able to UpdateAfter that ? I need to find that list again
Can't you plug your conversion in one of the systemgroups executed later
Well, thinking of it, that's not so easy
With a : GameObjectConversionSystem, you could [UpdateAfter(typeof(GameObjectAfterConversionGroup))]
so should be doable ๐ค
is there a thing like "!RequireForUpdate"...something that only runs onupdate if no entity<T> exist?
You could make an EntityQuery and .entityCount on it ?
hmm...indeed!
at the end, this is what I made: OnCreate: create entity with component FirstRun + RequireForUpdate, and OnUpdate destroy entity.
for a one-shot trigger system ? yeah that's the intended way
you can even put your singleton from editor instead of creating via code
I have yet to profile and discover whats better: have an empty onupdate VS have a requiredforupdate...perhaps setting everything in OnStartRunning would also work.
sauce?
Nvm it's only a few lines of code right ?
SAUCE? xD
What does that mean ?
I'm not english-native
My advice was useless, scratch that
your FirstRun component in onCreate is good, only a few lines of code
I'm still asleep ๐
spaniard by any chance?
I was going to dare to say something with my more-than-rusty french...but let it stay ๐
has anyone else come across a case where a second job in a Onupdate gets errors when trying to capture local variables
no...but I suggest to paste code
var TranslutionEnts = TestObjectQuery.ToComponentDataArray<Translation>(Allocator.TempJob);
Entities.WithReadOnly(TranslutionEnts).ForEach((ref Translation currPos, ref in MoveTargetChoice gohere) =>
{
int count = 0;
float3 diff = new float3();
var currycurrspeed = currspeed;
var tempdirect = math.select(targ2, targ1, gohere.intVal == 0);
var avoidirection = math.normalize(tempdirect - currPos.Value);
for (int i = 0; i < TranslutionEnts.Length; i++)
{
float distbetween = math.distance(currPos.Value, TranslutionEnts[i].Value);
if (!currPos.Value.Equals(TranslutionEnts[i].Value))
if (distbetween < toclosedist)
{
currycurrspeed = 0;
}
}
currPos.Value += avoidirection * currycurrspeed * Timmydelta;
}).Schedule();
var SecondTransEnts = TestObjectQuery.ToComponentDataArray<Translation>(Allocator.TempJob);
Entities.WithReadOnly(TranslutionEnts).WithAll<TestMoveojbectTag>().ForEach((ref Translation currPos, ref LocalToWorld myworld) =>
{
int total = 0;
float3 separation = float3.zero;
float3 alignment = float3.zero;
float3 coheshion = float3.zero;
}).Schedule();```
with the above code I get this error stactleAvoidanceTest.cs(301,9): error DCICE007: Could not find field for local captured variable for argument of WithReadOnly. Seeing this error indicates a bug in the dots compiler. We'd appreciate a bug report (About->Report a Bug...). Thnx! <3
line 301 is the start of the second job, I also get the same above error if I use the SecondTransEnts variable
I also get the same error if I completely comment out the first job, I must have found a really weird bug ๐
so I've seen an issue like this before @pliant pike not sure if yours is the same thing
but if you have variables defined that you don't actually use, sometimes the compiler will shoot out dumb errors
try just removing the "int total = 0;"
and stuff like that
Restart editor? Codegen might be stuck?
I've tried restarting the editor that didn't do anything and I've removed those variables and I've even swapped around the jobs and I still get the same error
I guess I'll just stick to one job for that system
Hello guys. I upgraded to latest LTS (2020.3.3f1), and have an issue on builds. I could reproduce on an empty build with just Entities+HDRP+Hybrid.
NullReferenceException: Object reference not set to an instance of an object at Unity.Scenes.ResourceCatalogData.GetGUIDFromPath (System.String path) [0x00096] in <5524df798ca94a05ab9ea2cd9248e5bc>:0 at Unity.Scenes.SceneSystem.GetSceneGUID (System.String scenePath) [0x0000b] in <5524df798ca94a05ab9ea2cd9248e5bc>:0 at Unity.Scenes.GameObjectSceneUtility.AddGameObjectSceneReferences () [0x00034] in <5524df798ca94a05ab9ea2cd9248e5bc>:0 at Unity.Entities.AutomaticWorldBootstrap.Initialize () [0x0000c] in <6e0804b517024e309eeab34e89d586b0>:0
Is that a known bug?
Found that actually: https://forum.unity.com/threads/got-nullreferenceexception-from-automaticworldbootstrap-initialize.1075933/
Any idea on what action I should take? we don't have any subscene, and we're building using BuildPipeline.BuildPlayer(buildPlayerOptions);
In your second ForEach you're not using the "TranslutionEnts" which is being passed in WithReadOnly. Based only on what you posted that looks like the source of that error
It seems you may be right, thanks Sark
As you can see in this snippet, I'm creating entities without mesh/prefab...just adding a few components I retrieved from json file:
for (int i = 0; i < list.GetLength(0); i++) {
for (int j = 0; j < list.GetLength(1); j++) {
tiles[i, j] = EntityManager.CreateEntity(Game.Archetype);
foreach (ISerializableComponent c in list[i, j]) {
c.addComponent(EntityManager, tiles[i, j]);
}
}
}
Depending of these components, sometimes I want to instantiate a prefab (with colliders) or a simple cube mesh (without physics).
I could do it after inner foreach like hascomponent(no_physics)... but prefab instantiation creates a new entity, and I already have one...is there a way to merge two entities? do you think there's a simpler way?
I can elaborate more if needed.
Hi guys does anyone know if this video is still useful today? https://youtu.be/C56bbgtPr_w
not really that is very old and out of date
Do you know anywhere I could learn up to date jobs? I know most things else in Ecs
it would help you as same as confuse you...
I mean there isn't many to be honest maybe some of codemonkeys later tutorials ones that use SystemBase and Entities.Foreach
I have been playing ecs for almost a week now, and I miss better theorical explanations, rather that monkeys coding...
Ok Iโll. Check them out thanks
Do you suggest sources to learn?
what base class you using?
you should use SystemBase
Thanks ๐
If your goal is to start learning just jobs ignoring ECS , I havent gone through the whole 25mins but looks pretty valid as an intro to me
older videos about physics collisions have an "isTrigger" property on physics shape, but im unable to see it now...trying to catch the event collision, but seems is not working. should i add an script via authoring or something?
Hey guys. I've had an issue for a few weeks now and I just don't know what to do. The JobsDebugger is automatically turned on every time I start Unity and I have to remember to turn it off. Anyone have any idea why that is?
Yeah I read that one but unfortunately it doesn't list any fix.
And I'm not getting Console errors. It just is on and causes overhead.
have you tried looking on your project setting file? perhaps you can remove the line...
Hadn't thought of that or even really messed with it. Let me google it. Thanks for the tip.
Side note - do you know if this is something I'd have to worry about on a build?
Or is it an in-editor-only kind of thing?
no clue
k. Thanks for the help!
Hey just to be clear when you say project setting file, is that the term I should be looking up?
Or did you mean the Project Settings in editor? Sounded like you mean a file I would edit.
@night venture
where you set debugger on?
That's the spot I found it.
Side note, while looking it up, I saw the Debugger only runs in Editor so at least that's not an issue for production.
then, thats probably on your ProjectSettings/EditorSettings.asset...but tbh, I have never used that
I'm using Emscripten to build to web and including native code in a cpp~ directory that gets found and included automatically by the build system. Does anybody know if all C++ standards should be supported there? C++11/14/17/20?
Check out that dropdown
Yea thats what i thought, but i dug into the code and the prefab tag step is coded to be after all conversion systems (then they do companion stuff)
already working. thanks anyway.
IIUC, trigger are raised when the colliders intersect and collide when the bodies intersect, right?
Heya, need a little help with some entity conversion.....
I seem to only be able to convert one material+mesh combo.....everything else that I try, even default meshes and materials are invisible when converting (mesh is still seen in wireframe mode, but material not displaying)
I am kinda baffled and have no idea what to do, haven't had this happen to me
Convert to entity component
the one you can convert
are you 100% sure its a entity?
it might still be a GO and nothing is converting right
Just to mention, RenderMesh is present on the entity, but material is invisible
No it's an entity
hybrid renderer v2?
Yes
Actually now that you mention it, I might have forgot to add the keyphrase in this particular project, let me try that
But even without the define, I still could use the instanced material properties that are only available in V2.....
Well the define "fixed" things, at least I can see them, but materials seem to be broken, I guess it's still better than plain mystical behavior
So apparently by injecting custom vertex data I can use Hybrid Renderer V1 with point lights......
AND with instanced properties
you can use v2 with point lights with deferred if you use urp from github ๐
mmmmmmm sounds enticing
Is using Mathf in Jobs fine, or is there some other Burst-optimized math lib I should be using
thanks
Mind sharing a link?
Is this the one?
https://github.com/Unity-Technologies/Graphics
So you'd need to clone and import the folder?
Are blobs assets constantly in memory or can you read them from disk whenever
Is it not wasteful to have arrays with length of thousands in memory as blob
depends on the data
also think memory is cheap
actually sorry that depends on your target audience
something like 45% of gamers have 16gb
your working in a 64 bit cpu/OS
so you can definitly use more then 3gb ๐
damn
steams stats are 16gb about 45% and 8gb about 27% seems like its ok to not worry too much about ram
If I have a position/Facing in Euler, how do I force an entity to those parameters. I have a 40 second video which is moderately cool showing what I am trying: https://www.youtube.com/watch?v=EdnxWRWvxy4
If you like what you saw, you can come to like the only positive zone of the Internet I know: www.twitch.tv/goodnewsjim The Bro Zone Layer.
Temporary offer for anyone of any skill level: Can someone contact me to promote my game? www.starfightergeneral.com I'll give you half the sales you drive.
Play the spiritual sucessor to xwing vs tiefight...
I'm already able to clone velocity.
Vector3.from something or quaternion.from something I forget
I tried: GameBoardModel.entityManager.AddComponentData(GameBoardModel.playerEntity, new RotationEulerXYZ { Value = new float3(vvv4.x,vvv4.y,vvv4.z) });
quaternion.Euler
Where vvv4 was gained from: rb.transform.eulerAngles;
there's a bunch of different ones
set that on the "Rotation" component
quaternion is a way to do rotation without gimbal lock
I use quats in Gameobjects
I just do not know how to set my Quat data to an Entity
I have an entity reference
Daaang you're right. You might be able to use the export group ? Manual says it's only for tiny but it's executed after the Prefab addition
EntityManager.SetComponentData(myEntity, new Rotation {Value=quaternion.Euler(x, y, x)});```
note quaternion != Quaternion
Let me try. Thank you Simoyd whether it works or doesn't work like me.
Simoyd, Rotation adds the Euler to the current Rotation, it does not set the Rotation it seems. Would you like to see the video?
there is no adding going on in the line I pasted
it's not getting the old data to add to
maybe add some logging before this line to double check your input x/y/z values are what you're expecting
I am going to add static values
to add one rotation to another you'd use math.mul(quat1, quat2)
I could be wrong on why it isn't working, but it isn't working
is it possible it's parented to something else somehow and adding that rotation in? double check your hierarchy doesn't have any rotation values in parents of the thing you're trying to rotate
i dont have experience with this tho. most of what I make is flat and I always zero out parents so I'm not sure how that translates with authoring and dots, but it's easy enough to check I guess
I may have grabbed the wrong euler from my gameobject, theres a couple dif options.
I'm zeroing in on this maybe...
nice! good to hear ๐
One thing I notice is that rotation in the entity debugger runs on the scale of -1 to 1, while rotation in GameObjects runs on the scale of 0 to 360.
Is there something funky going on in the translation?
1.4 most likely - radians
Here is a video of me trying to translate my facing of GameObject Player to my Entity Player and failing.
If you like what you saw, you can come to like the only positive zone of the Internet I know: www.twitch.tv/goodnewsjim The Bro Zone Layer.
Temporary offer for anyone of any skill level: Can someone contact me to promote my game? www.starfightergeneral.com I'll give you half the sales you drive.
Play the spiritual sucessor to xwing vs tiefight...
oh you're looking at the quaternion's components. Yea 0->1. For that code I glimpse at the end to have a shot of working @remote crater you want e.g. rb.transform.rotation.eulerAngles.x or instead of all that, just new Rotation { Value = rb.transform.rotation }
Perfect! Remember... If you guys ever see me make it big, remind me you helped me, and I'll drop you manilla envelopes.
version: 2020.3
unity docs on the preview package list
ECS packages are not listed
no entities, no hybrid renderer, no unity physics
that's because they hid them @waxen niche
here's a full list of all hidden packages.
https://forum.unity.com/threads/visibility-changes-for-preview-packages-in-2020-1.910880/
ohh thanks you :)
anyone know how to lazy instantiate a native colleciton?
e.g.
NativeHashSet<int> set;
if (SomeCondition)
set = new HativeHashSet<int>(10, Allocator.Temp);
set.Add();
It doesn't let me use 'set' because it's uninitialised, although it is guaranteed to be initialised by the time I use it...
and I can't set it to null..., struct...
Oh I suppose I can NativeHashSet<int> set = default;
oh it is not happy about that ๐
probably will work just need to rearrange stuff I think
it's not guaranteed to be initialised though
if SomeCondition is false, then set has never been assigned
i'm just following lazy pattern
when I want to use it, I check if it's been initialised first
works now by using 'default'
your code example immediately attempts to add to it though, which would be a problem if it was initialised to the default
#๐ปโcode-beginner you could use a singleton pattern instead
How do I get all overlaping colliders of a collider I have
im also having collision issues, if you want to share your thoughts...
so far, i have been able to detect collisions using ICollisionEventsJob and ITriggerEventsJob.
although i havent completely understood how they work yet
it seems latest examples could change how that could be achieved, but neither i have understood them properly
to sum up: i can tell you what i got running, how it's working and that'll change probably soon ๐
---
has anyone tested/profiled how much impact does:
protected override void OnUpdate() {} //Does nothing
VS.
RequireForUpdate(GetEntityQuery(typeof(Something_never_goint_to_exists))); //OnUpdate will never be invoked
?
anyone knows what axis to set in LimitedHingeJoint to limit rotation on the Z axis ?
A joint constraining the anchor point on body A to the target point on body B, where each body can rotate within a limited range about the vector where their axes align. The perpendicular axis of each body frame is used as a reference point for the range of motion
not so clear on this part
that's what my setup looks like rn
i'd expect the top right body to have some movement freedom above and below that white line but instead during the runtime it would seem rly stiff
( ^ moving each body individually via the mouse )
what i have rn is a glue of multiple constrains
it sort of limits the angle between -45 and 45 but its no accurate at all
Uh, so I am working on using my monobehavior player controller to double duty control an entity during entity game modes. It "works", but the aiming and such is jank. I would really like to: play as GameObject, yet mimic the location of the Entity right on top (mirror position/rotation), but an issue comes up. 1) If there is a collision in Entity space, how do I force feedback the collision parameters back to the gameObject?
example was incomplete
NativeHashSet<int> set = default;
bool initialised = false;
for (some loop)
{
if (earlyExitCondition)
{
continue;
}
if (!initialised)
{
set = new NativeHashSet<int>(10, Allocator.Temp);
initialised = true;
}
.. use set
}
have u ever heard about singleton pattern?
how will singletons help here?
NativeHashSet<int> set=null;
public NativeHashSet<int> getNativeHash(){
if (set==null){
set = new NativeHashSet<int>(10, Allocator.Temp);
}
return set;
}
for(...){
getNativeHash().add(...)
}
not singleton, but the singleton pattern
the singleton pattern just ensures only instance of something
look above you ๐
did using default work?
yes it did
ooo nice
I don't understand why you're saying the singleton pattern is a replacement for lazy loading
I need one hashset per job instance
but I only want to instantiate it if it's needed
what I mean is that you don't need the bool variable. but do it as you want. ie: use a function to "get or create".
Oh you're just saying I can do if (set == default) rather than using a bool
that's fair enough
could maybe use set.IsCreated instead of initialised bool too
not that it matters in perf/functionality, just throwing out that idea if you're gonna lazy load native collections in general
I'm not saying that. I'm saying not to check if set is initialized within the loop, but on the external function....but as I said, do whatever you want.
oh yeah, I could put it in a little method somewhere
but I do need to check if it's created when I dispose
ah actually having changed it a little I'm gonna put it back, my bool is called "regennedBoxFound" and is actually used later for other purposes too so it's a bit clearer in my case
but thanks for the ideas ๐
What transforms are affected after a collision? Just velocity and angular momentum?
I finally achieved to make my collision system work so entities get destroyed when they reach the borders.
Now, thinking about the spawn process, I'll need to detect when a position is free, and that probably can be made with collisions also.
Is there a way to detect when a collision has ended?
I need some help with abstracting my stats/buff/damage logic :/ I just cant find a nice structure...
Each entity has a bunch of stats : Health, Speed, AttackSpeed, PhysicalDamage, MagicDamage, PhysicalResistence, MagicResistence.
There should be conditional buffs which modify those values : When theres a holy tree near the entity, double the life, but substract PhysicalResistence
The damage calculation itself should also be conditional : When the damage hits an orc without armor, double the magic damage
Items should modify the players stats : When theres a holy sword inside the players inventory and/or equiped, grant 10% HP and more damage against unholy mobs
As you can see... its pretty complicated. I already solved some of that stuff...
// Stats are just components attached to an entity.
// Buff is a script due to its complexity. They are able to modify entity components and check conditions.
// Items are entities and their "ApplaybleBuffs" are getting "copied" into the player once he equips that item.
// Theres a buff system looping over "Buffs" to execute the scripts method which manipulate the entitys stats.
Player -> Entity{ Character, HP, PhysicalDamage, MagicResistence, Buffs{ list of scripts from holy sword } }
Holy Sword -> Entity{ Item, Sword, ApplyableBuffsForWearer{ list of scripts for player} }
So the buff/item/stats stuff is already working fine so far ๐ ( Still open for improvements ). BUT theres one thing i cant solve nicely. The damage calculation.
When a entity attacks another one it should deal damage. But, that calculation should be conditional : When we damage an orc without armor, double the calculated magic damage. And i do not want a huge method like CalculateDamage(entity, entity) where i have dozends of if statements.
I also thought about damage entities or events. But those have the same problem aswell... any tips and ideas ?
@stone osprey let me read and understand all before answering ๐
just my 2 cents:
- why aren't buffs/items also components? -> damageSystem could take them into accunt
- why don't yo make damageSystems based on mobType? -> damageOrc would look for <MultiplerAgainstOrcs> in order to calculate damage
anyway, I haven't figured out how you apply scripts to entities...and it sounds scary...
@night venture Because my items are complex... they should execute logic during runtime and its possible to have multiple of one type.
Oh those buff scripts arent burst compatible. They contain interfaces i call to evaluate the buff.
Besides that, the main problem is the damage calculation. Thats something i cant figure out... and i cant find ANY examples about that. Its like no one ever did that in an ECS. Because the damage calculation does not depend on mob types ^^ That was just an example... i want this as flexible as possible.
enum Trait
{
Orc,
NextToHolyTree,
Whatever,
Etc,
AndMore,
}
enum Action
{
BuffMagicDamage,
BuffPhysicsalDamage,
}
struct Buff
{
public BitMaskOfTraits Conditions;
public Action Action;
// 32 bytes of possible meta data for the action
// there are better and cleaner ways to solve this
public unsafe fixed byte ActionValue[32];
}
// then your damage loop would look something like that:
// group Target and Source buffs
// find all conditions that you need to calculate by merging the Condition masks
// calculate the conditions
// apply the buffs by checking if the conditions for the buff are met
That's something I just thought of maybe it works for you ๐คทโโ๏ธ
@north bay Thanks ! But this still requires a huge damage calculation method with many, many if statements... right ? :/ Thats what i want to avoid actually...
Well you need a method for each Trait and a method to apply each action
@north bay Ahhh... could you probably add an example ? This would help visualising a lot ๐ Oh... but i guess this wont work if one entity attacks multiple other ones, because this is based on the attackers stats in a 1 v 1 combat situation i assume
perhaps is more complex than Im thinking (please, ilustrate me), but I think this can be summarized in 2 systems:
dealDamageSystem
handleDamageSystem
dealDamage could add all "positive" items, bufs ans so on, using each component calculatedDamage() method
ie: holysword calculateDamage() { return damage*2 }
so foreach component { damage=c.calculateDamage(damage) }
Why not? You can also make an array of targets and group their buffs (or make traits that depend on multiple targets)
besides that, I don't undertstand how your item scripts work, so if you please can elaborate on how it works, i'll appreciate. perhaps is an interesting approach i could use someday
Oh damn... i still dont get it :/
So... the examples you gave ma are data driven, but they need a lot of new methods/conditions inside the systems. I think i am searching more for a way to inject the logic into the systems by data.
talking to me? otherwise i'll shut up
Well since you also need to inject the data into the buffs to calculate them, you would have to do a lot of unsafe magic when going the burst/jobs direction.
You know best what problems your project has and what stuff you want to solve.
My best advice is to look into burst function pointers and the physics package.
Otherwise there's always the option of doing code gen.
Thanks both of you !
So buffs and the damage calculation basically just should execute some scripts. This way i could "inject" data.
'
public struct Buff{
public string scriptPath;
}
'
Would it work to just give the buff a path to the script it should use and a system loads up that script to execute it ? Not sure about the performance... But it could work
Imho that's mixing data+code and i don't like it very much, tbh
Furthermore, are your scripts jobs?
that can be done with reflection, but that a harsh path i always try to avoid...like code gen.
Again, I think function composition do make sense: each items alter the "resulting" attack, once all the components have been checked, the resulting attack is made.
The complexity, then, is distributed between each item.
for example, if the helmet of the thousand truths is even better were worn toghether with the sword, that should by handled by the "thousand truths" component, nither the helmet or the sword. sword is multipliying attack*2, helmet is incrreasing resistance, and thousandtruths is taking both components are presents and adding +2 for each attribute
No just basic classes that inherit an interface ^^
I just think that one component per item is not that nice either... Well it makes sense for equipment, but we could just have a "Equiped" component with the same result ^^
I finally achieved to make my collision system work so entities get destroyed when they reach the borders.
Now, thinking about the spawn process, I'll need to detect when a position is free, and that probably can be made with collisions also.
Is there a way to detect when a collision has ended?I know I can setComponentData(true/false) on each frame, but seems a bad approach...did someone mention active waits?
I like kiwires solution better. Buffs are a subname for component-based Modifiers. They can be relative or absolute (+20% Intel, +5 Charisma, ....) . Debuffs are only negative buffs.
A system computes all buffs in a final equation including baseStatX, baseStatY, and their corresponding modifiers (multiplying/adding positive/negative values). This equation can be as simple as adding Damage modifiers and subtracting Armor modifiers, or as complex as a WarHammer/DnD paper games, where you have multiple levels of such stats and equipements, and Hero traits, and environment cover, and so on...
If i abstract more, I see it the same as a rocket explosion area-of-effect. Imagine you fire a rocket from a rocket launcher. On impact, you would do a distance/trigger check from pos+radius circle, and add a damage component to all entities. Later, a system will query to pick entities with that Damage component and do the math. For me it's the same thing, unless I don't get one specific requirement you have.
If i abstract more, I see it the same as a rocket explosion area-of-effect
Difference being, you don't apply it on rocket impact, but when you want from any other system: on item equipped, when Healer party member is close to you, inside bubble shield radius, .....
Damage entities seems like the most flexible approach to me. You write systems for the different kinds of effects that change the damage entity after it gets created but before it gets applied to the target. You can explicitly order the systems based on the requirements of your damage calculations
Yes it would be a lot of code, but you're describing a complex system. I don't understand how you want to get results without writing a lot of code
Yeah I think he's trying to optimise before even having written v1.
knuth come to us!
what if i have thousands of entities that dont need to be spawned all the time?
on monobehaviours i used to spawn them when player got close to them
but i dont think its good idea to have 7000 deactivated entities all the time
or more
it would be better to delete them IMO.. or not ?
I think you have things a little backwards. Pooling is useful for GameObjects. Rarely useful for entities. Entities are literally just two integers. Whether you create them anew from archetypes or leave them deactivated, they should have very little overhead to anything.
well these entities have models + parents etc
your question came here like a shotgun...next time, please, give us some intro.
you could create thounds of entities using DOTS, much faster/easier/ligther than with GO....
said so, you still can create entities only when you are close to "them"
so, please, give us some context in order to help you,. if you need so.
yeah i am wondering how
i used to load position etc data from disk when player got close, that would be a list with few thousands
maybe blob assets?
im still confused...lets talk about your "map"...can we call it "city" (for example purposes) ?
it would be universe. when player is about 700 meters close to a planet, i load models positions,model references, rotations etc from disk, and i keep this data in memory, but if players is getting further, i remove it from memory
i also instantiate models from that list but not all of them obviously, only the close ones/visible ones, and deinstantiate when player gets away
that was the case with GOs
ok...then you could make a distance calculation each frame, to know if the player is closer than 700m
when this condition is met, you "trigger" your entities creation. the same may apply when player is >800m, where entities are destroyed
to sum up: same as with GO
dont entities need to be created 'tightly' from same native array and in same time or something
(the ones made not via ConvertToEntity system)
what?...Im even more confused now.
you have assets/prefabs, you can instantiate them whenever you want. If you are converting a scene, where the objects are already placed, that's another story
and furthermore, I don't know why you are using nativearrays...
Learn how to get started using Unity ECS.
โ
Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=ILfUuBLfzGI
Unity DOTS Explained
https://www.youtube.com/watch?v=Z9-WkwdDoNY
If you have any questions post them in the comments and I'll do my best to answer them.
๐ Subscribe for more Unity Tutorials https://www.youtube...
he used native array here
this tutorials are quite outdated and i have suffered a lot to learn the basics this week
hold a sec
try this guy: https://www.youtube.com/watch?v=H-goqMxN0Bc. i just watched another video from him, and it was much explanatory. I haven't seen that one though
he does...when he createEntity+archetype
Anyway, you could have arguments about "pure ECS" in #here. AFAIK, seems authoring is the expected way for dots. You can do thing by code, and I encourage you to do it, in order to better understand what is going on.
Said so, i can help you with specific questions, if you are able to set them (and I know how to).
eg:
how can i create an entity?
how can i create an entity from a prefab?
how can i add a collider to an entity?
...
i do authoring but in this very case i think it should be via code
You said you load from disk, this means you use subscene as spatial chunks, right ? If so, you could add/remove the RequestSceneLoaded component to toggle the subscene (planet itself would be outside of subscene so you can still see it from afar the stellar system)
but the models are child of planet
no i havent tried out dots subscenes yet
and the planet can move from left side of map to right side
at least the planet visuals should be their own object, because there's a high chance they should be always visible (depending on your game scope)
Ok my advice doesn't apply then ๐
but that's how I'd do
Maybe someone has a better way
I finally achieved to make my collision system work so entities get destroyed when they reach the borders.
Now, thinking about the spawn process, I'll need to detect when a spawnPosition is free, and that probably can be made with collisions also.
Is there a way to detect when a collision has ended? (to mark the position as available)I know I can setComponentData(true/false) on each frame, but seems a bad approach...did someone mention active waits?
im not converting. im authoring prefabs and creating from scratch (both).
im authoring scene objects
im not using mesh colliders, but physics
without colliders?
physicscolliders
Mesh colliders convert fine if youre talking about physics @gusty comet
I do not see such system added in entity analyser
did you add physics body+shape components to GO?
i use default sphere mesh right now as collider because my mesh is dynamic
but it didnt work for mesh too
well it doesnt display at least
Did you add the physics package to your project?
no
display!=collide
Well start there ๐
thats quite important...
Havok ?
com.unity.physics
Unity Physics
Theyโre both technically by the havok team but unity physics is probably a better starting point, source is available to modify
You can swap between them at any time so you donโt need to worry about special setups unlike say the SRP workflows
Just note v1 wonโt get updates or fixes
oh well i tried to convert them myself it didnt work at all
i mean i probably did well.. but didnt fix the final error
Itโs doable, thereโs some hints in the big hybrid renderer thread on it. Took me a while but v2 performance is really good, though if your entities are mostly static v1 should work perfectly fine
Depends if you want sync only when you press play, or if you want it to also happen on the background
-sync
+compilation
Is there a way to detect when a collision has ended?
I know I can check true/false if collision is happening on each frame, but seems a bad approach...did someone mention active waits?
DOTS Physics is stateless so you have to add your own state if you want to detect OnEnter/OnLeft events
is there such state thing or you mean diy?
The physics examples do have some onenter onexit type stuff which arent yet built in
Does a collision only alter velocity and angular momentum in your transform? Or does it alter other things.
Originally I was using real 3d physics for space combat, but then realized you can't dodge lasers like you barely can in WW2 emulated dog fighting Xwing could. So I use a janky control to simulate Xwing which is great, but on collision, things get messy. If I keep Xwing controls of just redirecting velocity, the collision doesn't do anything. So I do a hybrid for a few seconds, then resume Xwing false physics. I want to do better.
What exactly does a collision affect in your gameobject or entity transforms?
Thank you,
Jim
only changes the PhysicsVelocity(linear/angular), but you could easily add a system to do more than that
Got a reply on reddit too: [โ]woomph [score hidden] 8 minutes ago
Generally, the outputs of the physics simulation are the Rigidbody velocity, angularVelocity, position and rotation, which are then applied to the transform position and rotation depending on what interpolation settings you use on the Rigidbody (interpolate uses position/rotation and lags behind by one frame, extrapolate uses the velocity and angular velocity to make up for that but generally ends up being quite janky).
Thank you thelebaron. I am now confirmed that PhysicsVelocity(linear/Angular) is all that would change)
any one knows ?
just trying to understand how the axis set in the bodies influence the calculations and how to control this
the limits should be straight forward , but i bet my axis is set-up incorrectly
Hi does anyone know how to acess or assign child entities thru script? (I'm using conversion workflow)
To assign a child you add the parent component to the child and set the entity value. The transform system should take care of the rest
so add parent component to child, & value = the desired parent entity?
Yeah
got it, thanks :0
what happens to scriptable objects assigned to public fields of IConvertGameObjectToEntity class
on conversion
i think that data is lost.. any way to preserve it?
A goodnight question: If my gameobject.transform was : "transform.Rotate(Vector3.right * scalar);" What would the entity equivalent be to set Angular?
You need to manually convert it, BlobAssets are pretty much the equivalent of ScriptableObjects
OH lol
yeah you see maybe i should store them on disk instead then load them via addressables. i do not really need them from entities as i use them only once per few seconds (i change entities mesh every few seconds if needed, so having that code in OnUpdate in entities would be a waste of computational power wouldnt it be )
oh ok cool, the scriptables still stay in scene after you convert their associated objects to entities.
I can find them with FindObjectsOfType<>()
Question about correct practice: I have about 3000+ assets in my game that I do not want to manually add a physics body and physics collider to them. I know it is possible to add components on the fly. Is it acceptable practice to add physics body and physics collider automatically, and if it turns out to be a bad collider, alter it hardcode style?
Oh you can just put em all in the scene and add physics body on all 3000 at once.
Wow, that's that. I now have a semi-functional MMO engine. Time to bring on my army of rev share world builders. About 50 people said they'd want to do it, so I'm thinking maybe 3 might help a little. LOL, rev share.
lol help, I can't remember enough basic C# and DOTS to solve this ๐
should mention the waves[idx] refers to a nativearray of entities
I swear coming back to working in Unity after an absense always feels like recovering from a stroke
still having 3000+ things all the time in the scene lags the editor
but yeah you can add components via code
or remove them
i dont understand why that line wont compile ๐ค
shit really? structs have to derive from IComponentData to be used as components?
thank you thank you
thats what I mean about forgetting the basics. I remember the advanced stuff I was working on, but the basics escape me
yes that was it
oh right, I had other structs in my project that I was using as fields in componentData, so the presence of the naked structs confused me
oh LOL convert to entity on prefabs works during runtime too (not only on start)
your welcome
@stone osprey fyi viz2k from Mirror/DOTSNET team has done a TON of work on serialization/deserialization on DOTS. He's been raving about his generic networkcomponents and getcomponents<T> implementation. might be worth talking to him about how he did it
how do you parent an entity?
not derive, they have to implement the empty interface to be "tagged" as components ๐
right, yes. Sorry, didn't mean to sully the ideology with inheritance language
wasn't meant as nitpicking ๐
haha, no I gotcha
oh nice
so, i should not use Convert to Entity or IConvertGameObjectToEntity?
i mean
you need the reference to entity
or maybe the latter is fine
COnvertToENtity is deprecated but it should convert all the GO hierarchy ?
If I remember well
no way
Well it's easy to prototype things
but then you should use one of the conversion ways or subscenes
sometimes between next year and in-5-years if I would approximate xD
It's not yet but it will be
i did read they want you to do things this way
You should be using both
You write your authoring scripts (IConvertGameObjectToEntity) and use converttoentity so your authoring scripts can go through the conversion process when you enter playmode
Or alternatively use subscenes
Personally the "ConverterVersion" thing is enough for me to not touch subscenes ever
given subscenes are finally compatible with uitk in the latest editor alpha, theyre really handy to improving scene load times
to already existing entity
Where did you red that ? make sure you use latest version of dcumentation
Hi, I am using raycasting to make boids (gameobjects) avoid objects. As far as I can tell from debug. stuff raycasting and checking if headed for collision is working. Problem is that the boids dont change their direction (stored in velocity array) and fly through the objects.
I am loosing my mind and the deadline is monday, any help is appreciated:)
public struct BoidAvoidObjJob : IJobParallelForTransform {
public float deltaTime;
public NativeArray<Vector3> velocity;
[ReadOnly] public NativeArray<bool> isHitObstacles;
[ReadOnly] public NativeArray<Vector3> hitNormals;
public void Execute(int i, TransformAccess transform) {
// in case of disaster change these:
int weight = 12;
var avoidanceVector = Vector3.zero;
var found = 0;
var rotationSpeed = 2;
Debug.DrawRay(transform.position, velocity[i] * 2, Color.yellow);
// at this point we know if boid is about to hit sth
if (isHitObstacles[i]) { // if the ray cast from a boid hits sth -> avoid
// calc new vector:
avoidanceVector = Vector3.Reflect(velocity[i], hitNormals[i]);
avoidanceVector *= weight;
velocity[i] = avoidanceVector;
// test to see if changing velocity works at all -> works!
//var test = Vector3.zero;
// velocity[i] = test;
}
}
}
setting up isHitObstacles Array (which tells us if boid is about to hit sth) and hitNormals (contains normal of object to avoid) (this happens in BoidManager.cs before the jobs are instantiated) :
// setting up isHitObstacles Array------------------------------------------------------------------------------------------------------
for (int i = 0; i < number; i++) {
RaycastHit hit;
// True when the sphere sweep intersects any collider, otherwise false.
if (Physics.SphereCast(BoidsPositionArray[i], 2, VelocitiesArray[i], out hit, raycastDistance)) {
hitNormals[i] = hit.normal;
isHitObstacles[i] = true;
}
else {
isHitObstacles[i] = false;
}
}
what causes them to build up velocity in the first place, @torn hollow ? My initial hypothesis is that you have an order of execution problem:
First, your obstacle detection system is running and velocity is set to the avoidance vector,
Then, your "move" system is running and adding velocity in the original vector - towards the object you are intending to avoid
could be wrong, I'm just testing the easiest hypotheses first
velocity is set up along the other arrays in start() of boidmanager
VelocitiesArray = new NativeArray<Vector3>(number, Allocator.Persistent);
for (int i = 0; i < number; ++i) {
goList.Add(Instantiate(prefab, Random.insideUnitSphere * StartRadius * AgentDensity, Random.rotation));
// ref to current gameobject
var obj = goList[i];
// for TransformAccessArray
TransformTemp[i] = obj.transform;
BoidsPositionArray[i] = obj.transform.position;
VelocitiesArray[i] = obj.transform.forward * maxVelocity;
}
TransformAccessArray = new TransformAccessArray(TransformTemp); // so far so good
and updated at the end of the update() loop in boidmanager
// UPDATE BOID-------------------------------------------------------------------------
for (int i = 0; i < number; i++) {
if (VelocitiesArray[i].magnitude > maxVelocity) {
VelocitiesArray[i] = VelocitiesArray[i].normalized * maxVelocity;
}
TransformAccessArray[i].up = VelocitiesArray[i]; // cannot turn this into a job bc transform.up
TransformAccessArray[i].position += VelocitiesArray[i] * Time.deltaTime;
}
okay, so the boids are only calculating their trajectory once at the beginning and then they just get deflected from that vector as they move?
I say that because I don't see anything in there determining their heading
theyre always just going forward
basically yeah, the rotation is randomized in the beginning and then according to the VelocitiesArray they change their position by changing TransformAccessArray[i].position
so the heading is always "forward"
and I take it you've tested with printstatements, etc, that the if statement is being triggered, and the reflected velocity looks right?
cause everything in that code seems right from what I can tell. so that could point to a collision problem or an order of operations problem in the update loop (like maybe it moves inside the sphere before it gets reflected so that next frame it gets reflected back along its original heading or something)
okay yeah interesting thought! will look into it rn, i tested a bit more and found that for one boid the avoidance vector is the same as the velocity vector * -1, whereas for multiple boids it isnt,
Also interesting to note that using velocity[i] += avoidanceVector; or velocity[i] = avoidanceVector; didnt make a difference in the single boid case since i thought it would
e.g. one boid
e.g. 100 boids
I have a problem that My Unity DOTS behaves differently when built vs in editor where it works: 43 sec video https://youtu.be/otND28wwQpE
In the editor, I can fly around my open galaxy in dots.
In the compiled game, it freezes.
I wonder why? Any help.
If you like what you saw, you can come to like the only positive zone of the Internet I know: www.twitch.tv/goodnewsjim The Bro Zone Layer.
Temporary offer for anyone of any skill level: Can someone contact me to promote my gam...
Fun show off stuff: I found out how to load a scene without destroying the current scene, and spawned hundreds of asteroids: https://youtu.be/cWoVYV9tTm0 & https://youtu.be/CJrOXTgW5cY
If you like what you saw, you can come to like the only positive zone of the Internet I know: www.twitch.tv/goodnewsjim The Bro Zone Layer.
Temporary offer for anyone of any skill level: Can someone contact me to promote my game? www.starfightergeneral.com I'll give you half the sales you drive.
Play the spiritual sucessor to xwing vs tiefight...
If you like what you saw, you can come to like the only positive zone of the Internet I know: www.twitch.tv/goodnewsjim The Bro Zone Layer.
Temporary offer for anyone of any skill level: Can someone contact me to promote my game? www.starfightergeneral.com I'll give you half the sales you drive.
Play the spiritual sucessor to xwing vs tiefight...
Are you using subscenes? If so are you building by using a BuildConfiguration?
@torn hollow in the case of one boid, im curious, if you do it for multiple frames, is the velocity vector oscillating back and forth?
actually it is
SubScenes in DOTS context are scenes that you use to convert your entities during edit time so you do not have to do any conversion during runtime.
I'm not referring to multiple unity scenes sorry if my question was confusing
gotcha. so then my hypothesis is that the boid moves inside the collision surface, because theres probably a one frame delay on reacting to the collision.
so, it moves inside at the beginning of the frame, and at the end of the frame it turns around. then next frame, it casts a raycast and collides again in the opposite direction, since the raycast originated inside the object its colliding with
I do establish a reference towards my entity through extending the create and destroy class.
Many youtubers use it...
the only question is why that doesn't cause it to just halt in place
huh what create and destroy class?
oh my god i would have never figured that out, thank you!!, ill test what happens if i move stuff in update() around
cool, I hope it helps. order of operations stuff like that is really common in collision
Convert to entity class
nice, i need to add asteroids in my game lol
Lots of cheap ones in asset store.
You know what. I can find help about why my game won't play live later. I'm sure it is a setting or something.
nah its not that easy, i have my hands full now with orbit and planets etc
I should work on other techs. Today is the day I world build.
Time is the enemy of man
And cleaning your house
Anyone have a link to the Unity Forums thread where people discussed the best patterns for extracting ECS code into self-contained, [BurstCompile]-able methods to improve code readability and maintenance without sacrificing performance?
I believe it was in reference to dropping support for IJob structs and moving to the newer Entities.ForEach APIs
extracting?
how do you spawn these things btw, CreateEntity or ConvertToEntity
In the code refactoring sense, calling methods instead of copy and pasting code everywhere ๐
I was just importing scenes
Mark everything on your scene as to not destroy
A script:
JohnOt: Use this script
And put it on every single object in your main scene
Then make other scenes without anything but objects and entities to load
So when you call:
SceneManager.LoadScene("SceneName");
It just throws it all in the mess ๐
Using scenes is finally awesome like it shoulda been 10 years ago.
I'm trying to figure out how to make a unity project without my scripts, just assets to allow my worldbuilders to make worlds, but not see my encryptions and protocols.
but it looks like youre using one scene
Then I want them in a live version to "Load their scene" into it
Well I don't despawn ANY of it. I just add a new scene into it
That was the script I posted above to not destroy objects on scene respawn
ctrl+a all your main scene, attach it to all, you're good to go
oh i never used unity scenes tbh
well i will prob load things from scriptable objects > CreateEntity(array)
You can do that, but I am employing lots of talentless world editors
All most of em they can do is drag and drop
oh ok lol
i have already convertToEntity orbits and planets
and now the models will be children of planets
but made from scriptable
yup, its fun to watch stuff orbit
3 types
i am still not sure how to exactly do this haha before planet had areas and areas had models so i wouldnt iterate over thousands but over hundreds
Found the underlying limitation in my refactoring. Given a method like this:
{
vout.X = (float) vin.x;
vout.Y = (float) vin.y;
vout.Z = (float) vin.z;
}```
I want to put this in a static class and call it from multiple Systems. This does not compile, due to the following error:
```Burst error BC1064: Unsupported parameter `Unity.Mathematics.double3` `vin` in function `double3ToFloat3(Unity.Mathematics.double3 vin)`: structs cannot be passed to or returned from external functions in burst. To fix this issue, use a reference or pointer.```
However, if I copy that method and put it inside the same class of the System I'm calling it from, it will compile.
So... Is there any way to neatly refactor this? ๐
ui toolkit ? ๐คฉ
public class ModelAuthor : MonoBehaviour, IConvertGameObjectToEntity
{
Entity parent;
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
dstManager.AddComponentData(entity, new Parent { Value = parent });
}
}
Do you guys know how to (having this script on prefab) set the parent variable, and THEN instantiate the prefab?
hmm maybe i could just change prefab value
but theres prob better way
i mean via code by the way
OH it seems i can instantiate first, and THEN set variable > add convert to entity ๐
yeah, Im having some odd issues updating my uitk stuff for the alpha and unexpected stuff broke that worked previously but subscenes finally work with it @karmic basin
I get an error on my standalone game that says: "the scene catalog has not been loaded yet" Why is this?
that's really good news ๐
I mean except your broken parts but I'm sure you'll figure that eventually ๐
where did this "BC1040: Loading from a non-readonly static field is not supported" nonesense come from?
You're reading from a non-readonly external variable inside a bursted function (e.g Entities.ForEach). You cant do that
Either label the variable as .ReadOnly(variable) or wrap it inside a unmanaged container (i.e NativeReference)
oh interesting, NativeReference is new to me
Or just not use burst (i.e WithoutBurst()), that also works.
although it occurs to me its weird that Im using the non readonly at all, now that you point it out.
Native Reference is a one sized native array. Nothing fancy.
I should be supplying a copy of it to the job
yeah actually. that was one of those instinctual "this code used to work! what happened?" that turns immediately into "why did this code ever work?" when you look at it closer
i set up a urp template and added the hybrid renderer v2 to the project, but for some reason the lit material is super reflective in the live link build
what am i missing? or is this normal?
Yea, I had the same problem. Hybrid renderer appears to double the shader values when used. It might be rendering things twice for some reason.
No clue why. One of my many reasons why I think Hybrid Renderer is garbage.
whats the alternative?
Personally, I've been hooking up various transforms and values to Entities manually using my own systems.
Then use HDRP, my project's renderer, like usual.
I kinda have a working DOTS game, but it doesn't work outside editor. Instead I get error: AssertionException: The scene has not been loaded yet. nextline: Assertion Failure. Value was False nextline:Expected True
How are you building the project? Are you using the Platforms build tool?
i forgot to answer earlier but your theory was right and i could fix my problem by reordering stuff in my update(), thank you again!!
I am simply hitting file->build settings ->build like all my exports have been so far to go live on Steam.
Dots however doesn't seem to like that.
you shgould use the new platforms/buildconfiguration workflow for building dots projects. subscenes dont get built in the old way build process
the samples should have an example but the gist is you add the Platforms package and then also the platform specific package(ie windows or mac, etc) and then create a buildconfiguration file which is just a scriptableobject, that has all the settings in it
rot.Value = quaternion.LookRotation(direction, math.up());```
what am i doing wrong here? ๐ค
in examples ive found this is how they seem to be doing it
ooh, was due to using Unity.Mathetmatics.math. Ignore me
my entities are getting rotated on creation, anybody had this issue (and found a way to overcome it)?
Wow thank you thelebaron! You sound like you know what you're talking about. I spent 10 hours trying to get it working today.
just note I think current ui toolkit packages somehow break subscenes unless youre on the current alpha editor ๐ฉ
I'm on alpha 10
11 and 12 will not work
Maybe I should aim at getting 12 to work?
im just staying on alpha9 for a bit, so far it seems good enough to keep using
A guy said windows platform doesn't go past 2020.3, but my code would not deowngrade and work: https://old.reddit.com/r/Unity3D/comments/moa9ks/what_could_cause_dots_to_fail_in_standalone/gu3q7dt/?context=3
2 votes and 9 comments so far on Reddit
given the beta is out of beta, and now alpha should be beta, id hope next release brings fixes for platforms for the next editor releases
I'm dumb
I thought I couldn't get my world editors working on this unless I can compile a stand alone.
I can legit give them version control access
And they can start making levels for when this is fixed
sweet! That's all I wanted to accomplish today.
is that not correct way to make prefab?
dstManager.AddComponentData(entity, new Prefab { Value = somePrefab });
dstManager.AddComponentData(entity, new Parent { Value = entity });
first line doesnt work
isnt prefab a tag component?
i kinda wanna use ConvertToEntity, but with the root prefab not converting https://i.imgur.com/wRwDDu1.png
so that the spheres are roots
oh well maybe ill just keep them
@gusty comet Like Roycon said, Prefab is a tag component. I think you confused with Parent. If I don't forget anything, what makes entity prefabs is just said Prefab tag so it gets ignored by default in queries +a LinkedEntityGroup to mimic GO hierarchy. Usually you would use lDeclareReferencedPrefabs to allow the conversion sysyems discover your prefabs.
But it looks like you're trying to do it at runtime ??
Nah I'm drunk looks like you're using conversion systems xD
Yeah so you need to declare your prefabs before conversion happens
well i thought about instantiating prefabs that have convertToEntity component and they would then convert automatically during runtime
or is your method better?
so something like Instantiage(PrefabWithConvertComponent) and it does the rest automatically
but maybe theres more performant way idk
@gusty comet No the ideal way to do it is to use IDeclareReferencedPrefabs
why
i took 2 day holiday from dots and you wrote more than ever!!!
anyway...here goes my question:
considering I have a component with a boolean property called foo, is there a way to get all components having that set true/false?
eg: Entities.WithAll<MyComp>().Having(foo==true).ForEach
:P
In a stats based combat mechanic... does it make sense to have single components for stats ?
Player{ Character, Health, PhysicalDamage, MagicResistence }
Or does it make more sense to have a single stats component ?
Player{ Character, Stats{ NativeHashMap<string, float> stats }
Because actually stats are always the same... some name and some ( mostly ) float value
I'm actually doing the first. it would probably better to use the second. You might be interested on my question (ie: selecting entities with specific values)
@night venture Thanks ^^ Yeah im also interested in that ๐ But is there any advantage over having one component per stat ? Well we can loop easily over them and add/remove them in a dynamic way... but i think thats all or ?
how do you access custom component data in Entities.Foreach of queried entity parent
oh well i figured it out
OrbitData orbitData = EntityManager.GetComponentData<OrbitData>(parent.Value);
galaxyData.currentAngle += orbitData.speed * 10f * deltaTime;
is that fast??
maybe its better to put variables inside queried entity data
so you dont have to check parent
its probably not good to use it in OnUpdate ._.
I'm sure there's advantages to both approaches. IMO having a component per stat will be more scalable. As your game become more complex, it will draw a map of archetypes, kinda optimising by default your data layout and thus queries.
But what about RPG games where you can have dozens (hundreds?) of such components, are hash maps a better approach ? I don't think I have the answer yet ๐คทโโ๏ธ would need to test a concrete example.
Also isn't that here ^ some kind of answer ?
Alright thanks ^^ i think im gonna go with the hashmap approach for the first... I guess thats easier to start with
if NOT every entity does have those stats, then it could make sense. if "house" only have health and can be equally damaged with magic or physical, then i would, for example, split health from the others.
---
Considering I have a component [MyComp] with a boolean property [foo]. Is there a way to get all components having an specific value for a property?
eg:Entities.WithAll<MyComp>().Having(foo==true).ForEach...
before i got my Systems to work but they dont work now. eg OnCreate, anyone knows why?
going to look into them...can you point closer to which example?
thats a though question...did you tried the old reliable Debug.Log("im here"); ?
yeah it executes
but it doesnt copy data
protected override void OnCreate()
{
Debug.Log("Start");
Entities.ForEach((ref GalaxyData galaxyData, ref Parent parent) =>
{
OrbitData orbitData = EntityManager.GetComponentData<OrbitData>(parent.Value);
galaxyData.persistentSpeed = orbitData.persistentSpeed;
galaxyData.persistentRadius = orbitData.persistentRadius;
}).WithoutBurst().Run();
}
you are iterating through ALL your entities?
wym
'cause i was expecting something like Entities.WithAll<affecteb_by_a>().ForEach
i mean im specifying two components so it filters them automatically right
if you get orbitdata as ref, you wont need EM, hence could use burst...isnt it?
nvm got it to work
oks
onstartrunning is executed BEFORE oncreate
i dont get what u mean
No way, oncreate didnt work for me
xDf
.WithAll<LocalToWorld>() // Require the LocalToWorld component
is that not the same?
Entities.ForEach((ref GalaxyData galaxyData, ref Parent parent) =>
and, be aware of (i wasn't) ons start running is run each time loop is "resumed"
i wouldn't expect it to be...but perhaps someone wants to correct me.
afaik, Entities.ForEach get all entities, and then you got their (ref GalaxyData galaxyData, ref Parent parent) components
perhaps, DOTS is intelligent enough to apply that as filter
but i would expect it returned null for entities which dont have those components
now faster?
Entities.WithAll<GalaxyData>().ForEach((ref GalaxyData galaxyData, ref Translation translation) =>
tbh maybe it would be better to not query the list every frame at all
and just cache the list
not sure if its possible with dots
WithAll<T> when you're only interested in finding entities with that component, ComponentData as a param in the Foreach lambda when you're also interested in read/write the Component
But yes Foreach params are also used in the query
hope that answers your concerns
so, essentially Entities.Foreach(Foo foo) and entities.WithAll<Foo>.ForEach(Foo foo) are the same?
is the performance the same
yes, but redondant, so it will throw an error or warning at least IIRC
for example you would query your component tags with WithAll<T>, it would be enough
I know where it is, I can show. Basically they use 3 DynamicBuffer s of entities (1 for each state OnEnter, OnStay, OnExit), and you can then check if your entity is in one of these States
Lemme find it again for you
And AFAYK, monsieur K, the only way to check a component value would be
Entities.WithAll.ForEach((MyComp c)=>{
if(c.foo) {return;}
//false, do things
}).Run();
or is there something like
Entities.WithAll<MyComp>().Having(foo==false).ForEach... ?
Be aware though, it looks more like custom hacked code than a final version for now I'd say. But still works ok
This another question, lets get back to it after
ill probably check each frame by now, which sucks. ๐คทโโ๏ธ
I recommend cloning the project and studying ALL SCENES in this folder : https://github.com/Unity-Technologies/EntityComponentSystemSamples/tree/master/UnityPhysicsSamples/Assets/Demos/2. Setup/2d. Events
Some quick summary from release notes:
* Improved usability of trigger events and collision events:
* Events (StatefulTriggerEvent and StatefulCollisionEvent) have states indicating overlap or colliding state of two bodies:
* Enter - the bodies didn't overlap or collide in the previous frame, and they do in the current frame
* Stay - the bodies did overlap or collide in the previous frame, and they do in the current frame
* Exit - the bodies did overlap or collide in the previous frame, and they do not in the current frame
* Events (StatefulTriggerEvent and StatefulCollisionEvent) are stored in DynamicBuffers of entities that raise them
* Reworked following demos to demonstrate new trigger event approach:
* `2d1a. Triggers - Change Material`
* `2d1b. Triggers - Portals`
* `2d1c. Triggers - Force Field`
* `2d2a. Collision Events - Event States` added to demonstrate new collision event approach.
+1 StatefulCollisionEvent
For your other question, having something like
Entities.WithAll<MyComp>().Having(foo==false).ForEach... ? doesn't exists as far as I'm aware
But, you could approach .Having(foo==false) like NOT having a component tag, and when true you add the tag ?
Or ISharedComponentData could be the way
otherwise yeah, put a component with a bool and check every frame in the system. Sure you will query entities and discard a lot
I'm pretty sure the docs talk about that specific scenario ? (not sure really)
Otherwise a lot of seasoned members here will correct me and give you the best approach they found ^^
Maybe Filters are the way, could be worth looking this way
- the bool was an example. actually, it would be bool array field.
- sharedcomponents looks promising, as it would group chunks
going to read those physics examples first
thanks!
You're welcome, happy coding
Just my opinion: bool checks tend to beat a lot of things in practice. If entities are going to keep a certain state for some time (rule of thumb order of magnitude > a few seconds) then it's often worth Tagging them. SCDs are rarely an overall win due to the chunk fragmentation but a) it can be worth using them for code simplicity sometimes and b) they can sometimes be a great tool imo provided the fragmentation isn't an issue. I think maybe 90%+ cases I've seen performance may be better switching on an enum instead.
Oh also, a lot of us are eagerly awaiting the .enabled states Unity are working on for components as the best compromise. Though it's been a year or so since we heard they were working on them without any sign they're in the codebase yet.
They will in theory act a lot like bool checks but have a simd optimised back end and by default a disabled component wouldn't be returned by a query. One day ๐ค
๐
Damn it's already been a year since enable/disable was first mentioned? ๐ด
don't quote me in that - feels like 3 years but it might be more like 6 months in reality
talking about that, can't wait to see 0.18 and what it brings. Should be around the corner now, right ?
ok...so after started reading docs, noticed OnStartRunning is expected to be invoked each time update is enabled (RequireForUpdate status changed again to true after being false).
if simulation is to be paused somehow, for example to display game menu, then OnStartRunning would be called again, and that make it unsuitable for initialization things
so, I could put initialization inside OnCreate, and that makes sense...but seems systemB is being invoked before systemA which is supposed to set some global variables first.
as I was using B's OnStartRunning everything was working, but when switching to B's OnCreate, it isn't anymore
it probably appears on docs, but is there a way to define system dependencies?
how could I be sure systemA has ended (at least OnCreate) before systemB OnCreate being executed?
perhaps something similar to RequireForCreate?
EntityManager.World.GetOrCreateSystem<SystemA> inside SystemB's OnCreate.
hmmm...arent my systems:systembase supposed to be invoked "automatically"?
all that will do is create the system first if it isn't yet - which you want if you want it to exist at that point
UpdateAfter UpdateBefore, and UpdateInGroup attributes ?
I would personally reserve those calls for the order you want the systems to execute - not necessarily the same as where you e.g. want to keep a native collection
that's only for update code, not for create code
fair enough
doesn't seem to work.
systemA initializes static variable which is used by systemB and it still complaining...
I'd avoid using statics altogether - you'll have to be super careful with fast enter playmode and disposing if you do use them
that's true...but it helped me detecting GetOrCreateSystem does not run "oncreate" befopre coming back
code?
hmm why not construct the world manually, initialize your statics first then construct the systems that need to rely on it?
SustemA : SystemBase {
public static EntityArchetype Archetype;
protected override void OnCreate() {
Archetype = EntityManager.CreateArchetype(
// Archetypes allow to have default values set
typeof(RenderBounds),
typeof(LocalToWorld)
);
...
}
SystemB : SystemBase {
protected override void OnCreate() {
EntityManager.World.GetOrCreateSystem<SystemA>();
...
for (int i = 0; i < list.GetLength(0); i++) {
for (int j = 0; j < list.GetLength(1); j++) {
tiles[i, j] = EntityManager.CreateEntity(SystemA.Archetype);
...
}
``ArgumentException: EntityArchetype argument is invalid. Calling new EntityArchetype() produces an invalid value. Call EntityManager.CreateArchetype() to get a valid EntityArchetype value.`
it's what I'm doing...but since the moment I moved code from start->create, it started failing
where's the call I suggested? EntityManager.World.GetOrCreateSystem<SystemA>()
forgot to copy it :P, but is there.
Well I was thinking more of implementing ICustomBootstrap
class SomeBootstrapper : ICustomBootstrap
{
public bool Intiialize(string defaultWorldName)
{
var world = new World("SomeName");
// Initialize your statics
some_static = world.EntityManager.CreateArchetype(...);
// Make the systems and push them to your world.
var systems = DefaultWorldInitialization.GetAllSystems(...);
DefaultWorldInitialization.AddSystemToRootLevelSystemsGroups(...);
World.DefaultGameObjectInjectionWorld = world;
...
}
}
i need to add models now ._.
so systemA which does initialization stuff only, should be implementing ICustomBootstrap instead?
can you filter Entities.ForEach basing on some component value ?
no this is just another class which is responsible for creating the world & systems (so your systems stay the same) @night venture
so far, seems shared componentdata could be a way for boolean properties. for float values, i have no clue yet
SystemA : SystemBase {
public EntityArchetype SomeArchetype;
protected override void OnCreate() {
SomeArchetype = EntityManager.CreateArchetype(
// Archetypes allow to have default values set
typeof(RenderBounds),
typeof(LocalToWorld)
);
}
}
SystemB : SystemBase {
protected override void OnCreate() {
var sysA = EntityManager.World.GetOrCreateSystem<SystemA>();
EntityManager.CreateEntity(sysA.SomeArchetype);
}
}``` - if you copy paste this, it throws the same error? I'm not in an ECS project right now.
on my way...but is essentially what im doing
there is a Filter job (can't remember the exact name) but all it does is iterate entities and compare values, writing them into a nativearray. Entities.ForEach(... if(foo.bar == 5)... ) is the expected pattern. That's partly why designing your archetypes is a very important part of the design process.
oh ok so you simply use IF statement inside Foreach
i will have lot of filtering later so not sure haha
yea, or switch an enum. If you want to switch on e.g. presence of a Tag you can either a) write multiple foreach's and put logic in statics), b) use HasComponent<SomeTag>() or c) write out the lambda as an IJobEntityBatch and switch at the chunk level (which is more efficient than branching per entity).
btw whats the IN keyword doing ?
hmm actually what's the major difference between IJobEntityBatch and IJobChunk? I still mainly use IJobChunk ๐
i know that ref is modifying the original
oh
say 1000 entities would fit in a single chunk, IJC is limited to running that on one worker. IJEB allows you to split them up into smaller batches, allowing you run parallel with a smaller number of entities.
oh, yea that's actually a pretty good case
further to what @coarse turtle said, you can safely read data in parallel. You can't safely write data in parallel. You want to use in everywhere possible so as much work can happen in parallel as possible. Unity's scheduling system handles making all of this safe.
Yea it's intended to completely replace IJC as with a value of 1 batch, it behaves identically to IJC
it works. but it's also working if i modify it to use static and static reference (class instead of instance)...perhaps is too small to impact. anyway, i understand what's your approach. Ill have a look at ICustomBootstrap
sounds, good - guess I'll start converting some IJC to IJEB
I modified it not to be static as it's better practice. An archetype is not valid across multiple worlds so that's another reason not to use static.
Main caveat is that if you use an ISystemBase - at the moment they error with IJEB's and only work with IJCs - though hopefully that'll change with 0.18
I dont have multiple worlds...don't I?
yea, i remember that issue with ISystemBase
if you do any conversion and those systems were to run for those subscenes, it would be - just all round a bad idea but by all means, stick with it for now.
not doing any conversiones neither having subscenes...but i'll take your advice...
i kinda wonder how to rotate planet in dots
rotate a planet?
ye but in specific way
i guess you mean not only sphere, but all object withing sphere surface?
nono the objects are children so its not a problem
...
rotating in the direction of black arrows
i guess i should try to design it in monobehaviours first lol
err...unity physics have gravity attractors
i dont want real gravity
then, its a simple rotate around a point or an axis (quaternion!)
i would say it otherway
place an object in the center, make it rotate and always move the world to new position based on the axis of rotation
probably math library has a simple function for that...but as a trick, consider the radius and the time u need to make a whole loop
is your planet an entity?
but, please...have in mind the example provided in physics...it could help you
furthermore if objects have mass xD
omg...is mars going to collide with earth???
thinking on your approach World.GetOrCreateSystem<SystemA>(); won't do the job, as systemA would then be initialized multiple times (as it does more thing just just defining the archetype)
it should only call OnCreate once
oh!...right...it's a singleton :S
no but GetOrCreate - will get the system if it exists - if it doesn't exist yet, it will create it
that kinda works for monobehaviours
void Update()
{
Vector3 dirToCenter = (Vector3.zero - transform.position).normalized;
transform.right = -dirToCenter;
if (counter < 360) counter += 1f;
else counter = 1;
transform.RotateAround(transform.position, transform.forward, counter);
}
so...should the dependant systems (systemB) invoke World.GetOrCreateSystem<whatever>(); to establish dependencies on creation? is that a correct way of handling it?
rotatearound changes from origion to destination, right?...why dont u use planet position?
counter = 1f ๐
If I understand you correctly then yes, I think that's perfectly reasonable. It's making your dependency explicit. It's a good pattern in the sense that if that system B is later deleted or no longer runs, everything works fine. Likewise if you add SystemC that also requires SysA but runs before SysB, everything will continue to work fine.
beside systemgroups...is there another way to specify job dependency, as far as you know? @amber flicker
what kind of game are you making kiwi
this kinda works for me
rotation.Value = math.mul(rotation.Value, quaternion.RotateX(math.radians(50f * originalDelta)));
except not completely.i think its not using localX
and theres one huge issue, lot of methods of Mathematics/math are not actually showing up despite being there
2d city ๐
but more learning ECS than other thing ๐
@amber flicker
SystemB.OnCreate start...
ArgumentException: EntityArchetype argument is invalid. Calling new EntityArchetype() produces an invalid value. Call EntityManager.CreateArchetype() to get a valid EntityArchetype value.
SystemA.OnCreate start...
SystemA.OnCreate end.
this "dependency" system doesn't work as expected
Still struggling around with what should be an entity or not. Inventory-Items for example. In my case they should have a name, an amount, some bools and probably some actions they execute once used or every tick. It could be an entity but there also other ways.
// Kinda like this
public struct Item{
FixedString32 name,
int amount,
Method onEquip,
Method onUnequip,
Method everyTick
}
Would you say such an inventory item should become an entity ? It still depends on the player and cant live without him... so i actually think it shouldnt be one. But it should also execute logic every frame.
This works:
Entities.WithAll<House>().ForEach((RenderMesh mesh) => {
mesh.material.color = new Color(1f, 1f, 1f);
//TOOO scale
}).WithoutBurst().Run();
This doesn't work:
Entities.WithAll<House>().ForEach((RenderMesh mesh, Transform transform) => {
mesh.material.color = new Color(1f, 1f, 1f);
//TOOO scale
}).WithoutBurst().Run();
shared components can't be messed the same time as non-shared?
seems [DisableAutoCreation] is the way to go. Altough I would suggest Unity to [EnableAutoCreation] instead
@night venture Transform isnt a componet
its the old MB transform
your probably thinking of translation
translation has only 1 value=position. im talking about SCALE
@stone osprey I would say yes Item should be a Entity, if it needs todo logic or needs to be queried for.