#archived-dots
1 messages Β· Page 241 of 1
Proper design patterns mean you code only once.
Anyway, it's rambly as all get out, but I'm sure one or two of you will have a light bulb go off and use your old GameObject game and slap some DOTS/ECS levels... Even more so when in a few weeks, I'll do an actual professional video and not just slapdash production.
Better video link: 18 minute https://www.youtube.com/watch?v=GIEV14B20Pc#t=18m
If you understand this video, you do not need to make new games from scratch. You can simply use your gameobject games and entityfy new levels with em. I apologize for this video being extremely rambling on, but I was also doing some dev and I plan on getting you a great video soon, but to some, this will be a God send Holy Grail of Dots ECS ...
Be sure to click link and not video picture. If you click picture, go to 18 minutes.
The only containers that get auto disposed are Allocator.Temp. Every other one you must dispose yourself.
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;
public class ChunkBoundaryRenderingSystem : SystemBase {
protected override void OnUpdate() {
var mapChunkBoundaryArchetype = EntityManager.CreateArchetype(
typeof(LocalToWorld),
typeof(Rotation),
typeof(Translation),
typeof(SpriteRenderer)
);
Entities
.WithStructuralChanges()
.ForEach((in MapChunk mapChunk) => {
Entity chunkBoundaryEntity = EntityManager.CreateEntity(mapChunkBoundaryArchetype);
var m_SpriteRenderer = EntityManager.GetComponentObject<SpriteRenderer>(chunkBoundaryEntity);
var sprite = Resources.Load<Sprite>("Sprites/Square.png");
//m_SpriteRenderer.color = Color.blue;
//m_SpriteRenderer.sprite = sprite;
var translation = EntityManager.GetComponentData<Translation>(chunkBoundaryEntity);
translation.Value = new float3(mapChunk.coordinate.originCoord.x, mapChunk.coordinate.originCoord.y, 0);
EntityManager.SetComponentData<Translation>(chunkBoundaryEntity, translation);
}).Run();
}
}
anyone got any ideas to make a spriterenderer?
the commented lines crash as not set to an instsance
When i wake up Im gonna try and create standard GOs instead somehow so I can use normal sprite stuff with them π
hey!
I'm trying to get into ECS
but the package manager isnt adding the hybrid renderer through the git URL
it doesnt appear in the package manager (yes I enabled preview packages and it still doesnt work)
so I wanted to add it with the git URL
but its not adding it
com.unity.rendering.hybrid
this the git URL and its not woking
plz help
this is fascinating. Can you condense to the written? This seems like info well worthy of being reference material
Did you try installing through the manifest.json file ?
Hey! It worked, I just needed to enable hybrid renderer V2
Thx anyway :)
how do you destroy an entity so that all its children die too
okay I have a weird problem
it seems when I assign my float3 variable into the job's float3 variable, it resets.
And I don't know why.
(unrelated to the issue above)
I found something annoying with float3 vs Vector3 when normalizing a 0 vector :
//float3 test = math.normalize(float3.zero);
Vector3 test = Vector3.zero.normalized;
float3 modifiedOldSteering = test* wanderData.radius_big;
works, but the commented float3 test crash with AABB related errors. The resulting vector is used to modify the Translation component of a rendered object. Not sure if bug, inconsistency or just me mistakenly expecting same behavior from both, so I just write it here
you want normalizesafe because 1/0 is NaN
oh didn't knew about that one, thanks a lot ! (I can now remove my ugly if/else :D)
doesn't look like you're using burst, kind of hard to know why it causes the float3 to reset.
maybe the ReadOnly messes w/ the jit instructions on top of the float3? Not sure if the compiler ignores it on those fields during compilation
is there a reason why in example code systems tend to allocate native arrays as temp every frame rather than just keeping and reusing a persistent one?
@digital kestrel add the children to a linkedentitygroup that sits on the entity you want to destroy
temp allows unity to handle disposing of the native array rather than you having to manually remember to do so.
I'm using urp and when I drag the textures to a model it creates materials without textures is there a way so it auto sets the textures for the materials?
float3 test = math.normalize(float3.zero);
Vector3 test = Vector3.zero.normalized;
What would you expect test to contain after either of those statements?
Normalize takes a vector and normalizes it to a length of 1.
A zero vector can't be normalized. It would cause a division by zero error.
The only reason Vector3.zero.normalized works is because of a safety check.
https://docs.unity3d.com/ScriptReference/Vector3-normalized.html
If the vector is too small to be normalized a zero vector will be returned.
So the net result of that block of code is modifiedOldSteering is a constant Vector3.zero
yep itsjustblank answered to it (see above). math.normalizesafe(float3) does what Vector3.normalized does, and what I wrongly expected math.normalize(float3) to do
I believe math.normalize doesn't raise an error to skip checks (performance?) so it just returns NaN which ends up being raised later on (probably somewhere in the renderer when it tries to display the mesh at position NaN ?)
thanks
if i create a gameobject in a system, cvan i store a reference to it in a buffer or something?
I guess I could name the gameobject using the entityid, then just do gameobject.find() (its only for a few objects at a time)
usually you just attached the gameobject to the entity or use a managed componentdata and add a reference in that
how to attach go to entity? Is it a simple line of code here?
.ForEach((Entity entity, in MapChunk mapChunk) => {
GameObject gameObject = new GameObject("go1", typeof(SpriteRenderer));
}).Run();
EntityManager.AddComponentObject(entity, yourmanagedcomponent)
then you can literally just
Entities.ForEach((Entity entity, GameObject go) => {}).WithoutBurst().Run();
if you ever need to access it
ok nice one thanks, so gameObject is my managed component here, awesome, ill read that doc as well though they tend to not help me too much compared to much experimenting π
the alternative is to use managedcomponent datas
which is what a unity dev recommends
public class GameObjectContainer : IComponentData
{
public GameObject GameObject1;
public GameObject GameObject2;
}
note it's a class
I see I have that class written already but as a struct, no wonder it failed π
you add it the same way, EntityManager.AddComponentData(entity, new GameObjectContainer {GameObject1 = new GameObject()});
same restrictions as above, you can't access it in burst, needs to be used on main thread etc
so should be avoided where possible but as it stands existing managed components are required
yeah hoping to have like all my gamelogic in entitys (many thousands), then like 4x 16x16 tilemaps, and <1000 sprites as GOs as my game.
but mostly just messing around and learning
awesome thanks again π
You can also use hybrid components https://docs.unity3d.com/Packages/com.unity.entities@0.17/manual/hybrid_component.html
It lets you tie the lifetime of your monobehaviours/prefabs to the entity they're attached to
And does extra stuff like syncing transforms
public use of hybrid components are deprecated in 0.5
Oh, that's news to me. They were literally just added in the latest versions
Well the last release was a while ago but yeah
Edit: One exception that I remembered now is that hybrid components are now called companion components and their public usage is deprecated. Right now the plan is that it will be a purely internal feature in the future.
Ah okay. Well in the current version componion objects are a lot older than hybrid components and don't do the fancy stuff like destroying with teh entity they're tied to or syncing transforms for you
At least afaik
Transform isn't a hybrid component
you can cause it to sync by just using AddComponentObject(entity, Transform)
It doesn't require AddHybridComponent
Ahh okay
Anyway that's why i avoided mentioning HybridComponents because it's the one thing we know might be breaking in 0.5
Yea, and that Unity rep before they went on vacation did not like ComponentObjects either. Who knows what management thinks about them.
did mention that here ^
personally i prefer to just directly attach the component, it just seems cleaner to me. but yeah s_schoener doesn't seem to like it
i guess if you're attaching multiple components it does avoid a lot of extra objects in your archetype
What's a better way to handle something like this?
I have multiple players, each with a player number, and multiple buttons that each lower the health of a player with a specific number by creating a new entity with the DamagePlayerEvent component.
It seems like I'm going about this the wrong way since I have to loop over every damage event for each player to find the right one.
protected override void OnUpdate()
{
var endSimulationEntityCommandBufferSystem = World.GetExistingSystem<EndSimulationEntityCommandBufferSystem>();
var ecb = endSimulationEntityCommandBufferSystem.CreateCommandBuffer().AsParallelWriter();
var damageQuery = GetEntityQuery(ComponentType.ReadOnly<DamagePlayerEvent>());
var damage = damageQuery.ToComponentDataArrayAsync<DamagePlayerEvent>(Allocator.TempJob, out var jobHandle);
var entity = damageQuery.ToEntityArrayAsync(Allocator.TempJob, out var jobHandle1);
Dependency = JobHandle.CombineDependencies(Dependency, jobHandle, jobHandle1);
Dependency = Entities.WithAll<Player, Health>()
.WithDisposeOnCompletion(damage)
.WithDisposeOnCompletion(entity)
.ForEach((
int entityInQueryIndex, ref Health health, in Player player) =>
{
for (int i = 0; i < damage.Length; i++)
{
float amount = damage[i].Amount;
if (damage[i].PlayerNumber == player.Number)
{
health.Current -= amount;
ecb.DestroyEntity(entityInQueryIndex, entity[i]);
}
if (health.Current < 0)
health.Current = 0;
}
}).ScheduleParallel(Dependency);
endSimulationEntityCommandBufferSystem.AddJobHandleForProducer(Dependency);
}
Generally dont deallocate inside a job, use the .Dispose(JobHandle); immediately after instead.
Disposing of native containers inside a job is only supported by NativeArrays() of allocation tempjob and persistant, not any of the others
so [DeallocateOnJobCompletion] only works on arrays?
Yep, NativeArray<>()
aaaaah
why target a player id instead of an entity?
company i joined ~2 years ago was doing something similar because they ported their classical unity code to entities so stuck with the targeting their own ID that assigned to actors
was a complete nightmare for the reason you're seeing
we had to go through and refactor the whole thing to remove this and just use the entity for all interactions

