#archived-dots
1 messages ยท Page 91 of 1
new release with an updated hybrid renderer should be out annnnnny tiiiime noooow...... ๐ฆ
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
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
yeah that's definitely true
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
Luckily I don't forsee having to mess with materials and such
next release is supposed to have that materialblock support
oh nice ๐
oh nice
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
Which unity errors are you talking about?
lucky yours keeps running, as soon as i ge tthe recursive mine locks up until i ctrl + alt + del it
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
not sure, the second it happens everything stops and can't debug it
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
unless you mean the default systems, i haven't added a single one and it happens
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
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?
basically stop thinking the way you think about programming
You have to split everything up to its smallest denominator and systemize it
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?
You could go about doing a IwasBornat component that stores their time of birth and compare to Time.time for your calculations
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. ...
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...
@onyx mist
For practical cases I normally look at https://www.youtube.com/watch?v=mL4qrt-15TE&t https://www.youtube.com/watch?v=ILfUuBLfzGI&list=PLzDRvYVwl53s40yP5RQXitbT--IRcHqba
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...
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...
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
basically top's theory, bottom is practice
Gotcha
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
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
@gritty grail you shouldnt be using the Proxy components, the conversion workflow is the recommended way to use ecs whether its hybrid or pure
proxy components?
ie TranslationProxy, RotationProxy, CopyTransformToGameObjectProxy
they are deprecated
Do you have docs or video reference of the alternative?
the entities samples repo shows the basics of it
something like https://pastebin.com/2rg1NUw1
Is there any way to see a full list of IComponentData components that Unity already implements?
how are you moving your player currently?
the transform system has a lot of well transform stuff https://docs.unity3d.com/Packages/com.unity.entities@0.0/manual/transform_system.html
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
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
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
But will this work for making the camera move without the proxy?
have you used any of the conversion stuff yet?
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);
}
}```
so id make something very similar for your player, so the camera system can find it
Well all of this stuff is an information overload so I might have to try to get back to it later
yeah just play around with something smaller
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.
@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
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
Has anyone heard anything about the new DOTS release lately?
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.
So what are you working with atm? Are you using quads for 2d representation?
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)
I guess you'll have to do an external conversion instead of a cast
basically not sure how convert the native array to Color[]
(I come from C++ land, so C# is making my brain hurt)
you can have a method that returns a color given a Texel Data
would that be performant? I want to avoid doing a per-element conversion if possible
https://docs.microsoft.com/dotnet/csharp/language-reference/operators/user-defined-conversion-operators maybe this is worth a read?
Uh, maybe in english? The change language option can be found at the bottom of the page, look for the globe icon
thanks. ๐
I personally just take out the localization tags in the hyperlink
Looks like that indeed works
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
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.
- there are various safety checks, leak detection etc that can be disabled in the jobs menu
- 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
- 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
Oh, okay, I thought it was the standard way
I also disabled the leak checks, debugging and other stuff and it did increase
With all that stuff down, it runs at around 450 FPS, 500 sometimes
however, with monobehaviour, it runs at 600 :s
profile in a build and check
How can I display the FPS on a build?
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
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
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
Tried spawning 6000 entities and got around 30 FPS. I'll make a small script to spawn 6000 GameObjects and see what I get
hmm that is very low even for a lowend cpu
I'm running an I3 3110m
might be gpu bound if you're rendering the ships
which is another reason to use milliseconds from the profiler vs just fps
also, with just 6 entites/objects, the frametime is 2.5 with entities, while 1.6 with monobehaviors
Tried spawning 6000 entities and got around 30 FPS
6000 per frame i hope ๐
hard to say where your performance is going without looking at the profiler
No, 6000 at Awake
just changing a single float3 like in your movementsystem, especially with burst + jobs should be able to handle 6000 easy
Okay, I spawned 6000 MonoBehaviour objects and got around 30 FPS as well. Frametime is at 25 ms
4 components - RenderMesh, Translation, LocalToWorld and Movement (custom component with a single float, named speed)
custom component is IComponentData?
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
do your entitles use the same RenderMesh?
Hi! I've got this script that generates a custom quad for me to plaster an image to but it seems that it only works well when the images only matches the global ppu. Code's here https://hatebin.com/eqjeshyeyq and here's a demonstration of current behaviour https://cdn.discordapp.com/attachments/497874004401586176/636979551834210304/asdf.gif
the grey shadows are just compression artifacts
ppu is a sprite importer setting isnt it
yeah, I have a variable called internal ppu set to 32 atm
works well when generating 1 unit quads but not anywhere else
@dry dune yes, the custom component is an IComponentData
I'll take a pics of the profiler/s
huh doesn't Sprite already generate a mesh you can use
or mesh dimensions at least
not for entities if i recall
but you're converting from a Sprite right
yeah, it's a sprite renderer
should be able to grab the mesh dimensions from the spriterenderer's sprite
ok, will try
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
@hollow sorrel just saw it, sprite doesnt have an intrinsic mesh component but it does have all the subparts
the default unlit materials don't feature GPU Instancing
use URP
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
@hollow sorrel I'd love to see your implementation, my brain's to puffy for today
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
well, I think you'd only gain a performance in setting the position/scale because adding components would need an ECB
yes 500 ecb commands per frame here
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
barely running > crashing
exactly
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.
I'm sorry, can you space out your message?
@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
What is the best way to destroy entity with all its childrens?
entities dont have children, are you talking about components?
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.
is NativeDisableParallelForRestriction necessary on ReadOnly fields?
I think not disable parallel is done so you can modify something outside the jobs entity
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
Thought it was modifying data outside the entity's job
nope.
To rephrase [ReadOnly, NativeDisableParallelForRestriction] - the NativeDisableParallelForRestriction would be pointless right? No performance gain or anything?
I believe so.. yeah
thanks
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
How should I go to send information back and forth from the ECS sytem and monobehaviors?
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
yeah..there is no "nice" way of doing it..
ideally they are not supposed to be passing information to each other
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
@hollow sorrel I usually use a sharedcomponentdata which has reference to the ui and make an updateui call manually from a ComponentSystem itself.
and your ui has references to all the ui pieces that need to update?
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. ๐
Does entityManager.DestroyEntity(entity); get rid of the components attached to that entity?
SystemStateComponents do not get removed.. normal components will be removed.
@deft niche Thank you so much. What is the correct way to remove SystemStateComponents. Feel free to just link me to the right direction
Yeah just found that. Sometimes googling ecs stuff can be tricky ish
yeah...
takes a bit of time
Those components are usually used as like notifications/events for something to happen..
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
interesting.. not dabbled with the ecs physics yet..
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#
Ohh wow.. yeah..working with pointers can always get weird in C#.
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 How do you destroy them. When I use EntityManager.destroyEntity they are still there
Same if I use EntityManager.RemoveComponent<PhysicsCollider>
strange, i really dont do anything special compared to other entities
can you destroy a regular entity or remove a different component without problems?
Everything about them disapears in the scene but my raycaster still collides with them after they are gone
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
just trying to help you embrace the dod
get all the benefits of that juicy jobified bursted code!
@ 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
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
have you experienced any heavy semaphore wait issues in your project @low tangle ?
None that wasn't just me making my life harder than it needed to be
Something happen to yours?
i do get strange hitches, pertaining to using transforms & CopyTransformToGameObject
Interesting
I didn't trust that system
Was getting weird results
So I cloned it and made a single component it ran on
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
Hm it's heavy ms but not really hitchy for me
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
Oh interesting
I'll profile mine tomorrow and see if I have one
Want me to ping you?
I'm heading to sleep is what I mean
oh, sure yeah

look at the performance of this one system, its hideous! https://gfycat.com/hiddenfocusedgreatdane
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;```
what's going on with that xform system @safe lintel lol
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);
});
}
}
}
hmm wow it's pretty simple
i do modify the localtoworld quite a bit via other systems, but this seems like a very uncharacteristic result
yea it's something I honestly wouldnt expect
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 ๐ฆ
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
are you using hybrid at all? any chance of mixing the two?
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
yeah they are, but it might be a little confusing when it uses conversion
i made a simple gif, all i call is DestroyEntity https://gfycat.com/feistyunfoldediguanodon
but can you tell me more about how you setup your colliders?
whats the converttoentity look like, destroy or inject?
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
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
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
could you get a before and after screenshot of what happens?
nothing better than waking up served a plate of code for breakfast
๐
@safe lintel why are you doing that on the main thread
throw that shit into a job and burst compile that shit
uh what setting the transform?
i dont think the job code would really effect it, but you mean to use TransformAccessArray to jobify it?
well thing is if I disable that system and use the built in copy system, that gets the same WaitForSignal delay issues
Is dots production ready?
Out of preview?
I've got no wait for signals in mine that see yet
@gusty comet not till next year
That doesn't sound that long.
I believe there aren't tons of tutorials yet.
Time to have fun with documemtations.
check out the pinned message here
same problem with the builtin system, https://gfycat.com/snoopyboilingcoyote anyway i took the time to report it, hoping its a builtin problem and not something to do with my usage
its like directly correlated to the amount of enemies that are in scene(gameobject based)
yeah number of transforms
Oof
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?
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.
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
I dont remember if regular dictionaries in C# allow multi threaded access ๐ค
I know there's a concurrent dict in C# systems lib
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
Ah cool
Hey guys, does someone know where these errors come from / how to move the player?
https://forum.unity.com/threads/dealing-with-non-custom-components.763559/#post-5100923
@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.
@tawdry tree this wasn't for me right =?
Err, no, lemme edit that to clarify
sorry ๐
Hello Everyone!
Can anyone show me how to use UdpNetworkDriver in parallel Jobs correctly ?
Code here + Errors
https://justpaste.it/7l0ej
Thanks in Advance!
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.
thanks @tawdry tree ill try it let you know
I've forgot but you cant use a simple array in a IComponentdata can you? you have to use a Dyamicbuffer is that right
yes
although fholm made https://github.com/fholm/UnsafeCollections for the intention of putting arrays in componentdata
or at least i think that was the main intention
cool thanks
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
@safe lintel yes, and I removed the fixedDeltaTime. Now the player is moving.
not sure why you have the burst error though
well thanks tho ๐
Recomendations for what unity versions to use with DOTS?
probably 19.3
Hello, has someone experience with EntityManagerExtensions class? There is a method "Instantiate" and it does nothing, someone know how to use it?
Judging by the name, that class probably extends EntityManager (adds extra methods)
.NET docs on extension method: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods
Not sure what you mean by does nothing, though. Can you not see any code? No effects of calling it? Or something else?
I am calling it, I am debugging it, but the created entites are empty.
Do you have have any IDE open?
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?
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
Oof, that's an old forum post
https://github.com/Unity-Technologies/EntityComponentSystemSamples/tree/master/ECSSamples/Assets/HelloCube I suggest trying a couple of the Hello Cube samples to get started, if you haven't.
๐ฆ
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
ok, what are conversion workflow components
Do you have the hybrid renderer package, for example?
the convert to entity component?
That's one
are there more?
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.
I already tried it with convert to entity component attached, not the expected result
Do you have the hybrid renderer package,
yes
And you are unable to make a gameobject in the world convert to an entity on play?
This is how I call it
This is from Unity
This is the result
Gameobject is a prefab with default Unity Components, no convert to entity, but it also makes no difference
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?
Yes I can convert but only if the object exists in the scene
I want to reference the prefab and create it that way
Right. Next question then is, why do you insist on spawning from a prefab, directly?
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?
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.
I try, but I will ask on Unity Forum, if this supposed to be used that way
I think it does essentially what you want to do, and what I'm talking about here
The difference is, object in scene or Object as prefab
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);
}
}
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)
wow ๐ฒ it works
That monobehaviour could very well create an entity with something like:
public struct MyPrefabComponent : IComponent {
public Entity Prefab;
}
I think EntityManagerExtensions is a dead end
And then you could access the entity prefab from any system after that. A bit cumbersome, but...
Thank you very much, I didn't saw the ConvertGameObjectHierarchy method
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
Thank you, I will do
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.
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?
i have a question about conversion as well https://forum.unity.com/threads/what-is-the-right-way-to-fine-tune-gameobject-conversion.767654/
@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)
@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
@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)
@glad solar I don't think you can do that in a job thread, no, but the system can.
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?
There are people doing production stuff with it
oh great... thnx!
so, i need DOTS basic package, windows package, Entities, MAthemtics and ... BURST compiler right?
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
well i will be using jobs and burst anyways, so using those either ways
so only DOTS basic package and windows package remains
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
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?
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
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
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. ...
oh yea. already saw that... already in love with DOTs and i wanna forget all about OOP :p
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
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)
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.
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.
If you could explain your goal, and what data you have, I could maybe point you in the right direction?
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;
}
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
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...
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
Data-Oriented Design
this is about data-oriented design without really going into ECS, but similar-ish
will probably give you ideas
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)
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
And entities are just the way you translate the output of systems into the "physical world"
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?
hmm. The player can directly interact with.
just found a cool picture
https://docs.unity3d.com/Packages/com.unity.tiny@0.15/manual/images/ECS_Infographic_EN.jpg
Tl;dr ECS is hovercars
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?
In Unity
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.
Physics is installed
I am checking the ecs physics example right now, maybe I find the answer there
Seems to be needed to be part of the simulation
Wait, your CHILD component has physics?
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?
Actually I just dropped a capsule collider into the gameobject and tested how it will behave
Does it work with physics only on the parent?
yes it does
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... ๐
thats right, but I though it would behave like a regular game object
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.
@gusty saffron Nope. There is no way to access sharedcomponentdata in a job
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?
You can use RuntimeInitiazeOnLoadMethod
Or the player loops
Player loops are out of experimental in 2019.3
Can't you send SharedComponentData into a job when you schedule it though?
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
@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
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
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?
i think creating systems is still the same
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
Does anyone know when the new entities package is going to come out ?
It was supposed to come out like 2 weeks ago ๐
i feel as if i will have aged significantly between releases this time
World.Active.GetOrCreateSystem<ProjectileSystem>();
can anyone tell me why this does not create the system anymore?
Are you sure it does not, in fact, create or get the system?
Grab the reference it returns and breakpoint it
Gonna need a bit more info than that @little tartan
The system will probably not run if there's nothing it can act on
Any "RequiredForUpdates" for that system to run ?
What do you see if you
void MakeSystem(){
var sys = World.Active.GetOrCreateSystem<ProjectileSystem>();
* Debug.Log(sys.ToString()); //* is breakpoint
}
are you sure HandleWorkerConnectionEstablished() gets called
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?
Seems like your system has no entities to work on..
@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
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?
it operates on projectiles so there will be none at the point where it's being created
Does the system work if you spawn some of those?
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
should
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
I'm just throwing out ideas to eliminate possibilities
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
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
}
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 >_<
๐คท Such is life with preview and WIP packages
thanks alot for the help mate!
No prob. Sometimes you gotta break down your objective, and occasionally you should stop doing the best practice and do something that works instead.
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()
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?
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.
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
plus idk how i feel about having tons of lookup tables, maybe it is worth using something like https://github.com/Cysharp/MasterMemory ?
and basically fill up the database at startup with all the immutable data
I'd put it in a blob for the sprites since its looks like you want to just read them
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.
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
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
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.)
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
use the [UpdateBefore] attribute. More details: https://docs.unity3d.com/Packages/com.unity.entities@0.1/manual/system_update_order.html
You can also define your own groups (derive a class from ComponentSystemGroup)
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
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)
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);
}```
make a new buffer element and then add the element to the buffer
it should be dstManager.AddBuffer
var bufferelement = new WayPointConnection{Connections = diddle.position}; tempbuff.Add(bufferelement);
doh! I always forget about the 'new' keyword thing thanks guys
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
Hmm let me look at my project to see if it generates gc
how do you check if it does generate gc anyway?
profiler
@safe lintel looks like it generates gc for me too ๐ค dunno if it will be cleaned up later down the road though
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!
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
@quaint zealot sorry to ping you but any word on when the new entities package is arriving?
also thanks for the gc alloc info
@rugged wagon Ive mainly used a do while loop to get the elements
Good to know I'm not doing anything too suboptimal, thanks
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
(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 ๐
@rugged wagon I think there is a .ToKeysArray()
@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
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!
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
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?
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 ?
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
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 ๐ค
Hi, I wanted to share these snippets I made for Visual Studio Code (in case it's of any use to someone) for some of the most common things that you usually end up writing when working with ComponentSystem (I'll keep adding more and including Jobs also): https://marketplace.visualstudio.com/items?itemName=diegosarmentero.unity-dots-snippets
@onyx mist You need to type that inside a method (like Update or OnCreate) or else the autocompletion won't find it
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.
@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'))
hello any idea how do I accomplish a thing like iterating over some entity query inside a IJobForEach?
@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
@safe lintel thanks for the answer but can I access a component data and change it there or just read it?
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]
Thank you
@rugged wagon you could potentially write your own iterator with some performance improvements. I havenโt worked with the multi version but hereโs an example for hashmap that is significantly faster https://gist.github.com/jeffvella/8ac73ba00552998b66140a886646a234 (though also more dangerous)
Thanks, I'll check it out @mint iron
I'm already fully down the dangerous rabbit hole with my current project haha
Guys any clues on how do I get a EntityCommandBuffer inside a Job to use?
|| @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);
How do I get a barrier system?
World.Active.GetOrCreateSystem
@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?
The code looks like that: https://hastebin.com/fusozaguvo.cs
and the line modyfing the value is 17th
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
So should I get a NativeArray<Entity> outside a job and use GetComponentDataFromEntity inside a job?
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>
No idea how to use it in this context
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
});
...
}
}
}
Thanks very much
@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;
Can you post the full job code?
I did everything as in your first example
you need to do ```
var x = movables[movableEntities[i]]
x.hitPoints -= 1;
movables[movableEntities[i]] = x
thnx @safe lintel ๐
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)
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
what does that change
@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
Yeah I think so too
But thanks to you both @safe lintel & @coarse turtle , Jobs and ECS are a struggle to me ;)
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
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.
Hey guys,
I've created a sample project using ECS to query the navmesh and moving 100,000 entities at the same time. I'm getting around 40-50 fps with...
Hello Guys,
i want to use the NagAgents in ECS therefore i used this github: https://github.com/zulfajuniadi/unity-ecs-navmesh
The Problem is that i...
There's a few things not natively supported in ECS: AI/Navigation is one of them.
SkinnedMeshes and animation as well.
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.
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
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 thank you,i didnt know why i not saw that uff
I dont suppose anyone knows if you can view a blobdata in the debugger or wherever?
Any news on the Hybrid Renderer being updated? I keep hearing any day now for the past 3 weeks lol
@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
figured thanks, its difficult to figure whether I'm doing things right without being able to view them
Donโt suppose thereโs been a new Entities package recently?
Is there some kind of equivalent to ComponentDataFromEntity, but with DynamicBuffers?
Want a chellenge in ECS / Jobs ? Come help me on the forum: https://forum.unity.com/threads/factory-grid-movement.769628/ . Much appreciated ๐
@solemn ice BufferFromEntity
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
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)
anyone know anything about nav system being updated for ecs?
You have a link to the forum up in the chat that discuss that
Response was, they will start with it on 2020
oh, didn't see that one, thanks!
@safe lintel How the hell did I miss this? Thanks!
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?
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
I'm not really interested in NetCode sample itself, I need functions that allow me to do my own stuff
well for example I've been trying to figure out this project https://github.com/Unity-Technologies/unite2019-scenedatatodots
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
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
i dont like why there are so many functions converting objects to entity... which one to choose
It's from unity
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
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>
are you trying to use them in a component
in a job
you cant have a nested nativearray
For example.. if i don't know what the size of that NativeArray is going to be in the list..
aargh...
you need to flatten the array unfortunately
yeah.. i did that for other things... i guess i will have to figure out a way for this situation as well.
theres a forum thread regarding 2d/3d arrays though could help out https://forum.unity.com/threads/how-to-solve-the-2d-or-3d-sub-array-algorithm-problem-with-dots.764114/
@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
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?
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
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!
Np ๐
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
@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.
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 :)
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
@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)
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?
@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 this can give you some ideas: https://youtu.be/BNMrevfB6Q0
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
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
Yes, I use pure ecs with the mesh renderer
if you want an Example of pure ecs and 3D objects you can check this: https://github.com/Unity-Technologies/EntityComponentSystemSamples
The Advanced example
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
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
CopyTo / CopyFrom ?
there's .asArray and .toArray as well I don't know if they would work
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>();
you can create a NativeArray with Allocator.Persistent in OnCreate function, dispose it in OnDestroy
right - so then use an IJobForEach instead of an entity query to fill the array?
just use allocator persistent instead of tempjob
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
No clue, they might release more information next week
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...};" ?
@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
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
What's your initialization like?
public readonly static Hash = new NativeArray<int>{
1,
2,
4,
8
//ETC. Standard collection initializer
};
@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
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:
- 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()
- 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.
@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
You can try passing the static readonly native array into the job via assignments
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
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
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
i posted about it in the forums here https://forum.unity.com/threads/cannot-get-unite-convert-nodes-project-to-work-in-my-own.770630/#post-5131424
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 ๐
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
ok thank you!
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
Hello, could it be that ECS Physics don't know Rigidbody constraints yet? Like Freeze Position?
@digital scarab thnx
Warning: Using EntityManager.SetName will cause build errors, because the SetName method is in Unity_Editor Preprocessor directives
so that's why I was getting weird errors with setname
Donโt suppose the new entities package is supposed to drop any time soon? ๐ฃ
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)
@digital scarab no pressure just excited for the new stuff
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
yeah it would be great to get more info about how some of this entity stuff works
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?
there was a project in the forums I saw
Looks like it will help lots from what I can see
yeah sounds great
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?
I guess the less boilerplate stuff is incremental?
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
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.
Keep up the good work ๐
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...
I expect with programming its hard to come up with and stick to fixed dates though
It always is
Not just programming, really, any slightly complex project has unknowns
like I've just found out I have to redo and start over on my project basically
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
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
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.
Will the warning about using [DisableAutoCreation] on abstract ComponentSystems finally be fixed in the next version? Its been around for a while
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 ๐ค
I wouldn't do it in a job to be honest
whys that? just too complex?
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)
ok then it probably is best in a job
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?
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
Alright thanks ya'll!
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();
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
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?
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?
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.
@glad solar yeah nativearrays dont work in Icomponentdatas
Calabi, is there a workaround for this?
I mean, it is easier to work with data instead of a bunch entities per position.
@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
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.
I would have thought it would be easier, entity's have plenty of ways to iterate through them
@prisma anchor you have to add it manually
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.
if the scale is like 1, 0, 1 - I believe it gets added automatically as its not uniform
@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());
}
}```
the TransformConversion adds it if the transform localScale != Vector3.one
ah ok
@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
@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.
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
Completely agree.
It would do wonders for many cases.
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
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?
@vagrant surge do you have a link to this talk? Sounds interesting
In this 2017 GDC session, Blizzard's Timothy Ford explains how Overwatch uses the Entity Component System (ECS) architecture to create a rich variety of laye...
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
@glad solar https://github.com/fholm/UnsafeCollections
@vagrant surge tbh I prefer the overwatch type of ecs
Yeah you give up some performance, absolutely
thats Entitas
Well, sure... but no thanks :p haha
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
Yeah
i think unity should definitely allow for storing managed references in components
Just feels like a bit too much was sacrificed on the altar of performance sometimes
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
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. ๐ก
There is a job for Physics.Raycast, the RaycastCommand
is tehre anything like that for OverlapCapsule?
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?
@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?
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
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/
can I use Debug.Log from a job? doesn't seem to like it very much
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
how do i refresh the entity debugger? it keeps saying that the number of entities is the starting amount, even though thousands have perished
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?
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!
oh hrm, didn't think about using multiple foreach
you can. But i don't know if it is the best practice
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"
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
hmm... and a separated system responsible to act upon that action.
i like it! thank you so much for sharing your knowledge.
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
it's much better. more ahead in development the work for balances issues won't be much if doing like this. impov
@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
dont you think 13.000.000 is going a bit too far?
ecs aint magic, thats still extreme