#archived-dots

1 messages Β· Page 241 of 1

remote crater
#

This is the Holy Grail of like reusing playercontrollers and not having to recode a whole game, or recoding two player controllers which is like impossible.

#

Proper design patterns mean you code only once.

#

Anyway, it's rambly as all get out, but I'm sure one or two of you will have a light bulb go off and use your old GameObject game and slap some DOTS/ECS levels... Even more so when in a few weeks, I'll do an actual professional video and not just slapdash production.

remote crater
#

If you understand this video, you do not need to make new games from scratch. You can simply use your gameobject games and entityfy new levels with em. I apologize for this video being extremely rambling on, but I was also doing some dev and I plan on getting you a great video soon, but to some, this will be a God send Holy Grail of Dots ECS ...

β–Ά Play video
#

Be sure to click link and not video picture. If you click picture, go to 18 minutes.

deft stump
#

does transformaccessarray get auto disposed once the job is completed?

#

it seems not

robust scaffold
graceful mason
#
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;


public class ChunkBoundaryRenderingSystem : SystemBase {

    protected override void OnUpdate() {


        var mapChunkBoundaryArchetype = EntityManager.CreateArchetype(
            typeof(LocalToWorld),
            typeof(Rotation),
            typeof(Translation),
            typeof(SpriteRenderer)
        );

        Entities
            .WithStructuralChanges()
            .ForEach((in MapChunk mapChunk) => {
                
                Entity chunkBoundaryEntity = EntityManager.CreateEntity(mapChunkBoundaryArchetype);

                var m_SpriteRenderer = EntityManager.GetComponentObject<SpriteRenderer>(chunkBoundaryEntity);
                var sprite = Resources.Load<Sprite>("Sprites/Square.png");
                //m_SpriteRenderer.color = Color.blue;
                //m_SpriteRenderer.sprite = sprite;
                
                var translation = EntityManager.GetComponentData<Translation>(chunkBoundaryEntity);
                translation.Value = new float3(mapChunk.coordinate.originCoord.x, mapChunk.coordinate.originCoord.y, 0);
                EntityManager.SetComponentData<Translation>(chunkBoundaryEntity, translation);


            }).Run();

    }
}

anyone got any ideas to make a spriterenderer?

#

the commented lines crash as not set to an instsance

graceful mason
#

When i wake up Im gonna try and create standard GOs instead somehow so I can use normal sprite stuff with them πŸ‘

sturdy bluff
#

hey!

#

I'm trying to get into ECS

#

but the package manager isnt adding the hybrid renderer through the git URL

#

it doesnt appear in the package manager (yes I enabled preview packages and it still doesnt work)

#

so I wanted to add it with the git URL

#

but its not adding it

#

com.unity.rendering.hybrid

#

this the git URL and its not woking

#

plz help

visual tundra
karmic basin
sturdy bluff
#

Thx anyway :)

digital kestrel
#

how do you destroy an entity so that all its children die too

deft stump
#

okay I have a weird problem

#

it seems when I assign my float3 variable into the job's float3 variable, it resets.
And I don't know why.

round shoal
#

(unrelated to the issue above)
I found something annoying with float3 vs Vector3 when normalizing a 0 vector :

//float3 test = math.normalize(float3.zero);
Vector3 test = Vector3.zero.normalized;
float3 modifiedOldSteering = test* wanderData.radius_big;

works, but the commented float3 test crash with AABB related errors. The resulting vector is used to modify the Translation component of a rendered object. Not sure if bug, inconsistency or just me mistakenly expecting same behavior from both, so I just write it here

coarse turtle
round shoal
coarse turtle
#

maybe the ReadOnly messes w/ the jit instructions on top of the float3? Not sure if the compiler ignores it on those fields during compilation

vast flicker
#

is there a reason why in example code systems tend to allocate native arrays as temp every frame rather than just keeping and reusing a persistent one?

safe lintel
#

@digital kestrel add the children to a linkedentitygroup that sits on the entity you want to destroy

robust scaffold
signal wing
#

I'm using urp and when I drag the textures to a model it creates materials without textures is there a way so it auto sets the textures for the materials?

junior mural
# round shoal (unrelated to the issue above) I found something annoying with float3 vs Vector3...

float3 test = math.normalize(float3.zero);
Vector3 test = Vector3.zero.normalized;

What would you expect test to contain after either of those statements?
Normalize takes a vector and normalizes it to a length of 1.
A zero vector can't be normalized. It would cause a division by zero error.

The only reason Vector3.zero.normalized works is because of a safety check.

https://docs.unity3d.com/ScriptReference/Vector3-normalized.html

If the vector is too small to be normalized a zero vector will be returned.

So the net result of that block of code is modifiedOldSteering is a constant Vector3.zero

round shoal
#

I believe math.normalize doesn't raise an error to skip checks (performance?) so it just returns NaN which ends up being raised later on (probably somewhere in the renderer when it tries to display the mesh at position NaN ?)

graceful mason
#

if i create a gameobject in a system, cvan i store a reference to it in a buffer or something?

#

I guess I could name the gameobject using the entityid, then just do gameobject.find() (its only for a few objects at a time)

rotund token
#

usually you just attached the gameobject to the entity or use a managed componentdata and add a reference in that

graceful mason
#

how to attach go to entity? Is it a simple line of code here?

.ForEach((Entity entity, in MapChunk mapChunk) => {

               GameObject gameObject = new GameObject("go1", typeof(SpriteRenderer));
               

            }).Run();
rotund token
#

EntityManager.AddComponentObject(entity, yourmanagedcomponent)

#

then you can literally just
Entities.ForEach((Entity entity, GameObject go) => {}).WithoutBurst().Run();

#

if you ever need to access it

graceful mason
#

ok nice one thanks, so gameObject is my managed component here, awesome, ill read that doc as well though they tend to not help me too much compared to much experimenting πŸ˜„

rotund token
#

the alternative is to use managedcomponent datas

#

which is what a unity dev recommends

#

public class GameObjectContainer : IComponentData
{
public GameObject GameObject1;
public GameObject GameObject2;
}

#

note it's a class

graceful mason
#

I see I have that class written already but as a struct, no wonder it failed πŸ™‚

rotund token
#

you add it the same way, EntityManager.AddComponentData(entity, new GameObjectContainer {GameObject1 = new GameObject()});

#

same restrictions as above, you can't access it in burst, needs to be used on main thread etc

#

so should be avoided where possible but as it stands existing managed components are required

graceful mason
#

yeah hoping to have like all my gamelogic in entitys (many thousands), then like 4x 16x16 tilemaps, and <1000 sprites as GOs as my game.

#

but mostly just messing around and learning

#

awesome thanks again πŸ˜„

zenith wyvern
#

It lets you tie the lifetime of your monobehaviours/prefabs to the entity they're attached to

#

And does extra stuff like syncing transforms

rotund token
zenith wyvern
#

Oh, that's news to me. They were literally just added in the latest versions

#

Well the last release was a while ago but yeah

rotund token
#

Edit: One exception that I remembered now is that hybrid components are now called companion components and their public usage is deprecated. Right now the plan is that it will be a purely internal feature in the future.

zenith wyvern
#

Ah okay. Well in the current version componion objects are a lot older than hybrid components and don't do the fancy stuff like destroying with teh entity they're tied to or syncing transforms for you

#

At least afaik

rotund token
#

Transform isn't a hybrid component

#

you can cause it to sync by just using AddComponentObject(entity, Transform)

#

It doesn't require AddHybridComponent

zenith wyvern
#

Ahh okay

rotund token
#

Anyway that's why i avoided mentioning HybridComponents because it's the one thing we know might be breaking in 0.5

robust scaffold
rotund token
#

personally i prefer to just directly attach the component, it just seems cleaner to me. but yeah s_schoener doesn't seem to like it

#

i guess if you're attaching multiple components it does avoid a lot of extra objects in your archetype

chilly crow
#

What's a better way to handle something like this?
I have multiple players, each with a player number, and multiple buttons that each lower the health of a player with a specific number by creating a new entity with the DamagePlayerEvent component.
It seems like I'm going about this the wrong way since I have to loop over every damage event for each player to find the right one.

    protected override void OnUpdate()
    {
        var endSimulationEntityCommandBufferSystem = World.GetExistingSystem<EndSimulationEntityCommandBufferSystem>();
        var ecb = endSimulationEntityCommandBufferSystem.CreateCommandBuffer().AsParallelWriter();

        var damageQuery = GetEntityQuery(ComponentType.ReadOnly<DamagePlayerEvent>());
        var damage = damageQuery.ToComponentDataArrayAsync<DamagePlayerEvent>(Allocator.TempJob, out var jobHandle);
        var entity = damageQuery.ToEntityArrayAsync(Allocator.TempJob, out var jobHandle1);
        Dependency = JobHandle.CombineDependencies(Dependency, jobHandle, jobHandle1);
        Dependency = Entities.WithAll<Player, Health>()
            .WithDisposeOnCompletion(damage)
            .WithDisposeOnCompletion(entity)
            .ForEach((
            int entityInQueryIndex, ref Health health, in Player player) =>
            {
                for (int i = 0; i < damage.Length; i++)
                {
                    float amount = damage[i].Amount;
                    if (damage[i].PlayerNumber == player.Number)
                    {
                        health.Current -= amount;
                        ecb.DestroyEntity(entityInQueryIndex, entity[i]);
                    }

                    if (health.Current < 0)
                        health.Current = 0;
                }
            }).ScheduleParallel(Dependency);
        endSimulationEntityCommandBufferSystem.AddJobHandleForProducer(Dependency);
    }
deft stump
#

I am confused

robust scaffold
# deft stump

Generally dont deallocate inside a job, use the .Dispose(JobHandle); immediately after instead.

#

Disposing of native containers inside a job is only supported by NativeArrays() of allocation tempjob and persistant, not any of the others

deft stump
#

so [DeallocateOnJobCompletion] only works on arrays?

robust scaffold
#

Yep, NativeArray<>()

deft stump
#

aaaaah

rotund token
#

company i joined ~2 years ago was doing something similar because they ported their classical unity code to entities so stuck with the targeting their own ID that assigned to actors

#

was a complete nightmare for the reason you're seeing

#

we had to go through and refactor the whole thing to remove this and just use the entity for all interactions

chilly crow
#

idk why this didn't come to mind

#

