#archived-dots

1 messages ยท Page 91 of 1

gusty comet
#

Ah yeah, that's what I need... Figured using ECS for an RTS like game would be far more efficient than pooling everything and such... Love the performance of ECS from what I've seen on the unite videos and such.

safe lintel
#

new release with an updated hybrid renderer should be out annnnnny tiiiime noooow...... ๐Ÿ˜ฆ

gusty comet
#

Unity just told me 2019.3.b8 just came out didn't see it in the list a few mins ago

#

Not sure if beta versions matter in what packages are shown

safe lintel
#

but i too am kinda stuck on an old unity until they release an updated version, and I dont fancy fixing the package myself as there are other dots bugs getting me down

gusty comet
#

yeah that's definitely true

hollow sorrel
#

you can def still use gameobjects for rendering + game in ecs
i'm using gameobjects with Sprite monobehaviours to render a dots 2d game

#

hybrid renderer should be better performance i think? but it doesn't support materialpropertyblocks (yet?) so there's still reasons not to use it for 3d also

gusty comet
#

Luckily I don't forsee having to mess with materials and such

safe lintel
#

next release is supposed to have that materialblock support

gusty comet
#

oh nice ๐Ÿ™‚

hollow sorrel
#

oh nice

gritty grail
#

I really hope they fix these Unity errors soon

#

Having to rerun the game 15 times just to be able to test things is a major hassle

gusty comet
#

Which unity errors are you talking about?

gritty grail
civic glen
#

lucky yours keeps running, as soon as i ge tthe recursive mine locks up until i ctrl + alt + del it

safe lintel
#

whats happening that causes those issues?

#

i think a while back i got some index out of range issues for trying to move static colliders

civic glen
#

not sure, the second it happens everything stops and can't debug it

safe lintel
#

well for both of you i would start going through 1 by 1 and adding a [DisableAutoCreation] to each system to find out what system is causing it

civic glen
#

unless you mean the default systems, i haven't added a single one and it happens

gritty grail
#

The errors are showing up in systems that I didn't make

#

For instance the Copy Transform to Game Object Proxy causes an error

#

As soon as I take that off

#

then MeshRenderV2 causes the same error

#

which I don't even use

#

And I'm not exactly sure how far I'm supposed to go to find the root of the issue

onyx mist
#

Im currently making an strategy game that heavily utilizes coroutines (MEC) to simulate time. For example, one character could be born in August 1st. To simulate aging I'd WaitForSeconds(365f) then age++. 1 second is one day and it scales with timescale. From what I've been reading coroutines aren't compatible with dots. What alternative system should I use in its place if I want to take advantage of what dots has to offer?

gusty comet
#

basically stop thinking the way you think about programming

#

You have to split everything up to its smallest denominator and systemize it

onyx mist
#

See that's where I'm having trouble imagining how I'd do that for my calendar system. I guess I can make entities read off a monobehavior global variable and use that to tell how much time has passed?

gusty comet
#

You could go about doing a IwasBornat component that stores their time of birth and compare to Time.time for your calculations

onyx mist
#

Oooo maybe

#

I'll keep that in mind thank you

gusty comet
#

Yeah, you can have multithreaded code doing it that way

#

Though as a start I recommend you watch the following vids https://www.youtube.com/watch?v=KuGRkC6wzMY https://www.youtube.com/watch?v=QbnVELXf5RQ&t

Interaction is fundamental in games, both in how players interact with a game and receive responses, and in how parts of the game interact with one another. ...

โ–ถ Play video

Watch to learn what's involved in migrating existing game code to the new Data-Oriented Technology Stack (DOTS), which comprises the C# Job System, the Entit...

โ–ถ Play video
#

@onyx mist

#

Get a high-level overview of the Entity Component System (ECS) and turn-based game loops, and see a proof of concept built using ECS. The session covers some...

โ–ถ Play video

Learn how to get started using Unity ECS. โœ… Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=ILfUuBLfzGI Unity DOTS Explained h...

โ–ถ Play video
onyx mist
#

I was just watching code monkey's one lol

#

I'll add all these to my playlist, tysm!

#

The turn based vid in particular seems like it'll be a perfect fit

gusty comet
#

basically top's theory, bottom is practice

onyx mist
#

Gotcha

hollow sorrel
#

with dots you could have an AgingSystem that iterates over all Age components and increments them by deltatime
rather than each character running its own coroutine, it'd just be one system that takes care of all

gusty comet
#

You can also do that, certainly. On both cases you'd have a huge switch where you add the necesary component to an entity when it has a bday or something of the like

safe lintel
#

@gritty grail you shouldnt be using the Proxy components, the conversion workflow is the recommended way to use ecs whether its hybrid or pure

gusty comet
#

proxy components?

safe lintel
#

ie TranslationProxy, RotationProxy, CopyTransformToGameObjectProxy

#

they are deprecated

gritty grail
#

Do you have docs or video reference of the alternative?

safe lintel
#

the entities samples repo shows the basics of it

gritty grail
#

But how do I use that to move the player with ecs?

#

I know how to do that stuff

covert spire
#

Is there any way to see a full list of IComponentData components that Unity already implements?

safe lintel
#

how are you moving your player currently?

#

for other things either check the source or just add converttoentity to something and see in the entity debugger what components get added to it

gritty grail
#

Well I'm not worried about the player

#

I'm worried about the camera

#
public class CameraSystem : JobComponentSystem
{
    public static CameraSystem Instance { get; private set; }
    public float xAxis, yAxis = 0;
    public const float convertRads = math.PI / 180;
    public const float moveSpeed = .5f;
    EntityManager em = World.Active.EntityManager;

    [RequireComponentTag(typeof(CameraTag))]
    struct CameraSystemJob : IJobForEach<Translation, Rotation>
    {
        [ReadOnly] public float3 playerPos;
        [ReadOnly] public float mouseX;
        [ReadOnly] public float mouseY;

        [BurstCompile]
        public void Execute([WriteOnly] ref Translation translation, [WriteOnly] ref Rotation rotation)
        {
            translation.Value = playerPos;
            rotation.Value = quaternion.Euler(new float3(mouseY, mouseX, 0));
        }
    }
    
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        if (Instance == null)
        {
            Instance = this;
        }
        
        yAxis -= Input.GetAxis("Mouse Y") * convertRads * moveSpeed;
        if (yAxis > 180)
        {
            yAxis -= 360;
        }

        yAxis = math.clamp(yAxis, -25 * convertRads, 25 * convertRads);

        xAxis += Input.GetAxis("Mouse X") * convertRads * moveSpeed;
        
        var job = new CameraSystemJob{
            playerPos = em.GetComponentData<Translation>(PlayerSpawner.Instance.entity).Value,
            mouseX = xAxis,
            mouseY = yAxis, 
        };

        return job.Schedule(this, inputDeps);
    }
}```
#

This is how I'm moving the camera at the moment

safe lintel
#

the job could be something like

    struct CameraSystemJob : IJobForEach<Translation, Rotation>
    {
    public Entity Player;
    [Readonly] public ComponentDataFromEntity<LocalToWorld> LocalToWorldData;
        [ReadOnly] public float mouseX;
        [ReadOnly] public float mouseY;

        [BurstCompile]
        public void Execute([WriteOnly] ref Translation translation, [WriteOnly] ref Rotation rotation)
        {
        if(LocalToWorldData.Exists(Player))
        {
            playerPos = LocalToWorldData[Player].Position;
        }
            translation.Value = playerPos;
            rotation.Value = quaternion.Euler(new float3(mouseY, mouseX, 0));
        }
    }

protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
if(!HasSingleton<PlayerTag>())
return inputDeps;

var job = CameraSystemJob{
    Player = GetSingletonEntity<PlayerTag>()
    //etc
}
}
#

also all public static CameraSystem Instance { get; private set; } // you can get another system simply by using World.Active.GetOrCreateSystem<CameraSystem>() from another system instead of this public float xAxis, yAxis = 0; //can be put into your job public const float convertRads = math.PI / 180; // public const float moveSpeed = .5f; // EntityManager em = World.Active.EntityManager; // EntityManager is a property of the JobComponentSystem and not needed to cache

gritty grail
#

But will this work for making the camera move without the proxy?

safe lintel
#

have you used any of the conversion stuff yet?

gritty grail
#
using Unity.Entities;
using Unity.Mathematics;
using UnityEngine;

[DisallowMultipleComponent]
[RequiresEntityConversion]
public class CameraComponent : MonoBehaviour, IConvertGameObjectToEntity
{
    public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
    {
        dstManager.AddComponent<CameraTag>(entity);
    }
}```
safe lintel
#

so id make something very similar for your player, so the camera system can find it

gritty grail
#

Well all of this stuff is an information overload so I might have to try to get back to it later

safe lintel
#

yeah just play around with something smaller

gritty grail
#

Thanks

#

I'm still trying to go through all of the relevant videos

old pulsar
#

EntityManager.CreateChunk() docs don't specify what happens when the number of entities to create exceeds capacity for the number of new chunks. Looking at the code, there don't seem to be any checks for this, and it just exceeds the bounds of the chunks array.

Likewise, when the number of new chunks needed is smaller than you pass in the chunks array, the array has blank ArchetypeChunk values representing no actual chunks. Seems like CreateChunk should return how many chunks it actually creates, and if the number of entities to create exceeds capacity of the provided chunks, it should create only so many as fit and tell you how many it created.

frosty siren
#

@tawdry tree Thx for explanation of collision filter. I thought the same way, but it was not obvious for me, so i asked for advice) Sorry for so late respond, i was AFK whole yesterday

gusty comet
#

How does convert and inject original work under the hood? I cant really wrap my head around how it works by looking at the ConvertToEntity.cs

slate breach
#

Has anyone heard anything about the new DOTS release lately?

dawn forum
#

Howdy - anyone have a good example of converting entity component data to a Texture2D (essentially treating each entity as a texel, and packing its data into a Texture2D)?

I'm close to what I want, but can't figure out how to convert the NativeArray I get back from an entity query to the Color[] array that SetPixels() wants.

gusty comet
#

So what are you working with atm? Are you using quads for 2d representation?

dawn forum
#

Yeah, I have a quad with a texture that I'd like to fill from entity data.
So, I have component data for a texel attached to each entity:
public struct TexelData : IComponentData
{
public float r;
public float g;
public float b;
public float a;
}

#

and want to do something like this:


       private void UpdateTexture()
       {

           NativeArray<TexelData> texelData = heightmapQuery.ToComponentDataArray<TexelData>(Allocator.TempJob);

           heightTexture.SetPixels((Color[])texelData.ToArray());
           heightTexture.Apply();
           texelData.Dispose();
       }

#

