#archived-dots

1 messages ยท Page 213 of 1

night venture
#

so recycling is another system

ocean tundra
#

eventually ( greater then 1000 systems) systems can have performance issues, but by the time you hit that Unity will have optimised them again

night venture
#

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?

ocean tundra
#

yup

night venture
#

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

naive ice
#

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)

night venture
#

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)
    })
});
night venture
#

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)

ocean tundra
#

at a guess putting center at 0.5 will offset the collider from translation

#

yea so querys are annoying

night venture
#

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
ocean tundra
#

just add that component to a GO

#

with ConvertToEntity

night venture
#

damn mudblood xD

solid rock
ocean tundra
#

nope

#

but theres some sort of new graphics API

#

hybrid renderer is using it

night venture
#

this morning or yesterday when dealing with meses i saw something...hold a sec

solid rock
#

Where would I look for more info on that?

ocean tundra
#

inside hybrid renderer somewhere

#

at a guess find any systems inside this group InstancedRenderMeshBatchGroup

solid rock
#

"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."

ocean tundra
#

its called something something batch ๐Ÿ˜›

solid rock
#

Yeah that sounds like exactly what I need lol

#

Ugh this stuff is all so immature

naive ice
#

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

ocean tundra
#

this is it i think

naive ice
#

Seems like a waste to have a pool of Mesh objects to abuse, which is what I did aaages ago

ocean tundra
#

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

ocean tundra
night venture
#

pst, @ocean tundra do you name your components...RoadComponent...TileComponent....~Component? ? ~Data? Nothing at all?...most of mines are tags...

ocean tundra
#

na i just name them what they are

#

eg Health

#

i do sometimes end tags with Tag ๐Ÿ˜›

night venture
#

thx...i share you pov

naive ice
ocean tundra
#

and all my systems end with System

#

i would focus batching for everything else ingame, eg trees would be great batched

ocean tundra
#

there is also a DisableRenderering component

#

as Disabled will prevent the whole entity from being processed in any system

night venture
#

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

ocean tundra
#

meh maybe

#

DOTS is wayyy faster

#

recycling isnt really needed

night venture
#

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

ocean tundra
#

i would just destory and recreate

#

its easier on brain power

night venture
#

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

ocean tundra
#

and the resetting of data could end up quite complex

night venture
#

i mean...cars[i]=new car(...)

#

as im not using nativearrays or anything similar, i dont have to dispose anything...

#

gc would take car

ocean tundra
#

no gc

#

dont worry about that

night venture
#

well...if recycler deletes the entity, freeing cars[x]

#

should i be checking cars.length to create? that sucks

ocean tundra
#

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

night venture
#

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?

ocean tundra
#

depends on the task

#

if its a entity thing just use Foreach

night venture
#

create a new entity

ocean tundra
#

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

night venture
#

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)

ocean tundra
#

you still call from OnUpdate

#

its just a job instead of a foreach

night venture
#

i didnt understood these 2 lines

ocean tundra
#

everything in dots happens in onupdate

night venture
#

ok,i got it

#

i like dots...

ocean tundra
#

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

night venture
#

yes, but i dont want to duplicate the code between systems

#

so recycler has to call spawner

ocean tundra
#

systems shouldnt call eachother

night venture
#

then recycler must die xD

ocean tundra
#

instead create 'trigger' entities to make systems work

night venture
ocean tundra
#

or when further along use the EventSystem on the forms

night venture
ocean tundra
#

ignore that for now

#

look into singleton entities

night venture
#

no, noo, noooo

ocean tundra
#

things like requiresingletonforupdate

night venture
#

you said 2 things, please, lets analyze

ocean tundra
#

and has singleton

night venture
#

whats that

when further along use the EventSystem on the forms
?

ocean tundra
#

honestly you dont need it

night venture
#

is this like the message queue between systems someone talk about a while ago?

ocean tundra
#

dont know

#

maybe

night venture
#

but essentially is a ecs-based event-"handler", right?

ocean tundra
#

yea

night venture
#

i would say broker/message queue