cheers!

unborn totem
#

hello all, does anyone here know if the Hybrid Renderer v2 has anyway of manually dictating "sort these meshes in this order please"?

#

the HDRP seems to with normal GameObjects, but I am using the Hybrid Renderer v2 & HDRP together and the Hybrid Renderer seems to ignore the values

#

there's two ways to do it according to these docs, on a per material basis (no instancing as far as I know) and a value on the MeshRenderer

#

(this technique only works on transparent materials, including adjusting the MeshRenderer value, but my materials are transparent)

unborn totem
#

it seems to me once the Hybrid Renderer takes over, the Priority of all meshes becomes 0 regardless of what you tell it when they are still gameobjects (before they are converted)

graceful mason
#

thanks Tertle finally got my infinite terrain renderer working so can get working on proper generation started now i can see the results πŸ™‚

unborn totem
#

Fwiw I found no equivalent entity component data that uses the monobehaviour's MeshRenderer's Priority value for anything in the Hybrid Renderer

#

Seems sorting order is just one of the current weaknesses of the hybrid renderer as it exists right now

indigo vigil
#

I'm looking for advice regarding using the DOTS stack & ECS architecture, coming from an OOP-mindset. I've looked at hours of DOTS videos, done some reading on entity component systems, and managed to make a simple moving object using DOTS. However, I'm having issues with materials being all black with the new ECS/hybdrid renderer, the job system being too much for me to handle at the moment, and DOTS apparently not being production ready yet.