(which doesn't compile, since types)

gusty comet
#

I guess you'll have to do an external conversion instead of a cast

dawn forum
#

basically not sure how convert the native array to Color[]

#

(I come from C++ land, so C# is making my brain hurt)

gusty comet
#

you can have a method that returns a color given a Texel Data

dawn forum
#

would that be performant? I want to avoid doing a per-element conversion if possible

gusty comet
tawdry tree
#

Uh, maybe in english? The change language option can be found at the bottom of the page, look for the globe icon

gusty comet
#

fuck, lemme edit

#

done

dawn forum
#

thanks. ๐Ÿ™‚

gusty comet
#

I personally just take out the localization tags in the hyperlink

tawdry tree
#

Looks like that indeed works

gusty comet
#

yeah, some websites are either en-en or just without it

#

@dawn forum as another thing, I recommend you make all your custom conversions explicit for easier prove of intent

forest gulch
#

Could anyone help me, please? I'm trying out DOTS and for some reason I'm getting less performance with DOTS than the "usual way". Shouldn't it be the other way around?

#

Here's the code I'm using on the system. It simply moves the objects up.

#
public class MovementSystem : ComponentSystem
{
    protected override void OnUpdate()
    {
        float dt = Time.deltaTime;
        Entities.ForEach((ref Movement sShip, ref Translation translat) =>
        {
            translat.Value = new float3{x = translat.Value.x, y =  translat.Value.y + 1 * sShip.speed * dt};
        });
    }
}```
#

The components are: Movement (contains speed), RenderMesh, Translation and LocalToWorld.

safe lintel
#
  1. there are various safety checks, leak detection etc that can be disabled in the jobs menu
#
  1. profiling in editor will always be slower than a build as afaik there are some things perfwise that cannot be disabled until it is built
#
  1. component system will only get you marginal improvements, its more for compatibility with monobehaviours. for max performance use a jobcomponentsystem with jobs and burst
#

that said nothing looks wrong with that at all

forest gulch
#

Oh, okay, I thought it was the standard way

#

I also disabled the leak checks, debugging and other stuff and it did increase

safe lintel
#

try Jobs>Jobs debugger off, leak detection off

#

see if that helps

forest gulch
#

With all that stuff down, it runs at around 450 FPS, 500 sometimes

#

however, with monobehaviour, it runs at 600 :s

safe lintel
#

profile in a build and check

forest gulch
#

How can I display the FPS on a build?

safe lintel
#

you can technically use fraps or something

#

but better to use the profiler

#

so check the ms of the system in editor and then in a build

forest gulch
#

I decided to use the JobComponentSystem first, is that right?

#
public class MovementSystem : JobComponentSystem
{
    [BurstCompile]
    struct JComponents : IJobForEach<Movement, Translation>
    {
        public float dt;
        public void Execute(ref Movement mov, ref Translation trans)
        {
            trans.Value = new float3{x = trans.Value.x, y = trans.Value.y + 1.0f * dt * mov.speed, z = 0.0f};
        }
    }
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        var job = new JComponents{dt = Time.deltaTime};
        return job.Schedule(this, inputDeps);
    }
}
#

By the way, here's how the system is created:

    private void Awake()
    {
        EntityManager shipManager = World.Active.EntityManager;

        EntityArchetype ship = shipManager.CreateArchetype(/*list of components here*/);
        NativeArray<Entity> ships = new NativeArray<Entity>(6, Allocator.Temp);

        shipManager.CreateEntity(ship, ships);
        foreach (Entity e in ships)
        {
            shipManager.SetComponentData(e, new Movement{speed = 1.5f});
            shipManager.SetSharedComponentData(e, new RenderMesh{mesh = meshToSet, material = materialToSet});
        }
        ships.Dispose();
    }
#

That's inside a monobehaviour, by the way

hollow sorrel
#

for 6 entities it should barely even show up on the profiler

#

try 6000 and profile the difference

#

also generally we use milliseconds not fps for performance profiling because the difference between 500-600 fps is much smaller than say 100-200 fps

#

also using regular componentsystem vs jobsystem is fine for small amounts of entities because scheduling a job has some overhead too

#

it should still be at least as performant as monobehaviour in the worst case scenario

forest gulch
#

Tried spawning 6000 entities and got around 30 FPS. I'll make a small script to spawn 6000 GameObjects and see what I get

hollow sorrel
#

hmm that is very low even for a lowend cpu

forest gulch
#

I'm running an I3 3110m

hollow sorrel
#

might be gpu bound if you're rendering the ships

#

which is another reason to use milliseconds from the profiler vs just fps

forest gulch
#

also, with just 6 entites/objects, the frametime is 2.5 with entities, while 1.6 with monobehaviors

dry dune
#

Tried spawning 6000 entities and got around 30 FPS
6000 per frame i hope ๐Ÿ™‚

hollow sorrel
#

hard to say where your performance is going without looking at the profiler

forest gulch
#

No, 6000 at Awake

hollow sorrel
#

just changing a single float3 like in your movementsystem, especially with burst + jobs should be able to handle 6000 easy

forest gulch
#

Okay, I spawned 6000 MonoBehaviour objects and got around 30 FPS as well. Frametime is at 25 ms

dry dune
#

how many components on you entity?

#

what kind of components?

forest gulch
#

4 components - RenderMesh, Translation, LocalToWorld and Movement (custom component with a single float, named speed)

dry dune
#

custom component is IComponentData?

hollow sorrel
#

check profiler pls
or at the least entitydebugger, it shows time per system too but i think it is less accurate than the profiler
but might be easier if you dont know how profiler works cuz you'd need to check the jobs in there

#

i'm guessing you have 30fps because of rendering

dry dune
#

do your entitles use the same RenderMesh?

gusty comet
#

the grey shadows are just compression artifacts

hollow sorrel
#

ppu is a sprite importer setting isnt it

gusty comet
#

yeah, I have a variable called internal ppu set to 32 atm

#

works well when generating 1 unit quads but not anywhere else

forest gulch
#

@dry dune yes, the custom component is an IComponentData

#

I'll take a pics of the profiler/s

hollow sorrel
#

huh doesn't Sprite already generate a mesh you can use

#

or mesh dimensions at least

gusty comet
#

not for entities if i recall

hollow sorrel
#

but you're converting from a Sprite right

gusty comet
#

yeah, it's a sprite renderer

hollow sorrel
#

should be able to grab the mesh dimensions from the spriterenderer's sprite

gusty comet
#

ok, will try

hollow sorrel
#

basically Sprite is a wrapper around texture that also has extra stuff like mesh info

#

so you dont have to do double work

#

holds uv info too in the case of spritesheets

forest gulch
dry dune
#

6k batches

#

enable instancing on the material

gusty comet
#

@hollow sorrel just saw it, sprite doesnt have an intrinsic mesh component but it does have all the subparts

hollow sorrel
#

yah

#

i think i did something similar i'll look it up when i'm back at pc later

forest gulch
#

the default unlit materials don't feature GPU Instancing

dry dune
#

use URP

forest gulch
#

With the lit materials, I get 120 FPS and 8.6 ms

#

I'll have to switch to URP later

#

I'll have to leave for now. Thanks a lot for the help, guys :D

gusty comet
#

@hollow sorrel I'd love to see your implementation, my brain's to puffy for today

dry dune
#

here each frame i spawn 500 entities, and set positions and scale + add one component
as soon as 5k on screen remove all and start over
40+ fps in editor without jobs
https://gph.is/g/ZdoWGww

gusty comet
#

well, I think you'd only gain a performance in setting the position/scale because adding components would need an ECB

dry dune
#

yes 500 ecb commands per frame here

stable fog
#

so

#

I was able to spawn 1 million blocks like that

#

but I did it in a single frame

#

it only locked up for like 2 seconds or so

#

however, after spawning that many, it was either 1 million or 10 million, it ws running at like 4 fps

#

either way, like, thats superior performance

gusty comet
#

barely running > crashing

stable fog
#

exactly

dry dune
#

1m objects is more than pixels on 1024x800 screen

#

so this is ridiculous

thorny halo
#

hello, does anyone know of a way to make terrain colliders inherit physics/collision detection from a NativeArray<float> without needing to copy all the data into a Physics world? I'm trying to make my runtime terrain deformation system work with collisions, but find myself bottlenecked using Unity's API as it does a lot of data conversion into Physics world that are way too costly.

Atm i'm creating my own collision casts and down the road, upgrading rigidbodies to work with the terrain. However, this will cost me quite a bit of time to develop.

Unity's Terrain Collider only has options to be directly updated through various methods which have severe overhead as they do additional things and the new Unity.Physics TerainCollider.Create() method is still really slow, with the only upside in performance being that it can be multithreaded, which is not enough due to the raw performance cost.

gusty comet
#

I'm sorry, can you space out your message?

hollow sorrel
#

@gusty comet hey this should work for converting a Sprite into a Mesh
https://hatebin.com/pmmorgjmfu
where m_mesh is the mesh to put into (could just be m_mesh = new Mesh())
and m_sprite is just the Sprite

basically all it is is copying 5 things that Sprite already has into the Mesh:
vertices, uv, colors, normals, triangles

#

this should work with spritesheets too if you mark them as "multiple sprites" in sprite import settings, if you were to just use the Texture data it'd create a Mesh as long as your entire spritesheet but by using Sprite it should use the correct uv's and everything

compact hound
#

What is the best way to destroy entity with all its childrens?

gusty comet
#

entities dont have children, are you talking about components?

slate breach
#

If it's an entity that was instantiated from a prefab with prefab entity children, they'll be in a linked entity group. If you delete the parent it will delete everything in the group.

gusty comet
#

is NativeDisableParallelForRestriction necessary on ReadOnly fields?

#

I think not disable parallel is done so you can modify something outside the jobs entity

deft niche
#

I don't think thats necessary at all if you are only reading

#

Its required if you are modifying the data in a parallel job

gusty comet
#

Thought it was modifying data outside the entity's job

deft niche
#

nope.

gusty comet
#

To rephrase [ReadOnly, NativeDisableParallelForRestriction] - the NativeDisableParallelForRestriction would be pointless right? No performance gain or anything?

deft niche
#

I believe so.. yeah

gusty comet
#

thanks

dry dune
#

without [NativeDisableParallelForRestriction] it is guarantied that you never create a race condition, by adding this you disable safety and take the responsibility for what you doing, whit this thing you easily can crash unity if do something wrong

gusty comet
#

How should I go to send information back and forth from the ECS sytem and monobehaviors?

coarse turtle
#

You could cache a ComponentSystem in your MonoBehaviour and interface a new Entities var so you can do the ForEach

class ForEachIteratorSystem : ComponentSystem { 
  public EntityQueryBuilder Entities => base.Entities;
  ....
}

public class SomeBehaviour : MonoBehaviour {
  void Start() {
    World.Active.GetOrCreateSystem<ForEachIteratorSystem>().Entities.ForEach(...);
  }
}

Another is to create a query and grab the entities via World.Active.EntityManager

#

neither way is really elegant

deft niche
#

yeah..there is no "nice" way of doing it..

#

ideally they are not supposed to be passing information to each other

hollow sorrel
#

2nd best ideal i think is to keep data flow one-way
e.g. only ecs to monobehaviour or only monobehaviour to ecs

on a related note i'd like to have uGUI get data from ecs to display in UI, but my current problem is that systems always update after monobehaviours, so the data displayed in UI will always be 1 frame old

#

players wouldn't really notice but i do ๐Ÿ™

#

could maybe add the ui monobehaviours to run in a system query and update it from ecs instead of monobehaviour.Update() but if anyone knows another way to make monobehaviours update after systems i'd love to hear it

deft niche
#

@hollow sorrel I usually use a sharedcomponentdata which has reference to the ui and make an updateui call manually from a ComponentSystem itself.

hollow sorrel
#

and your ui has references to all the ui pieces that need to update?

deft niche
#

yeah.. just 1 shared component that has references to all ui. I use the "ConvertToEntity" script and set it to "Convert and inject object". Through that , I can add the shared component on an entity.

#

Filter that entity through a query for the shared component inside a componentsystem and update specific views. ๐Ÿ™‚

hollow sorrel
#

ahh i see

#

pretty neat

coarse turtle
#

that's not a bad idea ๐Ÿค”

#

I've been remaking parts of it for my own needs

frosty holly
#

Does entityManager.DestroyEntity(entity); get rid of the components attached to that entity?

deft niche
#

SystemStateComponents do not get removed.. normal components will be removed.

frosty holly
#

@deft niche Thank you so much. What is the correct way to remove SystemStateComponents. Feel free to just link me to the right direction

frosty holly
#

Yeah just found that. Sometimes googling ecs stuff can be tricky ish

deft niche
#

yeah...

#

takes a bit of time

#

Those components are usually used as like notifications/events for something to happen..

frosty holly
#

Yeah I'm almost done with porting some code to ECS just fixing one last bug. I can't get the colliders to be destroyed

#

Not sure if I have to grab an unsafe pointer to it and destroy it or not

deft niche
#

interesting.. not dabbled with the ecs physics yet..

frosty holly
#

Its kind of weird and messy

        PhysicsCollider collider = entityManager.GetComponentData<PhysicsCollider>(entity);

        BoxCollider* boxCollider = (BoxCollider*)collider.ColliderPtr;
        BoxGeometry boxGeometry = boxCollider->Geometry;
        boxGeometry.Center = new float3(0f, height / 2f, 0f);
        boxGeometry.Size = new float3(1f, height, 1f);
        boxCollider->Geometry = boxGeometry;

I'm used to C++ pointers and what not just feels weird to use them in C#

deft niche
#

Ohh wow.. yeah..working with pointers can always get weird in C#.

frosty holly
#

On that note does anyone know the proper way to destroy an entity that has a physicscollider component. Haven't found anything yet and was curious if anyone knew.

I could be blind but I don't see an example in the Unity Physics samples

safe lintel
#

i just destroy em

#

same with entities with a rendermesh, just destroy en masse

frosty holly
#

@safe lintel How do you destroy them. When I use EntityManager.destroyEntity they are still there

#

Same if I use EntityManager.RemoveComponent<PhysicsCollider>

safe lintel
#

strange, i really dont do anything special compared to other entities

#

can you destroy a regular entity or remove a different component without problems?

frosty holly
#

Everything about them disapears in the scene but my raycaster still collides with them after they are gone

gritty grail
#

dots is hard with all of the boilerplate ๐Ÿ‘€

#

I'm not exactly sure what I'm supposed to do now that thelebaron called my dots programming out uwu

safe lintel
#

just trying to help you embrace the dod

#

get all the benefits of that juicy jobified bursted code!

low tangle
#

@ people asking about getting ecs into monobrhaviors
You just do. The data is there, no magical oop barriers and hoops. Query and find what you need

#

As for mono->ecs you just produce entities. Just that simple

gritty grail
#

ik xd

#

I just feel like I'm doing it all wrong

low tangle
#

World.Active.Entitymanager

#

There is no wrong way

#

Just data

#

Manipulate it as you see fit

#

Grab a pointer to a chunk and write random

#

Totally fine

safe lintel
#

have you experienced any heavy semaphore wait issues in your project @low tangle ?

low tangle
#

None that wasn't just me making my life harder than it needed to be

#

Something happen to yours?

safe lintel
#

i do get strange hitches, pertaining to using transforms & CopyTransformToGameObject

low tangle
#

Interesting

#

I didn't trust that system

#

Was getting weird results

#

So I cloned it and made a single component it ran on

safe lintel
#

funny thing is i did make a unique copy translation/rotation etc to the gameobject system(camera) and it is just this one thing that seems to take the hit

low tangle
#

Hm it's heavy ms but not really hitchy for me

safe lintel
#

so if it uses the built in system, that one suffers but if it separates out, it gets a huge waitforsignal that I dont really understand the cause of

low tangle
#

Oh interesting

#

I'll profile mine tomorrow and see if I have one

#

Want me to ping you?

safe lintel
#

ah i have a gif, ill upload

#

i dont mind talking here

low tangle
#

I'm heading to sleep is what I mean

safe lintel
#

oh, sure yeah

low tangle
safe lintel
frosty holly
#

Fixed I guess

#warning MASSIVE HACK THIS WILL CAUSE A MEMORY LEAK THE COLLIDER IS NOT BEING REMOVE
PhysicsCollider collider = entityManager.GetComponentData<PhysicsCollider>(logicalCellEntity);
BoxCollider* boxCollider = (BoxCollider*)collider.ColliderPtr;
BoxGeometry boxGeometry = boxCollider->Geometry;
boxGeometry.Center = new float3(0f, 0f, 0f);
boxGeometry.Size = new float3(Mathf.Epsilon, Mathf.Epsilon, Mathf.Epsilon);
boxGeometry.BevelRadius = 0f;
boxCollider->Geometry = boxGeometry;```
coarse turtle
#

what's going on with that xform system @safe lintel lol

safe lintel
#

its really sad

#

namespace Game.Modules.Transforms
{    
    public struct SetTransform : IComponentData { }
    
    //[DisableAutoCreation]
    [UpdateInGroup(typeof(TransformSystemGroup))]
    [UpdateAfter(typeof(EndFrameLocalToParentSystem))]
    public class SetTransformSystem : ComponentSystem
    {
        private EntityQuery m_SetTransformQuery;

        protected override void OnCreate()
        {
            base.OnCreate();
            m_SetTransformQuery = GetEntityQuery(typeof(Transform), typeof(LocalToWorld), typeof(SetTransform));
        }

        protected override void OnUpdate()
        {
            Entities.With(m_SetTransformQuery).ForEach((Transform transform, ref LocalToWorld localToWorld) =>
                {
                    transform.position = localToWorld.Position;
                    transform.rotation = new quaternion(localToWorld.Value);
                });
        }
    }
}

coarse turtle
#

hmm wow it's pretty simple

safe lintel
#

i do modify the localtoworld quite a bit via other systems, but this seems like a very uncharacteristic result

coarse turtle
#

yea it's something I honestly wouldnt expect

safe lintel
#

also @frosty holly are you just trying to destroy the entity or also cleanup the memory of the unneeded collider?

#

oh is it a system state component? ive not used those personally ๐Ÿ˜ฆ

frosty holly
#

I don't think it is a state system component. @safe lintel I just want to get rid of the collider. It still exists in the scene when I destroy the entity and therefore blocks my raycaster

safe lintel
#

are you using hybrid at all? any chance of mixing the two?

frosty holly
#

I couldn't find any examples of destroying physics objects in the physics examples

I had a look around the unity forums and couldn't really find anything

I looked through the source code and could only find systems for creating colliders

#

I am using hybrid

#

I don't think any of Unity's examples for physics are pure

safe lintel
#

yeah they are, but it might be a little confusing when it uses conversion

#

but can you tell me more about how you setup your colliders?

frosty holly
#

Hmmm yes I can ๐Ÿ˜„

#

My prefab is a simple box

safe lintel
#

whats the converttoentity look like, destroy or inject?

frosty holly
#

When its created I add a NonUniformScaleComponent

Entity sourceEntity = GameObjectConversionUtility.ConvertGameObjectHierarchy(cellEntityPrefab3D, World.Active);

...
for (int i = 0; i < ListContianingData.Count; i++)
{
        entityManager.SetComponentData(entity, new NonUniformScale
        {
            Value = new Vector3(1f, height, 1f)
        });
        PhysicsCollider collider = entityManager.GetComponentData<PhysicsCollider>(entity);

        BoxCollider* boxCollider = (BoxCollider*)collider.ColliderPtr;
        BoxGeometry boxGeometry = boxCollider->Geometry;
        boxGeometry.Center = new float3(0f, height / 2f, 0f);
        boxGeometry.Size = new float3(1f, height, 1f);
        boxCollider->Geometry = boxGeometry;

        // Set the position 
        Vector3 cellPosition = parent.position +
                logicalCell.ScenePosition.X * parent.right +
                logicalCell.ScenePosition.Z * parent.up +
                -logicalCell.ScenePosition.Y * parent.forward;
        entityManager.SetComponentData(entity, new Translation
        {
            Value = cellPosition
        });
}```
#

ConvertAndDestroy

#

NOTE: I don't have any other physics components on the prefab

safe lintel
#

i just dont see why destroying it wouldnt actually destroy it

#

i just cleaned this up, but could you try to recreate what i did and see if it actually destroys an entity?


using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using UnityEngine;

public struct Lifetime : IComponentData 
{
    public float Value;
}

public class LifetimeAuthoring : MonoBehaviour, IConvertGameObjectToEntity 
{
    [SerializeField] private float delay = 5f;

    public void Convert (Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem) 
    {
        dstManager.AddComponentData (entity, new Lifetime { Value = delay });
    }
}

public class LifeTimeSystem : JobComponentSystem 
{
    private EndSimulationEntityCommandBufferSystem m_EndSimulationEntityCommandBufferSystem;

    protected override void OnCreate () {
        base.OnCreate ();
        m_EndSimulationEntityCommandBufferSystem = World.Active.GetOrCreateSystem<EndSimulationEntityCommandBufferSystem> ();
    }

    struct DestroyJob : IJobForEachWithEntity<Lifetime> {
        public EntityCommandBuffer.Concurrent CommandBuffer;
        public float fixedDeltaTime;
        public void Execute (Entity entity, int index, ref Lifetime c1) {
            c1.Value -= fixedDeltaTime;
            if (c1.Value <= 0) {
                CommandBuffer.DestroyEntity (index, entity);
            }
        }
    }

    protected override JobHandle OnUpdate (JobHandle inputDeps) {

        var destroyJob = new DestroyJob {
            CommandBuffer = m_EndSimulationEntityCommandBufferSystem.CreateCommandBuffer ().ToConcurrent (),
            fixedDeltaTime = UnityEngine.Time.fixedDeltaTime
        };
        var destroyHandle = destroyJob.Schedule (this, inputDeps);
        m_EndSimulationEntityCommandBufferSystem.AddJobHandleForProducer (destroyHandle);

        return destroyHandle;
    }
}

#

just add the lifetimeauthoring onto something and it should destroy it

frosty holly
#

I'm not sure as well

    "com.unity.burst": "1.1.2",
    "com.unity.collections": "0.1.1-preview",
    "com.unity.entities": "0.1.1-preview",
    "com.unity.jobs": "0.1.1-preview",
    "com.unity.mathematics": "1.1.0",
    "com.unity.memoryprofiler": "0.1.0-preview.7",
    "com.unity.package-manager-ui": "2.1.2",
    "com.unity.physics": "0.2.4-preview",
    "com.unity.render-pipelines.lightweight": "5.7.2",
    "com.unity.rendering.hybrid": "0.1.1-preview",
    "com.unity.shadergraph": "5.7.2",
Unity 2019.1.12f1
#

Okay adding now

#

Objects disapear but there colliders remain with the code given

safe lintel
#

could you get a before and after screenshot of what happens?

candid bough
#

nothing better than waking up served a plate of code for breakfast

gusty comet
#

๐Ÿ

low tangle
#

@safe lintel why are you doing that on the main thread

#

throw that shit into a job and burst compile that shit

safe lintel
#

uh what setting the transform?

low tangle
#

yeah

#

let me get mine after I profile it

safe lintel
#

i dont think the job code would really effect it, but you mean to use TransformAccessArray to jobify it?

low tangle
#

correct

#

makes the copy quite cheap

safe lintel
#

well thing is if I disable that system and use the built in copy system, that gets the same WaitForSignal delay issues

gusty comet
#

Is dots production ready?
Out of preview?

low tangle
#

I've got no wait for signals in mine that see yet

deft niche
#

@gusty comet not till next year

gusty comet
#

That doesn't sound that long.

#

I believe there aren't tons of tutorials yet.
Time to have fun with documemtations.

safe lintel
#

check out the pinned message here

#

its like directly correlated to the amount of enemies that are in scene(gameobject based)

low tangle
#

yeah number of transforms

gusty comet
#

Oof

stable fog
#

okay, so I'm new to DOTS, and I've gone and created an entity composer fo rmyself and now I want to work on building something for spawning and I'm a little confused

#

Am I always going to be spawning entities from a GameObject's MonoBehaviour?

#

or can I make jobs that spawn entities?

untold night
#

You can make JobComponentSystem or ComponentSystems that spawn entities.

You don't necessarily need a GameObject or source entity, unless you want that to drive configuration/positional information.

hollow sorrel
#

i keep finding myself making static lookup tables for anything that isn't a struct, with an id as reference in the component where needed
e.g. a sprite dictionary for showing sprites
one for pretty much any scriptableobject data, like looking up an animation or sound etc

is there a better way to do this? feels weird to have so many especially for scriptableobjects

main use case is referencing a sprite or scriptableobject that can also be referenced from different components, but the scriptableobjects themselves are loaded once and never change

#

i don't even know if concurrently reading a static dictionary is fine, haven't tried with jobs yet

coarse turtle
#

I dont remember if regular dictionaries in C# allow multi threaded access ๐Ÿค”

#

I know there's a concurrent dict in C# systems lib

stable fog
#

no

#

I mean, you can access anything multi-threaded, its more a questino of whether you can do it without exploding things

#

but they are not threadsafe

#

ConcurrentDictionary works well enough

coarse turtle
#

Ah cool

shut python
tawdry tree
#

@hollow sorrel As long as you KNOW you are only reading, and there are no side-effects, any collection should be fine, I believe.
I'd put even more emphasis on 'know' if I could.

shut python
#

@tawdry tree this wasn't for me right =?

tawdry tree
#

Err, no, lemme edit that to clarify

shut python
#

sorry ๐Ÿ™‚

quaint snow
#

Hello Everyone!
Can anyone show me how to use UdpNetworkDriver in parallel Jobs correctly ?
Code here + Errors
https://justpaste.it/7l0ej
Thanks in Advance!

tawdry tree
#

Have you tried getting the concurrent driver in OnCreate, instead of OnUpdate?
Right now you're effectively converting the non-concurrent driver to a concurrent one each frame. Network calls are asynchronous and can(usually do) last several frames.

#

And in fact, you're doing it twice in one frame.

#

I am not familiar with netcode, especially in DOTS, though.

quaint snow
#

thanks @tawdry tree ill try it let you know

pliant pike
#

I've forgot but you cant use a simple array in a IComponentdata can you? you have to use a Dyamicbuffer is that right

hollow sorrel
#

yes

#

or at least i think that was the main intention

pliant pike
#

cool thanks

safe lintel
#

oh hey @shut python i think some of those errors are from the debugger itself, if you change your manifest package for properties to
"com.unity.properties": "0.6.4-preview",
it should show whats on that entity properly

shut python
#

@safe lintel yes, and I removed the fixedDeltaTime. Now the player is moving.

safe lintel
#

not sure why you have the burst error though

shut python
#

well thanks tho ๐Ÿ™‚

gusty comet
#

Recomendations for what unity versions to use with DOTS?

safe lintel
#

probably 19.3

gusty comet
#

Yeah, thats what I was thinking.

#

thanks

#

Reading the docs while downloading.

stuck hatch
#

Hello, has someone experience with EntityManagerExtensions class? There is a method "Instantiate" and it does nothing, someone know how to use it?

tawdry tree
#

Not sure what you mean by does nothing, though. Can you not see any code? No effects of calling it? Or something else?

stuck hatch
#

I am calling it, I am debugging it, but the created entites are empty.

#

Do you have have any IDE open?

tawdry tree
#

Does your GOs have conversion workflow components on them?

#

Mind you, the entire class might just be WIP, and we're not supposed to use it. What are you trying to achieve?

stuck hatch
#

Actually I just useing a regular gameobject with meshrender nothing more

#

I want to convert a Gameobject to entity, without creating the Gameobject, only using prefab

tawdry tree
#

Oof, that's an old forum post

stuck hatch
#

๐Ÿ˜ฆ

tawdry tree
#

If you can make your gameobject convert using the normal flow, then you could try using that instantiate method

#

It could just be that you've set up the prefab wrong, so it doesn't convert

stuck hatch
#

ok, what are conversion workflow components

tawdry tree
#

Do you have the hybrid renderer package, for example?

stuck hatch
#

the convert to entity component?

tawdry tree
#

That's one

stuck hatch
#

are there more?

tawdry tree
#

I'm not entirely sure what does and does not exist right now, but my point was that you ought to make sure the gameobject can be converted, then you can try going the prefab route

#

That said, if you have one copy of the prefab in your scene, or spawn it once (in some system) on startup, you can make the entity you get from that into a prefab entity, and use that as the source of new entities. I believe that's faster than always using the GO. Not that you might notice at the scale you're working on.

stuck hatch
#

I already tried it with convert to entity component attached, not the expected result

tawdry tree
#

Do you have the hybrid renderer package,

stuck hatch
#

yes

tawdry tree
#

And you are unable to make a gameobject in the world convert to an entity on play?

stuck hatch
#

Gameobject is a prefab with default Unity Components, no convert to entity, but it also makes no difference

tawdry tree
#

Again, I don't think you're supposed to be using that method. And since you have yet yo give me an answer:
Have you been able to convert any gameobject, even just a simple dumb cube, to an entity?

stuck hatch
#

Yes I can convert but only if the object exists in the scene

#

I want to reference the prefab and create it that way

tawdry tree
#

Right. Next question then is, why do you insist on spawning from a prefab, directly?

stuck hatch
#

Because I want to create many of them and to spawn the gameobjects first and transform them to entities seems the wrong way, why not create it directly as an entity?

tawdry tree
#

Ask Unity about that, the conversion workflow is the way things work :/

#

You could do it the slightly more roundabout way of:
-Spawn prefab from entity system
-Convert said prefab to an entity
-Make said entity into a prefab entity (disable it, but grab a reference)
You now have an entity you can spawn as many of as you like

#

The "HelloCube: SpawnFromMonoBehaviour" says: This sample demonstrates how to spawn Entities and Components using a Prefab GameObject.

stuck hatch
#

I try, but I will ask on Unity Forum, if this supposed to be used that way

tawdry tree
#

I think it does essentially what you want to do, and what I'm talking about here

stuck hatch
#

The difference is, object in scene or Object as prefab

tawdry tree
#

Digging into that sample:

public class Spawner_FromMonoBehaviour : MonoBehaviour{
  public GameObject Prefab;

  void Start(){
    //Convert GO prefab to entity prefab
    var prefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(Prefab, World.Active); 
  }
} 
stuck hatch
#

wait what?

#

I try

tawdry tree
#

Ideally you'd want to do this in a system, but that'd have it's own challenges (getting the prefab reference in the first place - you'd need to do some Asset magic)

stuck hatch
#

wow ๐Ÿ˜ฒ it works

tawdry tree
#

That monobehaviour could very well create an entity with something like:

public struct MyPrefabComponent : IComponent {
  public Entity Prefab;
}
stuck hatch
#

I think EntityManagerExtensions is a dead end

tawdry tree
#

And then you could access the entity prefab from any system after that. A bit cumbersome, but...

stuck hatch
#

Thank you very much, I didn't saw the ConvertGameObjectHierarchy method

tawdry tree
#

As I said, I highly recommend digging into the samples. Not necessarily recreating them, but at least read through the code and see what can be done and how

stuck hatch
#

Thank you, I will do

tawdry tree
#

it's a lot to take in, and it's hard to get into it - not just the whole DOD/ECS paradigm/pattern learning curve, but the specific ways to do things.

glad solar
#

There is a way to use debug in other to get information from my system when i'm using JobComponentSystem?
Or i still have to use ComponentSystem to perform that?

dry dune
tawdry tree
#

@glad solar What kind of information? Debugging from jobs is... but you can use Debug.Log() as long as you don't use burst (and you can just deisable it while debugging, then turn back on)

dry dune
#

@digital scarab at the moment of the conversion callback those components are not present yet

#

but in any case, i prefer not to remove them but to prevent their creation
i'm looking for a way to replace transform component conversion method with my own

#

found that it is possible to add a system that runs after conversion is done
using [UpdateGroup(typeof(GameObjectAfterConversionGroup))]

#

any other reason
pure perfectionism

glad solar
#

@tawdry tree when a job is runing in a thread it can call Debug.Log()?
The devs made it possible now? (There is a few months that i was away from Unity3D)

tawdry tree
#

@glad solar I don't think you can do that in a job thread, no, but the system can.

languid stirrup
#

ok... So i just learnt what DOTS is.. and im in love... its stable tho right? considering its in preview? shall i use it in my ongoing project or is it still buggy?

tawdry tree
#

There are people doing production stuff with it

languid stirrup
#

oh great... thnx!

#

so, i need DOTS basic package, windows package, Entities, MAthemtics and ... BURST compiler right?

tawdry tree
#

There are some key parts that are hard or impossible do do (out of the box) right now, but you can definitely start using it.

#

To get started, all you need is the entities package

languid stirrup
#

well i will be using jobs and burst anyways, so using those either ways

#

so only DOTS basic package and windows package remains

tawdry tree
#

Burst is to optimize the compiled code (more perf), and optional. I don't think you need the platform packages (as in, they don't do anything yet).
Read the description for mathematics, I don't remember if it's the core stuff, or just extensions

#

The jobs package is definitely just extensions. I mean, if you need those, sure, but a bunch of job types are actuallyin the default install

languid stirrup
#

well i will be playing around with procedural generation and curves... so i will need mathematics

#

job types are default too? so i can use full multi threadedness right of the bat now?

tawdry tree
#

You can at least use IJob out of the box

#

The entity-related jobs come with that

#

Again, read the package information, I think IJobParallelFor was one of the things you get from the jobs package

languid stirrup
#

it gives extention types like parrallelforbatch, forDefer and forFilter

#

so yea, i guess basic Ijobs are already in... just need to update unity to 2019.* then i guess lol, i have a relic one

tawdry tree
#

Uhh, yeah, definitely want the latest release, or even the beta for DOTS stuff

#

Beta for experimentation, mind you, not for more production ready stuff. Though be prepared to have to do quite a bit of experimentation to 'get' some of the key concepts. (at least if you're not already familiar with DOD)
The Entities interaction unite talk is a great piece:
https://www.youtube.com/watch?v=KuGRkC6wzMY

Interaction is fundamental in games, both in how players interact with a game and receive responses, and in how parts of the game interact with one another. ...

โ–ถ Play video
languid stirrup
#

oh yea. already saw that... already in love with DOTs and i wanna forget all about OOP :p

dry dune
#

when people say to forget OOP to learn DOD they don't actually mean it, what they mean is "be prepared to think in a different plane", OOP design patterns are good, just many of then don't apply to DOD

glad solar
#

if i use ISharedComponentData then i cannot use ForEach, therefore i have to search it using only EntityQuery, right?
I have a bunch of entities that are created in the map generation that contains (X,Y) values. and in gameplay some actions requires to change the some values in a specific (x, y) position.

Would be better to migrate this position from IComponentData to ISharedComponentData in order to filter one specific entity?
(well... i'm thinking that a whole bunch of rework on my systems will be required if i do that)

tawdry tree
#

What are you trying to achieve? ISharedComponentData is for shared data, and is used to group entities into chunks. You generally use it for models and such, which rarely change.

glad solar
#

It's kinda hurt my eyes, but it's the solution i made temporary:

private Entity GetCurrentNode(int x, int y, EntityManager entityManager) {
   Entity nodeEntity = Entity.Null;
   Entities.ForEach((Entity entity, ref MapNodeComponent node) => {
      if (node.X == x && node.Y == y) {
         nodeEntity = entity;
      }
   });

   return nodeEntity;
}

I think there is a better way of filtering it that i don't have to roll over all the the entities to find one specific every time i jump to this method.

#

@tawdry tree by what you said, i think i missunderstood the use of sharedComponentData. So it's not a good use for my case. Gonna re-read the documentation.

tawdry tree
#

If you could explain your goal, and what data you have, I could maybe point you in the right direction?

glad solar
#

sure

#

In my scene, the first process is the map generation.
It define a random size for width and height and generate one node for each position. For example if the map define the size of 10, i'd have 100 nodes for my map.

The process i create is: one temporary entity is created at the center of the map and for each position it goes, it defines that node as a "walkable" node.
That's the part where i need to get a specific node in x and y to change it's type from nothing to land (its an enum).
My node is simple:

public struct MapNodeComponent : IComponentData {
   public MapNodeType Type;
   public int X;
   public int Y;
}
vagrant surge
#

use a hashmap

#

not everything has to be as components

#

its also generally not so good to use entities for stuff like graph nodes

#

why do you need the entities there? you can just store the nodes in arrays

tawdry tree
#

So... you're generation the world in entity space? I'd argue that the generation should be separate from that.
To elaborate, you'd have the entity world doing whatever you want, and creating entities with components that communicate "I need to generate part of the map here!"
Then some system would read those, and kick off procGen. Crucially, said procGen would exist outside of the entities and any systems, as job(s) (potentially) spanning multiple frames. Then your system could see that your job was done (or threads or tasks or some other async/parallel way to do work), and create world entities with the map from that.

#

As for the lookups, stuff like that is often good to do in hashmaps like vblanco says.

#

There is no one solution, of course, but do remember that that also applies to entity-components - It might be a shiny new hammer, but not everything is a nail...

glad solar
#

hmm...
At first I tried to fill everything in one entity that would be the Map (or World) entity, but when i look at my gdd, the map is interactable. That's when i thought i would need to create each node as entity. I'll rethink the logic i need to apply here. thank you @vagrant surge and @tawdry tree

vagrant surge
#

this is about data-oriented design without really going into ECS, but similar-ish

#

will probably give you ideas

tawdry tree
#

The chunking pattern you'd use in gameobjects to split up the "physical" (collision, models) world still applies, though you can probably get away with bigger chunks. The generation itself should not "happen on entities" (logic belongs to systems)

vagrant surge
#

entities are mostly for complex objects where you want to add/remove components and run in systems

#

for something like a graph, its not that good of an idea

tawdry tree
#

And entities are just the way you translate the output of systems into the "physical world"

vagrant surge
#

also cross-system comunication

#

event entities are common

tawdry tree
#

If you have graphs and other think which are not part of the "physical world", then yeah, probably not the best to use events for.

#

At least, I find thinking of entities and their components as "the physical world" to be helpful. Is this part of the world the player directly interacts with? Or is it something that is merely in place to drive it?

glad solar
#

hmm. The player can directly interact with.

tawdry tree
#

Tl;dr ECS is hovercars

stuck hatch
#

Hello everyone, I have one more question. I am creating an entity from a gameobject and I can successfully use Translate to move it. The GameObject has a child with Meshrenderer component. As soon as I attach the Capsule Collider both entities are not attached to each other. The entity debugger shows a child entity as long as I am using no collider and with collider there is no child displayed anymore. Also the Translate only works on the parent entity. How to achieve the same behaviour with collider attached?

tawdry tree
#

Do you have DOTS physics installed?
You need that for physics + DOTS.
Also, not sure if DOTS physics supports joints or other linked entities yet. Might need to make your own system to make them move together, if that's your goal.

stuck hatch
#

Physics is installed

#

I am checking the ecs physics example right now, maybe I find the answer there

tawdry tree
#

Wait, your CHILD component has physics?

stuck hatch
#

yes

#

I think I use a system to move both

tawdry tree
#

Why, though? You can out multiple physics shapes on one gameobject (or entity), and physics+parenting can get... weird. If one just moves with the other, merge them (can be part of the conversion, BTW. that'd let you use hierarchy design-time), if they move separately... why are they parented?

stuck hatch
#

Actually I just dropped a capsule collider into the gameobject and tested how it will behave

tawdry tree
#

Does it work with physics only on the parent?

stuck hatch
#

yes it does

tawdry tree
#

At any rate, if it was just playing around, then you don't really have an issue, it was more of a 'can anyone clear this up?' question... ๐Ÿ˜›

stuck hatch
#

thats right, but I though it would behave like a regular game object

gusty saffron
#

Hi!
If I have an entity inside a job, can I access its ISharedComponentData from inside the job? I only need to read from it.

deft niche
#

@gusty saffron Nope. There is no way to access sharedcomponentdata in a job

languid stirrup
#

question. Is there something other than a monobehaviour that can trigger the behaviour system of ECS or do I have to use the monobehaviour as a starting point even for an ECS system project?

slow epoch
#

You can use RuntimeInitiazeOnLoadMethod

#

Or the player loops

#

Player loops are out of experimental in 2019.3

stable fog
#

Can't you send SharedComponentData into a job when you schedule it though?

dull copper
#

tried to fish out some estimate for DOTS hybrid getting HDRP's DXR support (DXR + hybrid doesn't play ball atm)

#

got response from HDRP lead: "Hi, this is under investigation, we have currently no ETA."

#

I mean, there's no surprises there considering DXR is still experimental on 2019.3

#

but yeah, I guess it doesn't really change anything, right now using hybrid in production is big risk anyway (so is DXR tbh), so it's still safest to use gameobjects for rendering

languid stirrup
#

@slow epoch thnx, but the RuntimeInitializeOnLoad invokes after the Awake function. and i have a few object that will need the init values in the awake functions... so this wont do

languid stirrup
#

ok, i am using a archetype RenderMesh for both my terrain meshes and player meshes... should i keep these separate or this way should work? i am worries about player mesh being rendered before the terrain mesh lol

little tartan
#

hello there!

#

I have a problem with manually creating systems in the default world since upgrading to unity 2019

#

before I was able to create the systems like so:

protected override void HandleWorkerConnectionEstablished()
{
            World.Active.GetOrCreateSystem<LeyLineHybridECS.MeshColorLerpSystem>();
            World.Active.GetOrCreateSystem<ProjectileSystem>();
            World.Active.GetOrCreateSystem<ClientCleanupSystem>();
}
#

can anyone here tell me how one manually creates systems in the default world now?

hollow sorrel
#

i think creating systems is still the same

little tartan
#

well the code snipped I posted gets called but the systems don't show up in the default world

#

no errors but the systems are not being created

deft niche
#

Does anyone know when the new entities package is going to come out ?

#

It was supposed to come out like 2 weeks ago ๐Ÿ˜

safe lintel
#

i feel as if i will have aged significantly between releases this time

little tartan
#
World.Active.GetOrCreateSystem<ProjectileSystem>();

can anyone tell me why this does not create the system anymore?

tawdry tree
#

Are you sure it does not, in fact, create or get the system?
Grab the reference it returns and breakpoint it

deft niche
#

Gonna need a bit more info than that @little tartan

tawdry tree
#

The system will probably not run if there's nothing it can act on

little tartan
#

it does not show up in the entity debugger

#

and I'm displying inactive systems

deft niche
#

Any "RequiredForUpdates" for that system to run ?

tawdry tree
#

What do you see if you

void MakeSystem(){
    var sys = World.Active.GetOrCreateSystem<ProjectileSystem>();
*  Debug.Log(sys.ToString()); //* is breakpoint
}
hollow sorrel
#

are you sure HandleWorkerConnectionEstablished() gets called

little tartan
#

yes

#

@tawdry tree

tawdry tree
#

So the system is created, but does not show up in the list.
What if you put a Debug.Log in the update method?
Does it have any entities to operate on?

#

And why are you manually creating the system?

little tartan
#

I tried the debug in the update loop

#

does not print anything

deft niche
#

Seems like your system has no entities to work on..

little tartan
#

@tawdry tree I need to get queries from other worlds and need to make sure the references to those worlds are set before the system is created

tawdry tree
#

What about entities for the system to operate on?

#

And why would the system need the references to be created? Couldn't you just short-circuit it if it lacked them?

little tartan
#

it operates on projectiles so there will be none at the point where it's being created

tawdry tree
#

Does the system work if you spawn some of those?

hollow sorrel
#

he said it doesn't show up with inactive systems ticked in debugger so if it had no entities it should still show up greyed out

tawdry tree
#

should

little tartan
#

well the debug.Log() inside the OnUpdate in the system debugs nothing

#

and the projectiles are not being moved

#

so no it doesn't do anything

tawdry tree
#

I'm just throwing out ideas to eliminate possibilities

little tartan
#

yeah thanks for trying to help it's much appreciated

#

honestly seems like a trivial problem but I'm at a loss here still

#

        m_MoveAnimData = Worlds.ClientWorld.CreateEntityQuery(
             ComponentType.ReadWrite<MovementAnimComponent>()
        );

        m_UnitData = Worlds.ClientWorld.CreateEntityQuery(
            ComponentType.ReadWrite<AnimatorComponent>()
        );

I have this inside ProjectileSystem

#

which is why I cannot simply remove the [DisableAutoCreation]

#
        protected override void HandleWorkerConnectionEstablished()
        {
            Worlds.ClientWorld = Worker.World.EntityManager;
            Worlds.DefaultWorld = World.AllWorlds[0].EntityManager;
            Debug.Log(Worlds.DefaultWorld.World.Name);
            WorkerUtils.AddClientSystems(Worker.World);
            var p = World.Active.GetOrCreateSystem<ProjectileSystem>();
}
#

because I need to be sure the Worlds script has the references to the other worlds

#

but I honestly have no clue why the system would not show up in the debugger / wouldn't do anything if it is in fact being created

tawdry tree
#

What if you do let it auto-create, but short circuit in OnUpdate?

//In OnUpdate
if (!Initialized && !Tryinitialize()) 

//Helper method, could be local or more likely a private class method
void TryInitialize(){
  //Check if the other world exist
  //Check if other world queries/systems exist/are done
  //Etc
  //Return true on success, false (and short circuit) if any check fails
}
little tartan
#

that might work

#

I'll check what happens if I let it autoCreate

#

okay

#

your workaround seems to do the trick

#

does not really explain the weirdness with

#
 var sys = World.Active.GetOrCreateSystem<ProjectileSystem>();
#

but at least I get my default world systems to run again >_<

tawdry tree
#

๐Ÿคท Such is life with preview and WIP packages

little tartan
#

thanks alot for the help mate!

tawdry tree
#

No prob. Sometimes you gotta break down your objective, and occasionally you should stop doing the best practice and do something that works instead.

twin raven
#

A bit late to the discussion, but could it be that it if you have tag [DisableAutoCreation] it does not end up in any systemgroup and therefore is not updated?

#

And you would have to manually call system.Update()

hollow sorrel
#

if i were to have an entity reference a common immutable class (not struct) for data, like a scriptableobject, or more specifically like EnemyData that contains health or whatever

should this be a SharedComponent or a BlobAsset?

deft niche
#

I would rather create a singleton instance of that database. Entity will just store component data which contains the id or something that will help me lookup that data from the database instead of an entity storing a scriptable object reference like that.

hollow sorrel
#

yea i thought about that too
i was also thinking in the case of a spriterenderer animation system where each animation is defined in a scriptableobject
but when using id that'd be a lot of lookups per frame

#

and basically fill up the database at startup with all the immutable data

coarse turtle
#

I'd put it in a blob for the sprites since its looks like you want to just read them

mint iron
#

How to handle config data well is still an open question in my mind. Iโ€™ve done prefabs with extensive conversions... but itโ€™s a lot of work. I have been playing with some ideas for scriptable objects... the unrefined version being here https://gist.github.com/jeffvella/aee47c7199f061c01d9fca68a42b25f9 also recursive posted more complicated version that works for sub scenes etc last week. My thought was that if you lock the chunks then the ptrs direct to component data wonโ€™t change and can be used for ultra fast access to what essentially becomes read only data. Although you can obviously still change it thru the ptr.

Gist

GitHub Gist: instantly share code, notes, and snippets.

fallen owl
#

https://github.com/lucascassiano/Unity-Arduino-Serial-Port-Finder
Guys, did anybody worked with this in previous. This is a project that works on setting up Arduino and Unity auto configuration. If yes please leave me a message. I've been sitting on make this thing work for one week

wary anchor
#

Hi all, I'm unsure of where in the update cycle to put certain systems. Should all movement related systems go into the TransformSystemGroup? I have some axis rotation stuff that's giving me weird results and I suspect it because it's in amongst all the EndFrameTLSLocalToWorld etc etc type of built in systems

worldly pulsar
#

Usually you'd want movement to happen before TransformSystems (this way you can move the car and then TransformSystems can take care of moving the wheels etc.)

wary anchor
#

is there a way to tell a system to update before a group?

#

I can either put them all into the TransformSystemGroup, or I appear to need a dummy system that sits before the TSG and then arrange everything to run before that

worldly pulsar
wary anchor
#

ahh yes I see that works, cheers

#

I'm sure I tried that before a while back!

worldly pulsar
#

You can also define your own groups (derive a class from ComponentSystemGroup)

wary anchor
#

So rotating a view would normally be done in eg late update, is it similar in ECS to move eg camera rotation to a late update group?

#

my view rotation system is currently running in the simulation system group right after the transform system group

worldly pulsar
#

if it's running after the transform group then the Rotation is not applied to the LocalToWorld matrix, and has no effect on e.g. rendering

#

(I mean it is applied on the next frame)

wary anchor
#

ahh yes okay that makes sense

#

thanks ๐Ÿ‘

pliant pike
#

ok I'm confused I don't suppose anyone knows why I cant add this float3 to a float3 buffer or any float3 for that matter

#
public struct WaypointConnections : IBufferElementData
{
    public float3 Connections;
}

 dstManager.AddComponent<WaypointConnections>(entity);
        foreach (var diddle in Dudese)
        {
            var tempbuff = dstManager.GetBuffer<WaypointConnections>(entity);
            float3 temppos = diddle.position;
            tempbuff.Add(temppos);

        }```
safe lintel
#

make a new buffer element and then add the element to the buffer

coarse turtle
#

it should be dstManager.AddBuffer

safe lintel
#

var bufferelement = new WayPointConnection{Connections = diddle.position}; tempbuff.Add(bufferelement);

pliant pike
#

doh! I always forget about the 'new' keyword thing thanks guys

safe lintel
#

btw does anyone know if entitycommandbuffers will always generate gc allocations? not sure if this is a early-preview-entities thing or i-am-structuring-my-game-wrong thing

coarse turtle
#

Hmm let me look at my project to see if it generates gc

pliant pike
#

how do you check if it does generate gc anyway?

coarse turtle
#

profiler

coarse turtle
#

@safe lintel looks like it generates gc for me too ๐Ÿค” dunno if it will be cleaned up later down the road though

quaint zealot
#

The GC allocation comes from the DisposeSentinel that gets created in editor builds (when safety checks are on). There should be no GC allocation in a standalone player!

rugged wagon
#

Are there any examples of how to use the native multihashmap in a job? The collection is new to me and I can't figure out how to elegantly iterate through every value at a key using TryGetFirstValue and TryGetNextValue
this is the best i could come up with

if (map.TryGetFirstValue(hash, out var otherValue, out var iterator))
{
    // do operation on first index
    while (map.TryGetNextValue(out otherValue, ref iterator))
    {
        // do exact same operation on next index
        // ^^ duplicate code แƒš(เฒ _เฒ แƒš)
    }
}
#

Duh I guess I could do this ๐Ÿ˜

if (map.TryGetFirstValue(hash, out var otherIndex, out var iterator))
{
    do
    {
        // do operation here
    }
    while (map.TryGetNextValue(out otherIndex, ref iterator))
}

haven't used a do-while loop in forever lol

safe lintel
#

@quaint zealot sorry to ping you but any word on when the new entities package is arriving?

#

also thanks for the gc alloc info

coarse turtle
#

@rugged wagon Ive mainly used a do while loop to get the elements

rugged wagon
#

Good to know I'm not doing anything too suboptimal, thanks

quaint zealot
#

No concrete date right now, but we're finishing up the last bit of work for the next release now

#

Should have more news by next week

tawdry tree
#

(News) Soonโ„ข

#

And I'm not trying to be snarky here or anything, if I could code that stuff my own I wouldn't be as hyped for someone else doing it for me ๐Ÿ˜›

haughty sand
#

@rugged wagon I think there is a .ToKeysArray()

rugged wagon
#

@haughty sand Yea I saw that but was trying to avoid allocating a new array. However I'm running into some really bad performance problems in my current job. Are there any common gotchas when it comes to the native multi hashmap? I'm using it to partition a grid of points so that I can (theoretically) do a better job at culling which pairs of points require distance checks between them. Here's the job if anyone actually wants to skim it https://pastebin.com/xDGNmgv4

grizzled bronze
#

I'm having a strange issue with one of my shaders. When I attach it to a regular GameObject, it works fine and all the lighting is correct, however when I assign the material to an entity's RenderMesh component, it displays fine, except for the lighting.
The lighting seems to be calculated as though the light was a child of the entity and rotated with it. When the entity's rotation changes, the lit part of the object rotates with it, which should obviously not be the case.

The only difference between the standard shader (which works fine with GameObjects and entities) and my shader (which works with GameObjects but not with entities) is this line in the fragment shader:
input.normalWS = normalize(cross(ddy(input.cameraRelativeWorldPos.xyz), ddx(input.cameraRelativeWorldPos.xyz)));
If I remove this line the lighting works fine, however I need this normal recalculation in order to achieve the desired effect.

input.cameraRelativeWorldPos is calculated like this in the vertex shader:
cameraRelativeWorldPos = (mul(unity_ObjectToWorld, float4(input.positionOS.xyz, 1.0)) - float4(_WorldSpaceCameraPos, 0.0)).xyz;

Any help would be greatly appreciated, as the amount of information out there about this stuff is quite sparse!

solar geode
#

I know that Burst isn't supported on the Switch right now, but is there any kind of timeline (however vage or broad)? I ask because my game uses Burst, but I need to justify it in my pitch to publishers.

#

If it won't be available within the next 8 months or so, then I'll need to either remove it from my game or spin the relevant features as a post-launch patch

gusty comet
#

Sorry to repost a forum post here, but I would greatly appreciate a quick response since it's a blocker:
I have a use case for NavMeshModifierVolume where I need to create/reuse hundreds of instances to populate a temporary grid of weights. I'm thinking about converting these heavyweight GameObjects into Entities with the bare minimum number of Components needed to get the job done (BoxCollider, Transform, NavMeshModifierVolume). Would this reduce the memory footprint, and if so, would the NavMeshModifierVolume Entities still work with NavMeshSurface?

haughty sand
#

Hi ! Anyone did some test with NativeHashMap ? Is is better to create a big one on init, and clear it before launching a job. Or recreate a new one with a kown right size before launching the job and dispose it after job is complete ?

grizzled bronze
#

So after some further testing, it appears that ambient light isn't accounted when using entities, even with the standard shader. Not sure if this is related to my problem, but I'm very much not a fan of pitch black shadows

onyx mist
#

how come i can see neither the entity class that i see people using entity.withall with, nor can i see the entity query class

#

oh i see the issue now

#

well, for the Entities issue that is

#

still not too sure about entityquery's disappearance ๐Ÿค”

hollow scroll
haughty sand
#

@onyx mist You need to type that inside a method (like Update or OnCreate) or else the autocompletion won't find it

onyx mist
#

it still cant find it :<

night cargo
#

Where do you guys create your EntityArchetypes? I'm trying to figure out where should I place this code to ensure they are created before any of the systems runs...

#

Right now I am placing this code in the OnCreate of the system that operates on such archetypes, but if conversion happens before it then I am screwed.

elder wharf
#

@onyx mist which version of the entities package do you use? (because you are using IJobProcessComponentData which is deprecated, so it may be possible that you have an old version that don't have 'EntityQuery' yet, if that the case, upgrade the package (but if you can't for whatever reasons, use 'ComponentGroup' instead of 'EntityQuery'))

gusty comet
#

hello any idea how do I accomplish a thing like iterating over some entity query inside a IJobForEach?

safe lintel
#

@onyx mist use it inside the ComponentSystem's OnUpdate, not the JobComponentSystem(i think they demoed something for jobcomponentsystem at unite but its not available yet)

#

@gusty comet if you want another query inside your job, you can use query.ToComponentDataArray<LocalToWorld>(Allocator.TempJob) or ToEntityArray

gusty comet
#

@safe lintel thanks for the answer but can I access a component data and change it there or just read it?

safe lintel
#

should be able to change it, my memory is a little hazy but you need to set the attributes in your job accordingly, i think [NativeDisableParallelForRestriction]

gusty comet
#

Thank you

mint iron
rugged wagon
#

Thanks, I'll check it out @mint iron

#

I'm already fully down the dangerous rabbit hole with my current project haha

gusty comet
#

Guys any clues on how do I get a EntityCommandBuffer inside a Job to use?

#

|| @safe lintel :)||