ocean tundra
#

tho more powerful

#

yea

night venture
#

ok...and apart from that, you also suggested using requiresingletonforupdate

#

which seems is something to ensure onupdate is only run on certain conditions

#

right?

ocean tundra
#

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

night venture
#

but there might be cases where this applies...

#

kind of triggering a system

#

and is based on creating an entity?

#

or a component?

ocean tundra
#

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

night venture
#

do you have an example at hand?...

ocean tundra
#

notreally

night venture
#

is set on system creation, right?

#

like a flag...

ocean tundra
#
em.createentity()
em.addcomponent<yourtriggercomponent>(entity)

inside your system

requireforupdate<yourtriggercomponent>()


END of onupdate

em.destoryEntity(getsingletonentity<yourtriggercomponent>())
night venture
#
public class my: SystemBase
{
    protected override void OnCreate()
    {
        RequireSingletonForUpdate<whatever>();
    }
    
    protected override void OnUpdate()
    {
        Debug.Log(GetSingleton<whatever>().Value);
    }
}
ocean tundra
#

yup

#

and cleanup at the end

#

otherwise it will keep running

night venture
#

by end you mean last line of onupdate, right?

ocean tundra
#

yea

night venture
#

how many years have u been messing with ecs? xD

ocean tundra
#

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 ๐Ÿ˜›

night venture
#

at this moment 0.17, right? when u think it will be 1.0?

ocean tundra
#

never

#

na like 5+ years

night venture
#

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?)

ocean tundra
#

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

night venture
#

does that mean if i want to play a sound ill need an hybrid GO to play it?

ocean tundra
#

yup

#

you can try the sound thing

#

but not sure its anygood yet

night venture
#

ok...well...enough chatting for now...going to fix this recycling thing

#

thanks, as usual!

karmic basin
#

@night venture loads of questions you ask are answered in the official manual. I suggest you read it 100% at least once.

safe lintel
#

theres technically a dots timeline package

#

its never been mentioned at all by any staff so take that for what its worth ๐Ÿ™‚

ocean tundra
#

๐Ÿ˜› im sure it will be great to use

night venture
#

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?

safe lintel
#

it even has (kinda working) samples @ocean tundra ๐Ÿ˜„

night venture
#

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.

safe lintel
#

your prefab is just a regular entity about with a Prefab component tag so it isnt visible by other systems be default

night venture
#

so prefabs are entities?

ocean tundra
#

yup

safe lintel
#

yes, the prefab tag means systems by default ignore it, in a similar manner they ignore entities with the Disabled tag

night venture
#

even i didnt expect the spanish inquisition, that doesnt explain how it's magically loaded, as im not typing "myprefab" anywhere...

safe lintel
#

well its not magically loaded, there are lots of conversion systems that create it for you behind the hood

night venture
#

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

night venture
#

As EntityManager.Instantiate(MyPrefab) being MyPrefab a GameObject loaded via Resources.Load is deprecated,

  1. what's the most straightforward way to create an entity around a prefab?
  2. can I archetype a prefab?
    if possible, I don't want a entities.foreach/existing object to clone, please
night venture
# ocean tundra yup

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.

zenith wyvern
night venture
#

if a gameobject using the prefab+component linking to the prefab, yep

night venture
zenith wyvern
#

This sample demonstrates a different way to spawn Entities and Components using a Prefab GameObject.

night venture
#

a gameobject that exists on scene

#

is not loading resources, but cloning from another entity

#

*or converting a gameobject to entity

zenith wyvern
#

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.

night venture
#

imho, it would make sense to have prefab as archetypes

zenith wyvern
#

Can you explain what you mean by that?

night venture
#

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)

zenith wyvern
#

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

ocean tundra
#

Create a singleton prefab 'container' with all your prefabs

night venture
zenith wyvern
#

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

night venture
night venture
zenith wyvern
#

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

night venture
#

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

zenith wyvern
#

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

night venture
#

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

zenith wyvern
#

Yes, it's a public field on the conversion script

night venture
#

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