I'm looking to make a small game that wouldn't benefit from all the performance gains from ECS but I was still attracted to the idea of composition and learning ECS. Is there any point is just using normal Unity scripting and building my own pseudo-ECS architecture? I.e., entity = GameObject, data-only components, and (singleton?) classes I just call "systems" that have all the logic? I've written some code with this architecture in mind and I'm now starting to approach an issue with copypasting a lot of my systems code to other systems and lacking nice syntactic sugar (even though I'm trying with generics).

Should I:

  1. Bite the bullet, dig in, and use DOTS instead + the usual Unity stuff for audio etc.
  2. Continue working in my pseudo-ECS architecture and deal with the lack of syntactic sugar.
  3. Drop the ECS-mindset and develop using the normal Unity paradigms?
#

I don't want to use the GameObject conversion workflow for ECS either. I'd rather learn to do it the right way or just not use it.

robust scaffold
#

We do have plans and an implementation for unmanaged shared components that work within Burst, but I am not sure whether this has made it into 0.50.Β 
Wooooo.

safe lintel
#

@indigo vigil Conversion is the right way, you are just swimming against the current if you are learning entities and want to ignore want unity encourage you to utilize.
I'd recommend not using entities or ecs based packages because quite frankly there's a lot to learn, a lot of things that aren't documented and you will only figure out through intense trial and error, basically zero support from unity themselves at this point and there aren't any updates for the time being. the bugs that exist, exist.
ecs will also force you to stay on 2020 lts given its incompatible with later editors if that makes a difference.

if the project is more of a learning one, you could disregard this, but if you actually want to ship something, I wouldnt. theres always burst & collections to use.

indigo vigil
# safe lintel <@!182500265427992587> Conversion is the right way, you are just swimming agains...

I would like to eventually ship it since I believe the project is already entirely within my ability to create. I'm just interested in ECS as a new thing to learn and learning it with a small project like this seemed like a good idea. Then again I've never shipped anything before and I do know you should just work with whatever you're familiar to actually get something done...

Thanks for the advice. To clarify, do you mean I should not utilize the ECS package, but look into using the Burst compiler and the job system along with whatever style I am comfortable programming in?

#

What exactly do you mean by collections?

safe lintel
#

its just a package for array type things which can be used with burst

#

anyway yes, use burst, jobs and collections(burst job compatible arrays, lists etc) but entities itself, well I love using it but its taken a long time to get comfortable with it and I am also quite familiar with current limitations, quirks and bugs

#

some bugs are coming up on 2 years just sitting around, still active apparently but no word on if theyre actually being fixed

indigo vigil
#

I on the other hand am oblivious to any limitations and bugs apart from reading that input and audio should still be handled with standard Unity components.

indigo vigil
safe lintel
#

"Studying ECS as the new cool thing while building a product seemed like a good idea from the studying perspective" I am in this hole πŸ₯²

safe lintel
#

@indigo vigil if 0.5 comes out soon you can reevaluate things, not sure how large the changes will be so maybe a lot of pain points will be fixed

deft stump
#

I see RigidTransform inside of mathematics.
can I somehow use Rigidbodies (or something to that effect) inside of (normal/Non-ECS)Jobs?

safe lintel
#

i think its for use in physics, its just a position and rotation container

#

as in if you arent using physics, theres not really any other functionality that uses it from what ive seen

remote crater
#

Looking to launch my MMORPG in dots imminently

#

Then I'll compile a video on how to use DOTS/ECS in any project, even existing mature GameObject projects with ease.

#

I have this weird feeling that if I don't show everyone how easy and powerful it is to do now

#

UNITY may remove the functionality that allows for it, lol.

#

You know how techs are, sometimes in upgrading they remove key features.

#

But if you get wide acceptance of em, then they don't get glossed over.

#

Even a self imposed race against time helps dev time. Just don't let crunch get you so you're distressed and lose a thought process so you code worse.

round shoal
#

is there a way to remove element from an entity buffer with ecb ?I.E. similar to the way we can add data to a buffer with :

ecb.AppendToBuffer<CellSpaceBuffer>(cellEntity, toAdd);
rotund token
#

AppendToBuffer exists so you can add virtual entities to a buffer before they're created

#

Why not just remove from the buffer directly instead of using ecb?

round shoal
#

I'm creating entities that repesent space cells, inside of each there is a buffer that contains "persons" entities. So that when I move a person entity in a way that makes it change space cell, I remove it from the cell and add to another one (including creating and deleting non-existing/empty cells)

#

oooooooooh I get what you said

hot basin
#

what would be best approach to monster spawner?
I mean i.e. monster spawner can have only 3 monsters spawned at the same time.
Should I maintain FixedList or DynamicBuffer on the spawner?
How to remove monster? Should I have entity link on the monster itself?
It's too much OOP thinking in my opinion, but what's the better alternative?

graceful mason
#

i personally would scan the area nearby for the 3 enemies rather than keep any lists to them, it means player can drag them out to spawn more at once if they wanted. (if thats fun or helpful in any way)

#

@remote crater what unity/entites version you use?

north bay
hot basin
rotund token
#

why does it need entity manager?

#

also side note, most of EntityManager is burstable

    public unsafe partial struct EntityManager : IEquatable<EntityManager>```
Anything not burst compatible has the [NotBurstCompatible] attribute
```        [NotBurstCompatible]
        public void AddComponentObject(Entity entity, object componentData)```
#

as this was required for ISystemBase

vast flicker
#

If im doing multiple jobs via Entities.ForEach( (int entityIndexInQuery... is there a way to guarantee that each entity is given the same index in every job? (assuming that each query gets the same set of entities)

rotund token
vast flicker
#

I tried it and it seemed to work, but just wanted to make sure 😁

#

thanks!

rotund token
#

It's a very useful pattern πŸ‘

pastel field
haughty rampart
pastel field
#

oh

#

This means that many things, like Havok / Unity Physics, are not yet supported in this beta.

haughty rampart
safe lintel
#

2020 is the only officially supported version for anything ecs @pastel field

graceful mason
#

what aboput dots versions to install?

hasty pecan
#

I got a question, can you mix DOTS with the normal object orientated programming that Unity uses?

#

For example maybe I want certain parts of a project to be extremely efficient but others not so much.

haughty rampart
haughty rampart
graceful mason
#

ah i see the recommended is the latest anyways πŸ˜„

#

I thought i was using an older version

#

yeah you can dragon

#

mostly outside of parallell / burst but you can do it

hasty pecan
haughty rampart
hasty pecan
haughty rampart
#

no problem. help is what this here is here for

deft stump
#

hrmmm are there any samples of using regular Physics inside of (non-ECS) jobs?
I think the better question is, are there samples of using Physics2D.jobOptions?

pastel field
#

@haughty rampart & @safe lintel Thanks for your answers πŸ‘
Support to 2020, but things also working OK in 2021.

remote crater
#

When it comes to the particle system

#

Is there anything special in ECS Unity done differently than gameobject Unity?

#

Or can I just convert to Entity my old particle effects?

#

I'm looking ahead to today's work

haughty rampart
#

1 - it only makes sense to use VFX graph in this day and age
2 - since VFX graph is gpu based, ecs has no real effect on it
@remote crater

coarse turtle
remote crater
#

ty Mindstyler

#

One more question, super dumb one:

#

What is the best way to identify an entity in script so I can easily look it up in the Entity Debugger?

#

Can you UnityEngine.Debug.Log( Somehow print the entity's name) ?

#

entitymanager.GetName

#

looks like.

#

Lets see!

coarse turtle
remote crater
#

yah, not a .foreach

#

So what's the most efficient/best way to know my entity giving data out?

#

I could set some flags

#

But I am not sure how to search those in entity debugger

#

Optimally, it would be a highlight console, ctrl+c, paste in debuggr

#

Oh I know

#

What I can do

#

is set flags inside icomponentdata

#

and then have the output be translated

#

via a method

#

then I can have it equal the name

#

by me forcing it, sweet

#

For those who don't understand my shorthand: In code, I set names of each entity Instantiated. But also set an index in it's Icomponentdata to reference the name for remembrance. Then when I print... It looks up the index references to the string name, and boom, I got it writing out on console. I can then copy from console, pasta it into Entity Debugger and know what i'm looking at.

graceful mason
#

whats best way to get a referenced thingy, this cant be done in burst etc

        Entities
            .ForEach(ref Biome biome) => {

                BiomeType biomeType = EntityManager.GetComponentData<BiomeType>(biome.biomeEntity);
}
graceful mason
#

awesome thanks how i missed thast

#

after 5 days of coding I have a very crummy endless 2d generator I can expand on πŸ˜„

#

the biomegenerator (striping my world as shown) was really hard to code and is a bit slow but oh well

#

super bad poc but cant think how to do it better

deft stump
#

seems unity's physics2D aren't bursted when I enable it for jobs

spark sleet
#

Hi I need help with physics I feel like I'm going insane

#

Everything disappears when I press play

haughty rampart
#

seems to be rather a hybrid renderer problem than a physics problem. have you checked if your entities exist? @spark sleet

safe lintel
#

if you dont have the hybrid renderer package installed, entities wont render

spark sleet
#

Is that compatible with URP?

haughty rampart
#

yes

spark sleet
#

Cool, it's working πŸ™‚

#

I have a script that moves the ball with a rigidbody, using AddForce, what's the equivalent here?

haughty rampart
spark sleet
#

All tutorials seem to use a rigidbody, not the actual physics components..

zinc palm
#

Can i put Components on Entities the same way i put components on GameObjects, even when the components were not made for DOTS?
and will that work?
components like animation rigging and Photon networking components.

Example: i have a "PhotonTransformView" component that sync a gameobject's transform across diffrent clients, will that component work if i put it on a Entity,

#

please ping me if anyone responds

unborn totem
#

you have to make things called Authoring Components you can place on Monobehaviours that convert into IComponents (also known as Entity Components)

unborn totem
#

Entity components are not "self contained" like Monobehaviour components either. Entity components only store data. You are meant to write Systems that contain the equivalent of a Monobehaviour component's Update loop (amongst other things), and process Entity behavior in there instead.

#

You can also process Entity behavior outside of Systems if you want to, of course. But the point is there are no methods inside of Entity Components (which are structs) like there are inside of Monobehaviour Components (which are classes).

#

Entity Components are structs for a few reasons, but the simple answer is they are that way so they can be made to be extremely memory efficient.

whole inlet
#

Does blendshapes/shapekeys work with ECS?

unborn totem
#

i do not believe blendshapes work in the hybrid renderer

whole inlet
haughty rampart
deft stump
#

when I deallocate an nativearray inside of a job.
Shouldn't isCreated be set to false automatically too?

#

I'm confused that after I complete a job.
when I do a check with isCreated, it tells me it's still true

spark sleet
haughty rampart
spark sleet
#

But, without a rigidbody, how would I do the same thing.

haughty rampart
spark sleet
haughty rampart
safe lintel
spark sleet
haughty rampart
gusty comet
#

Wassup

#

Boos

haughty rampart
gusty comet
#

I was supposed to say guys

#

But peel

#

Oh well

graceful mason
#

output = BiomeTypes.biomeTypes[0].primaryMaterial;
is not burstable

#

do i must use a NativeArray or I can use basic c#?

coarse turtle
haughty rampart
zenith wyvern
graceful mason
#

anychance could you show me example code I stuck for hours πŸ˜„ I edited the above to only burst types

public struct BiomeTypes {
    public struct Biome {
        //public string name;
        public readonly int primaryMaterial;

        public Biome(int primaryMaterial) {
            this.primaryMaterial = primaryMaterial;
        }

    }

    readonly static Biome grass = new Biome (1);


    public static readonly Biome[] biomeTypes = new Biome[1] { 
        grass, desert, mountains, hills, artic, jungle
    };
}
#

oh it works I think, thanks πŸ˜„

graceful mason
#

I just switched to 2021.2 and its like lightning compared to 2020

deft pilot
#

hey guys is there an example of how to do OnClick events with entities?

rotund token
#

need to be a bit more specific with what you are trying to do

deft pilot
#

hmm

rotund token
#

are you talking ui events? input events? something else?

deft pilot
#

i don't really know the terminology since i don't really use unity, but I'm creating an entity using the EntityManager, and assigning it afew types - this allows me to renderer it on screen

#

i want to also have some sort of "OnClick" event trigger for it

#

just not sure how to do that

#

it renderers currently with a mesh + material

#

using meshrenderer

rotund token
#

most basic approach is to use physics and fire a raycast from the camera into the world and see what it hits

deft pilot
#

that requires the entity to have physics right?

rotund token
#

yes

deft pilot
#

so i considered that

#

but i can't figure out how to give an entity physics

#

since you can't add typeof(PhysicsBody) and typeof(PhysicsShape)

#

they aren't valid types

rotund token
#

setting up physics by hand is a pain

#

what you're looking for is PhysicsCollider at the most basic

#

but you have to generate the collider yourself

#

it's highly recommended to setup physics via conversion so unity can do it all for you

deft pilot
#

i have to dynamically generate

#

these entities

#

so thats a no go

rotund token
#

what makes you have to dynamically generate an entity?

deft pilot
#

hmm my assumption is have to i guess

#

so what i'm trying to do it

#

(technically what i'm doing is trying out unity ECS)

#

but the tech demo i'm trying to create is

#

generating a ship builder

#

(with blocks)

#

it will randomly create blocks that you can use to add to your ship (think flat minecraft)

#

each block has its own components that i need to add

#

so like health being one of the basics

#

and then like damage/targetting etc... depending on if its a standard wall block or a weapon etc...

#

each one will have different sprites/texures/meshes not sure what im using here

#

so i was doing something like

#
    private void Start()
    {
        var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;

        for (int i = 0; i < shipComponentPositions.Length; i++)
        {
            var entity = entityManager.CreateEntity(
                typeof(RenderMesh),
                typeof(LocalToWorld),
                typeof(Translation),
                typeof(RenderBounds),
                typeof(HealthData)
            );

            entityManager.SetSharedComponentData(entity, new RenderMesh
            {
                mesh = mesh,
                material = shipComponentPositions[i].isFloor ? materials[1] : materials[0],
            });

            entityManager.SetComponentData(entity, new HealthData
            {
                Health = 100,
            });

            entityManager.SetComponentData(entity, new Translation
            {
                Value = shipComponentPositions[i].position,
            });
        }
#

to initially build the default ship

rotund token
#
                typeof(RenderMesh),
                typeof(LocalToWorld),
                typeof(Translation),
                typeof(RenderBounds),
                typeof(HealthData)
            );```
and what stops this being a converted entity prefab?
deft pilot
#

what i said above i guess?

#

it will have random components

#

it will have base ones i guess

rotund token
#

you literally replace your code with
var entity = entityManager.Instantiate(prefabEntity);

#

and it's exactly the same thing

deft pilot
#

hmm okay

rotund token
#

what i'm really just trying to get at is it's almost always wrong to generate any type of 'view' entity by code these days

#

packages like netcode require you very specifically to not do this

#

so if you ever want networking etc, you'll have to learn to use conversion

deft pilot
#

weird

#

i was reading and it said

#

conversion was bad

#

bleh

rotund token
#

who said that?

deft pilot
#

now i have to go read up on conversion

rotund token
#

runtime conversion is bad

#

(and is likely deprecated)

#

runtime conversion means ConvertToEntity script

#

when i'm talking about conversion I mean subscenes

graceful mason
#

is there just one global Fixed​Step​Simulation​System​Group or I can define my own ones with differrtnt intervals?

rotund token
#

you can define as many as you want

#

netcode has multiple types

deft pilot
#

prefabEntity what type is this?

rotund token
#

any component system group can be come a fixed stepped, you just need to define its FixedRateManager

rotund token
deft pilot
#

i'm probably missing something then

#

where do you get the reference for that

#

i'm guessing i create a prefab

#

[SerializeField] private Entity wallPrefab;

#

this doesn't seem to work

deft pilot
#

hmm okay

#

so use a system

#

that a struct has the entity type

rotund token
#

there's a lot of different ways you can architype your application, this will just explain the basic concept

#

you could have all your prefabs in 1 giant buffer if you wanted for example (ghost collection style)

deft pilot
#

i couldn't figure out how to do that

#

tried to google it

#

but wasn't getting anything useful in terms of how to use that with entities

graceful mason
#

i got to try and code a Oxygen notIncluded gas interaction system now

#

no idea how many tiles it could support hopefully enough πŸ˜„

rotund token
# deft pilot but wasn't getting anything useful in terms of how to use that with entities
    {
        public Entity Value;
    }

    public class MyPrefabAuthoring : MonoBehaviour, IDeclareReferencedPrefabs, IConvertGameObjectToEntity
    {
        [SerializeField]
        private GameObject[] prefabs;

        public void DeclareReferencedPrefabs(List<GameObject> referencedPrefabs)
        {
            foreach (var prefab in this.prefabs)
            {
                referencedPrefabs.Add(prefab);
            }
        }

        public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
        {
            var myPrefabs = dstManager.AddBuffer<MyPrefab>(entity);

            foreach (var prefab in this.prefabs)
            {
                myPrefabs.Add(new MyPrefab{ Value = conversionSystem.GetPrimaryEntity(prefab)})
            }
        }
    }```
#

throw MyPrefabAuthoring on gameobject in a subscene

#

add all your gameobjects

#

bam now you have a collection of all your prefabs in your world on the MyPrefab buffer

#

var prefabs = this.GetBuffer<MyPrefab>(this.GetSingletonEntity<MyPrefab>()));
var instance = [EntityManager|CommandBuffer].Instantiate(prefabs[5]);

deft pilot
#

i tried using the IBufferElementData

#

but seems like it would make more sense

#

the way you've done it

#

as i added a float3 as well in that

#

and it didn't like it

rotund token
#

i am using IBufferElementData

deft pilot
#

let me see if i can rewrite what i've got so far then

#

then i'll get back to the onclick stuff

deft pilot
#

Is it possible to use physics body with a 2d sprite

rotund token
#

"yes" but 2d isn't really supported with entities yet

#

(except tiny)

deft pilot
#

O.o 2d isn't supported by entities

rotund token
#

that said, there are many people who are writing some awesome looking 2d games

deft pilot
#

is this allowed?

public struct FooStruct : IBufferElementData
{
  public int Value;
}

public struct BarStruct : IBufferElementData
{
  public FooStruct Value;
  public int Value2;
}
#

trying to figure out a way to define how to load each component

graceful mason
#

in a parallell, i do:

public class MapChunkGenerator : SystemBase {
    EndSimulationEntityCommandBufferSystem m_EndSimulationEcbSystem;
    protected override void OnCreate() {
        // Find the ECB system once and store it for later usage
        m_EndSimulationEcbSystem = World
            .GetOrCreateSystem<EndSimulationEntityCommandBufferSystem>();
    }
    protected override void OnUpdate() {
        var ecb = m_EndSimulationEcbSystem.CreateCommandBuffer().AsParallelWriter();
         Entities
            .ForEach((Entity entity, int entityInQueryIndex, ref MapGridCoord mapGridCoord) => {
                //add new buffer to entity
                DynamicBuffer<FooStruct> fooBuffer= ecb.AddBuffer<FooStruct>(entityInQueryIndex, entity);
                //populate buffer with 1 to 50
                for (int x = 0; x < 50; x++) {
                        FooStruct fooElement = new FooStruct{ Value = x};
>                         fooBuffer.Add(fooElement);
}
}).ScheduleParallel();

        // Make sure that the ECB system knows about our job
        m_EndSimulationEcbSystem.AddJobHandleForProducer(this.Dependency);

    }
#

my components the same as yours

deft pilot
#

i'll have to come back to this

#

not sure if this answers my qs

graceful mason
#

I changed it to FooStruct

#

oh I see you want to go one more level deep, it may error πŸ˜„

deft pilot
#

var prefabs = this.GetBuffer<MyPrefab>(this.GetSingletonEntity<MyPrefab>()));
this doesn't seem to work if you try to do
var prefabs = entityManager.GetBuffer<BluePrintData>(entityManager.GetSingletonEntity<BluePrintData>()));

#

entityManager.GetSingletonEntity

#

doesn't seem to exist

unborn totem
#

it's somewhat necessary if your game has AssetBundles that you intend to turn into Entities

deft pilot
#

i'm kinda lost on lets say how to load an inventory in ecs

#

is there any examples i can read up on?

unborn totem
#

However, if you did convert from a GameObject at runtime, I wouldn't do it very often. You can do it once, and then create copies of the Entity that was created from the conversion.

deft pilot
#

like lets say i have a json file of data, that i want to convert into entities with specific components

#

they also relate to specific prefabs

#

whats the best approach to this?

unborn totem
#

you are kind of diving right into the most difficult part of Unity

#

a partially finished experimental set of APIs

deft pilot
#

are you implying i shouldn't do this?

unborn totem
#

no, but I could see how it can be taken that way

deft pilot
#

cause i can always swap back to entitas

#

i just wanted to try out unity's ecs

#

tho putting that aside do you happen to know a way to tackle what i mentioned earlier?

unborn totem
#

if you have a set of prefabs, you can use your JSON data to convert prefabs into Entities (which may or may not be useful, depending on the components on them. Not all components do anything during conversion, so it depends.)

deft pilot
#

the prefabs really just hold image data

#

i was told to do that

#

cause of creating physics manually is too hard

unborn totem
#

if this is for a UI, I don't believe Entities really makes sense

deft pilot
#

its not for UI

#

it was just an example

#

the concept is - ship building

#

block by block

unborn totem
#

right, right

deft pilot
#

storing that ship

#

and loading it

unborn totem
#

are you using the hybrid renderer?

deft pilot
#

yeah

unborn totem
#

ok

#

then i assume your prefabs are textured cubes with colliders on them

deft pilot
#

their meshes

#

with physic body/shapes on them

unborn totem
#

ok, textured meshes

#

good, so you got the components that do something during conversion on them already

#

yes, you could use your JSON file to determine which of those prefabs to spawn and where to put them

#

you'd convert them at runtime, but you'd only have to convert the prefab once, it would create an Entity with a PrefabTag component on it

#

some components in ECS have no data and are just used to "tag" entities

deft pilot
#

hmm the alternative was to create a buffer of them

#

so its just stored in one entity with an "array" of them

#

but i have that currently

#

my problem is getting the entity and "cloning it"?

unborn totem
#

right, what I do is store my own Dictionary of my Entites that have the Prefab IComponent on them and use that as my cache of converted Entities that I clone from

#

so when you convert a GameObject, ask your Dictionary if it has an entry, and if it doesn't, put one in there for later

deft pilot
#

oh right

#

i could just make the entity static

#

hmm

unborn totem
#

if it does, then just use that instead

deft pilot
#

then access it anywhere

#

instead of trying to find it

#

or does that cause problems?

#

since i only have 1 entity technically

unborn totem
#

well Entities are sort of designed to be lumped together and .ForEach'd over inside of Systems, that's a separate topic

deft pilot
#

since its a buffer of prefabs

#

so i don't actually need to get all entities with a prefab tag

#

since theres only ever gonna be one

#

var prefabs = entityManager.GetBuffer<BluePrintData>(entityManager.GetSingletonEntity<BluePrintData>())); hence why i tried to do this

#

which didn't work

unborn totem
#

oh ok, so if you only have a single GameObject you are converting, then yeah just do that once.

deft pilot
#
    [SerializeField]
    private GameObject[] prefabs;

    public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
    {
        var myPrefabs = dstManager.AddBuffer<PrefabData>(entity);

        foreach (var prefab in this.prefabs)
        {
            myPrefabs.Add(new PrefabData { Value = conversionSystem.GetPrimaryEntity(prefab) });
        }
    }
#

its more then one

#

but since its a buffer

#

only 1 entity ever needs to be accessed to get all the prefabs

#

so what i'm considering is just making entity be assigned to some public static in that class

#
public class PrefabAuthoring : MonoBehaviour, IDeclareReferencedPrefabs, IConvertGameObjectToEntity
{
    [SerializeField]
    private GameObject[] prefabs;

    public static Entity PrefabEntity;

    public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
    {
        var myPrefabs = dstManager.AddBuffer<PrefabData>(entity);

        foreach (var prefab in this.prefabs)
        {
            myPrefabs.Add(new PrefabData { Value = conversionSystem.GetPrimaryEntity(prefab) });
        }

        PrefabEntity = entity;
    }

#

so something like that

#

var prefabs = entityManager.GetBuffer<PrefabData>(PrefabAuthoring.PrefabEntity);

#

and then i could just access it like that

unborn totem
#

one moment

deft pilot
#

nope it didn't like that

#

ObjectDisposedException: Attempted to access BufferTypeHandle<PrefabData> which has been invalidated by a structural change.

#
public class ShipBluePrint : MonoBehaviour, IConvertGameObjectToEntity
{
    [SerializeField]
    private BluePrint[] bluePrints;

    public void Convert(Entity entity, EntityManager entityManager, GameObjectConversionSystem conversionSystem)
    {
        var prefabs = entityManager.GetBuffer<PrefabData>(PrefabAuthoring.PrefabEntity);

        foreach (var bluePrint in this.bluePrints)
        {
            var newEntity = entityManager.Instantiate(prefabs[(int)bluePrint.BlockType - 1].Value);
            entityManager.AddComponentData(newEntity, new HealthData { Value = bluePrint.Health });
            entityManager.AddComponentData(newEntity, new Translation { Value = bluePrint.Position });
        }

        entityManager.DestroyEntity(entity);
    }
}
#

what i tried to do

unborn totem
#

still here, just writing code atm

deft pilot
#

all good mate

#

its a free help service

#

so i'm already glad you are helping

unborn totem
#

just letting you know

#
[SerializeField]
private GameObject[] prefabs;

private Dictionary<int, Entity> _cachedEntityPrefabs = new Dictionary<int, Entity>();
private GameObjectConversionSettings _clientConversionSettings;
private EntityManager _entityManager = default;

private void Awake()
{
    _entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;

    var blobAssetStore = new BlobAssetStore();
    _clientConversionSettings = new GameObjectConversionSettings(
        World.DefaultGameObjectInjectionWorld,
        GameObjectConversionUtility.ConversionFlags.AssignName,
        blobAssetStore
    );
}

public Entity SpawnEntity(int key)
{
    if (!_cachedEntityPrefabs.TryGetValue(key, out Entity prefabEntity))
    {
        prefabEntity = GameObjectConversionUtility.ConvertGameObjectHierarchy(prefabs[key], _clientConversionSettings);
        _cachedEntityPrefabs.Add(key, prefabEntity);
    }

    return _entityManager.Instantiate(prefabEntity);
}
#

assuming your JSON file has an index of which prefab to spawn, this should work just fine

#

of course you probably also want to pass position data into the SpawnEntity or something

#

oh i missed a bit, there I fixed it with an edit

#

oh wait, nevermind, what I wrote at first would have been fine

#

changed it back to the original πŸ˜›

#

you don't have to do absolutely everything inside of Entities

#

you can do this on a Monobehaviour if you want to

#

if you're expecting to have like 100,000 different kinds of prefabs, then that's a different story

#

you'll of course need to call SpawnEntity yourself from somewhere in my example. The only special Unity method I am using is the Awake method, which any Monobehaviour will fire for you (assuming it is on an active GameObject).

deft pilot
#

so if i'm understanding this correct

#

_cachedEntityPrefabs doesn't have anything in it

#

as you pass through key it will populate it from whatever prefabs[key] is

#

thats assigned from the editor

#

how would this be accessible in a System?

#

ie/ if you needed to spawn an entity via a system

#

with a prefab

unborn totem
#

This spawns Entities outside of a System

#

if you want to access entities inside of a System, you use the Entites.ForEach method and filter which Entities you want to do stuff on

#

you don't have to spawn Entities while inside of a System

#

but you could put this code inside of a System class if you wanted to, I suppose

deft pilot
#

can you add multiple of the same component onto an entity?

unborn totem
#

no, I don't believe so

deft pilot
#

okay so i went a slightly different method

#

using everything you've explained

#

so i have like 4 things roughly

#
public struct BluePrintData : IBufferElementData
{
    public int ID;
    public int Health;
    public float3 Position;
}
#
[Serializable]
public struct BluePrint
{
    public BlockType BlockType;
    public int Health;
    public float3 Position;
}
#

so the first one is for the ecs to be able to act on the saved data

#

the second one is for disk data to be loaded into

#

then to test that

#
public class DefaultShipBluePrint : MonoBehaviour
{
    [SerializeField]
    private BluePrint[] bluePrints;

    private void Awake()
    {
        var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
        var entity = entityManager.CreateEntity(typeof(ShipBuilderTag));
        var buffer = entityManager.AddBuffer<BluePrintData>(entity);

        foreach (var bluePrint in this.bluePrints)
        {
            buffer.Add(new BluePrintData
            {
                Health = bluePrint.Health,
                ID = (int)bluePrint.BlockType,
                Position = bluePrint.Position,
            });
        }
    }
}
#

that creates an entity with the tag of ShipBuilderTag and adds all the information to build a ship to a buffer of type BluePrintData

#

then i have a system that acts on entities with that tag

#
public class ShipBuilderSystem : ComponentSystem
{
    protected override void OnUpdate()
    {
        var prefabs = EntityManager.GetBuffer<PrefabData>(this.GetSingletonEntity<PrefabData>());

        Entities
            .WithAll<ShipBuilderTag>()
            .ForEach((Entity entity) =>
            {
                var buffer = EntityManager.GetBuffer<BluePrintData>(entity);
                for (var i = 0; i < buffer.Length; i++)
                {
                    var bluePrintData = buffer[i];
                    var spawnedEntity = EntityManager.Instantiate(prefabs[bluePrintData.ID - 1].Value);
                    EntityManager.AddComponent<HealthData>(spawnedEntity);
                    EntityManager.AddComponent<Translation>(spawnedEntity);
                    EntityManager.SetComponentData(spawnedEntity, new HealthData { Value = bluePrintData.Health });
                    EntityManager.SetComponentData(spawnedEntity, new Translation { Value = bluePrintData.Position });
                }

                EntityManager.DestroyEntity(entity);
            });
    }
}
#

which works fine for the first entity created

#

but when it loops to the next item

#

ObjectDisposedException: Attempted to access BufferTypeHandle<BluePrintData> which has been invalidated by a structural change.

#

what caused the structural change?

unborn totem
#

try this

#
public class ShipBuilderSystem : ComponentSystem
{
    EntityCommandBufferSystem _ecbSystem;

    protected override void OnUpdate()
    {
        var prefabs = EntityManager.GetBuffer<PrefabData>(this.GetSingletonEntity<PrefabData>());
        var ecb = _ecbSystem.CreateCommandBuffer();

        Entities
            .WithAll<ShipBuilderTag>()
            .ForEach((Entity entity) =>
            {
                var buffer = EntityManager.GetBuffer<BluePrintData>(entity);
                for (var i = 0; i < buffer.Length; i++)
                {
                    var bluePrintData = buffer[i];
                    var spawnedEntity = EntityManager.Instantiate(prefabs[bluePrintData.ID - 1].Value);
                    EntityManager.AddComponent<HealthData>(spawnedEntity);
                    EntityManager.AddComponent<Translation>(spawnedEntity);
                    EntityManager.SetComponentData(spawnedEntity, new HealthData { Value = bluePrintData.Health });
                    EntityManager.SetComponentData(spawnedEntity, new Translation { Value = bluePrintData.Position });
                }

                ecb.DestroyEntity(entity);
            });
    }
}
#

i actually don't know much about buffers. it could be simply accessing it and iterating over it is causing a problem

deft pilot
#

EntityCommandBufferSystem _ecbSystem;

#

doesn't this require something to create it?

#

something like

#
    private EntityCommandBufferSystem commandBufferSystem;

    protected override void OnStartRunning()
    {
        commandBufferSystem = World.GetOrCreateSystem<EntityCommandBufferSystem>();
    }
#

and also don't you need to actually register the command buffer somewhere

#

otherwise it just does nothing

#

cause it never runs?

unborn totem
#

oh yeah, you have to create or get a command buffer system first

#

you could grab this one, which I think exists by default?

#
private EntityCommandBufferSystem commandBufferSystem;

protected override void OnStartRunning()
{
    commandBufferSystem = _ecbSystem = World.GetExistingSystem<EndSimulationEntityCommandBufferSystem>();
}
#

you can see a list of existing systems in the Entity Debugger

deft pilot
#
    private BeginInitializationEntityCommandBufferSystem entityCommandBufferSystem;

    protected override void OnStartRunning()
    {
        entityCommandBufferSystem = World.GetOrCreateSystem<BeginInitializationEntityCommandBufferSystem>();
    }

    protected override void OnUpdate()
    {
        var prefabs = EntityManager.GetBuffer<PrefabData>(this.GetSingletonEntity<PrefabData>());
        var commandBuffer = entityCommandBufferSystem.CreateCommandBuffer();

        Entities
            .WithAll<ShipBuilderTag>()
            .ForEach((Entity entity) =>
            {
                var buffer = EntityManager.GetBuffer<BluePrintData>(entity);
                for (var i = 0; i < buffer.Length; i++)
                {
                    var bluePrintData = buffer[i];
                    var spawnedEntity = commandBuffer.Instantiate(prefabs[bluePrintData.ID - 1].Value);
                    commandBuffer.AddComponent<HealthData>(spawnedEntity);
                    commandBuffer.AddComponent<Translation>(spawnedEntity);
                    commandBuffer.SetComponent(spawnedEntity, new HealthData { Value = bluePrintData.Health });
                    commandBuffer.SetComponent(spawnedEntity, new Translation { Value = bluePrintData.Position });
                }

                commandBuffer.DestroyEntity(entity);
            });

        entityCommandBufferSystem.AddJobHandleForProducer(this.Dependency);
    }
unborn totem
deft pilot
#

i think its something like this

#

oh missing a .Run()

#

but close enough

unborn totem
#

i'm not aware of you needing that last part, but maybe I'm not sure

#

entityCommandBufferSystem.AddJobHandleForProducer(this.Dependency);

deft pilot
#

oh

#

wait this doesn't work

#

cause i can't use EntityManager.GetBuffer

#

i guess i could just do .WithoutBurst()

#

and it works

#

nice

unborn totem
#

alright, well, good πŸ˜„

deft pilot
#

welp now to actually do the thing i asked here initially

#

click on entities that render a mesh and trigger events...

unborn totem
#

goodluck, bedtime for me

graceful mason
#

ok dumb quesiton, say I have

MyComponent myComponent = SomeComponent

can i get the entity it is attached to from that?

haughty rampart
#

you can do entitymanager.hascomponent(entitiy, component) if i remember correctly

#

or something similar

graceful mason
#

I dont have any entity

haughty rampart
#

well you need any entity

#

just iterate over all and test them

#

or save your entity reference in the component where you need it

graceful mason
#

I see, yeah im looping this:
NativeArray<MapGridCoord> mapGridsData = queryMapGrids.ToComponentDataArray<MapGridCoord>(Allocator.TempJob);

#

as otherwise I was getting burst errors, Ill try to think a diff way,

haughty rampart
graceful mason
#

So in this system, my entity, with a Coord, has now found the Coord of the adjacent tile

#

so I need to get its entity

#

or some other components that are attached to it

#

So I have... currently entity + coord --> found neighbour coord --> neighbour data?

#

I thinbk what you say before is best, I can loop every entity with a coord, instead of my NativeArray above, just gotta work out how πŸ˜„

#

just gotta get it into a NativeHasMaph I guess from what I know Coord Entity

#

not done one yet so will try

haughty rampart
#

hm, yeah......grids are kinda....not ideal currently in ecs. if your grid has a fixed size though, you can use a fixed array to look up the corresponding entity

graceful mason
#

its working well so far, my temperature system can simulate every 0.25 cell within like 0.04 seconds or something crazy

#

just only within each chunk, no talking to neighbours yet πŸ˜„

#

but its not fixed sizes

#
var queryMapGrids = GetEntityQuery(typeof(MapGridCoord));
NativeArray<MapGridCoord> mapGridsData = queryMapGrids.ToComponentDataArray<MapGridCoord>(Allocator.TempJob);

is the current code, That query is probs my entities πŸ˜„

#

do you have example to get both lines of data into Native formats?

haughty rampart
#

native formats?

graceful mason
#

a dictionary I can use with burst, I think is a NativeHashMap but not sure?

haughty rampart
#

yeah dictionary is nativehashmap

graceful mason
#

ok i will try to work out how to get a HashMap of <Component, Entity>

#

cheers

odd ridge
#

for a RTS game, how would a system that applies damage from units to other units work in DOTS?

graceful mason
#

Im super newb but would aim to have a Targeting System, which sets a refernce to the units target

then a shooting system, where units move to within range of there targets and aim+ fire

then a projectile system to manage all the projectiles in flight

then a damage system that reduces healths

by then ive learned more what I really need πŸ˜„

graceful mason
#

is there any simple list type I can use in a job?

#

I tried using NativeList, but I cant blit Buffers

#

just wanna chuck a bunch of buffers in a list

robust scaffold
graceful mason
#

can I add an element to them πŸ˜„ or i must do it define time? (then i cant pass in a basic array type in burst I dont think?)

#

ill try

graceful mason
#

say I want to process half my elements in one systems onUpdate call / frame, then the other half in another (to prevent write access to read only components)

hollow flame
#

Is dots better than mirror when it comes to a game like csgo

graceful mason
#

that would make sense right?

#

green could run/Write on Even frames, readonly from red, who run/Write on odd Frames readonly from green.

graceful mason
#

I just wanted to define my own fixed update system, but had to copy form the source

rotund token
#

side note, i hate that fact you named it the same thing as the built in one πŸ˜…

graceful mason
#

aha yeah ok, so line 28 to set it, and change its name πŸ˜„

#

tnaks

#

I did have some clashes already lol

haughty rampart
vast flicker
#

does [UpdateBefore(typeof(x))] guarantee that system x will finish all its code before starting the annotated system?

haughty rampart
#

yes

stiff skiff
#

kind off

rotund token
vast flicker
rotund token
#

yes

#

OnUpdate is on main thread

vast flicker
karmic basin
#

Also called blitting in GPU terms

graceful mason
#

thanks man, i went with that

graceful mason
#

is there a quick way to delete all of a component?

left oak
graceful mason
#

If I have this problem, is there any way around it beyond writing less data?

safe lintel
#

might need to instantiate via nativearray or destroy by query at that point

graceful mason
#

any weay to work out which systems commands are spamming it?

#

think i got my ONI style tile transfer systems in place and working at 200fps, for a 10km x 50m area

#

but will no doubt find its not working when i try to expand on the basic test πŸ˜„

graceful mason
#

nope had it commented out dang πŸ˜„

misty wedge
#

Is there a reason why writing to the same parallelwriter from 2 different jobs is not allowed?

last swan
#

Can I get the previous position from an entity (with LocalToWorld or Translation or somethin like that) or do I need to implement an entitybuffer to keep track of the last position?

safe lintel
#

gotta diy it although there is a case for handling it with physics interpolation

deft stump
#

do we have examples of GenericJobs?

#

or not possible?

remote crater
#

Hey my MMORPG enginie is almost ready to be tested. I have like 5 hours of easy work and maybe 8-12 of medium (2 days)

#

I have one question tho:

#

How do I get my subscenes to load in a standalone Windows compile? I am probably messing something up in my build file

#

these are my settings, what is wrong?

#

Again, everyone who helps me, when I'm making 1-100 million dollars a month, come ask to go out to eat and get a manilla gorilla envelope of green backs LOLOLOLOL πŸ™‚

rotund token
#

from memory, you shouldn't include your subscenes in the scene list - you're just including them twice then

safe lintel
#

subscenes should just build as long as you use the new platforms package which you appear to be doing. if its not working with that idk, maybe time for a bug report

wooden canopy
#

What is the status of dots + dots netcode with unity 2020? is it working? kind of working? stay the hell away from it?

rotund token
#

@remote crater what version of unity is a good question actually

rotund token
#

0.50 should bring a lot of fixes though

wooden canopy
#

whats the problem with mobile?

rotund token
#

i've never tried (pc/console dev) but from reading forums optimise has found a huge range of bugs with android in particular

#

just breaks after a while (i think it's the transport package not netcode in particular, it's probably fixed in the recent versions but netcode needs an update to use it)

north bay
wooden canopy
#

I opened the asteroid sample with 2020.3.23f (it was using an older one the sample), and it did not go well haha

wooden canopy
#

I think it dies way before that

#

Unable to load plugin network.bindings

north bay
#

Uhmm

#

The latest version I tried netcode with was .20 maybe something new came up πŸ˜„

wooden canopy
#

the only thing I did was, open with the new unity version, build the osx-clientserver

north bay
#

Oh sorry I have zero experience with mac

graceful mason
#

is it really bad to get a list of 1000s values, then loop EntityQuery.SetFilter()

digital kestrel
#

when did they say ECS 0.50 was gonna come out?

coarse turtle
safe lintel
#

really hope it is actually soon and not like enable disable soon

haughty rampart
#

well they still have 3 months

odd ridge
safe lintel
#

maybe entities only gets bumped up to 0.18 πŸ™‚

haughty rampart
#

no it'll be 0.50

odd ridge
#

is there a list of new features of 0.50 available?

#

like

#

enable/disable

haughty rampart
haughty rampart
karmic basin
vast flicker
#

So ive got a few singleton entities that contain some global settings that other systems access, is there a way to easy change the data in these entities during play from the editor?

haughty rampart
vast flicker
#

thanks anyway!

haughty rampart
rustic rain
#

Is DOTS still preview?

vast flicker
#

im changing a lot of things, so it's just annoying having to add/change/remove fields in lots of different places

haughty rampart
haughty rampart
rustic rain
#

so, dots is 1.0 already and can be used fully or only as hybrid?

haughty rampart
haughty rampart
#

only hybrid workflow for entites / ECS

rustic rain
#

I guess I'm getting it confused with ecs yeah

haughty rampart
#

ECS 0.50 will be released in Q1 2022

#

ECS 1.0 probably in Q4 2022

#

ECS 1.0 will ONLY support a hybrid approach

vast flicker
rustic rain
#

wait, I'm getting confused here

#

so, ECS is approach to programming

haughty rampart
rustic rain
#

so what is DOTS then? Just a packages for Unity with ECS approach ?

haughty rampart
# rustic rain so what is DOTS then? Just a packages for Unity with ECS approach ?

no. DOTS is unity's Data Oriented Technology Stack. Entities (ecs for unity) is included under DOTS, but DOTS is way bigger than mere ecs. DOTS also includes burst (compiler for c# to native code), jobs (easy multithreading solution for gaming), collections (native collections for c#), math (SIMD library for burstable math), and all other packages that may or may not be related to entities

rustic rain
#

so, in short DOTS is just overhaul of Unity engine?

rustic rain
#

ok, I'll just give some more time learning about it, before I ask more stupid questions xD

last swan
#

Can I make a System skip some UpdateLoops? I dont want this system to run every frame, but, eg every 3rd or 4th frame?

coarse turtle
coarse turtle
#

Yea

sturdy bluff
#

Hey!
I want to use the burst compiler without having to rewrite my scripts in ECS, because they're very complex.
Do I need to use the C# job system to use the burst compiler?

#

My scripts use a ton of references, so I can't really use the c# job system

#

I tried, but I couldn't get it to work as intended

karmic basin
coarse turtle
sturdy bluff
#

Im getting performance issues

#

I looked at the profiler

#

and fixed a lot of stuff

#

but the only way to really get performance is with DOTS

zenith wyvern
sturdy bluff
#

oh ok

#

thx

coarse turtle
#

curious if anyone knows this, but with the conversion workflow can we define what the destination world is? I'm trying to figure out a way for multi world setup + entity authoring πŸ€”

haughty rampart
coarse turtle
#

maybe? I don't remember if I saw an API like that

#

I can take a look later today, but it'd be nice if I can just dictate that entity A moves to x world and entity B moves to y world instead of moving them to a staging world and then move them to the correct worlds on runtime πŸ€”

remote crater
#

It may be in my packages

#

How do I upload all my packages I use?

#

I thought there was a manifest.json but I cant find it

#

found it

karmic basin
coarse turtle
remote crater
#

The error message in standalone is visible in that image.

karmic basin
#

If just code you can define a custom bootstrap

coarse turtle
#

just code, I'm currently using an ICustomBootstrap + Subscenes. But yea I think what I want are editor tools, but that's definitely not coming till much later from Unity

karmic basin
#

From memory Netcode definitely comes with inspector components aware of multiple worlds (server/clients)
Dunno if that's clean code though

remote crater
coarse turtle
karmic basin
#

If not in netcode package, maybe i saw it in the old FPS dots multiplayer sample

coarse turtle
karmic basin
#

Was thinking of the FPS one, cant remember for the third person one

coarse turtle
#

kk - i'll look around then

remote crater
#

Unity needs an "Update all packages button" that looks for the most basic dependencies and updates them first. If compilation errors occur, rolls it back to last version, then moves on to try and update other packages, informing the user of what happened.

lusty otter
#

Is it possible to get Time.realTimeSinceStartUp inside a Bursted job?

#

I have many chunks of calculations (which I cannot estimate how long each chunk will take) and I'd like to spread them out over multiple frames.

remote crater
# haughty rampart not really

I personally lost 50+ hours and counting to a problem that would take an official Unity dev less than 30 hours to solve(update all packages). There are more users than just me. I'm a time management Ux designer. I don't think they teach this in school because all the big players get it wrong. Anyone try and use Google ads or Starcarft2's Map Editor? Whoa, its like no one knows what they're doing out there. Even windows still has forced alt tab, tightly bound windows to processes(noticeable when you can't alt tab to unity editor). Multi billion dollar corporations don't even have the first clue of what they're doing it seems. PS: I still can't update my packages properly, still erroring out.

rustic rain
#

Can you guys recommend where to look for up-to-date guides/tutorials/examples? Besides docs.
I'v watched a lot of tutorials, but it appears they use obsolete code

#

I pretty much got the concept of ECS and now I just want to look through some most recent examples

worn valley
rustic rain
#

Thanks, will take a look

graceful mason
#

if an Component in one DynamicBuffer, needs to interact with another in a different buffer, whats the best way for them to reference each other?

#
       BufferFromEntity<MapChunkTileLastTickBufferElement> lookup = GetBufferFromEntity<MapChunkTileLastTickBufferElement>(true);
        if (surroundingTiles.tileAbove != Entity.Null) {
            neighboursBufferTop = lookup[surroundingTiles.tileAbove];
        } else {
            neighboursBufferTop = new DynamicBuffer<MapChunkTileLastTickBufferElement>();
        }
        if (surroundingTiles.tileBelow != Entity.Null) {
            neighboursBufferBottom = lookup[surroundingTiles.tileBelow];
        } else {
            neighboursBufferBottom = new DynamicBuffer<MapChunkTileLastTickBufferElement>();
        }

        int index = 0;
        for (int x = 0; x < EngineSettings.ChunkWidth; x++) {
            for (int y = 0; y < EngineSettings.ChunkHeight; y++) {
               indexAbove = aCheapFunction()
                indexBelow = aCheapFunction()
                MapTile tileAbove = neighboursBufferTop[indexAbove].Value;
                MapTile tileBelow = neighboursBufferBottom[indexBelow].Value;

}}```
#

at the moment i just do this which i guess is super bad

worn valley
#

Which ways do they have to interact? Do they write to each other??

graceful mason
#

not fully decided, but at the moment due to complexity with that, they dont πŸ™‚

#

so they are slightly different component types at the moment, but representing the same data

#

I write to a buffer not shown above

#

MapChunkTileLastTickBufferElement Read, MapChunkBufferElement Write

#

I was debating creating a new system, that reads each tile sequentially and populates an new buffer that the adjacent tile needs and can then read sequentially.
That would be like this but Native or whatever for burst, is random writes to fixed array as bad as reads?

Dictionary <int, int[]> ()
Dictionary .Add(1, [12, 16, 20, 24])
Dictionary .Add(2, [13, 17, 21, 25])
outArray = (26)[]
for (int x = 0; x < BufferLength; x++) {
    outIndices = Dictionary[x];
    for (outIndice in ){
         outArray [outIndice] = Buffer[outIndice]
 }
}
#

Im guessing that would be a waste of time πŸ™‚

zenith wyvern
graceful mason
#

Ah i see, I had that at first but wanted ot move it to a generic function I could call from anywhere, but if thats more performant I can do that way again thanks!

zenith wyvern
#

When I was doing something like this a I had a single "VoxelWorld" struct that I passed around which provided immediate access to any block. It could be build from any system and would populate itself with the necessary BufferFromEntitys/CommandBuffers

graceful mason
#

I think that what I want

graceful mason
#

I have something working just want to try and oxygen not included ify it up

zenith wyvern
#

It's pretty convoluted as it needs to account for read only access and read/write access but it worked

graceful mason
#

awesome that looks amazing thanks

#

Ive got all the same functions pretty much πŸ˜„

#

just used very differently

#

that repo looks cool why you stop πŸ˜„

zenith wyvern
#

Yeah I'm not gonna say it's a great solution, but it did work

#

I couldn't really figure out a good way to handle spawning new chunks. I ended up with a convoluted pooling system that I hated so much and I couldn't figure out something better so I gave up on it

graceful mason
#

I wanted to make a minecraft clone, mixed with rimworld somehow. now im making a minecraft clone, mixed with rimworld, oni perdspective (2d) instead

#

Im just rewriting my chunk system now I think this will work well based on my last attempt :D... I have this in a system:

 SectorCoordinate requestedCoordinate = new SectorCoordinate(objectsSectorCoordinate.Value.x + xOffset, objectsSectorCoordinate.Value.y + yOffset);

                        // Set the sector to active
                        if (sectorDictionary.ContainsKey(requestedCoordinate)) {
                            EntityManager.AddComponent<Active>(sectorDictionary[requestedCoordinate]);
                        } 
                        // Create a new active sector
                        else {
                            CreateNewSector(requestedCoordinate);
                        }
#

which basically spawns very lite entities for every chunk

zenith wyvern
#

I wanted any system to be able to spawn a new chunk and create blocks in it arbitrarily, but since the results of an ecb are meaningless outside a single job I couldn't figure out a good way to handle it

graceful mason
#

then another system operates on those Entities, that dont have the tileBuffer component, either loading it from disk, or generating the new tile and populatring the buffer

#

within a Parallell()

#

my last attempt had the chunkmanager above, running in a parallell.burst, and after many thousands of chunks added it choked up jsut looping the datas to find the right entity to see if it existed or not. now in main thread its super lightweight anyway seems to wrok well afdter testing for 2 mins πŸ˜„

#

I see yeah that sounds complex, for me I would just generate that entire chunk in its entirety πŸ˜„

zenith wyvern
#

Depending on if the game is "infinite" or not I don't think it's practical to spawn them in a loop on the main thread. That's a lot of syncing. And then any operation that potentially creates a block becomes asynchronous as it's just a request, rather than dealing with the actual live state of the world

graceful mason
#

mines super at early stages of dev with no real functionality yet so will learn much

zenith wyvern
#

Which complicates it more

graceful mason
#

mines infinite, but spawns em super fast ish but the algo is just a simple heightmap so far lol

#

and also my pc is a bit powerful so may not be representative

#

my ecbs got full last time though, so now i have a lot less changing of components, hopefully

#

in version about 9 of my minecraft clones πŸ™‚

zenith wyvern
#

It's a fun problem to try to solve, but yeah making it play nice with jobs was too much for me sadly

#

I think you're on the right track though, if I was doing it again I would probably restrict "random" access to the main thread so there's a simple logical order to how the world gets written to in that case, and save the job stuff for world gen which should be able to go parallel in some cases

vivid robin
#

Dots seems so nice- I’m excited for it to become available for 2022.1

graceful mason
#

your code is like foreign language to me, but will be good to try and learn πŸ˜„

#

mine is beginner style aha

#

I realised I need a WorldXY to SectorCell lol, how i not needed that yet i not sure

graceful mason
graceful mason
#

the oni heat style thing will have to be taken out as too complex to implement efficiently for me πŸ˜„

north bay
#

Anyone here noticed that IJobEntityBatchWithIndex with parallel scheduling and more than one batch per chunk falls apart? πŸ˜„

last swan
#

Hello, before I try I wanted to ask if I can query for DynamicBuffers on the Entities.ForEach, like .WithNone<DynamicBuffer>()?

north bay
last swan
#

Yes that of course, just wanted to make clear what I wanted to do - thanks

deft stump
#

what are the real world example uses of FunctionPointers?

graceful mason
#

for managed components, you just always have to use 'in' ?

#

got so confused thinking I learned in and ref wrong way round 1000x πŸ˜„

haughty rampart
haughty rampart
last swan
#

Can I use the BinaryWriter in a System with WithoutBurst() and Run()? like, putting using around the whole Entities.ForEach?

coarse turtle
#

don't think you'll get any compiler errors πŸ€”

last swan
#

that'd be fantastic I will try this tomorrow

remote crater
#

Why would Unity even care if my scene was in file->build setting since that is not what the Scripted Build Pipeline uses?

coarse turtle
#

the log message might be generic, maybe you're missing it from the scene list info in the build pipelines

remote crater
#

I definitely have it there. But maybe another option is disabled.

coarse turtle
#

I wouldn't be sure then

remote crater
#

I'm thinking of not even using subscenes at all, or making an interpreter script to compress, and read em in so I can instantiate.

north bay
#

Is NewMoba a subscene which throws the errors when loading it?

#

If so how are you trying to load it?

remote crater
#

It works in editor, but not standalone.

#

I can show you a video. Thank you for interest.

#

SceneManager.UnloadSceneAsync("NEWMOBA");

#

SceneManager.LoadScene("NEWMOBA", LoadSceneMode.Additive);

#

Only two lines of code I believe

north bay
#

Huh that is indeed rather strange
I never had problems with that 😬

remote crater
#

Ty for trying

zenith wyvern
haughty rampart
zenith wyvern
#

There is no ambiguity for a managed component. It's always on the main thread so it's always read-write.

haughty rampart
zenith wyvern
#

How so?

coarse turtle
#

yea im confused by that, how? You can't pass a class as a ref/in param πŸ€”

zenith wyvern
#

By definition a managed component is a reference type so it makes no difference whether you pass it by value or reference

#

So as far as i know the convention is to leave off the ref/in modifier for those types

zenith wyvern
coarse turtle
#

o πŸ‘€
that's some weird tidbit to know lol. I haven't really used the lambda stuff since everything has been job structs.

rotund token
#

void TestCaller()
{
    var test1 = new Test() {Value = 2};
    Method1(ref test1);
    Debug.Log(test1.Value); // 1

    var test2 = new Test() {Value = 2};
    Method2(test2);
    Debug.Log(test2.Value); // 2
}

void Method1(ref Test test) { test = new Test() {Value = 1}; }
void Method2(Test test) { test = new Test() {Value = 1}; }```
zenith wyvern
#

Ohh I see, I didn't know that. So you can assign to the reference type itself if you pass it by ref, neat

worn valley
#

@zenith wyvern all structs are passed by value (which means they are copied into the method) and classes are always passed by ref even if you don't have ref in there. Using ref makes it explicit that you are passing in the reference to the struct instead of a copy of the struct. There are some exceptions to the above rule, but that is the general rule.

zenith wyvern
#

I could be wrong but I think the ref gets stripped from managed types during code gen anyways as it has a completely different meaning in that context

#

Either way I remember at one point reading that we're meant to leave ref/in off managed types in the ForEach lambdas

vivid robin
#

Has anyone here found a way to hack dots’ ecs into working acceptably on 2022.1b?

coarse turtle
vivid robin
#

Whoa- I had compile errors just trying it

#

Template type mishandling due to nullables, afaik

coarse turtle
#

can you share* the package list you have installed?

vivid robin
#

It was collections 1.1 and entities latest as of uh… last week

#

Will post back in 5

coarse turtle
#

I know not every package associated with Entities will work w/ 2021.1b

#

Ah yea, you gotta downgrade collection to 0.15 preview

vivid robin
#

It was entities itself that had templating errors

karmic basin
coarse turtle
# vivid robin It was entities itself that had templating errors
    "com.unity.burst": "1.7.0-pre.1",
    "com.unity.collections": "0.15.0-preview.21",
    "com.unity.entities": "0.17.0-preview.42",
    "com.unity.mathematics": "1.2.5",
    "com.unity.platforms": "0.8.0-preview.2",
    "com.unity.platforms.android": "0.10.0-preview.10",
    "com.unity.platforms.desktop": "0.10.0-preview.10",
    "com.unity.platforms.macos": "0.10.0-preview.10",
    "com.unity.platforms.windows": "0.10.0-preview.10",
    "com.unity.properties": "1.7.0-preview",
    "com.unity.properties.ui": "1.7.1-preview",
    "com.unity.scriptablebuildpipeline": "1.19.3",
    "com.unity.transport": "0.6.0-preview.7",

well if it helps, here are the package versions I have in 2022.1b

vivid robin
coarse turtle
#

Yea I think you can. I believe they're all under the Unity Companion License.

vivid robin
#

I haven’t read up much on that one yet

coarse turtle
#

Probably would just have to double check the license if anything πŸ€”

vivid robin
#

Most of my homework ended up being on the renderer, which- unless dots saves me- may actually force me to swap to unreal

coarse turtle
#

ah - I can't vouch for Hybrid Renderer in 2022.1b. I don't use it and just rolled my own stuff

vivid robin
#

Cameras apparently can’t render β€œjust this scene” or β€œjust this geometry” in a scalable and dynamic manner

#

I need multiple scenes to be loaded concurrently but independently, and the SRP’s design appears to make proper culling and target selection (almost?) impossible

#

Render layers might work but they require a huge amount of manual management that has room for mistakes that lead to something rendering on the wrong layers, especially if user-created content is involved

#

The hybrid renderer might save the day though, if it can do selective rendering - and if it works on 2022 at all; I’ve been trying to get HDRP to do it but it seems to be an architectural flaw

haughty rampart
#

if you want to use it, use 2020

vivid robin
#

Entities isn't "supported" in 2022 either- whether or not it can be hacked into working, I haven't tried yet, but with entities actually existing, it could be possible

safe lintel
#

hybrid definitely isnt compatible by accident

#

whats forcing you to 2022 anyway?

vivid robin
#

linux compatibility, shader keyword limits, and HDRP 13

rotund token
#

bit late to party but there's a significant breaking change in srp that completely breaks hybrid renderer in 2022

#

from what i hear, do not expect compatibility till later half of 2022

safe lintel
#

0.50 already slipping to q2?

vivid robin
#

ugh. Well, I hope the massive breaking change fixes the fundamental lack of any mechanism for implementing efficient culling

rotund token
vivid robin
#

😒

rotund token
#

they specifically said only 2020.3 and then 2021 support in the post

#

The first is a set of experimental packages updated to version 0.50, compatible with Unity 2020 LTS at first and targeting compatibility with the upcoming Unity 2021 LTS later in the coming year.

#

entities 1.0 is for 2022 and doesn't sound like it'll support 2020 or 2021 (again 2022 is really breaking)
The second milestone is the actual transition from experimental packages to full release status with the version we call Entities 1.0, which will be fully supported much like any other released feature of Unity. The 2022 LTS cycle is our preferred target for this release, but we have yet to confirm it. Entities 1.0 will not be compatible with earlier LTS versions.

safe lintel
#

im always expecting the worst at this point as far as further delays πŸ₯²

vivid robin
#

I wonder if I should drop all non-vulkan APIs and just use a native plugin to supplement a custom SRP

#

there's gotta be a way to prevent it from adding objects to batches

deft stump
#

I noticed that project Tiny isn't active in the forums

rotund token
#

you mean community wise?

deft stump
gray nexus
#

I can't get the entity system to work with urp

rotund token
#

what version

gray nexus
#

i made a new project and can't get ecs to work with urp lit shadeers

#

i get an error

#

it doesn't support

vivid robin
#

Error messages generally help people to help you

gray nexus
#

and can't get the material working

#

it's a clean project from the lts version

rotund token
#

2020.3?

#

have you installed the hybrid renderer?

#

have you enabled V2 on the hybrid renderer?

gray nexus
#

how do you enable it?

gray nexus
#

Thanks a lot πŸ˜„

#

Awesome it works

rustic rain
#

Is there a full list of everything related to ECS in package names for unity?

#

is that all?

graceful mason
#

on this page, the menu on left, at the bottom

rustic rain
haughty rampart
#

2020

#

also, if you're upgrading an from an older version, unity has a habit to break things even though new projects work perfectly fine. best to put all your assets in a unity package, export it, create a new newer unity project and import the unitypackage

rustic rain
#

169 red errors

#

kek

haughty rampart
rustic rain
#

oh, what

#

is 2021 some kind of ugly duck of unity?

haughty rampart
rustic rain
#

that's sad to know

haughty rampart
# rustic rain that's sad to know

no. they were / are in the process of rewriting lots of core things but those don't get pushed to the public. though entities 0.5 will be available in a few weeks, but only compatible with 2020 as well. a few weeks / months later it will be available for 2021 as well. and in q4 of 2022 1.0 will become available

rustic rain
#

so for now I jsut install 2020 and all DOTS packages will work fine with it, I assume?

haughty rampart
rustic rain
#

I'm just a student for now, but I want to learn all DOTS related stuff, entities and jobs. So I guess I better learn all of them

haughty rampart
rustic rain
haughty rampart
rustic rain
#

ah, I see

karmic basin
#

You don't have to install all DOTS packages manually. There's a dependency chain involved and trying to install a specific version yourself on top of it might mess things up

#

From the package manager window there's an inspector view where you can see which dependencies are resolved

#

Can't screenshot it for you, not in front of computer

#

But I hope it brings help :p

rustic rain
#

But I just prefer to know what I install and why

sturdy wolf
#

Hoping to get help here
I'm trying to create ArchetypeChunkComponentType variable in my ijobchunk but it doesnt show up
The documentation says its under Unity.Entities which as you can see is already included

#

Anyone has any idea what I might be missing?

rustic rain
#

Are sub scenes specifically made for Entities conversion?

zenith wyvern
#

Well apparently the documentation is wrong there too which is pretty funny. But it shows the correct way to do it in the actual example. ComponentTypeHandle

sturdy wolf
#

omg that was exactly the problem
Arghh

#

Thankss

graceful mason
#

im still reading your source @zenith wyvern , does using getblock randomly not have issues with random buffer accessing?

zenith wyvern
#

If I remember right the idea was that any system that needed random access would include other accessing systems as a dependency. The same way AddJobHandleForProducer works

graceful mason
#

I think my tick system is basically doing the same as your methods, but cant be 100% sure πŸ˜„

#

I have reference to adjacent entities, and get buffer from them

#

so I already have: TryGetVoxelChunkFromIndex saved for a given tile (and loaded at sector level), then var blocksBuffer = world.BlocksFromEntity[chunkEntity]; is similar to my neighboursBufferTop = lookup[neighbourSectors.tileAbove];

#

but then i dont reinterpret as array which you do

zenith wyvern
#

It sounds like it yeah. Rather than tracking neighbours per chunk I just have a big hashmap that I can index to from anywhere

graceful mason
#

yeah i didnt know about them so i will defo do that as well

zenith wyvern
#

The hashmap will tell me if there's a chunk there or not as it won't have a key for that chunk index if it's not present

graceful mason
#

I have a public dictionary I cant access from within burst and stuff, I guess you can with that?

zenith wyvern
#

Yes NativeHashMap is basically a burst friendly version of dictionary

graceful mason
#

I dont think its possible to tick every tile quickly enough, but thats no problem i can do some game design instead to solve it πŸ˜„

#

I wonder how ONI is coded

zenith wyvern
#

Apparently it was made in unity

graceful mason
#

ah someone pasted this

#

C# is doing a good job, and where it doesn't you use native c++ code... ONI is doing it's simulations natively (simdll) because C# would be like 10 times slower on that part

#

is that still true with DOTs? I guess not

zenith wyvern
#

No, in theory fully optimized burst code should be as fast or faster than C++. Good luck writing it though

haughty rampart
#

dots can even be faster than native c++

graceful mason
#

I see oni only has approx 100k tiles, and I was testing at 1mill - 2mill πŸ˜„

#

it was beast moding it at 100k tiles, food for thought for me anyways πŸ‘

rustic rain
#

Hmmm. So I read through DOTS tutorial https://dots-tutorial.moetsi.com/
And it mentions "running code on main thread" a lot.
Am I correct to assume that by that they mean simply running code in MonoBehaviour?

coarse turtle
#

Looks like they're talking about running a job on the main thread (which is perfectly valid for when you know the cost of scheduling a thread versus executing things immediately)

rustic rain
#

I know what main thread is, I'm just not really familiar with how Unity handles it.

rustic rain
#

which kind of tells that threaded job is still better in this scenario, I'm just asking how to make sure your code runs on main thread

coarse turtle
#

Job.WithCode(() => {}).Run()

#

or new JobStruct().Run() (depending on the interface implemented)

rustic rain
#

oh wait

#

so

#

All systems you create, code is run on main thread?

#

and you either .Run() or .Schedule().?

coarse turtle
#

yea pretty much, create the job on the main thread, call run to execute immediately on the main thread, or call schedule so that it's submitted to the job queue and internally unity will figure out when to execute those jobs

rustic rain
#

looks simple enough, if it's some GameSettings entity you just run job instead scheduling

#

as example

coarse turtle
#

yea

rustic rain
#

yeah, thank you

graceful mason
#

everyones always talking bout jobs, they are much better than entities.foreach?

rustic rain
#

uuugh, grammar is being funny with those comments

#

can anyone explain a bit differently?

coarse turtle
rustic rain
#

I just don't get the right meaning of what they tried to say here

coarse turtle
#

However because it's codegen you also don't get as much control in how it's generated

coarse turtle
worn valley
#

Everything is created into jobs, but the code to make jobs is so much typing it makes my hands hurt. So Unity compiles the simple stuff for you.

graceful mason
#

ok thanks

rustic rain
#

?

graceful mason
#

@rustic rain yeah

coarse turtle
#

yea

worn valley
#

Every job needs to have it's inputs and outputs put into a big struct which is a pain in the butt to type out everytime

#

I prefer the control of actually writing all the code out, but it takes forever

rustic rain
#

and can I just store it inside of field or?

#

I guess I can

worn valley
#

what do you mean store?

rustic rain
#

but I don't want because I want settings to be changed at some point

graceful mason
#

that line of code does it good

rustic rain
#

and only once

#

just like prefab

worn valley
#

So every time you run OnUpdate it is grabbing the information from the Singleton

graceful mason
#

you can, but your job cant read from a field. so will need to read it from field instead outside the job.

worn valley
#

you can change the Singleton at any point

#

OnUpdate is issued every frame

graceful mason
#

so you end up with a slightly different line of code, and potential for 2 sources of truth

worn valley
#

I've found with a few years of DOTS development the implementation of things is less important and you have to get your head around how to bring in the data you need.

rustic rain
#

Soooo, I don't really get. How exactly it gets this component

#

what if I have several entities with that component

worn valley
#

I think it's more closely aligned with procedural component

graceful mason
#

it runs getEntity query, and returns an error if theres more than 1

worn valley
#

@rustic rain you shouldn't do that. Then it isn't a singleton

rustic rain
#

oh

#

so it's supposed to be only 1

worn valley
#

Singleton means there is one and only one of that component anywhere

#

yeah πŸ™‚

rustic rain
#

ok

#

I'm guessing hierarchy wise, I can put set this entity absolutely any way I want

#

I actually wonder at what points this system might choke

#

where GetSingleton or smth like it will become slow

graceful mason
#

with jobs,

        // This completes the scheduled jobs to get the result immediately, but for
        // better efficiency you should schedule jobs early in the frame with one
        // system and get the results late in the frame with a different system.
        this.CompleteDependency();

am i meant to save this in a public dictionary or something, and then call that in a different system?
and when it talks about times in the frame, this is like uisng the init, simulation and render groups?

worn valley
#

It won't choke, it's grabbing the smallest amount of data. But you shouldn't have a singleton that is 16KB of data

#

@rustic rain I seem to recall that using Singletons is not a great practice. So try to use it sparingly for things like settings and stuff that doesn't change. If you need to write back to the singleton in the same frame you are gonna run into hiccups

#

I am not sure what you are asking @graceful mason

#

The steps for using jobs are, 1. You create the job, you schedule the job and then leave for a while

graceful mason
#

how do i call that job to complete in a diff system ?, later in the frame

worn valley
#

Like you need that job to be completed before you can do something else?

graceful mason
#

im just learning, like how to run a slow job over a longer time.

worn valley
#

Oh hmmm. That is a pretty complex question TBH.

rustic rain
#

you mean async job?

worn valley
#

For simple stuff, I create a job, schedule it and then check back in every few frames to see if it is done.

#

There is a struct called a JobHander

#

you can call .Complete() on it at any time

#

but that pauses everything and completes that job at that moment. That is bad

#

You can check the handler with .IsComplete and that returns true if the job is done

#

I think what this.CompleteDependency() does is call complete on all the jobs up till that point for that system

#

so you don't want to do that. I would just have something checking to see if the job is complete every frame in an OnUpdate()

rustic rain
#

hmmmm

#

what about jobs running in ticks?

#

for simulation type of games

#

that have pause and etc

#

does DOTS has any sort of implementation for it?

graceful mason
#

how to get handle from that?

            for (int i = 0; i < 100; i++) {
                result[0] += i;
            }
        }).Schedule();
#

or you use other jobs system?