safe lintel
#

you need to get a barrier system such as EndSimulationEntityCommandBufferSystem
then create the ecb like m_EndSimulationSystem.CreateCommandBuffer() in the job creation(there is also CreateCommandBuffer.ToConcurrent() for use in ijobforeach)
after the job is scheduled, you also need to add m_EndSimulationSystem.AddJobHandleForProducer(jobhandle);

gusty comet
#

How do I get a barrier system?

safe lintel
#

World.Active.GetOrCreateSystem

gusty comet
#

Thank you so much

#

It works

gusty comet
#

@safe lintel
Everything works as charm except it turns out modifying values from NativeArray of IComponentData's doesnt do anything cause its just a copy. Is there any way I can get it by reference as in Entities.ForEach?

coarse turtle
#

Replace the NativeArray with ComponentDataFromEntity<Movable> and you should be able to manipulate that data (you may need to disable restrictions - I cant remember from the top of my head which can be typically unsafe if you have multiple threads accessing the same data), another option is to also grab the associated entity and use a CommandBuffer and reset the entity's hitPoints value

#

you should be able to assign ComponentDataFromEntity<Movable> with GetComponentDataFromEntity<Movable>(false) function from the JobComponentSystem

  • false param is so that its not readonly by default
gusty comet
#

So should I get a NativeArray<Entity> outside a job and use GetComponentDataFromEntity inside a job?