zenith wyvern
#

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

night venture
#

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...

zenith wyvern
night venture
zenith wyvern
#

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

night venture
#

and no, it doesnt require an editor rep of an entity, as im coding and its done at runtime

zenith wyvern
#

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

night venture
#

and im noooot

zenith wyvern
#

...but you're talking about Resources.Load and Prefabs. How is that not using the editor?

night venture
#

really?

zenith wyvern
#

Alright I surrender, I guess I just don't get what you're trying to do. Good luck brother

night venture
#

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)

hollow sorrel
#

@night venture alternatives to resources.load are using addressables package or like said above make your own prefab container

safe lintel
#

addressables are constrained to gameobjects which it seems like hes trying to avoid

ocean tundra
#

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 ๐Ÿ˜›

karmic basin
#

yourScene.SceneGUID ?

karmic basin
#

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 ๐Ÿค”

night venture
#

is there a thing like "!RequireForUpdate"...something that only runs onupdate if no entity<T> exist?

karmic basin
#

You could make an EntityQuery and .entityCount on it ?

night venture
#

hmm...indeed!

night venture
#

at the end, this is what I made: OnCreate: create entity with component FirstRun + RequireForUpdate, and OnUpdate destroy entity.

karmic basin
#

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

night venture
#

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.

karmic basin
#

Nvm it's only a few lines of code right ?

night venture
karmic basin
#

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 ๐Ÿ˜

night venture
karmic basin
#

Frenchy

#

neighboor \o/

night venture
#

I was going to dare to say something with my more-than-rusty french...but let it stay ๐Ÿ˜‰

pliant pike
#

has anyone else come across a case where a second job in a Onupdate gets errors when trying to capture local variables

night venture
#

no...but I suggest to paste code

pliant pike
#
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 ๐Ÿ˜•

slim nebula
#

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

safe lintel
#

Restart editor? Codegen might be stuck?

pliant pike
#

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

eager jungle
#

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?

zenith wyvern
pliant pike
night venture
#

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.

ornate jasper
pliant pike
ornate jasper
night venture
pliant pike
#

I mean there isn't many to be honest maybe some of codemonkeys later tutorials ones that use SystemBase and Entities.Foreach

night venture
#

I have been playing ecs for almost a week now, and I miss better theorical explanations, rather that monkeys coding...

ornate jasper
#

Ok Iโ€™ll. Check them out thanks

ornate jasper
night venture
slim nebula
#

you should use SystemBase

sharp flax
night venture
#

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?

rapid agate
#

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?

rapid agate
#

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.

night venture
#

have you tried looking on your project setting file? perhaps you can remove the line...

rapid agate
#

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?

rapid agate
#

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

night venture
rapid agate
#

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.

night venture
#

then, thats probably on your ProjectSettings/EditorSettings.asset...but tbh, I have never used that

runic moth
#

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?

ocean tundra
night venture
sour sorrel
#

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

ocean tundra
#

how are you converting?

#

subscenes?

sour sorrel
#

Convert to entity component

ocean tundra
#

the one you can convert

#

are you 100% sure its a entity?

#

it might still be a GO and nothing is converting right

sour sorrel
#

Just to mention, RenderMesh is present on the entity, but material is invisible

#

No it's an entity

ocean tundra
#

hybrid renderer v2?

sour sorrel
#

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

sour sorrel
#

So apparently by injecting custom vertex data I can use Hybrid Renderer V1 with point lights......

#

AND with instanced properties

safe lintel
#

you can use v2 with point lights with deferred if you use urp from github ๐Ÿ˜Ž

sour sorrel
#

mmmmmmm sounds enticing

solid rock
#

Is using Mathf in Jobs fine, or is there some other Burst-optimized math lib I should be using

ocean tundra
#

math

#

in the pinned messages

solid rock
#

thanks

sour sorrel
gusty comet
#

Are blobs assets constantly in memory or can you read them from disk whenever

ocean tundra
#

in memory

#

you could manually manage them to stream in/out

gusty comet
#