idk why this didn't come to mind
cheers!
hello all, does anyone here know if the Hybrid Renderer v2 has anyway of manually dictating "sort these meshes in this order please"?
the HDRP seems to with normal GameObjects, but I am using the Hybrid Renderer v2 & HDRP together and the Hybrid Renderer seems to ignore the values
there's two ways to do it according to these docs, on a per material basis (no instancing as far as I know) and a value on the MeshRenderer
(this technique only works on transparent materials, including adjusting the MeshRenderer value, but my materials are transparent)
it seems to me once the Hybrid Renderer takes over, the Priority of all meshes becomes 0 regardless of what you tell it when they are still gameobjects (before they are converted)
thanks Tertle finally got my infinite terrain renderer working so can get working on proper generation started now i can see the results π
Fwiw I found no equivalent entity component data that uses the monobehaviour's MeshRenderer's Priority value for anything in the Hybrid Renderer
Seems sorting order is just one of the current weaknesses of the hybrid renderer as it exists right now
I'm looking for advice regarding using the DOTS stack & ECS architecture, coming from an OOP-mindset. I've looked at hours of DOTS videos, done some reading on entity component systems, and managed to make a simple moving object using DOTS. However, I'm having issues with materials being all black with the new ECS/hybdrid renderer, the job system being too much for me to handle at the moment, and DOTS apparently not being production ready yet.
I'm looking to make a small game that wouldn't benefit from all the performance gains from ECS but I was still attracted to the idea of composition and learning ECS. Is there any point is just using normal Unity scripting and building my own pseudo-ECS architecture? I.e., entity = GameObject, data-only components, and (singleton?) classes I just call "systems" that have all the logic? I've written some code with this architecture in mind and I'm now starting to approach an issue with copypasting a lot of my systems code to other systems and lacking nice syntactic sugar (even though I'm trying with generics).
Should I:
- Bite the bullet, dig in, and use DOTS instead + the usual Unity stuff for audio etc.
- Continue working in my pseudo-ECS architecture and deal with the lack of syntactic sugar.
- Drop the ECS-mindset and develop using the normal Unity paradigms?
I don't want to use the GameObject conversion workflow for ECS either. I'd rather learn to do it the right way or just not use it.
We do have plans and an implementation for unmanaged shared components that work within Burst, but I am not sure whether this has made it into 0.50.Β
Wooooo.
@indigo vigil Conversion is the right way, you are just swimming against the current if you are learning entities and want to ignore want unity encourage you to utilize.
I'd recommend not using entities or ecs based packages because quite frankly there's a lot to learn, a lot of things that aren't documented and you will only figure out through intense trial and error, basically zero support from unity themselves at this point and there aren't any updates for the time being. the bugs that exist, exist.
ecs will also force you to stay on 2020 lts given its incompatible with later editors if that makes a difference.
if the project is more of a learning one, you could disregard this, but if you actually want to ship something, I wouldnt. theres always burst & collections to use.
I would like to eventually ship it since I believe the project is already entirely within my ability to create. I'm just interested in ECS as a new thing to learn and learning it with a small project like this seemed like a good idea. Then again I've never shipped anything before and I do know you should just work with whatever you're familiar to actually get something done...
Thanks for the advice. To clarify, do you mean I should not utilize the ECS package, but look into using the Burst compiler and the job system along with whatever style I am comfortable programming in?
What exactly do you mean by collections?
its just a package for array type things which can be used with burst
anyway yes, use burst, jobs and collections(burst job compatible arrays, lists etc) but entities itself, well I love using it but its taken a long time to get comfortable with it and I am also quite familiar with current limitations, quirks and bugs
some bugs are coming up on 2 years just sitting around, still active apparently but no word on if theyre actually being fixed
I on the other hand am oblivious to any limitations and bugs apart from reading that input and audio should still be handled with standard Unity components.
I was afraid that would be the case. It would be nice to actually complete a project for once. Studying ECS as the new cool thing while building a product seemed like a good idea from the studying perspective even though it will naturally slow me down a lot, which is bad for actually completing the thing.
"Studying ECS as the new cool thing while building a product seemed like a good idea from the studying perspective" I am in this hole π₯²
@indigo vigil if 0.5 comes out soon you can reevaluate things, not sure how large the changes will be so maybe a lot of pain points will be fixed
I see RigidTransform inside of mathematics.
can I somehow use Rigidbodies (or something to that effect) inside of (normal/Non-ECS)Jobs?
i think its for use in physics, its just a position and rotation container
as in if you arent using physics, theres not really any other functionality that uses it from what ive seen
Looking to launch my MMORPG in dots imminently
Then I'll compile a video on how to use DOTS/ECS in any project, even existing mature GameObject projects with ease.
I have this weird feeling that if I don't show everyone how easy and powerful it is to do now
UNITY may remove the functionality that allows for it, lol.
You know how techs are, sometimes in upgrading they remove key features.
But if you get wide acceptance of em, then they don't get glossed over.
Even a self imposed race against time helps dev time. Just don't let crunch get you so you're distressed and lose a thought process so you code worse.
is there a way to remove element from an entity buffer with ecb ?I.E. similar to the way we can add data to a buffer with :
ecb.AppendToBuffer<CellSpaceBuffer>(cellEntity, toAdd);
Why would you ever need to do this?
AppendToBuffer exists so you can add virtual entities to a buffer before they're created
Why not just remove from the buffer directly instead of using ecb?
I'm creating entities that repesent space cells, inside of each there is a buffer that contains "persons" entities. So that when I move a person entity in a way that makes it change space cell, I remove it from the cell and add to another one (including creating and deleting non-existing/empty cells)
oooooooooh I get what you said
what would be best approach to monster spawner?
I mean i.e. monster spawner can have only 3 monsters spawned at the same time.
Should I maintain FixedList or DynamicBuffer on the spawner?
How to remove monster? Should I have entity link on the monster itself?
It's too much OOP thinking in my opinion, but what's the better alternative?
i personally would scan the area nearby for the 3 enemies rather than keep any lists to them, it means player can drag them out to spawn more at once if they wanted. (if thats fun or helpful in any way)
@remote crater what unity/entites version you use?
I would probably keep a dynamicbuffer on the spawned and check the lifetime of the monsters each tick
You could also have some kind of ISystemStateComponent link that "notifies" the spawn point when a monster despawns
Buuuut I would most likely go with checking the lifetime each tick to keep it simple
Main problem with this is that check uses entity manager so it's not burstable
why does it need entity manager?
also side note, most of EntityManager is burstable
public unsafe partial struct EntityManager : IEquatable<EntityManager>```
Anything not burst compatible has the [NotBurstCompatible] attribute
``` [NotBurstCompatible]
public void AddComponentObject(Entity entity, object componentData)```
as this was required for ISystemBase
If im doing multiple jobs via Entities.ForEach( (int entityIndexInQuery... is there a way to guarantee that each entity is given the same index in every job? (assuming that each query gets the same set of entities)
It's guaranteed by default if you query the same components
It's a very useful pattern π
Does anyone else running into this ?
https://forum.unity.com/threads/hybrid-renderer-not-supported.1217130/
hybrid renderer is currently not supported in 2022
oh
This means that many things, like Havok / Unity Physics, are not yet supported in this beta.
everything is not officially supported in 2022
2020 is the only officially supported version for anything ecs @pastel field
what aboput dots versions to install?
I got a question, can you mix DOTS with the normal object orientated programming that Unity uses?
For example maybe I want certain parts of a project to be extremely efficient but others not so much.
yes and no. you currently actually need to mix them if you want to make a real game but in what aspect exactly do you mean?
wdym?
ah i see the recommended is the latest anyways π
I thought i was using an older version
yeah you can dragon
mostly outside of parallell / burst but you can do it
I was thinking maybe I could use dots for loading in objects more efficiently, if I have an open world game with many type of assets in it. But for player controls and enemy AI I could use the normal object orientated code. Would that be a reasonable use?
if you switch it around exactly then that's reasonable
I'm still very new to DOTS, but am trying to figure out how to use what I know already with what I would like to learn, sorry if it seemed like a silly question, and thank you for the help. π
no problem. help is what this here is here for
hrmmm are there any samples of using regular Physics inside of (non-ECS) jobs?
I think the better question is, are there samples of using Physics2D.jobOptions?
@haughty rampart & @safe lintel Thanks for your answers π
Support to 2020, but things also working OK in 2021.
When it comes to the particle system
Is there anything special in ECS Unity done differently than gameobject Unity?
Or can I just convert to Entity my old particle effects?
I'm looking ahead to today's work
1 - it only makes sense to use VFX graph in this day and age
2 - since VFX graph is gpu based, ecs has no real effect on it
@remote crater
looks like it's just a bunch of control parameters that you pass into the jobOptions π€
I think internally, it will just use multiple cores to simulate. Might be worth seeing what happens if you manually invoke Physics2D.Simulate()
ty Mindstyler
One more question, super dumb one:
What is the best way to identify an entity in script so I can easily look it up in the Entity Debugger?
Can you UnityEngine.Debug.Log( Somehow print the entity's name) ?
entitymanager.GetName
looks like.
Lets see!
that only works in editor
yah, not a .foreach
So what's the most efficient/best way to know my entity giving data out?
I could set some flags
But I am not sure how to search those in entity debugger
Optimally, it would be a highlight console, ctrl+c, paste in debuggr
Oh I know
What I can do
is set flags inside icomponentdata
and then have the output be translated
via a method
then I can have it equal the name
by me forcing it, sweet
For those who don't understand my shorthand: In code, I set names of each entity Instantiated. But also set an index in it's Icomponentdata to reference the name for remembrance. Then when I print... It looks up the index references to the string name, and boom, I got it writing out on console. I can then copy from console, pasta it into Entity Debugger and know what i'm looking at.
whats best way to get a referenced thingy, this cant be done in burst etc
Entities
.ForEach(ref Biome biome) => {
BiomeType biomeType = EntityManager.GetComponentData<BiomeType>(biome.biomeEntity);
}
awesome thanks how i missed thast
after 5 days of coding I have a very crummy endless 2d generator I can expand on π
the biomegenerator (striping my world as shown) was really hard to code and is a bit slow but oh well
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
super bad poc but cant think how to do it better
seems unity's physics2D aren't bursted when I enable it for jobs
Hi I need help with physics I feel like I'm going insane
Everything disappears when I press play
seems to be rather a hybrid renderer problem than a physics problem. have you checked if your entities exist? @spark sleet
How do you mean?
if you dont have the hybrid renderer package installed, entities wont render
Is that compatible with URP?
yes
Cool, it's working π
I have a script that moves the ball with a rigidbody, using AddForce, what's the equivalent here?
All tutorials seem to use a rigidbody, not the actual physics components..
Can i put Components on Entities the same way i put components on GameObjects, even when the components were not made for DOTS?
and will that work?
components like animation rigging and Photon networking components.
Example: i have a "PhotonTransformView" component that sync a gameobject's transform across diffrent clients, will that component work if i put it on a Entity,
please ping me if anyone responds
you have to make things called Authoring Components you can place on Monobehaviours that convert into IComponents (also known as Entity Components)
so the short answer is no, and the long answer is you can write your own
Entity components are not "self contained" like Monobehaviour components either. Entity components only store data. You are meant to write Systems that contain the equivalent of a Monobehaviour component's Update loop (amongst other things), and process Entity behavior in there instead.
You can also process Entity behavior outside of Systems if you want to, of course. But the point is there are no methods inside of Entity Components (which are structs) like there are inside of Monobehaviour Components (which are classes).
Entity Components are structs for a few reasons, but the simple answer is they are that way so they can be made to be extremely memory efficient.
Does blendshapes/shapekeys work with ECS?
i do not believe blendshapes work in the hybrid renderer
dang. alright thanks
they are using physics components
when I deallocate an nativearray inside of a job.
Shouldn't isCreated be set to false automatically too?
I'm confused that after I complete a job.
when I do a check with isCreated, it tells me it's still true
I am aware, hence my original question.
wait so what's the problem? i don't understand
My original code to move the player ball was to AddFroce to the rigidbody.
But, without a rigidbody, how would I do the same thing.
you can not use a rigidbody with entities. you have to use the entities specific physics components
I am aware. This is why my question was What Is The Equivalent.
and i linked you a post where you can see how to do it
at the most basic level, you add to the linear value of the physicsvelocity component @spark sleet, the extension class https://docs.unity3d.com/Packages/com.unity.physics@0.6/api/Unity.Physics.Extensions.PhysicsComponentExtensions.html gives you a more accurate equivalent that takes mass and other properties into account
Thanks, but I've decided to try and make it work with the built in physics.
wdym built in physics? what he and i linked ARE the 'built in' dots physics
?
output = BiomeTypes.biomeTypes[0].primaryMaterial;
is not burstable
do i must use a NativeArray or I can use basic c#?
either NativeArray, another NativeContainer (like NativeHashMap) or their unsafe counterparts
you can only use elements part of HPC# for bursting
You can read from a managed array in burst if it's static read-only and contains a burst safe type
anychance could you show me example code I stuck for hours π I edited the above to only burst types
public struct BiomeTypes {
public struct Biome {
//public string name;
public readonly int primaryMaterial;
public Biome(int primaryMaterial) {
this.primaryMaterial = primaryMaterial;
}
}
readonly static Biome grass = new Biome (1);
public static readonly Biome[] biomeTypes = new Biome[1] {
grass, desert, mountains, hills, artic, jungle
};
}
oh it works I think, thanks π
hey guys is there an example of how to do OnClick events with entities?
need to be a bit more specific with what you are trying to do
hmm
are you talking ui events? input events? something else?
i don't really know the terminology since i don't really use unity, but I'm creating an entity using the EntityManager, and assigning it afew types - this allows me to renderer it on screen
i want to also have some sort of "OnClick" event trigger for it
just not sure how to do that
it renderers currently with a mesh + material
using meshrenderer
most basic approach is to use physics and fire a raycast from the camera into the world and see what it hits
that requires the entity to have physics right?
yes
so i considered that
but i can't figure out how to give an entity physics
since you can't add typeof(PhysicsBody) and typeof(PhysicsShape)
they aren't valid types
setting up physics by hand is a pain
what you're looking for is PhysicsCollider at the most basic
but you have to generate the collider yourself
it's highly recommended to setup physics via conversion so unity can do it all for you
what makes you have to dynamically generate an entity?
hmm my assumption is have to i guess
so what i'm trying to do it
(technically what i'm doing is trying out unity ECS)
but the tech demo i'm trying to create is
generating a ship builder
(with blocks)
it will randomly create blocks that you can use to add to your ship (think flat minecraft)
each block has its own components that i need to add
so like health being one of the basics
and then like damage/targetting etc... depending on if its a standard wall block or a weapon etc...
each one will have different sprites/texures/meshes not sure what im using here
so i was doing something like
private void Start()
{
var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
for (int i = 0; i < shipComponentPositions.Length; i++)
{
var entity = entityManager.CreateEntity(
typeof(RenderMesh),
typeof(LocalToWorld),
typeof(Translation),
typeof(RenderBounds),
typeof(HealthData)
);
entityManager.SetSharedComponentData(entity, new RenderMesh
{
mesh = mesh,
material = shipComponentPositions[i].isFloor ? materials[1] : materials[0],
});
entityManager.SetComponentData(entity, new HealthData
{
Health = 100,
});
entityManager.SetComponentData(entity, new Translation
{
Value = shipComponentPositions[i].position,
});
}
to initially build the default ship
typeof(RenderMesh),
typeof(LocalToWorld),
typeof(Translation),
typeof(RenderBounds),
typeof(HealthData)
);```
and what stops this being a converted entity prefab?
what i said above i guess?
it will have random components
it will have base ones i guess
you literally replace your code with
var entity = entityManager.Instantiate(prefabEntity);
and it's exactly the same thing
hmm okay
what i'm really just trying to get at is it's almost always wrong to generate any type of 'view' entity by code these days
packages like netcode require you very specifically to not do this
so if you ever want networking etc, you'll have to learn to use conversion
who said that?
now i have to go read up on conversion
runtime conversion is bad
(and is likely deprecated)
runtime conversion means ConvertToEntity script
when i'm talking about conversion I mean subscenes
is there just one global FixedβStepβSimulationβSystemβGroup or I can define my own ones with differrtnt intervals?
prefabEntity what type is this?
any component system group can be come a fixed stepped, you just need to define its FixedRateManager
Entity
i'm probably missing something then
where do you get the reference for that
i'm guessing i create a prefab
[SerializeField] private Entity wallPrefab;
this doesn't seem to work
highly recommend you go through all of this
https://github.com/Unity-Technologies/EntityComponentSystemSamples/tree/master/ECSSamples/Assets/HelloCube
there's a lot of different ways you can architype your application, this will just explain the basic concept
you could have all your prefabs in 1 giant buffer if you wanted for example (ghost collection style)
i couldn't figure out how to do that
tried to google it
but wasn't getting anything useful in terms of how to use that with entities
i got to try and code a Oxygen notIncluded gas interaction system now
no idea how many tiles it could support hopefully enough π
{
public Entity Value;
}
public class MyPrefabAuthoring : MonoBehaviour, IDeclareReferencedPrefabs, IConvertGameObjectToEntity
{
[SerializeField]
private GameObject[] prefabs;
public void DeclareReferencedPrefabs(List<GameObject> referencedPrefabs)
{
foreach (var prefab in this.prefabs)
{
referencedPrefabs.Add(prefab);
}
}
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
var myPrefabs = dstManager.AddBuffer<MyPrefab>(entity);
foreach (var prefab in this.prefabs)
{
myPrefabs.Add(new MyPrefab{ Value = conversionSystem.GetPrimaryEntity(prefab)})
}
}
}```
throw MyPrefabAuthoring on gameobject in a subscene
add all your gameobjects
bam now you have a collection of all your prefabs in your world on the MyPrefab buffer
var prefabs = this.GetBuffer<MyPrefab>(this.GetSingletonEntity<MyPrefab>()));
var instance = [EntityManager|CommandBuffer].Instantiate(prefabs[5]);
thanks, i'll take a read
i tried using the IBufferElementData
but seems like it would make more sense
the way you've done it
as i added a float3 as well in that
and it didn't like it
i am using IBufferElementData
let me see if i can rewrite what i've got so far then
then i'll get back to the onclick stuff
Is it possible to use physics body with a 2d sprite
O.o 2d isn't supported by entities
https://docs.unity3d.com/Packages/com.unity.2d.entities@0.32/manual/index.html
only fully with project tiny
that said, there are many people who are writing some awesome looking 2d games
is this allowed?
public struct FooStruct : IBufferElementData
{
public int Value;
}
public struct BarStruct : IBufferElementData
{
public FooStruct Value;
public int Value2;
}
trying to figure out a way to define how to load each component
in a parallell, i do:
public class MapChunkGenerator : SystemBase {
EndSimulationEntityCommandBufferSystem m_EndSimulationEcbSystem;
protected override void OnCreate() {
// Find the ECB system once and store it for later usage
m_EndSimulationEcbSystem = World
.GetOrCreateSystem<EndSimulationEntityCommandBufferSystem>();
}
protected override void OnUpdate() {
var ecb = m_EndSimulationEcbSystem.CreateCommandBuffer().AsParallelWriter();
Entities
.ForEach((Entity entity, int entityInQueryIndex, ref MapGridCoord mapGridCoord) => {
//add new buffer to entity
DynamicBuffer<FooStruct> fooBuffer= ecb.AddBuffer<FooStruct>(entityInQueryIndex, entity);
//populate buffer with 1 to 50
for (int x = 0; x < 50; x++) {
FooStruct fooElement = new FooStruct{ Value = x};
> fooBuffer.Add(fooElement);
}
}).ScheduleParallel();
// Make sure that the ECB system knows about our job
m_EndSimulationEcbSystem.AddJobHandleForProducer(this.Dependency);
}
my components the same as yours
I changed it to FooStruct
oh I see you want to go one more level deep, it may error π
var prefabs = this.GetBuffer<MyPrefab>(this.GetSingletonEntity<MyPrefab>()));
this doesn't seem to work if you try to do
var prefabs = entityManager.GetBuffer<BluePrintData>(entityManager.GetSingletonEntity<BluePrintData>()));
entityManager.GetSingletonEntity
doesn't seem to exist
I don't believe converting GameObjects at runtime is deprecated
it's somewhat necessary if your game has AssetBundles that you intend to turn into Entities
i'm kinda lost on lets say how to load an inventory in ecs
is there any examples i can read up on?
However, if you did convert from a GameObject at runtime, I wouldn't do it very often. You can do it once, and then create copies of the Entity that was created from the conversion.
like lets say i have a json file of data, that i want to convert into entities with specific components
they also relate to specific prefabs
whats the best approach to this?
I think it helps to understand how Entities differ from Monobehaviours, if you are someone who was previously comfortable with them. But you said earlier you don't really use Unity.
you are kind of diving right into the most difficult part of Unity
a partially finished experimental set of APIs
are you implying i shouldn't do this?
no, but I could see how it can be taken that way
cause i can always swap back to entitas
i just wanted to try out unity's ecs
tho putting that aside do you happen to know a way to tackle what i mentioned earlier?
if you have a set of prefabs, you can use your JSON data to convert prefabs into Entities (which may or may not be useful, depending on the components on them. Not all components do anything during conversion, so it depends.)
the prefabs really just hold image data
i was told to do that
cause of creating physics manually is too hard
if this is for a UI, I don't believe Entities really makes sense
from this conv
its not for UI
it was just an example
the concept is - ship building
block by block
right, right
are you using the hybrid renderer?
yeah
ok, textured meshes
good, so you got the components that do something during conversion on them already
yes, you could use your JSON file to determine which of those prefabs to spawn and where to put them
you'd convert them at runtime, but you'd only have to convert the prefab once, it would create an Entity with a PrefabTag component on it
some components in ECS have no data and are just used to "tag" entities
hmm the alternative was to create a buffer of them
so its just stored in one entity with an "array" of them
but i have that currently
my problem is getting the entity and "cloning it"?
right, what I do is store my own Dictionary of my Entites that have the Prefab IComponent on them and use that as my cache of converted Entities that I clone from
so when you convert a GameObject, ask your Dictionary if it has an entry, and if it doesn't, put one in there for later
if it does, then just use that instead
then access it anywhere
instead of trying to find it
or does that cause problems?
since i only have 1 entity technically
well Entities are sort of designed to be lumped together and .ForEach'd over inside of Systems, that's a separate topic
since its a buffer of prefabs
so i don't actually need to get all entities with a prefab tag
since theres only ever gonna be one
var prefabs = entityManager.GetBuffer<BluePrintData>(entityManager.GetSingletonEntity<BluePrintData>())); hence why i tried to do this
which didn't work
oh ok, so if you only have a single GameObject you are converting, then yeah just do that once.
[SerializeField]
private GameObject[] prefabs;
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
var myPrefabs = dstManager.AddBuffer<PrefabData>(entity);
foreach (var prefab in this.prefabs)
{
myPrefabs.Add(new PrefabData { Value = conversionSystem.GetPrimaryEntity(prefab) });
}
}
its more then one
but since its a buffer
only 1 entity ever needs to be accessed to get all the prefabs
so what i'm considering is just making entity be assigned to some public static in that class
public class PrefabAuthoring : MonoBehaviour, IDeclareReferencedPrefabs, IConvertGameObjectToEntity
{
[SerializeField]
private GameObject[] prefabs;
public static Entity PrefabEntity;
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
var myPrefabs = dstManager.AddBuffer<PrefabData>(entity);
foreach (var prefab in this.prefabs)
{
myPrefabs.Add(new PrefabData { Value = conversionSystem.GetPrimaryEntity(prefab) });
}
PrefabEntity = entity;
}
so something like that
var prefabs = entityManager.GetBuffer<PrefabData>(PrefabAuthoring.PrefabEntity);
and then i could just access it like that
one moment
nope it didn't like that
ObjectDisposedException: Attempted to access BufferTypeHandle<PrefabData> which has been invalidated by a structural change.
public class ShipBluePrint : MonoBehaviour, IConvertGameObjectToEntity
{
[SerializeField]
private BluePrint[] bluePrints;
public void Convert(Entity entity, EntityManager entityManager, GameObjectConversionSystem conversionSystem)
{
var prefabs = entityManager.GetBuffer<PrefabData>(PrefabAuthoring.PrefabEntity);
foreach (var bluePrint in this.bluePrints)
{
var newEntity = entityManager.Instantiate(prefabs[(int)bluePrint.BlockType - 1].Value);
entityManager.AddComponentData(newEntity, new HealthData { Value = bluePrint.Health });
entityManager.AddComponentData(newEntity, new Translation { Value = bluePrint.Position });
}
entityManager.DestroyEntity(entity);
}
}
what i tried to do
still here, just writing code atm
just letting you know
[SerializeField]
private GameObject[] prefabs;
private Dictionary<int, Entity> _cachedEntityPrefabs = new Dictionary<int, Entity>();
private GameObjectConversionSettings _clientConversionSettings;
private EntityManager _entityManager = default;
private void Awake()
{
_entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
var blobAssetStore = new BlobAssetStore();
_clientConversionSettings = new GameObjectConversionSettings(
World.DefaultGameObjectInjectionWorld,
GameObjectConversionUtility.ConversionFlags.AssignName,
blobAssetStore
);
}
public Entity SpawnEntity(int key)
{
if (!_cachedEntityPrefabs.TryGetValue(key, out Entity prefabEntity))
{
prefabEntity = GameObjectConversionUtility.ConvertGameObjectHierarchy(prefabs[key], _clientConversionSettings);
_cachedEntityPrefabs.Add(key, prefabEntity);
}
return _entityManager.Instantiate(prefabEntity);
}
assuming your JSON file has an index of which prefab to spawn, this should work just fine
of course you probably also want to pass position data into the SpawnEntity or something
oh i missed a bit, there I fixed it with an edit
oh wait, nevermind, what I wrote at first would have been fine
changed it back to the original π
you don't have to do absolutely everything inside of Entities
you can do this on a Monobehaviour if you want to
if you're expecting to have like 100,000 different kinds of prefabs, then that's a different story
you'll of course need to call SpawnEntity yourself from somewhere in my example. The only special Unity method I am using is the Awake method, which any Monobehaviour will fire for you (assuming it is on an active GameObject).
so if i'm understanding this correct
_cachedEntityPrefabs doesn't have anything in it
as you pass through key it will populate it from whatever prefabs[key] is
thats assigned from the editor
how would this be accessible in a System?
ie/ if you needed to spawn an entity via a system
with a prefab
This spawns Entities outside of a System
if you want to access entities inside of a System, you use the Entites.ForEach method and filter which Entities you want to do stuff on
you don't have to spawn Entities while inside of a System
but you could put this code inside of a System class if you wanted to, I suppose
can you add multiple of the same component onto an entity?
no, I don't believe so
okay so i went a slightly different method
using everything you've explained
so i have like 4 things roughly
public struct BluePrintData : IBufferElementData
{
public int ID;
public int Health;
public float3 Position;
}
[Serializable]
public struct BluePrint
{
public BlockType BlockType;
public int Health;
public float3 Position;
}
so the first one is for the ecs to be able to act on the saved data
the second one is for disk data to be loaded into
then to test that
public class DefaultShipBluePrint : MonoBehaviour
{
[SerializeField]
private BluePrint[] bluePrints;
private void Awake()
{
var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
var entity = entityManager.CreateEntity(typeof(ShipBuilderTag));
var buffer = entityManager.AddBuffer<BluePrintData>(entity);
foreach (var bluePrint in this.bluePrints)
{
buffer.Add(new BluePrintData
{
Health = bluePrint.Health,
ID = (int)bluePrint.BlockType,
Position = bluePrint.Position,
});
}
}
}
that creates an entity with the tag of ShipBuilderTag and adds all the information to build a ship to a buffer of type BluePrintData
then i have a system that acts on entities with that tag
public class ShipBuilderSystem : ComponentSystem
{
protected override void OnUpdate()
{
var prefabs = EntityManager.GetBuffer<PrefabData>(this.GetSingletonEntity<PrefabData>());
Entities
.WithAll<ShipBuilderTag>()
.ForEach((Entity entity) =>
{
var buffer = EntityManager.GetBuffer<BluePrintData>(entity);
for (var i = 0; i < buffer.Length; i++)
{
var bluePrintData = buffer[i];
var spawnedEntity = EntityManager.Instantiate(prefabs[bluePrintData.ID - 1].Value);
EntityManager.AddComponent<HealthData>(spawnedEntity);
EntityManager.AddComponent<Translation>(spawnedEntity);
EntityManager.SetComponentData(spawnedEntity, new HealthData { Value = bluePrintData.Health });
EntityManager.SetComponentData(spawnedEntity, new Translation { Value = bluePrintData.Position });
}
EntityManager.DestroyEntity(entity);
});
}
}
which works fine for the first entity created
but when it loops to the next item
ObjectDisposedException: Attempted to access BufferTypeHandle<BluePrintData> which has been invalidated by a structural change.
what caused the structural change?
try this
public class ShipBuilderSystem : ComponentSystem
{
EntityCommandBufferSystem _ecbSystem;
protected override void OnUpdate()
{
var prefabs = EntityManager.GetBuffer<PrefabData>(this.GetSingletonEntity<PrefabData>());
var ecb = _ecbSystem.CreateCommandBuffer();
Entities
.WithAll<ShipBuilderTag>()
.ForEach((Entity entity) =>
{
var buffer = EntityManager.GetBuffer<BluePrintData>(entity);
for (var i = 0; i < buffer.Length; i++)
{
var bluePrintData = buffer[i];
var spawnedEntity = EntityManager.Instantiate(prefabs[bluePrintData.ID - 1].Value);
EntityManager.AddComponent<HealthData>(spawnedEntity);
EntityManager.AddComponent<Translation>(spawnedEntity);
EntityManager.SetComponentData(spawnedEntity, new HealthData { Value = bluePrintData.Health });
EntityManager.SetComponentData(spawnedEntity, new Translation { Value = bluePrintData.Position });
}
ecb.DestroyEntity(entity);
});
}
}
i actually don't know much about buffers. it could be simply accessing it and iterating over it is causing a problem
EntityCommandBufferSystem _ecbSystem;
doesn't this require something to create it?
something like
private EntityCommandBufferSystem commandBufferSystem;
protected override void OnStartRunning()
{
commandBufferSystem = World.GetOrCreateSystem<EntityCommandBufferSystem>();
}
and also don't you need to actually register the command buffer somewhere
otherwise it just does nothing
cause it never runs?
oh yeah, you have to create or get a command buffer system first
you could grab this one, which I think exists by default?
private EntityCommandBufferSystem commandBufferSystem;
protected override void OnStartRunning()
{
commandBufferSystem = _ecbSystem = World.GetExistingSystem<EndSimulationEntityCommandBufferSystem>();
}
you can see a list of existing systems in the Entity Debugger
private BeginInitializationEntityCommandBufferSystem entityCommandBufferSystem;
protected override void OnStartRunning()
{
entityCommandBufferSystem = World.GetOrCreateSystem<BeginInitializationEntityCommandBufferSystem>();
}
protected override void OnUpdate()
{
var prefabs = EntityManager.GetBuffer<PrefabData>(this.GetSingletonEntity<PrefabData>());
var commandBuffer = entityCommandBufferSystem.CreateCommandBuffer();
Entities
.WithAll<ShipBuilderTag>()
.ForEach((Entity entity) =>
{
var buffer = EntityManager.GetBuffer<BluePrintData>(entity);
for (var i = 0; i < buffer.Length; i++)
{
var bluePrintData = buffer[i];
var spawnedEntity = commandBuffer.Instantiate(prefabs[bluePrintData.ID - 1].Value);
commandBuffer.AddComponent<HealthData>(spawnedEntity);
commandBuffer.AddComponent<Translation>(spawnedEntity);
commandBuffer.SetComponent(spawnedEntity, new HealthData { Value = bluePrintData.Health });
commandBuffer.SetComponent(spawnedEntity, new Translation { Value = bluePrintData.Position });
}
commandBuffer.DestroyEntity(entity);
});
entityCommandBufferSystem.AddJobHandleForProducer(this.Dependency);
}
i'm not aware of you needing that last part, but maybe I'm not sure
entityCommandBufferSystem.AddJobHandleForProducer(this.Dependency);
oh
wait this doesn't work
cause i can't use EntityManager.GetBuffer
i guess i could just do .WithoutBurst()
and it works
nice
alright, well, good π
welp now to actually do the thing i asked here initially
click on entities that render a mesh and trigger events...
goodluck, bedtime for me
ok dumb quesiton, say I have
MyComponent myComponent = SomeComponent
can i get the entity it is attached to from that?
you can do entitymanager.hascomponent(entitiy, component) if i remember correctly
or something similar
I dont have any entity
well you need any entity
just iterate over all and test them
or save your entity reference in the component where you need it
I see, yeah im looping this:
NativeArray<MapGridCoord> mapGridsData = queryMapGrids.ToComponentDataArray<MapGridCoord>(Allocator.TempJob);
as otherwise I was getting burst errors, Ill try to think a diff way,
why do you need the entity though?
So in this system, my entity, with a Coord, has now found the Coord of the adjacent tile
so I need to get its entity
or some other components that are attached to it
So I have... currently entity + coord --> found neighbour coord --> neighbour data?
I thinbk what you say before is best, I can loop every entity with a coord, instead of my NativeArray above, just gotta work out how π
just gotta get it into a NativeHasMaph I guess from what I know Coord Entity
not done one yet so will try
hm, yeah......grids are kinda....not ideal currently in ecs. if your grid has a fixed size though, you can use a fixed array to look up the corresponding entity
its working well so far, my temperature system can simulate every 0.25 cell within like 0.04 seconds or something crazy
just only within each chunk, no talking to neighbours yet π
but its not fixed sizes
var queryMapGrids = GetEntityQuery(typeof(MapGridCoord));
NativeArray<MapGridCoord> mapGridsData = queryMapGrids.ToComponentDataArray<MapGridCoord>(Allocator.TempJob);
is the current code, That query is probs my entities π
do you have example to get both lines of data into Native formats?
native formats?
a dictionary I can use with burst, I think is a NativeHashMap but not sure?
yeah dictionary is nativehashmap
for a RTS game, how would a system that applies damage from units to other units work in DOTS?
Im super newb but would aim to have a Targeting System, which sets a refernce to the units target
then a shooting system, where units move to within range of there targets and aim+ fire
then a projectile system to manage all the projectiles in flight
then a damage system that reduces healths
by then ive learned more what I really need π
is there any simple list type I can use in a job?
I tried using NativeList, but I cant blit Buffers
just wanna chuck a bunch of buffers in a list
NativeArray<UnsafeList<StructStuff>>(). Note, nested arrays are not proper DOTS design.
can I add an element to them π or i must do it define time? (then i cant pass in a basic array type in burst I dont think?)
ill try
say I want to process half my elements in one systems onUpdate call / frame, then the other half in another (to prevent write access to read only components)
Is dots better than mirror when it comes to a game like csgo
that would make sense right?
green could run/Write on Even frames, readonly from red, who run/Write on odd Frames readonly from green.
no
anyone got examples of defining a system update group of there own, I tried with this code which I think is working but no idea if I did it ok:
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I just wanted to define my own fixed update system, but had to copy form the source
World.DefaultGameObjectInjectionWorld.GetOrCreateSystem<FixedStepSimulationSystemGroup>().Timestep = 2f;
why do you need this when you can just set it in FixedStepSimulationSystemGroup
side note, i hate that fact you named it the same thing as the built in one π
aha yeah ok, so line 28 to set it, and change its name π
tnaks
I did have some clashes already lol
these two are not even tangentially related. so no
does [UpdateBefore(typeof(x))] guarantee that system x will finish all its code before starting the annotated system?
yes
kind off
it only guarantees OnUpdate will run before, not that the jobs from one system will complete before another (unless you switch to simple schedule mode)
i.e. the first system has to finish its OnUpdate function before the second system's OnUpdate function starts?
Thanks!
There's the double buffering way. Looks like what you describe but without worrying about managing half of the stuff. You still handle the whole collection but you now make a copy of it, which is in the past (1 frame old). You write to one, read from the other, then swap them, and so on
Also called blitting in GPU terms
thanks man, i went with that
is there a quick way to delete all of a component?
You can pass an EntityQuery to RemoveComponent
If I have this problem, is there any way around it beyond writing less data?
might need to instantiate via nativearray or destroy by query at that point
any weay to work out which systems commands are spamming it?
think i got my ONI style tile transfer systems in place and working at 200fps, for a 10km x 50m area
but will no doubt find its not working when i try to expand on the basic test π
nope had it commented out dang π
Is there a reason why writing to the same parallelwriter from 2 different jobs is not allowed?
Can I get the previous position from an entity (with LocalToWorld or Translation or somethin like that) or do I need to implement an entitybuffer to keep track of the last position?
gotta diy it although there is a case for handling it with physics interpolation
Hey my MMORPG enginie is almost ready to be tested. I have like 5 hours of easy work and maybe 8-12 of medium (2 days)
I have one question tho:
Starfighter MMORPG engine test launch imminent next few days. Can you help me figure out why my subscene ain't loading?
StarfighterGeneral.com Bloopers, Bugs and Outtakes: https://www.youtube.com/playlist?list=PLOQ-J23AJUfSCeuHkKQtL1Al70iAWnbSO
Been #1 in the world at every online ladder video game I played even the highest skill games Star...
How do I get my subscenes to load in a standalone Windows compile? I am probably messing something up in my build file
these are my settings, what is wrong?
Again, everyone who helps me, when I'm making 1-100 million dollars a month, come ask to go out to eat and get a manilla gorilla envelope of green backs LOLOLOLOL π
from memory, you shouldn't include your subscenes in the scene list - you're just including them twice then
subscenes should just build as long as you use the new platforms package which you appear to be doing. if its not working with that idk, maybe time for a bug report
What is the status of dots + dots netcode with unity 2020? is it working? kind of working? stay the hell away from it?
@remote crater what version of unity is a good question actually
netcode is /fine/ if you don't target mobile
0.50 should bring a lot of fixes though
whats the problem with mobile?
i've never tried (pc/console dev) but from reading forums optimise has found a huge range of bugs with android in particular
just breaks after a while (i think it's the transport package not netcode in particular, it's probably fixed in the recent versions but netcode needs an update to use it)
I would say that it works pretty well in general
The two most 'urgent' bugs that I know of are https://forum.unity.com/threads/ack-desync-detected-case-1326809.1087292/ and https://forum.unity.com/threads/netcode-prediction-jitter.985701/
The current version of netcode also doesn't support ISystemBases by default
I opened the asteroid sample with 2020.3.23f (it was using an older one the sample), and it did not go well haha
You have to do some source code edits to the PhysicsWorldHistory for it to work with .16(?) and above
the only thing I did was, open with the new unity version, build the osx-clientserver
Oh sorry I have zero experience with mac
is it really bad to get a list of 1000s values, then loop EntityQuery.SetFilter()
when did they say ECS 0.50 was gonna come out?
supposedly q1 of 2022, so "soon"
really hope it is actually soon and not like enable disable soon
well they still have 3 months
we jumping from 0.17 to 0.50 in one go?
maybe entities only gets bumped up to 0.18 π
no it'll be 0.50
that will not be in 0.50
not yet
You can dig through the forum post they released just before Christmas. No hardcoded feature list but can give you some hints (that's where they stated no enable/disable yet for sure)
So ive got a few singleton entities that contain some global settings that other systems access, is there a way to easy change the data in these entities during play from the editor?
if you want manual changes, you'd need to have a legacy monobehaviour on an object in your scene and have a system or the monobehaviour sync data changes that happen to that monobehaviour to your singleton entities
thats what i thought :/
thanks anyway!
it's not really a lot of work though
Is DOTS still preview?
im changing a lot of things, so it's just annoying having to add/change/remove fields in lots of different places
ECS is. DOTS is not
write a source generator for it
so, dots is 1.0 already and can be used fully or only as hybrid?
burst, jobs, collections, mathematics are all fully supported and can be used as is
there is nor ever was a DOTS hybrid
only hybrid workflow for entites / ECS
I guess I'm getting it confused with ecs yeah
ECS 0.50 will be released in Q1 2022
ECS 1.0 probably in Q4 2022
ECS 1.0 will ONLY support a hybrid approach
ngl haven't actually looked into source generators before, but i will now. Thanks again!
unity currently only supports API 1.0 of source generators though. even though API 2.0 is way better, make sure to write for API 1.0
so what is DOTS then? Just a packages for Unity with ECS approach ?
no. DOTS is unity's Data Oriented Technology Stack. Entities (ecs for unity) is included under DOTS, but DOTS is way bigger than mere ecs. DOTS also includes burst (compiler for c# to native code), jobs (easy multithreading solution for gaming), collections (native collections for c#), math (SIMD library for burstable math), and all other packages that may or may not be related to entities
so, in short DOTS is just overhaul of Unity engine?
no
ok, I'll just give some more time learning about it, before I ask more stupid questions xD
Can I make a System skip some UpdateLoops? I dont want this system to run every frame, but, eg every 3rd or 4th frame?
You can set the componentsystemgroup's time step, so you can make one update at 30fps instead of 60 fps
I gave it a bit of googling, you mean something like this: https://forum.unity.com/threads/ifixedratemanager-has-me-a-little-nervous.997868/ ?
Yea
Hey!
I want to use the burst compiler without having to rewrite my scripts in ECS, because they're very complex.
Do I need to use the C# job system to use the burst compiler?
My scripts use a ton of references, so I can't really use the c# job system
I tried, but I couldn't get it to work as intended
Well it could be in a far future, but for now, gameobjects/monobehabiours are here to stay
you're going to have to rewrite some of your stuff if you want to utilize burst + jobs. If you have a ton of references and don't want to rewrite things why not stick with C# thread pool?
Im getting performance issues
I looked at the profiler
and fixed a lot of stuff
but the only way to really get performance is with DOTS
You don't need to use jobs with burst, it can run on the main thread. But it still has all the same restrictions - no managed types, no mutable statics, etc
curious if anyone knows this, but with the conversion workflow can we define what the destination world is? I'm trying to figure out a way for multi world setup + entity authoring π€
if i remember correctly, can't you pass the injection world as a parameter to the entity manager?
maybe? I don't remember if I saw an API like that
I can take a look later today, but it'd be nice if I can just dictate that entity A moves to x world and entity B moves to y world instead of moving them to a staging world and then move them to the correct worlds on runtime π€
2020.3.25f1 Been like this for the past 40 version + or so
It may be in my packages
How do I upload all my packages I use?
I thought there was a manifest.json but I cant find it
found it
I have an official error when running standalone in debug;
Through the GameObjectConversionSettings ?
Probably π I noticed I could access the destination world. I think I need to figure out multi world setup in the editor
The error message in standalone is visible in that image.
"in the editor" you mean you want to build visual tools ?
If just code you can define a custom bootstrap
just code, I'm currently using an ICustomBootstrap + Subscenes. But yea I think what I want are editor tools, but that's definitely not coming till much later from Unity
From memory Netcode definitely comes with inspector components aware of multiple worlds (server/clients)
Dunno if that's clean code though
Tertle sir, Why would it even care about file->build settings when I use a Build pipeline. Something is amiss.
good info, I'll take look into it
If not in netcode package, maybe i saw it in the old FPS dots multiplayer sample
wait the FPS sample or their third person one?
Was thinking of the FPS one, cant remember for the third person one
kk - i'll look around then
Unity needs an "Update all packages button" that looks for the most basic dependencies and updates them first. If compilation errors occur, rolls it back to last version, then moves on to try and update other packages, informing the user of what happened.
not really
Is it possible to get Time.realTimeSinceStartUp inside a Bursted job?
I have many chunks of calculations (which I cannot estimate how long each chunk will take) and I'd like to spread them out over multiple frames.
I personally lost 50+ hours and counting to a problem that would take an official Unity dev less than 30 hours to solve(update all packages). There are more users than just me. I'm a time management Ux designer. I don't think they teach this in school because all the big players get it wrong. Anyone try and use Google ads or Starcarft2's Map Editor? Whoa, its like no one knows what they're doing out there. Even windows still has forced alt tab, tightly bound windows to processes(noticeable when you can't alt tab to unity editor). Multi billion dollar corporations don't even have the first clue of what they're doing it seems. PS: I still can't update my packages properly, still erroring out.
Can you guys recommend where to look for up-to-date guides/tutorials/examples? Besides docs.
I'v watched a lot of tutorials, but it appears they use obsolete code
I pretty much got the concept of ECS and now I just want to look through some most recent examples
This is pretty up to date, it does cover the Networking aspect, but it does basic ECS stuff too
Thanks, will take a look
if an Component in one DynamicBuffer, needs to interact with another in a different buffer, whats the best way for them to reference each other?
BufferFromEntity<MapChunkTileLastTickBufferElement> lookup = GetBufferFromEntity<MapChunkTileLastTickBufferElement>(true);
if (surroundingTiles.tileAbove != Entity.Null) {
neighboursBufferTop = lookup[surroundingTiles.tileAbove];
} else {
neighboursBufferTop = new DynamicBuffer<MapChunkTileLastTickBufferElement>();
}
if (surroundingTiles.tileBelow != Entity.Null) {
neighboursBufferBottom = lookup[surroundingTiles.tileBelow];
} else {
neighboursBufferBottom = new DynamicBuffer<MapChunkTileLastTickBufferElement>();
}
int index = 0;
for (int x = 0; x < EngineSettings.ChunkWidth; x++) {
for (int y = 0; y < EngineSettings.ChunkHeight; y++) {
indexAbove = aCheapFunction()
indexBelow = aCheapFunction()
MapTile tileAbove = neighboursBufferTop[indexAbove].Value;
MapTile tileBelow = neighboursBufferBottom[indexBelow].Value;
}}```
at the moment i just do this which i guess is super bad
Which ways do they have to interact? Do they write to each other??
not fully decided, but at the moment due to complexity with that, they dont π
so they are slightly different component types at the moment, but representing the same data
I write to a buffer not shown above
MapChunkTileLastTickBufferElement Read, MapChunkBufferElement Write
I was debating creating a new system, that reads each tile sequentially and populates an new buffer that the adjacent tile needs and can then read sequentially.
That would be like this but Native or whatever for burst, is random writes to fixed array as bad as reads?
Dictionary <int, int[]> ()
Dictionary .Add(1, [12, 16, 20, 24])
Dictionary .Add(2, [13, 17, 21, 25])
outArray = (26)[]
for (int x = 0; x < BufferLength; x++) {
outIndices = Dictionary[x];
for (outIndice in ){
outArray [outIndice] = Buffer[outIndice]
}
}
Im guessing that would be a waste of time π
You would typically access the other buffer through it's entity with a BufferFromEntity that you get from the system in OnUpdate and pass into the job.
Ah i see, I had that at first but wanted ot move it to a generic function I could call from anywhere, but if thats more performant I can do that way again thanks!
When I was doing something like this a I had a single "VoxelWorld" struct that I passed around which provided immediate access to any block. It could be build from any system and would populate itself with the necessary BufferFromEntitys/CommandBuffers
I think that what I want
I have something working just want to try and oxygen not included ify it up
It's pretty convoluted as it needs to account for read only access and read/write access but it worked
awesome that looks amazing thanks
Ive got all the same functions pretty much π
just used very differently
that repo looks cool why you stop π
Yeah I'm not gonna say it's a great solution, but it did work
I couldn't really figure out a good way to handle spawning new chunks. I ended up with a convoluted pooling system that I hated so much and I couldn't figure out something better so I gave up on it
I wanted to make a minecraft clone, mixed with rimworld somehow. now im making a minecraft clone, mixed with rimworld, oni perdspective (2d) instead
Im just rewriting my chunk system now I think this will work well based on my last attempt :D... I have this in a system:
SectorCoordinate requestedCoordinate = new SectorCoordinate(objectsSectorCoordinate.Value.x + xOffset, objectsSectorCoordinate.Value.y + yOffset);
// Set the sector to active
if (sectorDictionary.ContainsKey(requestedCoordinate)) {
EntityManager.AddComponent<Active>(sectorDictionary[requestedCoordinate]);
}
// Create a new active sector
else {
CreateNewSector(requestedCoordinate);
}
which basically spawns very lite entities for every chunk
I wanted any system to be able to spawn a new chunk and create blocks in it arbitrarily, but since the results of an ecb are meaningless outside a single job I couldn't figure out a good way to handle it
then another system operates on those Entities, that dont have the tileBuffer component, either loading it from disk, or generating the new tile and populatring the buffer
within a Parallell()
my last attempt had the chunkmanager above, running in a parallell.burst, and after many thousands of chunks added it choked up jsut looping the datas to find the right entity to see if it existed or not. now in main thread its super lightweight anyway seems to wrok well afdter testing for 2 mins π
I see yeah that sounds complex, for me I would just generate that entire chunk in its entirety π
Depending on if the game is "infinite" or not I don't think it's practical to spawn them in a loop on the main thread. That's a lot of syncing. And then any operation that potentially creates a block becomes asynchronous as it's just a request, rather than dealing with the actual live state of the world
mines super at early stages of dev with no real functionality yet so will learn much
Which complicates it more
mines infinite, but spawns em super fast ish but the algo is just a simple heightmap so far lol
and also my pc is a bit powerful so may not be representative
my ecbs got full last time though, so now i have a lot less changing of components, hopefully
in version about 9 of my minecraft clones π
It's a fun problem to try to solve, but yeah making it play nice with jobs was too much for me sadly
I think you're on the right track though, if I was doing it again I would probably restrict "random" access to the main thread so there's a simple logical order to how the world gets written to in that case, and save the job stuff for world gen which should be able to go parallel in some cases
Dots seems so nice- Iβm excited for it to become available for 2022.1
your code is like foreign language to me, but will be good to try and learn π
mine is beginner style aha
I realised I need a WorldXY to SectorCell lol, how i not needed that yet i not sure
heres my latest test: https://clips.twitch.tv/WittyBlightedKaleDoritosChip-ea3lJgoP_Hn8HcRp
it shows heat spreading (first 15 secs - each cell talks to neighbour cells 5x a second and does math) and endless generation (last 15 secs, basic heightmap)
the oni heat style thing will have to be taken out as too complex to implement efficiently for me π
Anyone here noticed that IJobEntityBatchWithIndex with parallel scheduling and more than one batch per chunk falls apart? π
Hello, before I try I wanted to ask if I can query for DynamicBuffers on the Entities.ForEach, like .WithNone<DynamicBuffer>()?
Yes but replace "DynamicBuffer" with your struct implementing IBufferElementData
Yes that of course, just wanted to make clear what I wanted to do - thanks
what are the real world example uses of FunctionPointers?
for managed components, you just always have to use 'in' ?
got so confused thinking I learned in and ref wrong way round 1000x π
they are pretty much equal to delegates, but more lightweight and more native. they get compiled to calli calls and not heavy virtual dispatch calls. you can use them for anything you'd use delegates for in normal c#. e.g. lambda use cases
i don't think so
Can I use the BinaryWriter in a System with WithoutBurst() and Run()? like, putting using around the whole Entities.ForEach?
yea should be possible
don't think you'll get any compiler errors π€
that'd be fantastic I will try this tomorrow
Why would Unity even care if my scene was in file->build setting since that is not what the Scripted Build Pipeline uses?
the log message might be generic, maybe you're missing it from the scene list info in the build pipelines
I definitely have it there. But maybe another option is disabled.
I wouldn't be sure then
I'm thinking of not even using subscenes at all, or making an interpreter script to compress, and read em in so I can instantiate.
Is NewMoba a subscene which throws the errors when loading it?
If so how are you trying to load it?
It works in editor, but not standalone.
I can show you a video. Thank you for interest.
Starfighter MMORPG engine test launch imminent next few days. Can you help me figure out why my subscene ain't loading?
StarfighterGeneral.com Bloopers, Bugs and Outtakes: https://www.youtube.com/playlist?list=PLOQ-J23AJUfSCeuHkKQtL1Al70iAWnbSO
Been #1 in the world at every online ladder video game I played even the highest skill games Star...
SceneManager.UnloadSceneAsync("NEWMOBA");
SceneManager.LoadScene("NEWMOBA", LoadSceneMode.Additive);
Only two lines of code I believe
Huh that is indeed rather strange
I never had problems with that π¬
Ty for trying
By convention for managed components you should use neither ref nor in
that really depends on what you want to achieve
There is no ambiguity for a managed component. It's always on the main thread so it's always read-write.
there's still differences if you pass a managed component with ref, in or without anything
How so?
yea im confused by that, how? You can't pass a class as a ref/in param π€
By definition a managed component is a reference type so it makes no difference whether you pass it by value or reference
So as far as i know the convention is to leave off the ref/in modifier for those types
I believe due to the weird code gen magic you can still do it (I think, it's been a while) but yeah it makes no difference afaik
o π
that's some weird tidbit to know lol. I haven't really used the lambda stuff since everything has been job structs.
just for the record, method(ref class) and method(class) are not the same thing
void TestCaller()
{
var test1 = new Test() {Value = 2};
Method1(ref test1);
Debug.Log(test1.Value); // 1
var test2 = new Test() {Value = 2};
Method2(test2);
Debug.Log(test2.Value); // 2
}
void Method1(ref Test test) { test = new Test() {Value = 1}; }
void Method2(Test test) { test = new Test() {Value = 1}; }```
Ohh I see, I didn't know that. So you can assign to the reference type itself if you pass it by ref, neat
@zenith wyvern all structs are passed by value (which means they are copied into the method) and classes are always passed by ref even if you don't have ref in there. Using ref makes it explicit that you are passing in the reference to the struct instead of a copy of the struct. There are some exceptions to the above rule, but that is the general rule.
just as i said
I could be wrong but I think the ref gets stripped from managed types during code gen anyways as it has a completely different meaning in that context
Either way I remember at one point reading that we're meant to leave ref/in off managed types in the ForEach lambdas
Has anyone here found a way to hack dotsβ ecs into working acceptably on 2022.1b?
curious as to which part isn't working since I'm using Entities in 2022.1b without much of an issue. π
Whoa- I had compile errors just trying it
Template type mishandling due to nullables, afaik
can you share* the package list you have installed?
It was collections 1.1 and entities latest as of uh⦠last week
Will post back in 5
I know not every package associated with Entities will work w/ 2021.1b
Ah yea, you gotta downgrade collection to 0.15 preview
It was entities itself that had templating errors
I kinda remember we went through it monthes ago. I forgot the details but it was along the lines of trying to access from/to your player controller class. So probably something like you are trying to move your player before the scene is loaded or something like that ? Worth the investigation around that side (I would check back the log file as a starting point)
"com.unity.burst": "1.7.0-pre.1",
"com.unity.collections": "0.15.0-preview.21",
"com.unity.entities": "0.17.0-preview.42",
"com.unity.mathematics": "1.2.5",
"com.unity.platforms": "0.8.0-preview.2",
"com.unity.platforms.android": "0.10.0-preview.10",
"com.unity.platforms.desktop": "0.10.0-preview.10",
"com.unity.platforms.macos": "0.10.0-preview.10",
"com.unity.platforms.windows": "0.10.0-preview.10",
"com.unity.properties": "1.7.0-preview",
"com.unity.properties.ui": "1.7.1-preview",
"com.unity.scriptablebuildpipeline": "1.19.3",
"com.unity.transport": "0.6.0-preview.7",
well if it helps, here are the package versions I have in 2022.1b
Interesting- I wonder if we should (or, according to licensing, even could) fork it for 2022.1b support for the latest version if that was the issue
Yea I think you can. I believe they're all under the Unity Companion License.
I havenβt read up much on that one yet
Probably would just have to double check the license if anything π€
Most of my homework ended up being on the renderer, which- unless dots saves me- may actually force me to swap to unreal
ah - I can't vouch for Hybrid Renderer in 2022.1b. I don't use it and just rolled my own stuff
Cameras apparently canβt render βjust this sceneβ or βjust this geometryβ in a scalable and dynamic manner
I need multiple scenes to be loaded concurrently but independently, and the SRPβs design appears to make proper culling and target selection (almost?) impossible
Render layers might work but they require a huge amount of manual management that has room for mistakes that lead to something rendering on the wrong layers, especially if user-created content is involved
The hybrid renderer might save the day though, if it can do selective rendering - and if it works on 2022 at all; Iβve been trying to get HDRP to do it but it seems to be an architectural flaw
hybrid renderer is not supported in 2022
if you want to use it, use 2020
Entities isn't "supported" in 2022 either- whether or not it can be hacked into working, I haven't tried yet, but with entities actually existing, it could be possible
linux compatibility, shader keyword limits, and HDRP 13
bit late to party but there's a significant breaking change in srp that completely breaks hybrid renderer in 2022
from what i hear, do not expect compatibility till later half of 2022
0.50 already slipping to q2?
ugh. Well, I hope the massive breaking change fixes the fundamental lack of any mechanism for implementing efficient culling
0.5 isn't supporting 2022
π’
they specifically said only 2020.3 and then 2021 support in the post
The first is a set of experimental packages updated to version 0.50, compatible with Unity 2020 LTS at first and targeting compatibility with the upcoming Unity 2021 LTS later in the coming year.
entities 1.0 is for 2022 and doesn't sound like it'll support 2020 or 2021 (again 2022 is really breaking)
The second milestone is the actual transition from experimental packages to full release status with the version we call Entities 1.0, which will be fully supported much like any other released feature of Unity. The 2022 LTS cycle is our preferred target for this release, but we have yet to confirm it. Entities 1.0 will not be compatible with earlier LTS versions.
im always expecting the worst at this point as far as further delays π₯²
I wonder if I should drop all non-vulkan APIs and just use a native plugin to supplement a custom SRP
there's gotta be a way to prevent it from adding objects to batches
I noticed that project Tiny isn't active in the forums
you mean community wise?
more like unity isn't talking about Tiny even in the forums
I can't get the entity system to work with urp
what version
latest
i made a new project and can't get ecs to work with urp lit shadeers
i get an error
it doesn't support
Error messages generally help people to help you
I know but i tried to change to everything, I made a new URP project and installed ecs packages
and can't get the material working
it's a clean project from the lts version
2020.3?
have you installed the hybrid renderer?
have you enabled V2 on the hybrid renderer?
how do you enable it?
Is there a full list of everything related to ECS in package names for unity?
is that all?
yeah, I'v seen it. But for some reason installing them results in unity loading with compiler errors.
Do I need to use specific unity version for DOTS?
2020
also, if you're upgrading an from an older version, unity has a habit to break things even though new projects work perfectly fine. best to put all your assets in a unity package, export it, create a new newer unity project and import the unitypackage
2022 is partially supported, 2020 is fully supported, 2021 is not supported
no. but anything after 2020 does not support most dots packages. that 2022 is partially working is a mere coincidence, not a wanted behaviour
that's sad to know
no. they were / are in the process of rewriting lots of core things but those don't get pushed to the public. though entities 0.5 will be available in a few weeks, but only compatible with 2020 as well. a few weeks / months later it will be available for 2021 as well. and in q4 of 2022 1.0 will become available
so for now I jsut install 2020 and all DOTS packages will work fine with it, I assume?
mostly that'll be the case. i personally had a few errors when using the latest jobs package in 2020 but there is nothing marginal in it anyway so you can just install a version below latest if you need that package at all
I'm just a student for now, but I want to learn all DOTS related stuff, entities and jobs. So I guess I better learn all of them
the jobs package only brings a few helper extension methods to the table though, so you don't absolutely need it to work with jobs
I don't? You mean it's because related stuff (like thread scheduler and etc) can be written by ourselves or because code for jobs is part of smth else?
jobs is integrated into unity. the package only offers a few extension methods
ah, I see
You don't have to install all DOTS packages manually. There's a dependency chain involved and trying to install a specific version yourself on top of it might mess things up
From the package manager window there's an inspector view where you can see which dependencies are resolved
Can't screenshot it for you, not in front of computer
But I hope it brings help :p
yeah, I installed hybrid pipeline and it practically resolved everything itself
But I just prefer to know what I install and why
Hoping to get help here
I'm trying to create ArchetypeChunkComponentType variable in my ijobchunk but it doesnt show up
The documentation says its under Unity.Entities which as you can see is already included
Anyone has any idea what I might be missing?
Are sub scenes specifically made for Entities conversion?
You may be looking at old documentation https://docs.unity3d.com/Packages/com.unity.entities@0.17/manual/chunk_iteration_job.html#define-the-ijobchunk-struct
Well apparently the documentation is wrong there too which is pretty funny. But it shows the correct way to do it in the actual example. ComponentTypeHandle
yes
im still reading your source @zenith wyvern , does using getblock randomly not have issues with random buffer accessing?
If I remember right the idea was that any system that needed random access would include other accessing systems as a dependency. The same way AddJobHandleForProducer works
I think my tick system is basically doing the same as your methods, but cant be 100% sure π
I have reference to adjacent entities, and get buffer from them
so I already have: TryGetVoxelChunkFromIndex saved for a given tile (and loaded at sector level), then var blocksBuffer = world.BlocksFromEntity[chunkEntity]; is similar to my neighboursBufferTop = lookup[neighbourSectors.tileAbove];
but then i dont reinterpret as array which you do
It sounds like it yeah. Rather than tracking neighbours per chunk I just have a big hashmap that I can index to from anywhere
yeah i didnt know about them so i will defo do that as well
The hashmap will tell me if there's a chunk there or not as it won't have a key for that chunk index if it's not present
I have a public dictionary I cant access from within burst and stuff, I guess you can with that?
Yes NativeHashMap is basically a burst friendly version of dictionary
I dont think its possible to tick every tile quickly enough, but thats no problem i can do some game design instead to solve it π
I wonder how ONI is coded
Apparently it was made in unity
ah someone pasted this
C# is doing a good job, and where it doesn't you use native c++ code... ONI is doing it's simulations natively (simdll) because C# would be like 10 times slower on that part
is that still true with DOTs? I guess not
No, in theory fully optimized burst code should be as fast or faster than C++. Good luck writing it though
dots can even be faster than native c++
I see oni only has approx 100k tiles, and I was testing at 1mill - 2mill π
it was beast moding it at 100k tiles, food for thought for me anyways π
Hmmm. So I read through DOTS tutorial https://dots-tutorial.moetsi.com/
And it mentions "running code on main thread" a lot.
Am I correct to assume that by that they mean simply running code in MonoBehaviour?
Looks like they're talking about running a job on the main thread (which is perfectly valid for when you know the cost of scheduling a thread versus executing things immediately)
I know what main thread is, I'm just not really familiar with how Unity handles it.
It's actually mentioned in this context
which kind of tells that threaded job is still better in this scenario, I'm just asking how to make sure your code runs on main thread
Job.WithCode(() => {}).Run()
or new JobStruct().Run() (depending on the interface implemented)
oh wait
so
All systems you create, code is run on main thread?
and you either .Run() or .Schedule().?
yea pretty much, create the job on the main thread, call run to execute immediately on the main thread, or call schedule so that it's submitted to the job queue and internally unity will figure out when to execute those jobs
looks simple enough, if it's some GameSettings entity you just run job instead scheduling
as example
yea
yeah, thank you
everyones always talking bout jobs, they are much better than entities.foreach?
uuugh, grammar is being funny with those comments
can anyone explain a bit differently?
Entities.ForEach generates a Job struct, you can take a look at the DOTS compiler (DOTS -> DOTS Compiler -> Open Inspector)
I just don't get the right meaning of what they tried to say here
However because it's codegen you also don't get as much control in how it's generated
GetSingleton is effectively a main thread only call. So the idea is that you call GetSingleton<T>(), copy the value over to the Job struct if you need to read the data.
Everything is created into jobs, but the code to make jobs is so much typing it makes my hands hurt. So Unity compiles the simple stuff for you.
ok thanks
oh, so I call it inside of OnUpdate() but outside of Job lambda
?
@rustic rain yeah
yea
Every job needs to have it's inputs and outputs put into a big struct which is a pain in the butt to type out everytime
I prefer the control of actually writing all the code out, but it takes forever
what do you mean store?
but I don't want because I want settings to be changed at some point
that line of code does it good
it writes it to local variable, I mean write it to field
and only once
just like prefab
So every time you run OnUpdate it is grabbing the information from the Singleton
you can, but your job cant read from a field. so will need to read it from field instead outside the job.
so you end up with a slightly different line of code, and potential for 2 sources of truth
I've found with a few years of DOTS development the implementation of things is less important and you have to get your head around how to bring in the data you need.
Soooo, I don't really get. How exactly it gets this component
what if I have several entities with that component
I think it's more closely aligned with procedural component
it runs getEntity query, and returns an error if theres more than 1
@rustic rain you shouldn't do that. Then it isn't a singleton
ok
I'm guessing hierarchy wise, I can put set this entity absolutely any way I want
I actually wonder at what points this system might choke
where GetSingleton or smth like it will become slow
with jobs,
// This completes the scheduled jobs to get the result immediately, but for
// better efficiency you should schedule jobs early in the frame with one
// system and get the results late in the frame with a different system.
this.CompleteDependency();
am i meant to save this in a public dictionary or something, and then call that in a different system?
and when it talks about times in the frame, this is like uisng the init, simulation and render groups?
It won't choke, it's grabbing the smallest amount of data. But you shouldn't have a singleton that is 16KB of data
@rustic rain I seem to recall that using Singletons is not a great practice. So try to use it sparingly for things like settings and stuff that doesn't change. If you need to write back to the singleton in the same frame you are gonna run into hiccups
I am not sure what you are asking @graceful mason
The steps for using jobs are, 1. You create the job, you schedule the job and then leave for a while
how do i call that job to complete in a diff system ?, later in the frame
Like you need that job to be completed before you can do something else?
im just learning, like how to run a slow job over a longer time.
Oh hmmm. That is a pretty complex question TBH.
you mean async job?
For simple stuff, I create a job, schedule it and then check back in every few frames to see if it is done.
There is a struct called a JobHander
you can call .Complete() on it at any time
but that pauses everything and completes that job at that moment. That is bad
You can check the handler with .IsComplete and that returns true if the job is done
I think what this.CompleteDependency() does is call complete on all the jobs up till that point for that system
so you don't want to do that. I would just have something checking to see if the job is complete every frame in an OnUpdate()