coarse turtle
#

You can get the NativeArray<Entity>and call GetComponentDataFromEntity outside the job too to create the job struct

#

You should probably use the EntityCommandBuffer instead to decrement the hitPoints with the NativeArray<Entity>

gusty comet
#

No idea how to use it in this context

coarse turtle
#

if you wanted to use the ComponentDataFromEntity to play around (as a crude example) (Fixed with @safe lintel 's correction)

struct SomeJob : IJobForEach<T0, T1> {
   [NativeDisableParallelForRestriction] public ComponentDataFromEntity<Movable> Movables;
   [ReadOnly, DeallocateOnJobCompletion] public NativeArray<Entity> Entities;

   public void Execute(ref T0 c0, ref T1 c1) {
     for (int i = 0; i < Entities.Length; i++) {
       var val = Movables[Entities[i]];
       val.hitpoints -= 1;
      Movable[Entities[i]] = val;
     }
   }
}

class SomeJobComponentSystem : JobComponentSystem {
  protected override void OnUpdate(JobHandle inputDeps) {
     return new SomeJob {
        Movables = GetComponentDataFromEntity<Movable>(false), 
        Entities = ... 
     }.Schedule(this, inputDeps);
  }
}
#

If you wanted to use an ECB

struct SomeJob : IJobForEach<T0, T1> {
   [NativeDisableParallelForRestriction] public ComponentDataFromEntity<Movable> Movables;
   [ReadOnly, DeallocateOnJobCompletion] public NativeArray<Entity> Entities;
   public EntityCommandBuffer.Concurrent CmdBuffer;

   public void Execute(ref T0 c0, ref T1 c1) {
     for (int i = 0; i < Entities.Length; i++) {
       var movable = Movables[Entities[i]];
       CmdBuffer.SetComponentData(some_job_index, Entities[i], new Movable {
          // Decrement the hitpoints 
          hitpoints = movable.hitpoints - 1
       });
       ...
     }
   }
}
gusty comet
#

Thanks very much

gusty comet
#

@coarse turtle
im getting this error error CS1612: Cannot modify the return value of 'ComponentDataFromEntity<Movable>.this[Entity]' because it is not a variable when trying to modify the value like that:

movables[movableEntities[i]].hitPoints -= 1;
coarse turtle
#

Can you post the full job code?

gusty comet
coarse turtle
#

I'll take a look in a bit I'm not at a desktop atm

#

Or computer

gusty comet
#

I did everything as in your first example

safe lintel
#

you need to do ```
var x = movables[movableEntities[i]]
x.hitPoints -= 1;
movables[movableEntities[i]] = x

coarse turtle
#

thnx @safe lintel ๐Ÿ‘

rugged wagon
#

Is there a Mathematics function for getting the unsigned difference between two angles, or do I need to make it myself? For instance, passing it 361f and 1f would return 2f.

#

I've made a few methods that already existed in Mathematics b/c I didn't recognize the new name (ex: was looking for inverse lerp instead of unlerp)

onyx mist
#

this is the one i have

safe lintel
#

also @gusty comet forgot there was another step but this should be it

            var t = m_Query.ToComponentDataArray<Translation>(Allocator.TempJob);            
            m_Query.CopyFromComponentDataArray(t);

from https://forum.unity.com/threads/how-to-set-nested-translation-to-world-position.756224/#post-5041658

gusty comet
#

what does that change

safe lintel
#

@onyx mist wasnt me who asked about the version but did you sort out your problem of the entities.with query ?

#

@gusty comet from earlier if you used the nativearray of a component query in a job, that lets you set the copy back into the query after the job

#

might have to use .Complete() with it, tbh I havent personally tried it since the old days of Inject so not really up to date as I could be

#

anyway if ComponentDataFromEntity works, probably easiest to stick with that

gusty comet
#

Yeah I think so too

#

But thanks to you both @safe lintel & @coarse turtle , Jobs and ECS are a struggle to me ;)

dusky wind
#

Is there a way to create custom physics colliders from code?

#

As well as locking rotation completely?

#

Trying to make a 2.5D collider that is diamond shaped based on a non-ECS GameObject hiearchy

#

Checkign the documenatation this seems to be exactly what a Plane colldier is

#

my only question is if that plane is limited in size or considered infinite in size

ashen gull
#

Hello Guys,

im working with dots right now and i didn't found any implementations for Navagents in pure ecs. The only things i found for navagents in ecs were this custom ones, will there maybe a Unity release in future for it? https://forum.unity.com/threads/100-000-entities-traversing-navmesh.534526/
https://forum.unity.com/threads/navmeshsurface-updatenavmesh-with-a-entity.766148/

The Problem is the custom NavAgent implementation have not all features from the standard navagent and dont use the new physics system.

dusky wind
#

There's a few things not natively supported in ECS: AI/Navigation is one of them.

#

SkinnedMeshes and animation as well.

ashen gull
#

Will they comme in future for ecs implementation? If yes im fine with the custom ones, they a little bit buggy but work for now. So i dont need to change the custom ones and fix the bugs there.

dusky wind
#

IIRC, AI/Navigation is planned for 2020 (search the forums for that one)

#

and I am waiting as well for the moment when skinned meshes are added

#

The Coppenhagen Unite Keynote supposedly was using one, but I don't see any sign of it being added anytime soon

#

And there is a hack to do batching of skinned meshes by baking the animation into a texture

#

but I need more animations than individual instances

#

so such a solution wouldn't work in my case

ashen gull
#

ah ok didnt saw the forum thread for that. maybe you can post me the link for it? ๐Ÿ™‚
Yeah the animation part will be the next thing i like to do but i can wait for that, first i need the simple things to implement in my game.

dusky wind
ashen gull
#

@dusky wind thank you,i didnt know why i not saw that uff

pliant pike
#

I dont suppose anyone knows if you can view a blobdata in the debugger or wherever?

gusty comet
#

Any news on the Hybrid Renderer being updated? I keep hearing any day now for the past 3 weeks lol

coarse turtle
#

@pliant pike not ATM I imagine you can follow the blob ptr and grab the serialized types to view the data and put it into an editor window

pliant pike
#

figured thanks, its difficult to figure whether I'm doing things right without being able to view them

rare umbra
#

Donโ€™t suppose thereโ€™s been a new Entities package recently?

solemn ice
#

Is there some kind of equivalent to ComponentDataFromEntity, but with DynamicBuffers?

haughty sand
safe lintel
#

@solemn ice BufferFromEntity

weak oak
#

Hi everyone! I got a question: With dots. How many game objects can be loaded in the scene at the same time?

#

As in if i were to make a voxel terraingenerator that loads blocks. How many blocks should go in the scene simultaniously and if blocks exist under the top layer, would those be loaded? Kind of minecraft style terrain

slow epoch
#

Minecraft only renders cubes which are touching the "air"

#

And well if the amount of blocks would depend on a lot of factors to be precise

#

How you render them, if you are gonna do procedural generation, the textures, etc

#

And also would depend on how you use dots for it (Jobs, ECS, etc)

gusty comet
#

anyone know anything about nav system being updated for ecs?

slow epoch
#

You have a link to the forum up in the chat that discuss that

#

Response was, they will start with it on 2020

gusty comet
#

oh, didn't see that one, thanks!

solemn ice
#

@safe lintel How the hell did I miss this? Thanks!

heady edge
#

Hi all, trying to figure out how to best approach networking with dots tech, I see there is code that calculates diffs and can even create and apply patches, but all of it is internal. Is there API to access it from the game code?

pliant pike
#

I really hate trying to figure out how things work just from pure code examples, unless you copy them exactly I can never get them to work, or I can never get the exact information I want for my unique case and even when I do copy them they don't work exactly, and copying isn't learning I don't know what I'm doing and why

#

what I'm trying to say is I hate blobs and after 2 weeks of trying I give up trying to use them, I hope we get some proper docs and tutorials some time

heady edge
#

I'm not really interested in NetCode sample itself, I need functions that allow me to do my own stuff

pliant pike
#

somehow they add a monobehaviour without an iconvert script and its still converted and I try and do the same it does not work, I'm not even sure where I'd begin to figure it out

#

so this code would automatically be added to the entity

#
public class NodeAuthoring : MonoBehaviour
{
    public NodeAuthoring[] links;

    void OnDrawGizmos()
    {
        var position = transform.position;

        foreach (var link in links)
            Gizmos.DrawLine(position, link.transform.position);

        Gizmos.DrawWireCube(position, Vector3.one);
    }
}```
#

yeah when I search for it I cannot find it

#

but somehow in their example that code with the links is automatically or I cant see how converted into the entity

slow epoch
#

I think what @pliant pike means is that in the code example they can convert that MonoBehaviour without using IConverGameObjectToEntity and probably they are doing it from another place

#

But he can't find it

#

Yeah but the code he pasted is from the example

languid stirrup
#

i dont like why there are so many functions converting objects to entity... which one to choose

slow epoch
#

It's from unity

pliant pike
#

thanks everyone, sorry for my rant earlier, this stuff is hard to get my head around sometimes

#

just as another example from that project I linked which I dont understand

#

how they are able to pass more than one variable or component in a single argument with this NodeAuthoring[] authoringNodes

deft niche
#

NativeArray<NativeArray> or NativeHashmap<NativeArray> can't be used because NativeArray is not blittable

#

Is there any workaround for something like it ?

#

Actually wanted to use NativeList<NativeArray>

pliant pike
#

are you trying to use them in a component

deft niche
#

in a job

safe lintel
#

you cant have a nested nativearray

deft niche
#

For example.. if i don't know what the size of that NativeArray is going to be in the list..

#

aargh...

safe lintel
#

you need to flatten the array unfortunately

deft niche
#

yeah.. i did that for other things... i guess i will have to figure out a way for this situation as well.

safe lintel
dusky wind
#

@deft niche if the size is fixed beforehand,idx = w * x + y?

#

Ultimately that's what an 2D native array would end up being

#

And if you don't need ordering NativeMultihashmap

onyx mist
#

im still having trouble getting entityqueries working :(

#

they dont show up anywhere

#

spent a good amount of time this week researching and no one else seems to have this issue so i have no idea what im doing wrong

#

or has it been replaced with componentgroup?

coarse turtle
#

ComponentGroup is renamed to EntityQuery

#

Not sure what version of Entities you're on, but 2019.2/2019.3 should have preview-0.1.1 as the latest version

onyx mist
#

oh god im on version 0.0.1.2

#

lord almighty

#

oh

#

i started up the unity 2018 shortcut instead of the 2019 one...

#

to the recycle bin with you

#

thanks for the help!

coarse turtle
#

Np ๐Ÿ‘

stuck hatch
#

Hello, is it possible to rename Entities? (Entity 0 -> Entity Player) I want to distinguish them on the Entity Debugger. Just to make reading easier

golden heron
#

@stuck hatch i think so, not sure how tho.

#

Does anyone know if dots unity physics works by preserving the momentum data, or by preserving velocity data?

#

If you use velocity, an objects rotations are unrealistically stable. I wanted the natural instabilities caused by momentum of irregular objects, so was hoping it might use momentum instead.

golden heron
#

Not yet, call this an exploratory question ;)

#

However i am currently opening the samples - ive actually built my own physics engine in monobehaviours before to be able to fully follow the process. So, if you know yes or no, thats helpful, but i dont need code suggestions :)