Is it not wasteful to have arrays with length of thousands in memory as blob

slim nebula
#

depends on the data

ocean tundra
#

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

slim nebula
ocean tundra
#

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

remote crater
#

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...

โ–ถ Play video
#

I'm already able to clone velocity.

slim nebula
#

Vector3.from something or quaternion.from something I forget

remote crater
#

I tried: GameBoardModel.entityManager.AddComponentData(GameBoardModel.playerEntity, new RotationEulerXYZ { Value = new float3(vvv4.x,vvv4.y,vvv4.z) });

slim nebula
#

quaternion.Euler

remote crater
#

Where vvv4 was gained from: rb.transform.eulerAngles;

slim nebula
#

there's a bunch of different ones

#

set that on the "Rotation" component

#

quaternion is a way to do rotation without gimbal lock

remote crater
#

I use quats in Gameobjects

#

I just do not know how to set my Quat data to an Entity

#

I have an entity reference

karmic basin
slim nebula
#
EntityManager.SetComponentData(myEntity, new Rotation {Value=quaternion.Euler(x, y, x)});```
#

note quaternion != Quaternion

remote crater
#

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?

slim nebula
#

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

remote crater
#

I am going to add static values

slim nebula
#

to add one rotation to another you'd use math.mul(quat1, quat2)

remote crater
#

I could be wrong on why it isn't working, but it isn't working

slim nebula
#

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

remote crater
#

I may have grabbed the wrong euler from my gameobject, theres a couple dif options.

#

I'm zeroing in on this maybe...

slim nebula
#

nice! good to hear ๐Ÿ˜„

remote crater
#

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?

amber flicker
#

1.4 most likely - radians

remote crater
#

Here is a video of me trying to translate my facing of GameObject Player to my Entity Player and failing.

amber flicker
#

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 }

remote crater
#

Perfect! Remember... If you guys ever see me make it big, remind me you helped me, and I'll drop you manilla envelopes.

waxen niche
#

version: 2020.3
unity docs on the preview package list
ECS packages are not listed
no entities, no hybrid renderer, no unity physics

deft stump
waxen niche
#

ohh thanks you :)

minor sapphire
#

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

solar spire
#

it's not guaranteed to be initialised though

#

if SomeCondition is false, then set has never been assigned

minor sapphire
#

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'

solar spire
#

your code example immediately attempts to add to it though, which would be a problem if it was initialised to the default

vagrant lotus
#

How do I get all overlaping colliders of a collider I have

night venture
#

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
?

deft stump
#

afaik

#

the empty OnUpdate doesn't get called at all

hollow jolt
#

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

remote crater
#

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?

minor sapphire
night venture
minor sapphire
#

how will singletons help here?

night venture
#
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

minor sapphire
#

the singleton pattern just ensures only instance of something

night venture
hollow sorrel
#

did using default work?

minor sapphire
#

yes it did

hollow sorrel
#

ooo nice

minor sapphire
#

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

night venture
minor sapphire
#

Oh you're just saying I can do if (set == default) rather than using a bool

#

that's fair enough

hollow sorrel
#

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

minor sapphire
#

yeah that will work too

#

I will use IsCreated ๐Ÿ™‚

night venture
minor sapphire
#

oh yeah, I could put it in a little method somewhere

#

but I do need to check if it's created when I dispose

night venture
#

the same way...make a dispose method which ignores if null.

#

cleaner code!

minor sapphire
#

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 ๐Ÿ™‚

remote crater
#

What transforms are affected after a collision? Just velocity and angular momentum?

night venture
#

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?

stone osprey
#

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 ?

night venture
#

@stone osprey let me read and understand all before answering ๐Ÿ˜‰

#

just my 2 cents:

  1. why aren't buffs/items also components? -> damageSystem could take them into accunt
  2. 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...

stone osprey
#

@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.

north bay
#
    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 ๐Ÿคทโ€โ™‚๏ธ

stone osprey
#

@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...

north bay
#

Well you need a method for each Trait and a method to apply each action

stone osprey
#

@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

night venture
#

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) }

north bay
night venture
#

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

stone osprey
#

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.

night venture
north bay
stone osprey
#

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

night venture
# stone osprey Thanks both of you ! So buffs and the damage calculation basically just should...

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

stone osprey
#

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 ^^

night venture
#

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?

karmic basin
#

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, .....

zenith wyvern
#

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

karmic basin
#

Yeah I think he's trying to optimise before even having written v1.

night venture
#

knuth come to us!

gusty comet
#

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 ?

amber flicker
gusty comet
#

well these entities have models + parents etc

night venture
#

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.

gusty comet
#

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?

night venture
#

im still confused...lets talk about your "map"...can we call it "city" (for example purposes) ?

gusty comet
# night venture im still confused...lets talk about your "map"...can we call it "city" (for exam...

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

night venture
#

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

gusty comet
#

nah i do it every few seconds lol

#

so i should not use blob assets?

gusty comet
#

(the ones made not via ConvertToEntity system)

night venture
#

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...

gusty comet
#

he used native array here

night venture
#

this tutorials are quite outdated and i have suffered a lot to learn the basics this week

#

hold a sec

gusty comet
#

he does not mention pure ecs though

#

(pure ecs so not via conversion system)

night venture
# gusty comet he does not mention pure ecs 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?
...

gusty comet
#

i do authoring but in this very case i think it should be via code

karmic basin
#

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)

gusty comet
#

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

karmic basin
karmic basin
#

but that's how I'd do

#

Maybe someone has a better way

night venture
#

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?

gusty comet
#

mesh colliders dont convert?

#

did your colliders convert kiwi

night venture
#

im not converting. im authoring prefabs and creating from scratch (both).

gusty comet
#

im authoring scene objects

night venture
#

im not using mesh colliders, but physics

gusty comet
#

without colliders?

night venture
#

physicscolliders

safe lintel
#

Mesh colliders convert fine if youre talking about physics @gusty comet

night venture
gusty comet
night venture
#

did you add physics body+shape components to GO?

gusty comet
#

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

safe lintel
#

Did you add the physics package to your project?

gusty comet
#

no

night venture
#

display!=collide

safe lintel
#

Well start there ๐Ÿ˜€

night venture
gusty comet
#

Havok ?

night venture
#

com.unity.physics

safe lintel
#

Unity Physics

gusty comet
#

so its different from havok?

#

oh

#

yeah its different

safe lintel
#

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

gusty comet
#

my shaders are not srp compatible

#

so i stayed with hybrid renderer v1

safe lintel
#

Just note v1 wonโ€™t get updates or fixes

gusty comet
#

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

safe lintel
#

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

gusty comet
#

no theyre moving

#

should i have that one checked on

karmic basin
#

Depends if you want sync only when you press play, or if you want it to also happen on the background

#

-sync

#

+compilation

night venture
#

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?

north bay
night venture
#

is there such state thing or you mean diy?

safe lintel
#

The physics examples do have some onenter onexit type stuff which arent yet built in

remote crater
#

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

safe lintel
#

only changes the PhysicsVelocity(linear/angular), but you could easily add a system to do more than that

remote crater
#

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)

hollow jolt
#

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

ornate jasper
#

Hi does anyone know how to acess or assign child entities thru script? (I'm using conversion workflow)

zenith wyvern
ornate jasper
#

so add parent component to child, & value = the desired parent entity?

zenith wyvern
#

Yeah

ornate jasper
#

got it, thanks :0

gusty comet
#

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?

zenith wyvern
#

Not sure how it works though, I've never used it

remote crater
#

A goodnight question: If my gameobject.transform was : "transform.Rotate(Vector3.right * scalar);" What would the entity equivalent be to set Angular?

bright sentinel
gusty comet
#

OH lol

gusty comet
#

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 )

gusty comet
#

oh ok cool, the scriptables still stay in scene after you convert their associated objects to entities.

I can find them with FindObjectsOfType<>()

remote crater
#

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.

tight blade
#

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

gusty comet
#

but yeah you can add components via code

#

or remove them

tight blade
#

i dont understand why that line wont compile ๐Ÿค”

gusty comet
#

shouldnt that struct derive from : IComponentData ?

#

just add that after name

tight blade
#

shit really? structs have to derive from IComponentData to be used as components?

gusty comet
tight blade
#

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

gusty comet
#

oh LOL convert to entity on prefabs works during runtime too (not only on start)

#

your welcome

sturdy rune
#

@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

gusty comet
#

how do you parent an entity?

karmic pilot
tight blade
#

right, yes. Sorry, didn't mean to sully the ideology with inheritance language

karmic pilot
#

wasn't meant as nitpicking ๐Ÿ™‚

tight blade
#

haha, no I gotcha

gusty comet
#

oh nice

gusty comet
#

i mean

#

you need the reference to entity

#

or maybe the latter is fine

karmic basin
#

COnvertToENtity is deprecated but it should convert all the GO hierarchy ?

gusty comet
#

is it really ?

#

i thought its the main way of doing things

karmic basin
#

If I remember well

gusty comet
#

no way

karmic basin
#

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

zenith wyvern
#

It's not yet but it will be

gusty comet
#

i did read they want you to do things this way

zenith wyvern
#

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

gusty comet
#

yeah I use IConvert

#

and wanna set parent inside that script

safe lintel
#

given subscenes are finally compatible with uitk in the latest editor alpha, theyre really handy to improving scene load times

gusty comet
#

to already existing entity

karmic basin
torn hollow
#

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;
    }
}
tight blade
#

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

torn hollow
#

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;
        }
tight blade
#

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

torn hollow
#

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"

tight blade
#

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)

torn hollow
#

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

remote crater
#

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...

โ–ถ Play video
#

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...

โ–ถ Play video

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...

โ–ถ Play video
north bay
#

Are you using subscenes? If so are you building by using a BuildConfiguration?

tight blade
#

@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?

torn hollow
#

actually it is

remote crater
#

Script, the bug happens before I load another scene.

#

I am using multi scenes tho

north bay
#

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

tight blade
#

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

remote crater
#

I do establish a reference towards my entity through extending the create and destroy class.

#

Many youtubers use it...

tight blade
#

the only question is why that doesn't cause it to just halt in place

north bay
torn hollow
remote crater
tight blade
#

cool, I hope it helps. order of operations stuff like that is really common in collision

remote crater
#

Convert to entity class

gusty comet
remote crater
#

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.

gusty comet
#

nah its not that easy, i have my hands full now with orbit and planets etc

remote crater
#

I should work on other techs. Today is the day I world build.

#

Time is the enemy of man

#

And cleaning your house

naive ice
#

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

gusty comet
#

extracting?

gusty comet
naive ice
#

In the code refactoring sense, calling methods instead of copy and pasting code everywhere ๐Ÿ˜„

remote crater
#

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.

gusty comet
#

but it looks like youre using one scene

remote crater
#

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

gusty comet
#

oh i never used unity scenes tbh

remote crater
#

They used to suck and serve no purpose

#

Now they're awesome

gusty comet
#

well i will prob load things from scriptable objects > CreateEntity(array)

remote crater
#

You can do that, but I am employing lots of talentless world editors

#

All most of em they can do is drag and drop

gusty comet
#

oh ok lol

#

i have already convertToEntity orbits and planets

#

and now the models will be children of planets

#

but made from scriptable

remote crater
#

yup, its fun to watch stuff orbit

gusty comet
#

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

naive ice
#

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? ๐Ÿ˜„

gusty comet
#
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 ๐Ÿ˜„

safe lintel
#

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

remote crater
#

I get an error on my standalone game that says: "the scene catalog has not been loaded yet" Why is this?

karmic basin
#

I mean except your broken parts but I'm sure you'll figure that eventually ๐Ÿ‘Œ

tight blade
#

where did this "BC1040: Loading from a non-readonly static field is not supported" nonesense come from?

robust scaffold
robust scaffold
tight blade
#

oh interesting, NativeReference is new to me

robust scaffold
#

Or just not use burst (i.e WithoutBurst()), that also works.

tight blade
#

although it occurs to me its weird that Im using the non readonly at all, now that you point it out.

robust scaffold
tight blade
#

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

lucid rapids
#

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?

robust scaffold
robust scaffold
lucid rapids
#

whats the alternative?

robust scaffold
#

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.

remote crater
#

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

robust scaffold
torn hollow
remote crater
#

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.

safe lintel
#

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

sullen mason
#

                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

sullen mason
#

my entities are getting rotated on creation, anybody had this issue (and found a way to overcome it)?

remote crater
#

Wow thank you thelebaron! You sound like you know what you're talking about. I spent 10 hours trying to get it working today.

safe lintel
#

just note I think current ui toolkit packages somehow break subscenes unless youre on the current alpha editor ๐Ÿ˜ฉ

remote crater
#

I'm on alpha 10

#

11 and 12 will not work

#

Maybe I should aim at getting 12 to work?

safe lintel
#

im just staying on alpha9 for a bit, so far it seems good enough to keep using

remote crater
safe lintel
#

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

remote crater
#

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.

gusty comet
#

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

ocean tundra
#

isnt prefab a tag component?

gusty comet
#

so that the spheres are roots

#

oh well maybe ill just keep them

karmic basin
#

@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

gusty comet
#

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

bright sentinel
#

@gusty comet No the ideal way to do it is to use IDeclareReferencedPrefabs

gusty comet
#

why

night venture
#

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

stone osprey
#

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

night venture
stone osprey
#

@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 ?

gusty comet
#

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 ._.

karmic basin
# stone osprey <@!483700836397088768> Thanks ^^ Yeah im also interested in that ๐Ÿ˜„ But is there...

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.

karmic basin
stone osprey
#

Alright thanks ^^ i think im gonna go with the hashmap approach for the first... I guess thats easier to start with

night venture
#

---

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...

gusty comet
#

before i got my Systems to work but they dont work now. eg OnCreate, anyone knows why?

night venture
gusty comet
#

oh well it works..

#

a bit

night venture
gusty comet
#

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();
    }
night venture
#

you are iterating through ALL your entities?

gusty comet
#

wym

night venture
#

'cause i was expecting something like Entities.WithAll<affecteb_by_a>().ForEach

gusty comet
#

i mean im specifying two components so it filters them automatically right

night venture
#

if you get orbitdata as ref, you wont need EM, hence could use burst...isnt it?

gusty comet
#

nvm got it to work

night venture
gusty comet
#

OnCreate was too early

#

there were no entities yet i think

#

OnStartRunning worked

night venture
#

onstartrunning is executed BEFORE oncreate

gusty comet
#

No way, oncreate didnt work for me

night venture
#

sorry

#

my bad

#

onstart before onupdate xD

gusty comet
#

xDf

#

.WithAll<LocalToWorld>() // Require the LocalToWorld component

#

is that not the same?

  Entities.ForEach((ref GalaxyData galaxyData, ref Parent parent) =>
night venture
#

and, be aware of (i wasn't) ons start running is run each time loop is "resumed"

night venture
#

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

gusty comet
#

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

karmic basin
#

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

night venture
gusty comet
#

is the performance the same

karmic basin
#

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

karmic basin
#

Lemme find it again for you

night venture
#

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... ?

karmic basin
#

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

night venture
karmic basin
#

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.
night venture
#

+1 StatefulCollisionEvent

karmic basin
#

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

night venture
#
  1. the bool was an example. actually, it would be bool array field.
  2. sharedcomponents looks promising, as it would group chunks
#

going to read those physics examples first

#

thanks!

karmic basin
#

You're welcome, happy coding

amber flicker
#

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 ๐Ÿคž

karmic basin
#

๐Ÿ‘

safe lintel
#

Damn it's already been a year since enable/disable was first mentioned? ๐Ÿ‘ด

amber flicker
karmic basin
#

talking about that, can't wait to see 0.18 and what it brings. Should be around the corner now, right ?

night venture
#

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?

amber flicker
#

EntityManager.World.GetOrCreateSystem<SystemA> inside SystemB's OnCreate.

night venture
#

hmmm...arent my systems:systembase supposed to be invoked "automatically"?

amber flicker
#

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

karmic basin
#

UpdateAfter UpdateBefore, and UpdateInGroup attributes ?

amber flicker
#

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

night venture
karmic basin
#

fair enough

night venture
amber flicker
#

I'd avoid using statics altogether - you'll have to be super careful with fast enter playmode and disposing if you do use them

night venture
coarse turtle
#

hmm why not construct the world manually, initialize your statics first then construct the systems that need to rely on it?

night venture
# amber flicker code?
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.`