#

Specifically, i want to know if an object rotating with a specific rotational speed will continue to spin in a stable way, or if it will infact begin to oscillate in certain ways that real physics defines, with relation to an unbalanced inertia tensor.

#

@digital scarab

#

Fair enough, one of the big excitements with this physics is that the c# code should be visible, and i can look for stuff like that :)

jade siren
#

Hi everyone, i'm trying to get into my ecs to render some meshes. Which is the best way to load them?
Right now i'm using the Hybrid Renderer's RenderMesh. But i'm not sure about the best way to load the meshes into the SCD.
Does anyone knows of any good tutorial or sample that is up to date ?

#

My other systems works nice, but i'm not rendering anything ๐Ÿ˜›

#

I have other question related to Physics and Collisions in ECS. But the mesh thing is more important

hollow scroll
#

@jade siren Hi, I'm using the Hybrid Renderer, it does the converstion automatically for every MeshRenderer that has a ConvertToEntity (you need to set the object to Convert and Destroy or you are going to end up with the mesh being render twice)

jade siren
#

I was setting everything up from code. So I assume this means I have to create the Game objects in the scene and add the components as previously?

hollow scroll
#

@jade siren yes, you can do that... at least for me it's easier for 3D things to see what I'm working with... and if you are spawning that in a system or something you can use the conversion system to get the Entity representation of the prefab, and spawn entities directly

jade siren
#

Nice thanks

#

I think I saw it, but I'll re visit it

hollow scroll
#

I'm sharing that video for the convert prefabs to entity part, and instantiate that (faster than instantiate prefabs and have the conversion process being executed for each instance)

#

There is happening in a Monobehaviour, but the same works in a System too

jade siren
#

There is no way to have pure ecs to render meshes right?

#

Because I think this will mess how I set the entities and stuff.

#

But again, I'll re-watch the video

hollow scroll
#

Yes, I use pure ecs with the mesh renderer

#

The Advanced example

jade siren
#

I was using the examples of the HelloCube

#

i don't know how i missed the Advanced ๐Ÿ˜›

#

@hollow scroll it seems that the advanced is using the Convert to entity approach. But its a great place to start.
Thanks!

#

Is really hard to find updated docs and code examples

dawn forum
#

Is there a way to copy componentData into a pre-allocated array on the main thread, rather than letting ToComponentDataArray() allocate internally? I see there is a CopyFromComponentDataArray, but I want CopyComponentDataToArray() where I'm passing in an already allocated array I want to fill

haughty sand
#

CopyTo / CopyFrom ?

pliant pike
#

there's .asArray and .toArray as well I don't know if they would work

dawn forum
#

Is CopyTo() an EntityQuery function?