night venture
amber flicker
#

where's the call I suggested? EntityManager.World.GetOrCreateSystem<SystemA>()

night venture
#

forgot to copy it :P, but is there.

coarse turtle
# night venture it's what I'm doing...but since the moment I moved code from start->create, it s...

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;

    ...
  }
}
gusty comet
#

i need to add models now ._.

night venture
gusty comet
#

can you filter Entities.ForEach basing on some component value ?

coarse turtle
#

no this is just another class which is responsible for creating the world & systems (so your systems stay the same) @night venture

night venture
amber flicker
# night venture ``` SustemA : SystemBase { public static EntityArchetype Archetype; prot...
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.
night venture
amber flicker
gusty comet
#

oh ok so you simply use IF statement inside Foreach

#

i will have lot of filtering later so not sure haha

amber flicker
#

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).

gusty comet
#

btw whats the IN keyword doing ?

coarse turtle
#

hmm actually what's the major difference between IJobEntityBatch and IJobChunk? I still mainly use IJobChunk ๐Ÿ˜…

gusty comet
#

i know that ref is modifying the original

coarse turtle
#

in is a readonly reference

#

so you can't modify the values

gusty comet
#

oh

amber flicker
coarse turtle
amber flicker
# gusty comet oh

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.

amber flicker
night venture
coarse turtle
#