#

oh, on the NativeArray.

#

basically, I want to turn this:

NativeArray<Normal> normalData = heightmapQuery.ToComponentDataArray<Normal>(Allocator.TempJob, out normalDeps);

into

#

preallocatedNativeArray = heightmapQuery.CopyToNativeArray<Normal>();

haughty sand
#

you can create a NativeArray with Allocator.Persistent in OnCreate function, dispose it in OnDestroy

dawn forum
#

right - so then use an IJobForEach instead of an entity query to fill the array?

safe lintel
#

just use allocator persistent instead of tempjob

dusky wind
#

Anyone know when the DOTS Animation package may be available?

#

They said 2019.3

#

In their roadmap

#

But I haven't seen anything suggesting a preview will be available

coarse turtle
#

No clue, they might release more information next week

covert spire
#

So I'm trying to create a Burst-compatible noise library. I have a constant array of integers that I use in calculating noise. How do I declare it such that it will work with burst? I can't use a normal array because it is managed. Is there a way to say something to the effect of "NativeArray<int> hash = {1,2,3...};" ?

dusky wind
#

@covert spire declare it static readonly

#

Burst will compile it into a lookup table

#

Just be aware that changing it's contents will not be recognized by any Burst compiled job and attempting to mutate it will hard crash the process

covert spire
#

Am I supposed to access it differently than hash[index]? I'm getting "accessing a managed array is not supported by burst". The array is static readonly

tawdry tree
#

What's your initialization like?

public readonly static Hash = new NativeArray<int>{
  1,
  2,
  4,
  8
  //ETC. Standard collection initializer
};
dusky wind
#

@covert spire are you directly accessing the array via the static variable?

#

You can't pass it in as a instance variable of the job

#

Burst needs to provably tell it's statically initialized

#

And it should work as a normal manage array declaration

frosty siren
#

In my project NPC must be able to see another NPC'c. But different NPC'c belongs to different physics categories (layers). Some time NPC may need to see 0 layer for one algorithm, sometime 1 layer for another, sometime both.

I see 2 possible approaches:

  1. I make just one physics query inside some "VisionSystem" and setting the collision filter from outside of that system depending on what NPC need to see. After that i have raw Entity collection that i need to sort (cause as i say entities will be used for different algorithms) by ComponentDataFromEntity.Exists()
  2. I make physics query in every algorithm that need too "see" entities and have no centralized "VisionSystem"

The question is: what approach are more performant?
Maybe i should ask it on a forum. Maybe i miss something important that can help in this case.

covert spire
#

@dusky wind calling a static function Noise.Simplex(...params...), which is accessing the static readonly array

#

@tawdry tree that initialization doesn't work with nativearray

coarse turtle
#

You can try passing the static readonly native array into the job via assignments

covert spire
#

well that doesn't really make sense does it? say with the Unity.Mathematics library, its just a static class that you can call its functions like math.sqrt(x). I'm trying to do something similar where I can do Noise.getNoise(x,y), and the noise function accesses the hash

#

Is there some explicit way I can make it a lookup table instead of an array?

#

and the hash array in question is "static readonly" and will never change

coarse turtle
#

the only way I can think of making an array a look up table is allowing your (x, y) inputs hash to an index of an array (assuming its a 1D array) ๐Ÿค”

#

afaik i dont think there's a way to treat it specifically as a look up table like a NativeHashMap of sorts

pliant pike
#

the conversion process is really confusing, code changes dont seem to update when you do certain things with subscenes, I thought my code was working when it wasn't actually because of it

pliant pike
#

basically from the two code examples if I dont rebuild the entity cache when changing from the top code to the bottom code, it appears to work and the blob is still created

#

but if I rebuild the entity cached then it stops working and the blob is not created

#

so basically GameObjectConversionSystem is run basically when you press the rebuild entity cache, its run before the program runs at all?

#

I see, and I guess it requires a primaryentity in some manner also

#

that's probably the other part, don't worry about it, you've helped me understand how the subscenes are converted, thanks ๐Ÿ˜ƒ

onyx mist
#

how do i have a native array of ints in my icomponentdata struct?

#

i keep getting these errors

#

the error doesnt happen if i comment the array out so its definitely the cause

onyx mist
#

ok thank you!

hollow jolt
#

Is there an up to date tutorial ( besides the documentation ) where to learn dots/ecs from ? I had found few articles / tutorials / videos, but they seem to be outdated. Cheers

stuck hatch
#

Hello, could it be that ECS Physics don't know Rigidbody constraints yet? Like Freeze Position?

hollow jolt
#

@digital scarab thnx

stuck hatch
#

Warning: Using EntityManager.SetName will cause build errors, because the SetName method is in Unity_Editor Preprocessor directives

pliant pike
#

so that's why I was getting weird errors with setname

rare umbra
#

Donโ€™t suppose the new entities package is supposed to drop any time soon? ๐Ÿ˜ฃ

tawdry tree
#

Google, make a reminder: Yell at Topher in one week
๐Ÿ˜›

#

But that's nice to hear.
I'd like a bit more transparency, even just a known channel we could use to check for status on upcoming updates to packages. And since, presumably, anyone using Unity and interested enough to get hyped for the Freshestโ„ข updates, have experience with software development, disclaimers and qualifiers of 'probably' and 'maybe' will be understood. (as opposed to: any game which has to push back an update)

rare umbra
#

@digital scarab no pressure just excited for the new stuff

tawdry tree
#

Actually, is there a roadmap with (loose) estimates for new features and such for the packages? I know there's one for Unity itself, but now that updates are spread out among packages...

#

Consider that feedback, then ๐Ÿ™‚

#

Should I write down/post the suggestion somewhere? Where?

#

I'm pretty sure I've seen an issue tracker for unity somewhere

pliant pike
#

yeah it would be great to get more info about how some of this entity stuff works

tawdry tree
#

So would it be worthwhile to post the suggestion somewhere? Or is it 'on the radar' enough that it wouldn't make a difference?

#

The primary question I'd have about Entities would be how far we are from the ECS editor experience, as shown on Unite.
Specifically the live reload thing to multiple devices and entity preview.
Oh, and less boilerplate, though since I've been busy with life stuff I haven't checked if that's in the latest version.

#

And while not specifically to the staff: Does anyone know of a project where people have used ECS and VR?

pliant pike
#

there was a project in the forums I saw

rare umbra
#

Looks like it will help lots from what I can see

pliant pike
#

yeah sounds great

tawdry tree
#

Ah yes, LiveLink was the name.
So that in the next release (the one coming Soonโ„ข, right?),
preview in that one or the next(?),
and less boilerplate we basically get as it's finished and tested enough to unleash on the world?

rare umbra
#

I guess the less boilerplate stuff is incremental?

vagrant surge
#

it comes on the next updte

#

the issue is that the "next update" was coming "next week"

#

at unite

#

so its several weeks delayed already

tawdry tree
#

I'm fine with that, but again, more transparency with roadmaps, and in this case, that there is/will be delays and new estimates, would be nice.

rare umbra
#

Keep up the good work ๐Ÿ‘

tawdry tree
#

Or put more succinctly, it's nice to know if something has been delayed.

#

With previews a status of "probably soon" "probably not in a while" and the like is enough to set expectations

#