sounds, good - guess I'll start converting some IJC to IJEB

amber flicker
amber flicker
night venture
coarse turtle
amber flicker
night venture
gusty comet
#

i kinda wonder how to rotate planet in dots

night venture
#

rotate a planet?

gusty comet
#

ye but in specific way

night venture
#

i guess you mean not only sphere, but all object withing sphere surface?

gusty comet
#

nono the objects are children so its not a problem

night venture
#

...

gusty comet
#

rotating in the direction of black arrows

#

i guess i should try to design it in monobehaviours first lol

night venture
#

err...unity physics have gravity attractors

gusty comet
#

i dont want real gravity

night venture
#

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

gusty comet
#

yeah

#

easy in monobs

night venture
#

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

gusty comet
#

no it would break things

#

real gravity = planets can hit each other

night venture
#

omg...is mars going to collide with earth???

night venture
amber flicker
night venture
#

oh!...right...it's a singleton :S

amber flicker
#

no but GetOrCreate - will get the system if it exists - if it doesn't exist yet, it will create it

gusty comet
#

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);
    }
night venture
#

so...should the dependant systems (systemB) invoke World.GetOrCreateSystem<whatever>(); to establish dependencies on creation? is that a correct way of handling it?

night venture
#

counter = 1f ๐Ÿ˜›

amber flicker
#

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.

night venture
#

beside systemgroups...is there another way to specify job dependency, as far as you know? @amber flicker

gusty comet
#

what kind of game are you making kiwi

gusty comet
#

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

night venture
#

but more learning ECS than other thing ๐Ÿ˜

gusty comet
#

lul

#

me too recently

night venture
stone osprey
#

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.

night venture
#

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?

night venture
ocean tundra
#

@night venture Transform isnt a componet

#

its the old MB transform

#

your probably thinking of translation

night venture
ocean tundra
#

@stone osprey I would say yes Item should be a Entity, if it needs todo logic or needs to be queried for.