While they aren't even 'properly' released I wouldn't expect actual dates until they were ready to release, and as I understand it you just release them when they're ready, so...

pliant pike
#

I expect with programming its hard to come up with and stick to fixed dates though

tawdry tree
#

It always is

#

Not just programming, really, any slightly complex project has unknowns

pliant pike
#

like I've just found out I have to redo and start over on my project basically

tawdry tree
#

In that light, to those who understand it (ie. other people in the same field), a status that is not when it will be done, but rather "how done is it right now?" can be more useful

#

Oh well, there's not really any 'right' answer to these things, except that radio silence is the worst option

pliant pike
#

yeah I think with programming its particularly difficult though, your working in an unknown space solving never before solved problems, and it could be the road your going down to solve it isn't the road that's going to solve it in the way you want, but you don't know that until your over half way down that road

#

I don't know sometimes I think its best not to announce anything your not absolutely sure you can deliver

tawdry tree
#

That's with actual dates, yeah, but "we're working on X, expect more news around Y time" is pretty safe

#

At least if you know it will be done, at some point, and it's within a field such as software dev, where you can expect the 'customers' to understand that things take time

#

If it's to the average consumer... wait until you not only know it will be done, but have done all the foundational work and started on the more specific details. And that's just a reveal/teaser/hype thing. Though, for consumers you never want to hype for longer than a few months, unless you can have sustainable and continuous reveals. AMrketing is hard, but no reason to make it harder on yourself.

stiff skiff
#

Will the warning about using [DisableAutoCreation] on abstract ComponentSystems finally be fixed in the next version? Its been around for a while

onyx mist
#

how do i go about destroying an entity after a random x seconds within a job?

#

if i do a time.time check it would pause the thread ๐Ÿค”

pliant pike
#

I wouldn't do it in a job to be honest

onyx mist
#

whys that? just too complex?

pliant pike
#

no command buffer sync points

#

if its 1 every x seconds theres no need for a job

onyx mist
#

the reason its in a job is because theres millions of entities

#

basically i want to simulate medieval child mortality

#

if they're marked for death(25% chance) they should die sometime within the year (360 seconds)

pliant pike
#

ok then it probably is best in a job

safe lintel
#

pass whatever you are using to measure the time into your job at the creation of the job

#

oh do you want a random time?

pliant pike
#

yeah something like this maybetickTimer += Time.deltaTime; if (tickTimer >= TICK_TIMER_MAX) { tickTimer -= TICK_TIMER_MAX; tick++;

#

you'd have to pass it in every update

onyx mist
#

Alright thanks ya'll!

tawdry tree
#

Wouldn't something like this be more lightweight, and still very ECS?

struct DestroyAtComponent {
  float TimeToDestroy;
}

//when making the thing:
component.TimeToDestroy = time.Time + timeRng;

//And some system to actually destroy
if (component.TimeToDestroy <= time.Time) Destroy();
vagrant surge
#

ive used those kind of components with simulations of 400k+ entities, and its fine

#

good ol "lifetime component" or other name

#

that just destroys when the time arrives

glad solar
#

I'm trying to hold a collection of data inside of my ComponentData for grid porpuses, but i'm receiving this message where which is neither primitive nor blittable.
I try using array, NativeArray or even NativeList (which i allocated as "Persistent").

Here the struct i'm trying to create as a collection:

public struct NodeData {
   public MapNodeType Type; // this is an enum
   public int X;
   public int Y;
}

And this is where i'm trying to use it:

public struct Map : IComponentData {
   public int Size;
   private NodeData[] Nodes;
   //private NativeArray<NodeData> Nodes;
   //private NativeList<NodeData> Nodes;
}

I'm probably doing something stupid. Please, what am i missing?

glad solar
#

I'm trying to get rid of creating multiple entities as one store it's own data. ๐Ÿค”
But i stumble in this problem. ๐Ÿ˜ž

How one entity can hold a list of data so the systems can work with it, instead of creating one entity for each position?

prisma anchor
#

I am trying to do a non uniform scale. I saw that there is component data called NonUniformScale but How do you add it to an object. When I look at the entity debugger, its not there.

pliant pike
#

@glad solar yeah nativearrays dont work in Icomponentdatas

glad solar
#

Calabi, is there a workaround for this?
I mean, it is easier to work with data instead of a bunch entities per position.

pliant pike
#

@prisma anchor you just add Nonuniformscale to an entity the same way you would any component

#

you use buffers

#

I'm not sure theres much problem with using a single entity for each position

glad solar
#

I'm trying to use cellular automata to create my grid, but its a pain to look for each entity when i'm in smoothing step.

pliant pike
#

I would have thought it would be easier, entity's have plenty of ways to iterate through them

coarse turtle
#

@prisma anchor you have to add it manually

glad solar
#

If i could query IComponentData would be nice and it would solve my issue with this as i just query the entity with X and Y position.

coarse turtle
#

if the scale is like 1, 0, 1 - I believe it gets added automatically as its not uniform

glad solar
#

i'll search how i'm gonna use buffers now.

#

ty

prisma anchor
#

@coarse turtle I am:

    public class GameBoardAuthoringComponent : MonoBehaviour, IConvertGameObjectToEntity
    {
        public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
        {
            dstManager.AddComponentData(entity, new GameBoardComponentData());
            dstManager.AddComponentData(entity, new NonUniformScale());
        }
    }```
coarse turtle
#

the TransformConversion adds it if the transform localScale != Vector3.one

prisma anchor
#

ah ok

coarse turtle
#

also if there is a parent to the gameObject

#

sorry ignore that last statement

vagrant surge
#

@glad solar there is a library around for containers that you can use inside components

#

unsafe arrays and the like

#

made by @trail burrow

#

stuff like a celular automata is precisely where you absolutely shouldnt be using entities. You might "attach" entities at some special cells, but in general cellular automata is much better kept in arrays

#

btw, using entities for a "block" of cells is actually a very good idea

#

like say, 64x64 cells

glad solar
#

@vagrant surge thats why i'm trying to hold the data in array and use entities in the special cells (as you said) that the player will interact with.
I'm playing with DinamicBuffer to see if i can hold all the cell data instead of entities.

vagrant surge
#

dynamic buffer is not really it i believe

#

what you definitely want is something like the unsafe collections thing

#

unity really needs to add singleton components that ARENT icomponentdata as soon as possible

glad solar
#

Completely agree.
It would do wonders for many cases.

vagrant surge
#

Blizzard in their ECS talk comment on the importance of singleton components

#

to hold "system" data

#

like octrees and the like in a collision system

glad solar
#

you meantion unsafe collections above.
I'm looking at Unity.Collections.LowLevel.Unsafe (API), specific: UnsafeList, but i can't use it in my code.

I'm using the package "Collections v0.1.1". Am i doing something wrong?

rare umbra
#

@vagrant surge do you have a link to this talk? Sounds interesting

vagrant surge
#

the first half they explain the ECS pattern

#

keep in mind one importnat thing. Their ECS is not a performance oriented ECS at all

#

they have fat components and barely add/remove things. small components with smart matching is what unity ecs does

#

but the general architecture of how to make the systems and stuff is nice

#

i know a team who did pretty much the same type of ecs architecture for a multiplayer mobile game, and they did the entire thing in parallel, ended up with the same conclusions

trail burrow
#

@vagrant surge tbh I prefer the overwatch type of ecs

#

Yeah you give up some performance, absolutely

vagrant surge
#

thats Entitas

trail burrow
#

Well, sure... but no thanks :p haha

vagrant surge
#

also Entt on C++ land

#

its not like th eoverwatch ECS type is slow

#

its still significantly faster than OOP architectures

#

its just not extreme like unity is

trail burrow
#

Yeah

vagrant surge
#

i think unity should definitely allow for storing managed references in components

trail burrow
#

Just feels like a bit too much was sacrificed on the altar of performance sometimes

vagrant surge
#

so you could do something like a component that points into a "normal" C# class

#

in Entt (c++) you can make a component that holds a unique_ptr of something, and it will work great

#

but i see the main focus, of focusing on making sure the core is crazy fast

#

and focus on making it approchable later

glad solar
#

When i think i solved my problem with DynamicBuffers... My entity is losing its buffer data after i update any value in any other ComponentData that this entity holds. ๐Ÿ˜ก

stable fog
#

There is a job for Physics.Raycast, the RaycastCommand

#

is tehre anything like that for OverlapCapsule?

rare umbra
#

Hey all, architecture question. I'm implementing an Item Component with a basic name, some stats etc. I'd like to differentiate between items that are instanced (e.g. random drops) vs. the generic form of the item (that might be advertised in a merchant's store in game). I'm thinking about adding a couple of other components "Instanced" with a GUID field and "Equippable" with details about what kind of character can equip the item. Does that sound logical? Is it better to merge them all into one or keep them seperate?

glad solar
#

@rare umbra you could add a empty component as "tag" when an item is dropped. Example:

public struct ItemDropped: IComponentData {}

When the player pick it up, you remove the component. This way you can filter by including or excluding when doing ForEach.

Entities.WithNone<ItemDropped>().ForEach();
// or
Entities.WithAll<ItemDropped>().ForEach();

This helps?

rare umbra
#

yeah, I was thinking more about it being in inventory but allowed or not allowed to be equipped, but same logic applies and the tag concept works for that

#

but then again, having a field on the item "requiredClass" can help figure out what's equippable

#

currently that's the only rule so I'll do it this way I think

glad solar
#

At moment i can't think on anything else, since i use this concept quite often to diferentiate entities in a context.

#

Glad it help. o/

rare umbra
#

can I use Debug.Log from a job? doesn't seem to like it very much

coarse turtle
#

You can - I've certainly been able to do so - you wont be able to debug.log a bursted job

#

you'd just have to disable Burst compilation in the editor

onyx mist
#

how do i refresh the entity debugger? it keeps saying that the number of entities is the starting amount, even though thousands have perished

rare umbra
#

Thanks @digital scarab great news!

One more question for the channel:

How do I use a system to interact with 2 entities with different components. Say one entity contains WalletComponent with different currencies and values and another entity contains a purchaseableItemComponent and a PlayerPurchaseRequestedComponent

I can use a system that checks for PurchaseableItemComponent and PlayerPurchaseRequestedComponent in order to figure out that cost x needs to be deducted from the player and once that's successful they need to be awarded with the purchaseable item. However, how do I access the wallet data to deduct the currency?

glad solar
#
WalletComponent wallet;
Entities.ForEach((ref WalletComponent walletComponent) => {
   wallet = walletComponent;
})

Entities.ForEach((ref purchaseableItemComponent purchaseableItem, ref PlayerPurchaseRequestedComponent playerPurchaseRequest) => {
   // your code here. You have access to wallet data readonly here, but you can do another foreach after or inside here to update the wallet
});

Hope this helps and if my vision is wrong please someone correct me!

rare umbra
#

oh hrm, didn't think about using multiple foreach

glad solar
#

you can. But i don't know if it is the best practice

coarse turtle
#

I think another way to do it is if you had a form of a messaging system - where you can produce an entity for the entity with the wallet to "consume"

glad solar
#

hmm

#

psuong can you elaborate on that? you got my attention!

coarse turtle
#

so the idea is - an event occurs and you need 2 entities to interact with each other -

so let's say you buy something - ideally we want the wallet's

#

value to decrease, so an entity is produced with

- Cost
- Entity reference to purchasable item
- some sort of ID to the wallet entity or an Entity reference to the wallet

you can potentially have a consumption system which enacts on these entities and decreases your wallets value and store them into a DynamicBuffer<T> so you can keep it in some inventory of sorts

#

I've done something like this for an entity doing damage to another entity, where detecting a hit would produce a "DamageRequest" and would store

  • the ID of the player
  • The amt of dmg to do
  • Point of contact on the player
#

but it allowed 2 entities to interact with each other and for me to have systems in between to tweak the "DamageRequest" for any kind of gameplay effect I wanted to do

glad solar
#

hmm... and a separated system responsible to act upon that action.

#

i like it! thank you so much for sharing your knowledge.

rare umbra
#

yeah this is the pattern I was considering but it's a bit more work and testing (I'm only at the prototype stages), but you've convinced me to give it a shot

glad solar
#

it's much better. more ahead in development the work for balances issues won't be much if doing like this. impov

rare umbra
#

@coarse turtle the only real question is how do I fetch the wallet entity's ID so I can attach it to the request. I guess I need to cache it somewhere. Not sure where would be best

onyx mist
#

what are some ways i can optimize this? with 13mil entities this takes 14ms

vagrant surge
#

dont you think 13.000.000 is going a bit too far?

#

ecs aint magic, thats still extreme

onyx mist
#

well yeah, rn im just testing the limits

#

the commandbuffer is whats holding me back so i was curious if there was something about it i was missing

vagrant surge
#

adding and removing components is kinda expensive to do when you have millions

#

you might want to just have a component with an enum to filter adult vs elder

#

tho it depends on your algos