#archived-dots
1 messages · Page 90 of 1
thx!
you should benchmark in your own project though, it depends on a lot of variables like system count, frequency etc.
Yeah, saw this talk that really focused on relations frecuency and cost in ecs
Does any1 know how to fix problem with Hybrid Renderer and HDRP 7.1.2 in Unity 2019.3.0b ?
Hi all.
I'm misusing an array somehow but I'm not entirely sure how. The error in the console is:
ReadWriteBuffers are restricted to only read & write the element at the job index. You can use double buffering strategies to avoid race conditions due to reading & writing in parallel to the same elements from a job.
and this is referring to the "float3 checkAtomPosition" line below, where the AtomDataArray is a persistent NativeArray<float4> calculated elsewhere and used here only as a lookup reference.
private byte CheckTestVector(float3 testVector, int atomIndex)
{
for (int i = 0; i < AtomDataArray.Length; i++)
{
if (i == atomIndex)
continue;
float3 checkAtomPosition = new float3(AtomDataArray[i].x, AtomDataArray[i].y, AtomDataArray[i].z);
float checkSqDist = ((AtomDataArray[i].w * 0.5f) + SpawnPointSphereCollisionCheckRadius) * ((AtomDataArray[i].w * 0.5f) + SpawnPointSphereCollisionCheckRadius);
if (math.distancesq(testVector, checkAtomPosition) < checkSqDist)
return 0;
}
return 1;
}```
whats the atomdataarray declared as?
wheres it grabbed in the chunk/entity as well
hm nativearray
sub range makes me think of the index passed to the job
yes sorry incomplete data, I'll post the class 1 sec
It's not refactored yet, apologies for the sprawl
no worries, I'll give it a good shot but I've gotta sleep very soon
math.normalize(gridPosition - translation.Value);
are you sure your key is normalized?
if so, does normalizesafe change the outcome?
else
testVectors[flatIndex] = float3.zero;
the else condition might be out of range maybe?
makes me wonder if the native array is getting passed in short or empty possibly? or do you always fill it to full?
oh intresting
int atomIndex = index;
I can use normalisesafe for the possibility that an atom position overlaps with a grid position - that doesn't fix the problem though. I think it's to do with the way I'm setting up the job as a foreach with entity
the job index is the thread index / index into the chunk based on the archtype of said chunk
ahh, okay so the index in the foreach with entity isn't going to overlap with the array's index
I want to exclude "this" atom from the collision check
where can you find its index?
or its key
is it the float3 position?
you got the translation right there handy
no, it's the index of the atom within the AtomDataArray NativeArray
ah will have to scan for it then, for the array, do a compare till you find it
hmm might be faster to add a component containing that data then
okay I'll give that a shot, thank you again @low tangle !
Cheers 🙂
Mmm that doesn't seem to work, it's weird it's like it's limiting my ability to step through the whole of the the AtomDataArray. I'll try it via the translation.Value
CreateChunk() takes a NativeArray<ArchetypeChunk> and an int for entityCount. The documentation says it creates enough chunks to hold the entityCount number of entities, but what if the number of created chunks is less then or greater than the length of the NativeArray? If less than, what tells you how many were created?
hm
not sure on that one brian
@wary anchor I would look into the source array, just skimmed the rest and I see no glaring issues atomGridUpdateSystem.AtomDataArray
The docs also sorta suggest that the chunks are always new rather than ever using any existing chunks, but it's not unambiguous about that.
does the chunks have a .IsCreated maybe? @old pulsar
chunks and entities inside them is a pretty even 1:1 relationship of the size of the archtype
Mmmm It's odd. I use that array as a reference in several places without issue, but this is the first time I'm stepping through the whole thing within a job for each with entity for each of a bunch of different vectors.
ArchetypeChunk has no such member. I'm just curious about this reading the docs, though. I have no concrete use case. Thanks
I'm seeing 4 such messages, and I reckon this input file probably has 4 different atom types, so they'll be made in 4 different chunks
Mmmmm I don't think these should be separate chunks at all
Food for thought, I won't keep you more from sleep, thank you @low tangle
I dont suppose anyone knows how you get a reference to a blobasset inside a job without using a foreach?
I can get the values in the blob asset fine outside the job(so it seems)
I've tried everything I can think of inside the job but I just get garbage data
@pliant pike did you grab by reference to the BlobAssetReference's data?
yep I used ref var tempblob = ref blobbarray
I've tried that every way I can think of inside and out
hmm I might have an example in my current project...or I might've nuked it a while back when I was refactoring my client code
let me take a look
I'm getting the blob with getsingleton so I don't know if that maybe effects it in some way
This is a bit old, might have to update it but this is all I did b/c I was lazy and short handed things. But judging from Unite vids, you can likely do ref ComponentData.BlobAsset.Value.Ptr
BlobAssetReference looks like they use relative addressing
I think they mentioned blobs work by an offset or something
Yea, its to allow read speed ups
so you pass around the root address and the refs allow for relative addresses
I'll play around with it sometime today, I haven't touched blobs lately after my first set up
I cant seem to get it to work, this is my blob data anyway
public struct WaypointBlobs
{
public BlobArray<float3> Waypoints;
public static BlobAssetReference<WaypointBlobs> ConstructBlobdata(Translation[] Waypointgameobjects)
{
using (var builder = new BlobBuilder(Allocator.Temp))
{
ref var root = ref builder.ConstructRoot<WaypointBlobs>();
var nodearray = builder.Allocate(ref root.Waypoints, Waypointgameobjects.Length);
for (int i = 0; i < Waypointgameobjects.Length; i++)
{
var tempawapp = Waypointgameobjects[i];
nodearray[i] = tempawapp.Value;
}
return builder.CreateBlobAssetReference<WaypointBlobs>(Allocator.Persistent);
}
}
}
public struct WaypointWalker : IComponentData
{
public BlobAssetReference<WaypointBlobs> Waypoints;
}```
I'm getting the waypoints from converted gameobjects
Uhh for now lazy hand it and try
public struct WaypointWalker : IComponentData
{
public BlobAssetReference<WaypointBlobs> Waypoints;
// See if you can grab the data like so in a job since you have the root ptr
// stored in the BlobAssetReference, this could be a function too
public float3 this[int i] => WayPoints.Value.WayPoints[i];
}
yeah thanks, I think I may have the answer from the forums
I was getting the blob array like this waypoints = dudewalker.waypoints.value.waypoints
when it should probably just be waypoints = dudewalker
ah cool, lmk how it works 👍
Going to get back to doing some more dots stuff hopefully this week
Does any1 know how to fix problem with Hybrid Renderer and HDRP 7.1.2 in Unity 2019.3.0b ?
yes
but I also answered on the forums, you have to fix it manually
if you really want to go down that path, there are two options: update Hybrid itself to the newer API
or roll the 7.1.2's api to the older setup for the parts that hybrid uses
I haven't checked recent changes but like few weeks back, you only had to revert one git commit to roll back the related HDRP API changes
that being said, i'm sure Unity will fix this once 2019.3 releases as they need these all to play ball together with the dots shooter sample
@dull copper Thank you!
Has anyone worked on an Entity construction pipeline?
as in an editor extension that lets you compose entities from existing IComponentData types?
thats how current conversion works
@stable fog
you have an IComponentData with [generate authoring], and it shows in the editor
when you have it inside a subscene, then it will convert whenever you change the components
O.o
it sorta sounded like someone managed to do that with odininspector but there werent any details of it in their post
wait is that available now @vagrant surge ?
oh
ah, so not how the current version works
yeah been twiddling my thumbs waiting for that too 🙂
So basically they willl act like MonoBehaviours inside the editor, in terms of how you compose things?
Maybe I shouldn't waste my time building this editor to compose entities then
yes
I mean, It may still be useful for my needs
it looks like a monobehavior, but its an authoring component
on conversion it becomes i component data
you can also preview what entity will get generated
And all you have to do is write the IComponentData and decorate it with an attribute?
yes
at the moment you need to do the authoring component yourself wich is annoying
ah neat, then It may still be worth while to continue down the path I am
but next update is just ananotation
been working on a thing to just build it in a single behaviour
hey is there any good tutorial for ecs that's in the context of making actual gameplay
I'm not good at learning with just abstract concepts rather than actual examples
there's not really many tutorials that are current and up to date
oof
that youtuber has some good vids on it though
will check them out thanks
also there's this project that was posted in the forums recently
yeah I like programming in dots it feels much better than oop
it looks like it has a proper, imposed structure which is why I'm interested
also multiple active scene in one instance of your game
(At least) one of the Unite talk basically makes a tiny prototype of a game, but it blazes over things. I would suggest starting at the more abstract concepts, just going over them, then finding one of the sadly few tutorials out there. Sadly I don't have any links to contribute there.
the structure part is a very big deal
its super rigid, but it also means your game becomes a "main loop" that you can trivially check
I don't mind rigid
in fact I think it's good since I don't have to figure out what's the best structure for my various systems and then try to stick to that structure
yeah that was one of my main struggling points with oop
what do I define as an object, in an data exchange, where do I put the code that exchanges data between two objects, either one, or do I create a new one for the exchange
looking at that zombie dots game and it's more in line with what I was looking for
interesting
I found a pretty nice tutorial the other day
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...
these two were the ones that finally got me over the hump
Learn how to get started working with the Unity Job System to run super fast code! ✅ Get the Project files and Utilities at https://unitycodemonkey.com/video...
oh you linked code monkey, my bad
Yeah I'll check his stuff out when I have the time
no worries we definitely know they are good ones then 😄
My entity conversions never seem to work properly in a built game - if I drop a cube down, scale it up, make a subscene out of it and play, it remains that size. Then if I build the game it either doesnt show, or its off by some metres and significantly smaller.
Though funny enough some things like a player controller worked, so I created a new universal RP project with the latest beta, grabbed entities & hybrid renderer and dropped down a cube, same issue.
maybe the entity conversion isn't complete yet, like I know you need the nonuniformscale or uniformscale component for object scaling to work in dots
idk, I noticed it first happening when I decided to try the classic 300 rotating cubes in my otherwise fine ECS project. Was just a convert to entity script with a prefab conversion as the github repo has, but they wouldn't appear at all in the build.
I'll see if the uniform scaling works
but you'd think it wouldn't work in playmode right?
I wonder is it possible for them to check all the changes you can make to an object and have them fully converted into the entity 🤔
I mean it might be difficult for them
honestly i just want something to work at this point 😩
I would just add a scale component in the conversion and just set it in there to what I wanted to be honest
ahhh it still doesn't work
I put a scale component onto the cubes in the system which definitely worked in playmode, had a good 20 thicc cubes
But the built game is devoid of cubes
whats the code
https://pastebin.com/TJqHGJY5 - Authoring
https://pastebin.com/nr8Kz9gv - SpawnerSystem
https://pastebin.com/AfaC04Hb - CubeSystem
Authoring sits on an otherwise empty game object inside a subscene
it's a fair bit of boilerplate hence the pastebin, sry
it's basically the exact same code as found in the pinned github repo examples in this channel
HelloCube
I meant just on the specific where you added the component
second link
code seems ok, sorry I dont know then, it's weird that the build is different to play mode
yeah :c mystery
I'll drop a post on the unity forums if I don't figure it out, but thanks for checking the code out
@gusty comet Are you building il2cpp?
Isn't all of job systems code handled with reflection? So it wouldn't be referenced and therefore stripped?
its not me its @gusty comet
Right!
Fixed 🙂 regardless that could be why.
I've not tried to build anything with DOTS and il2cpp yet. So I can't say for certain.
the code isn't in a job though
Im using mono :v
my running theory is it's the scriptable render pipeline and hybrid renderer not playing correctly
because the entities ARE converting, when i build the game I can run around, which is handled by a job system
yeah must be some kind of render issue
def
@gusty comet there is a bug with builds at the moment, could be what you're experiencing https://forum.unity.com/threads/dots-hybrid-renderer-issue-all-transforms-are-reset-to-defaults-in-builds.757268/#post-5044190
i still get it in the builtin non srp renderer 🤷
unfiltered textures? 😋
Does anyone know if there is there a way to generate entities through code using DOTS and have them displayed or converted as game objects in the project hierarchy rather than solely in the entity debugger?
currently there's no way to do that afaik
I do agree that it's a bit cumbersome to do it through the entity debugger
How do I know which batch count to use when scheduling a job? Is there a way to figure out what value to use?
I know lots of work per Execute = low batch count, less work = high batch count
Is there any word of when next dots release will be out?
The stuff they showed at Copenhagen
They said that most stuff about copenhagen would be this week
new entities this week and dots fps in 3-4 weeks
anyone know a way to accurately time a section of code within a burst job?
is that even possible 🤔
I donno why I'm spending time on this entity composer, when supposedly we will have a better solution soon
I mean I would just do a timer in the onupdate either side of the job @mint iron and you could then set it return at that specific code in the job
oh that feeling when you wake up in the morning and the insane coding session you did the previous night still works fine
donno if I'm missing anything here, I have the ability to add 4 component types to a model and give that model a name, and at runtime I can create archetypes from the models
WTF is going on... Can someone explain this to me:
I have an entity buffer
[InternalBufferCapacity(8)]
public struct E : IBufferElementData{
public static implicit operator Entity(E e) { return e.Value; }
public static implicit operator E(Entity e) { return new E { Value = e }; }
public Entity Value;
}```
when I'm using it this way it works as expected
```cs
var a = EntityManager.CreateEntity( typeof( A ) );
var b = EntityManager.GetBuffer<E>( e );
b.Add( a );```
but when i'm using it like this i'm getting " The NativeArray has been deallocated" error
```cs
var b = EntityManager.GetBuffer<E>( e );
var a = EntityManager.CreateEntity( typeof( A ) );
b.Add( a );```
Yea timing sections within a job is tricky. I did some hacky thing where I passed key press 1-10 into the job and early out at various points so I could easily do runtime comparisons. Also did some of the benchmark test runner stuff which is good but I found it very hard to get highly repeatable results. Not sure if that’s partly due to cpu branch prediction or something for me.
@dry dune
var b = EntityManager.GetBuffer<E>( e );
var a = EntityManager.CreateEntity( typeof( A ) ); // creating an entity --> structural change happening, so chunks contents are moved
b.Add( a );
The first option work since you get the buffer after a structural change.
In the last option, the buffer will get deallocated since a structural change is happening (entity creation).
If you want the buffer to not be deallocated on a structural change, you can make it allocate outside of the chunks (by increasing the capacity...):
var buffer = EntityManager.GetBuffer<E>(e);
buffer.Reserve(buffer.Capacity + 1); // since we increase the capacity, the buffer will be allocated outside of the chunk
var a = EntityManager.CreateEntity((typeof(A));
buffer.Add(a); // no errors!
thank you this is great explanation
but buffer do not belong to chunk where i'm adding new entity, so no memory moving was involved 🤔
I think happening something kind of: sync point caused by creating new entity deallocates everything that had Allocator.Temp including array internally used by buffer.
i think sync invalidates everything everywhere.
public class TestSystem2 : ComponentSystem
{
public struct BufferData : IBufferElementData { }
protected override void OnUpdate()
{
var e = EntityManager.CreateEntity(typeof(BufferData));
var buffer = EntityManager.GetBuffer<BufferData>(e);
buffer.Reserve(buffer.Capacity + 1);
EntityManager.CreateEntity();
buffer.Add(default); // <---- error
}
}
@mint iron for timing a burst job, would the Profiler.Beginsample work? I'm also curious
Unless burst doesn't support it... 🤔
ill check Profiler.Beginsample.... [Edit] doesn't seem possible because it requires a string through to the internal calls and burst wont compile it.
I found something called ProfilerMarker which has a NativeDisableUnsafePtrRestriction on the pointer which means somebody has been intending to use it in jobs. https://hatebin.com/uadhwcnmqs
ah nice 👍
I get an error "InvalidCastException: Specified cast is not valid." when trying to inspect the entity. And i found trigger: it happens only when entity has attached physics body and physics shape of Unity Physics package.
Maybe one of you has encountered this problem and can help me
@frosty siren the inspector was broken with physics components on one of the earlier versions, i'm not sure if its fixed in newer versions because i haven't updated to latest yet. The bug was in versions before com.unity.properties-0.6.4-preview. But properties package is not something you can get from the PackageManager. What i did to fix it was download the package from the repo https://unity.bintray.com/unity/com.unity.properties/-/ and extracted it to my projects' /Packages folder and renamed it to com.unity.properties-0.6.4-preview - i believe it should detect the package appearing and remove it from your Library\PackageCache automatically. Back up all your stuff before trying.
@coarse turtle figured how how to use ProfilerMarker 😄
Oh sweet thnx @mint iron
its quite tricky to trick a burst job into doing work, its pretty good at knowing when it can just pre-compute the value.
its also a shame that the timing resolution on the profiler window is only 0.00 😦
yeah lol
I wonder if anyone doing this as well? 🙂
public abstract class Sys : ComponentSystem{
public EntityManager em => EntityManager;
public EntityCommandBuffer ecb => PostUpdateCommands;
}```
@mint iron are all this emotions mean yes?
hehe, maybe 🙂
I generally keep to microsofts naming conventions; i do have a bunch of abstract systems, mostly for events.
this one might bake your noodle. https://gist.github.com/jeffvella/495b0ce61c6e2fcfdf4b2b9665f22a54
mostly just playing around with different ideas, they don't always end up being more readable or efficient.
yes have few monstrous generic systems :)
private struct TweenJob<TSpecific>:IJobForEachWithEntity<Tweener<TSpecific,T>, Tween> where TSpecific:ITweenSpecificFunctions<TComponent,T>{ ... }```
😄 nice one
here's another interesting one https://gist.github.com/jeffvella/59ceddab394f2ab7842838228e919a0c
looks like this examples are parts of some event driven framework?
oh i got it this is GOAP
it uses a modified version of the events system by Timothy Raines https://github.com/tertle/com.bovinelabs.entities
so that particular example is used like this: https://gist.github.com/jeffvella/9a052c5a17137eed9c5d913db98eb81b
two different events with a buffer of elements that share an interface
Ah I always love drawing into the histogram 🙃
whats that?
I see that BuildPhysicsWorld dispose bodies and it causes errors if another system trying to read CollisionWorld. I wrote [UpdateAfter(typeof(BuildPhysicsWorld))] on top of my sys and it works. But is it ok?
Also thx @mint iron for explanation of broken properties, info is very helpful!
Ah so I made my own scriptable render pass and I found out Unity renders their ChunkInfo using the same functionalities to render their game/scene view lol
@coarse turtle I got same effect without any custom scriptable render passes
Yeah should just be through the Graphics CommandBuffer
I usually forget it happens so I typically find it amusing when it happens
Hello
Can you help me change a field's value from one structure to another script and then use it in another script
Struct script
public struct SpaceInvadersGameState
{
public const float projectileSpeed = 0.5f / 60f * 10f;
public float gameSpeed;
}
An other script
private void DefineGameSpeed(int dropDownIndex)
{
switch (dropDownIndex)
{
case 0:
SpaceInvadersGameState.gameSpeed = SpaceInvadersGameState.projectileSpeed * 1f;
break;
}
}
An other script
speed = Vector2.right * SpaceInvadersGameState.gameSpeed
hey so you need a ref to the struct if you want to modify the contents of said struct, likewise, not sure if this is DOTs oriented, but if it isn't there's a #💻┃code-beginner channel
this code do not look like dots at all )
Maybe it's just a little part)
yeah - I won't deny it - but yeah hopefully the ref tip helps 👍
np
So I'm writing a ECS Job for a projectile and I'm having a hard time understanding how to "Hit" another entity.
bool didHit;
Entity result = ProjectileSystem.Raycast(pos.Value, nextPosition, out didHit);
if (didHit)
{
//delete bullet
CommandBuffer.DestroyEntity(index, entity);
//hit enemy
//????
}```
I've got the other Entity that the projectile has hit, what's the right way to go about writing to it's health to hit it?
I believe using the EntityManager isn't an option if I want this to be Jobs friendly.
thinking from the top of my head, you could try using ComponentDataFromEntity<Health> since you've got the other entity you hit
you can use the ECB to update the other entities health, or directly modify/reassign the ComponentDataFromEntity<Health>()[otherEntity].Current - some_value (where ComponentDataFromEntity<Health>() is stored to a struct var)
i think you might have to disable some safety checks if you go for the latter option
I've got a ECB setup, which I'm using to destroy the bullet
Although I'm not sure how to use it to write.
There are add/remove calls for components, but that's not quite what I need.
ECB.SetComponent(otherEntity, new Health { ... });
So, there's 2 problems I ran into trying to use that
- Accessing that health, so I can modify it instead of just overriding its value.
- it asks for a
JobIndexand I'm not sure what that is
I believe the IJobForEachWithEntity's jobindex param might be enough from the interface
I've certainly done that without any issues so far
is that just the int next to the entity in the "Execute" method?
yea
Boy I wish Unity had some better and more centralized docs on this stuff.
I'll give that a swing, thank you for your help 🙏
Having 5 separate youtube videos from Unite conferences and outdated example projects does not feel like the right way to be learning this.
Oh, any idea on the "Accessing that health, so I can modify it instead of just overriding its value" bit?
typically if you have a reference/ptr to the Health - you can update its member variables
How would I get it though?
As i remember LTW automatically copying Translation values but CopyTanformFromGameObject writes directly to LTW. And to affect collider position with gameobject changes of position i need manually set Translation.Value from LTW.Position. Or i understand something wrong?
ComponentDataFromEntity<T> stores the reference (or ptr?) to the struct so you can modify its structure (depends if you make it readonly, i think it's read/write by default)
"Having 5 separate youtube videos from Unite conferences and outdated example projects does not feel like the right way to be learning this."
Yes, @quick jolt , i hope some day unity team will update documentation with all that stuff
Oh, I didn't realize what ComponentDataFromEntity<T> was
where is the [Inject] attribute to set that up? I'm not seeing it in the Unity.Entities namespace that documentation says it belongs to
Inject is deprecated
there's a pinned message which has the deprecation forum thread
You're a godsend psuong 🙏
I'd thank @dull copper for pinning it 🙂
so, from what I understand, right now if you want to convert prefabs into entities you have to write the code that does the conversion and spawning yourself, there isn't just a "InstantiateAsEntity" function or something
this manual cover most of things https://docs.unity3d.com/Packages/com.unity.entities@0.0/manual/index.html
thanks
@runic crystal yes, no magic, mesh renderer, transform and hierarchy are converter automatically, all custom components you have to convert yourself
kk
I imagine they'll eventually have either full automatic conversion or a proper entity prefab system?
full automatic is impossible, there going to be half-automatic soon
some info on conversion workflow future are here https://forum.unity.com/threads/701909/
thanks
@quick jolt @coarse turtle actually I had to let that thread go from the pinned message as i couldn't fit the rest anymore with it 🙂
but it's pinned on the dots subforums - which link is in the pinned here too
had i known this, i would have made two messages initially
I guess i still could, would just need to get it pinned again
I think the link to the forum is enough. I found it 🤗
Can you use the ECS Physics raycast to query non-ECS colliders?
@quick jolt I has checked this a moment ago and an answer is "no"
Or u meaning building your own physics world with non-ECS colliders data?
I think the answer is no then. /
You can do the latter though, right? Just GameObjectEntities
InvalidOperationException: The native container has been declared as [WriteOnly] in the job, but you are reading from it.
I'm getting this error on collisionWorld.CastRay(input, out rh); inside a IJobForEachWithEntity's Execute
Any thoughts?
I might have found it, it's that I was fetching the physics world inside the Job .
Is there anyway to use StartCoroutine in a system?
Looking at Entities.ForEach, it seems to do surprising things. As far as I can gather, it copies components and entity ids of the matching chunks into new arrays, passes them by ref into your lambda, and then writes back the component values to the actual chunk subarrays after each lambda call. ForEach allows you to make structural changes (like deleting entities) in the lamba, but I'm not sure how this avoids interfering with its iteration. However it's done, I assume it incurs overhead.
Am I misreading the code/docs? Seems very odd that we're trying to maximize performance but then the most convenient methods for accessing components involves a lot of copying rather than just direct access to the chunk subarrays. Are there good reasons to avoid direct access, or is it somehow impossible to provide a convenient API for doing so?
@gritty grail Think I saw a recent discussion of coroutines in the dots forum. End verdict is 1) you can use them 2) but not in jobs 3) and there are more proper dots solutions for the same problems.
@gritty grail If you're asking how to call the method, it's a monobehavior method, so you just need to get a ref to the relevant monobehavior object in the system, using GameObject.Find() or the like.
i remember something from a recent Unite presentation where they mentioned .ForEach (in the past) not being good to use generally, but that they were doing some specialcase optimization for it or such.
@wild dove I know they've said the lambda is somehow specially compiled to avoid producing garbage, but I don't recall which vid that was.
Exciting updates including Data-Oriented Tech Stack (DOTS), Unity Simulation, Scriptable Render Pipelines, multiplayer services, our new 2D tools, and much m...
I wonder if IJobForEach has the same problems. I assume IJobChunk does not.
https://forum.unity.com/threads/584248/#post-3896620
Joachim_Ante:
We recommend IJobProcessComponentData as the default way of writing ECS code.
a bit later IJobProcessComponentData was renamed to IJobForEach
seems like they want ForEach as a quick way to code things that mirrors IJobForEach, so later it should be easy to move that code into jobs for performance.
Also Entities.With().ForEach() should be changing with the next version so that it compiles a job underneath; they demo'd the code at unite copenhagen.
@old pulsar IJobForEach passes a refs directly to the component in chunk, IJobChunk lets you do the same as GetNativeArray<T> is mapped to the existing component array in chunk.
Has anyone had luck compiling DOTS to Linux or Windows?
Can't seem to get it to work even with the packages installed for platforms
me too, its so cool to get something similar in perf to C++ while keeping most of the things i like about using C#.
Is there a way to bind gameobject to entity from code?
You'd typically do EntityManager.AddComponentObject(entity, object)
thx
Now i can delete IConvertGameObjectToEntiy Mono after conversion and Instantiate new GO and entity apart and then bind them
Can i get gameobject which attached to entity from entity? I mean inside ForEach code
Now i just get Transform and then get gameobject from it. Looks dirty, want better solution)
Entities.ForEach(F_C_delegate), where F_C takes in a Component Object, you can look at the EntityQueryBuilder class for the other delegates you can use in a ForEach
C: ComponentObject
D: ComponentData
S: SharedComponentData
B: Buffer<IBufferElementData>
I think i've missed something. What are component objects?
Can't find any docs about it
They're just regular objects
Regular as C# objects or Unity objects
I believe they allow regular C# ones by default
So you can add a monobehaviour to an entity?
Yep
Although i know is not the best think to do
Damn that's gonna solve a lot of problems i had
wonder if the entities release has been delayed 😦
yea wondering that too 🤔
is there a math method that returns angle between two float3?
I'd expect them to target something closer to 2019.3 release at this point
I mean 2019.3 final was originally planned to get out at the end of this month
so realistically could expect something like few first weeks of November
is it not?
If I want a subtracted component for a job. Do I need to use EntityQuery? (solved; ExcludeComponent)
I suppose 2019.3.0b7 still has a large number of known issues, sadly a bug with SerializedReference isn't on it
having big list of known issues haven't stopped them from releasing in past 😄
lol
they mainly care of the critical issues when it comes to upcoming launch
I don't understand why that serializeReference bug isn't on the list, it really concerns me
makes me think they are not going to deal with it
there are tons of bugs they don't list on those notes
If you're not aware, if you have class which has an array of itself, and you have an array of that class, and you instantiate an element into the array, unity automatically populates the inner array with the outer array's first element, creating a circular reference and if you modify any other property on that instance, unity hard crashes
presumably because of some infinite loop/stack overflow in the editor
https://issuetracker.unity3d.com/issues/serializereference-crash-when-changing-a-shared-child-node vote here if you want serialize reference to work well!
To reproduce: 1. Create a new project and add the TestRef.cs Script. 2. Add the Script to a Scene and press Play 3. Expand the nodes...
How can I make JobA dependent on JobB which doesn't share any Components, but a HashMap?
Related, does Schedule(system, JobHandle) take the the EntityQuery and use it as dependency to the job?
And in that context, what happens if a Job that doesn't use ComponentA, use a query which says it should exist? Will it only create the dependency and still run, or will it add the requirement to run? 😛
is there a reason that using the jobhandles doesnt work for dependencies? also just from one anecdotal experience, was that when I had two jobs(jobA,jobB) where jobB was dependant on jobA, if the query for jobB wasnt met, jobA didnt run. ill be honest i just restructured things but didnt investigate it really so not sure if there are ways around it, that it was unintended behaviour or not
@slow epoch adding Object to Entity makes this Entity impossible to serialize using SerializeUtility and SerializeUtilityHybrid
When doing entity queries should I care about the ordering when using WithAll with WithNone
@gusty comet no, order doesn't mater
Hey, thanks!
hmm anyone had any issues with the URP and DOT's Hybrid Renderer? The issue I'm seeing right now is the rendered quad's position visually doesn't update, but the LocalToWorld matrix certainly did 🤔
I wonder if it's even been updated for URP name change 🤔
there's limited 2019.3 changes on hybrid atm
Ah okay nevermind, I found my issue, looks like the Experimental 2D Renderer in URP isn't compatible w/ DOTs as it forces an orthographic projection
Yeah haha
afaik, there will also be separate 2D renderer for tiny(?)
Hello! How would I go about moving this code https://hatebin.com/tijtecqfng to a jobs one? I cant seem to be able to access postUpdateCommands in one
but I doubt it be anywhere as complex as URP's 2D
Yea I imagined that would be the case and @gusty comet you can use an IJobForEach with the [ExcludeComponenTag(...)] attribute on the job struct
and the postUpdateCommand?
Or you can do a IJobChunk and disregard the CanDoActionFlag
You would use EntityCommandBuffer
in place of PostUpdateCommands
I'd imagine you have to use the Concurrent EntityCommandBuffer
and I guess I'll just be passing it on the jobs OnUpdate
yep
thx man
@gusty comet something like this https://hatebin.com/zfoiuwgqbg (untested)
Anyone know how to add dependency between jobs for Presistant NativeHashMap?
Ok, it seems like I really had the wrong idea of JobHandles. Anyone have any resource of this actually works? E.g. if I have JobA and JobB, but they don't share any components to iterate over, but schedule B with the handle from A. Will B wait for A to complete?
yeah... so jobhandles really dont have anything to do with components.
JobComponentSystem does some magic based on which queries you've used GetEntityQuery on to figure out some dependencies.
but its just JobHandle waiting for all the other jobs it was given as a dependency to complete before running.
so, JobHandle.CombineDependencies(...) everything u need to be finished.
Ok, so it's basically empty as it comes as paremeter into a system?
most of the time i believe so
thats why u have to manually register your jobs with Phsyics systems and command buffers
if you look at what happens there, they just keep lists of job handles and call Complete() on them or pass it into their own jobs as dependency list
Hmm, still don't get how it knows the component dependencies of the jobs though then.
So must be like Can I schedule this job, or is it depenent on other jobs that haven't completed?(yes/no) Is any current job working on component this one wants to write/read of? (yes/no) => check next job. Right?
But it feels more complicated then that cause systems still have order, that also is translated into job order ? o.o
i've heard people talk about that, im not sure where it comes from, but i havent seen any evidence of it in the source. i'd love to be wrong, but it seems to be purely based on job handles with 'x jobs must complete before me'. How that dependency list is constructed might be done in the component system base where they know what queries you've used, or it could be something in the pre-compiled info of the job itself.
aha
the other side of it, is that the sentinel/safety system, which will throw if you try to do something that hasn't been declared. like when you try to write to a collection with the an invalid safety. But i don't think that factors into scheduling.
god my english is bad today lol
Yeah, I've noticed that x) Just feels like passing handles could've been changed to something simpler like a Attribute on the job to depend on another, but I guess you can do more advanced stuff with handles like condition based dependencies.
@mint iron thx for the code rewrite!
I have a real hard question
Do Burst compiler support dll plugins?
I mean, write a class that references job system, burst and stuff
write there actual job constructor and job struct with [BurstCompile]
compile only that class into DLL
and plug into unity game?
I am compiling some scripts in runtime using Assembly c#
and whole script DOES work, except burst doesn't know what to do
at Mono.Cecil.BaseAssemblyResolver.Resolve (Mono.Cecil.AssemblyNameReference name, Mono.Cecil.ReaderParameters parameters) [0x00105] in <28cdca1704d2491781795499c297b78b>:0
at Burst.Compiler.IL.AssemblyLoader.Resolve (Mono.Cecil.AssemblyNameReference name) [0x00058] in <3179d4839c86430ca331f2949f40ede5>:0
at Burst.Compiler.IL.AssemblyLoader.Resolve (Burst.Compiler.IL.Helpers.SimpleTypeReferenceString simpleTypeReferenceString) [0x00015] in <3179d4839c86430ca331f2949f40ede5>:0
at Burst.Compiler.IL.AssemblyLoader.Resolve (Burst.Compiler.IL.Helpers.SimpleTypeReferenceString simpleTypeReferenceString) [0x00120] in <3179d4839c86430ca331f2949f40ede5>:0
at Burst.Compiler.IL.AssemblyLoader.Resolve (Burst.Compiler.IL.Helpers.MethodReferenceString methodReferenceString) [0x0000e] in <3179d4839c86430ca331f2949f40ede5>:0
at Burst.Compiler.IL.Jit.JitCompilerService.Compile (Burst.Compiler.IL.Jit.JitCompilerService+CompileJob job) [0x001d9] in <3179d4839c86430ca331f2949f40ede5>:0
While compiling job: Unity.Jobs.IJobExtensions+JobStruct`1[[Mod_WorldGen_FloatingIslands+ChunkGen, ig6cxzim, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null::Execute(Mod_WorldGen_FloatingIslands+ChunkGen&, ig6cxzim, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null|System.IntPtr, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089|System.IntPtr, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089|Unity.Jobs.LowLevel.Unsafe.JobRanges&, UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null|System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)```
I can't hold a reference type in a component can I?
structs are all pass-by-value. You'll have to pass the reference on the OnUpdate job
@gusty comet so if i have struct inside that dynamically compiled .cs file, i have to pass ref to it somewhere?
If so, how and where? 😮
no idea I was responding to Diviel
https://docs.unity3d.com/Packages/com.unity.burst@1.2/changelog/CHANGELOG.html Anyone know what were the changes to burst in 1.2.0-preview6 ?
The changelog does not show that version but package manager does
@deft niche
Improve BurstCompiler.CompileFunctionPointer to compile asynchronously function pointers in the Editor
Improve of error codes and messages infrastructure.
Upgraded Burst to use LLVM Version 8.0.1 by default, bringing the latest optimization improvements from the LLVM project.
Fix issue with libtinfo5 missing on Linux.
Fix possible NullReferenceException when an entry point function is calling another empty function.
Fix an exception occurring while calculating the size of a struct with indirect dependencies to itself.
Fix potential failure when loading MDB debugging file.
Fix linker issue with folder containing spaces.
Fix issue with package validation by removing ifdef around namespaces.
Fix issue with an internal compiler exception related to an empty stack
you have that on top of list
@sonic oyster Ohh..just found out that its not the latest changelog. Its showing the changelog for com.unity.burst@1.1. The latest preview version is 1.2.0-preview6
@deft niche but you linked correct one 😄
hahah... yeah but it shows changes only till preview 5. 😦 no idea what changes happened in preview 6
Does NativeArray<T0>.Reinterpret allocate a new array or does it let you write to the original memory as if it's a different type?
@rugged wagon It does allocate a new NativeArray
Ok thanks
@rugged wagon Reinterpret doesn't allocate, it gives you a NativeArray with the same underlying memory (with Allocator.Invalid to make sure you don't double free). You can write to it and observe the changes in the original array.
How would you guys go about designing a state machine that works with DOTS?
@worldly pulsar great! I was pretty sure it didn't allocate a new array haha. Seems really useful!
Anyone know if ECS is OK to use for AR?
Hello, I've been busy working on cleaning up some of my ECS utilties into something a bit more useful for folks:
https://github.com/periodyctom/Hydrogen.Entities
Has helper types, docs, and example code for the following:
- A ScriptableObject -> Blob Asset conversion pipline, with examples of Blob usage.
- Saving Singleton Data Components to SubScenes, handling multiple scene loads, Singleton data reloading. Especially useful (at least in my projects and tests) for getting config data that can be loaded or set from many places instead of trying to write and maintain a complex bootstrapping process if all you need is to load some data.
- Full test coverage for the above, both in Hybrid and Pure.
Feedback/suggestions are appreciated.
what does dots stand for and what is dots?
@analog beacon Data-Oriented Tech Stack -> https://unity.com/dots
it's quite a bit more involved than just multi-threading - it changes how data is organized and accessed by the CPU in order to get improved performance (the big win is data contiguity and reducing cache misses for your CPU's cache registries)
that's the ECS portion, anyhow
😁 I like it.The new systems just seem to not have a place I could go to learn them
yeah, it's still fairly new and the documentation appears to be going through rapid iterations and changes
though I've noticed that the changes are starting to calm down
hmm, so if I wait a while tutorials will start to show up?
I'd imagine so - we're currently working on a project that we're intending to use the full offering of DOTS for, but we're focusing on getting a working build using MonoBehaviours while it's still in heav(ier) development. Eventually we'll have a big porting phase where we rip apart many of our MonoBehaviours and convert them to components and systems.
Not sure if other people here have alternate suggestions to that approach or not - perhaps I'm missing a goldmine of up-to-date resources?
I want to make a multiplayer project in 2019(it's not big, probably needs to have like 2 players in a session), but I don't know where to start with it.
I'd honestly start with monobehaviours and look into Photon (a networking library) for the time being - you can always refactor code later
it's easy to stall out and make no progress by spending too much time trying to make optimization decisions early on
just get something going 🙂
@gritty grail
How would you guys go about designing a state machine that works with DOTS?
in fact ECS is a big state machine itself
good advice, thanks, I believe it is called Photon PUN?
correct
I will get into it 😁 your advice is quite good
👍 glad I could help
Hello, please help me.
Im using dots physic package at my game. Its work awsome on unity but when i build , the velocity of entities resets on each frame.
Im using ijob foreach to set velocity and never writes on linear velocity at other systems
How should I go about tag generation for a system like binary spatial division?
@untold night what triggers the conversion of a ScriptableObject? is it when it appears referenced within a GameObject that is being converted?
Are you using (fixed)DeltaTime?
Sounds like we'd need more information to help you, but someone who has experience with DOTS physics might be able to point you in the right direction, or something like that.
Then I got nothing. Haven't used DOTS physics, so I don't know what could be wrong if it's not deltatime-perf differences between editor/build
Please check it https://forum.unity.com/threads/velocity-is-different-on-build-dots-physics-package.763682/
Ok thanks @tawdry tree
How could I go about implementing a command-like system in ecs?
@gusty comet Why do you want to implement the command pattern? It is an OOP pattern, so you likely want something else for ECS.
@slow epoch Presumably something like math.clamp(fl3.magnitude, 0, 1)?
Haven't used it enough to get you more accurate syntax, but magnitude is a single number, so just get that and clamp it as normally?
Or do you mean normalizing the vector so that its magnitude is 1?
Guess I'll go with component composition like
@gusty comet you create new entities as events
and forget about OOP patterns in ecs forever, its a different thing
As vblanco says, you can create entities that communicate intent, such as "system X do Y".
I'm pretty sure there's some examples/discussions out there, though I don't have any right now
And yeah, whenever you think "I should use pattern P", stop and ask yourself:
- Is this an OOP pattern?
- Why do I want to use it?
Sometimes the pattern isn't necessarily OOP, and it could make sense, but usually it's just habits, and you need to find a way to translate your intent to proper ECS
Well, DOP feels like a the dark forest you explore while out of school and I try to keep myself grounded
most of the OOP design patterns exist to categorize different ways of communication beetween classes. Most of those are unnecesary in ecs-land
ok, So if I wanted two entites to communicate I just create a 3rd entity holding both entities ids and my intent?
Not necessarily like that, but in general, yes.
Do you have a specific case?
This Unite talk is about communication between systems and entities
(Options for Entity interaction - Unite Copenhagen)
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. ...
@tawdry tree many thanks, I've been looking for something like that
I found that video exceedingly useful, it really made a few important things 'click'
So I share it whenever relevant
atm for interaction I use flag components from the making a turn based game talk
After all, communication between things is absolutely critical for most, if not all games
flag components are dangerous
they are very slow in general
with unity ECS, adding and removing components is kinda expensive
much faster than old add/remove component, but still not something you want to use tens of thousands of times a frame
Well, for the turn based unite talk, the change is "whenever the user gives input", meaning less than once per frame. But yes, it's important to remember the potential perf cost. The talk does touch on that, though
Yeah, if it's thoughthans times a frame just have bool if its low freq flag comps are good
what would be the alternative to tag components?
bool in the component that tags instead of removing it
You can also use the change filter, I suppose, but that's a little brittle, since a change is registered whenever any system requires write access to a component, not when an actual change occurs
https://docs.unity3d.com/Packages/com.unity.entities@0.0/manual/component_group.html
Here's some documentation on using change filters with entity queries.
https://docs.unity3d.com/Packages/com.unity.entities@0.0/manual/entity_iteration_job.html
Describes an attribute to use with jobs
Tags are likely the cleanest solution but you may run into performance issues.
Something something premature optimization
Just be sure to use the entity command buffer when you use tags or you may be introducing sync points all over the place
Yeah, clean should be the first choice and then optimization if you actually run into issues imho
Side note: if you do use the entity command buffer to set tags be aware that any systems that run after the system that sets the tag and before the entity command buffer executes will not yet be aware of the tag.
Think about perf and whether you should do it that way whenever you do anything that would add/remove components, but often the answer is "Yes, this is the best way". Sometimes it's the best perf way, but more likely it's simply the way which is the least costly, development wise (code complexity, maintainability, brittleness, etc)
this probably gets asked a lot, but aside from the performance benefits, what do you guys think of ecs in unity? is it worth using now for developing games? I'm not talking about the overall dots environment, but just the ecs itself. Is it worth the trade offs etc
"Performance by default"
so if monobehavior was just as fast as ecs, you would use mb rather than ecs?
@gusty comet it cant, due to the laws of physics
ECS works more like how the CPUs are designed, so its stronger
I'm not asking if it can or not, I'm just asking would you use mb approach or ecs approach if performance or dod wasn't a concern at all
i would still use ECS instead of MB if the cpu cost was closer. Of course talking about a possible finished ECS framework
saying that if mb was just as fast was just a quick way of putting it
the pattern was created for MMOs, before the perf concerns
the hyperfast version is more of an evolution
Entitas at the moment has been used for full games, and its not really that much faster than monobehaviors
its also an ECS, just a bit less restrictive than unity one
one of the main characteristics ECS has is "high modularity" and separation of concerns
each system does one thing and one thing only, and wont reference that it doesnt need. Stuff is very weakly coupled
this makes it great for scalability in big projects. Adding new code wont affect old code, nor you will need to do anything about that old code
its also extremelly popoular in rogelikes
@gusty comet I would use ECS over monobehaviour any day
just the structure helps me a lot it being about separation of data and systems, its a lot cleaner/clearer
so much easier to rip a system out of existence and it doesnt hose your entire project
In addition to what has been said about separation of concerns and clean code, ECS code is testable by default - create a world, create any entities and systems you need, then run update.
here is the very old but still nice article about ecs, and why it is right choice for games https://www.richardlord.net/blog/ecs/why-use-an-entity-framework.html
also this article https://www.richardlord.net/blog/ecs/what-is-an-entity-framework.html
the earliest models i can find are from 2007
and preciselly about mmo development (ecs has some qualities that makes it god tier for networking)
Well what I wanna do is make a state machine for AI
And I was thinking maybe have the AI switch component tags depending on the state they're in
but I don't know what the most optimal way of doing that is.
Like for instance how do I want to add and remove the components from each individual agent? Do I just put that in update? Should I run a system or job on all agents that does that?
do you already done with this talk? 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. ...
its very common to use component tags as state machine
just be careful with how many you got
well, more like how often are you switching
Dead is an absolute classic
What's the best way to assign many entities component tags? And I was going to go through all of the talks today actually
there are batch add/remove components i think
until you have less than 100 agents do not waste your time on finding the most performant way, you need to start care about this when you get above 1000 add/remove component operations per frame
Well I was just trying to make a test case game with thousands of AI
with dozens of state changes, you are good. With thousands... it depends on how often you change it
state components are very very fast to update
just the cost of switch
i recommend to start with simplest setup, get it working, and then optimize for performance
Well I was going to deal with a few states
Well right now just 2
First state is wait 10 second, second state is move to position
tag is a good approach here, as long as to move in a fastest manner you want entities you going to move to be in the same chunk, most of the time your agents going to be in "move" or in "wait" state, not in "switch states" state
What if I have an int state in an entity component, and a switch statement that will add and remove tags maybe?
in case when for state you use only int value in a component your move system going to iterate over all entities (including those which are in wait state)
you need tags to make all moving agents belong to separate archetype
and when you have tag you don't need to duplicate it with int
in that case
have your state components hold the data needed too
your Wait component has "float TimeLeft"
and your MoveTo component has "float 3 Target"
I'll think about it a bit more
you'll need 3 systems:
• Move system iterates on entities with move component and after finishing move removes that component (also it may add Arrived component to let state-manager system know that agent was in move state)
• Wait system iterates on entities with wait components and removes that component when time is out
• StateManager system iterates on all agents without both move and wait and sets new state
what ive seen is also using 1 system that does the 3 queries
it doesn't mater where 3 queries placed in one system on in 3 different, this is 3 queries and 3 iterators anyway )
so... no new entities this week for us?
@mint iron - yes. It currently piggybacks off of IConvertGameObjectToEntity but conversion can happen manually outside of that.
i only see that com.unity.burst 1.2.0-preview.6 released 2 days ago
I thought the Entities auto conversion stuff was being updated this week? 😂
Would anyone know what may cause these kinds of errors?
protected override JobHandle OnUpdate(JobHandle inputDeps)
{
cameraRot = AddCameraTag.Instance.camera.GetComponent<Transform>().rotation;
var physicsWorld = World.Active.GetExistingSystem<Unity.Physics.Systems.BuildPhysicsWorld>().PhysicsWorld;
var job = new MoveJob{
horizontal = Quaternion.Euler(new float3(0,cameraRot.eulerAngles.y,0)) * new float3(1, 0, 0) * Input.GetAxis("Horizontal") * 3,
vertical = Quaternion.Euler(new float3(0,cameraRot.eulerAngles.y,0)) * new float3(0,0,1) * Input.GetAxis("Vertical") * 3,
space = Input.GetKeyDown(KeyCode.Space),
physicsWorld = physicsWorld,
filter = new CollisionFilter {
BelongsTo = ~0u,
CollidesWith = (uint)(1 << 0),
},
cameraRot = cameraRot,
};
var newDeps = JobHandle.CombineDependencies(inputDeps, World.Active.GetExistingSystem<Unity.Physics.Systems.BuildPhysicsWorld>().FinalJobHandle);
var handle = job.Schedule(this, newDeps);
handle.Complete();
return handle;
}```
struct MoveJob : IJobForEach<PhysicsVelocity, Translation, Rotation>
{
public float3 horizontal;
public float3 vertical;
public bool space;
bool hit;
[ReadOnly]
public PhysicsWorld physicsWorld;
public CollisionFilter filter;
public Quaternion cameraRot;
public void Execute(ref PhysicsVelocity velocity, ref Translation translation, ref Rotation rotation)
{
rotation.Value = Quaternion.Euler(new float3(0, cameraRot.eulerAngles.y, 0));
var rayInput = new RaycastInput();
rayInput.Filter = filter;
for(int i = -1; i < 2; i+=2)
{
rayInput.Start = new float3((float)i / 2,0,0) + translation.Value;
rayInput.End = new float3((float)i / 2,0,0) + translation.Value + 1.1f * new float3(0,-1,0);
hit = physicsWorld.CollisionWorld.CastRay(rayInput);
if (hit)
{
break;
}
rayInput.Start = new float3(0,0,(float)i/2) + translation.Value;
rayInput.End = new float3(0,0,(float)i/2) + translation.Value + 1.1f * new float3(0,-1,0);
hit = physicsWorld.CollisionWorld.CastRay(rayInput);
if (hit)
{
break;
}
}
if (space && hit)
{
velocity.Linear = new float3(velocity.Linear.x, 6, velocity.Linear.z);
}
velocity.Linear = new float3(vertical.x, velocity.Linear.y, vertical.z) + new float3(horizontal.x, 0, horizontal.z);
}
}```
I believe that it's being caused by this
And maybe specifically trying to raycast
Well I guess it isn't specifically due to raycast, nvm.
Does raycasting work at all
every time I try no matter how much I strip down, I just get an assertion failure in my console and all my entities break
following the code from the docs, not that that's ever a great idea lmao
idk, my project is straight up broke now
👀
I might try to redo it
And try to pay a bit more attention to what's causing my issues
So what happened to project tiny? I cant find it in any project manager
@gusty comet seems like this
thx! I wanted to see how they handled animation/events
oh thank god I got raycasting to work at least outside of a job
it is possible
btw, remember that you can actually download the megacity project files for you to mess around with
kinda sworn off of downloading unity projects since I've yet to get one that isn't very crashy/actually plays
I personally really want to look into that streaming code
Well you can get raycasting to work in a job
I made a tutorial on it on YouTube if you want me to share it @gusty comet
Just the issue is the errors you get every once in awhile :??
consistent array slice errors
yeah
sure I'm interested
and other errors
Extra video notes: -I forgot to explain why you want to change the y size value of the plane's physics shape. It's because the raycast will bug out if the y ...
Not a great tutorial but hopefully it works for you
PhysicsWorld.FinalJobHandle looks like the magic bit
thanks dud i'll try it out later
Can I make a component hold references to entities of a certain Archetype?
Agh now CollisionFilters are giving me hell. Am I right in thinking that, in order to hit only colliders who belong to layer 8, 1u << 8 in the BelongsTo and ~0u in the CollidesWith fields would be the correct values? I've tried just adding 8u in as well, assuming the filter works in the inverse, but no matter what I always get back something on layer 7 😩
The RaycastHit is definitely giving me the right colliders w/ their filters because turning on unsafe code and dereferencing the pointer to the collider returned gives the correct looking mask :v
why do you do 1u?
unless it's the same thing as saying
(uint)(1 << 8)
Also
when you say ~0u for collides with,
It will collide with everything no matter what
BelongsTo says what kind of collider it is
You should make it the raycast collider
and the CollidesWith should only collide with whatever layer 8 is.
And I believe you have to make sure your other colliders in the physics component does not collide with your raycast if you don't want it to
so it has to be set up both ways
@gusty comet
1 << 8 shifts the integer 8 against the integer 1, and then you're explicitly casting it to an unsigned integer
1u << 8 left shifts the int literal 8 against the uint literal 1, returning a uint
fully defined in C# afaik
I mean that's how they showed it in their examples
anyway so what you're saying is the raycast is a collider unto itself, and the filter actually acts as the raycast's "belongs to" and "collides with" properties?
yes
from the docs it implies those are masks used to calculate which colliders to consider
just like Unity's old raycasts
Yes.
So BelongsTo says what collider the object is
and CollidesWith says what colliders the object will collide with
I'm aware of that
Well what you said you did looks incorrect
in what way
1u << 8 in the BelongsTo and ~0u in the CollidesWith fields would be the correct values?
If you have the collideswith set as ~0u it's going to give you layer 7, and every other layer for that matter
yeah so, I want to filter by colliders which:
Collide with everything ~0u
Belong to layer 8 1u << 8
Well what are you trying to do exactly?
So you only want the raycast to say true if it collides with layer 8 specifically?
exactly
well what is layer 8?
You're saying that the raycast belongs to layer 8
and you're also saying that the raycast can collide with all layers
You're saying the raycast belongs to layer 8
if that were true
it wouldn't be named "filter"
nor would the docs mention it functioning the same as Unity's old layerMask in a raycast call
Well my code works exactly the way I've described it
So you should give it a try and see if it fixes the issue
Set BelongsTo to the raycast layer, and the CollidesWith to layer 8
good lord
welp
if i had a hat i'd eat it
it works :v
on one hand, thank you
on the other, I have never hated Unity's documentation and naming conventions more in my entire life
you're welcome
Hello, why unity dots physics collision detection is fast at server mode? How can i fix it?
you mean that the simulation itself runs fast?
That wouldn't be an issue, now would it?
At least, I'm pretty sure you wouldn't complain about having too much perf if you're using DOTS
@tawdry tree , @dull copper
Im add velocity to tank shell and i expect the bullet to move slowly and collision to target, then i remove bullet.
But when i spawn bullet, it will be destroy on start . because the bullet collids the wall. I lost animation of movement over velocity.
When i remove the wall, bullet will be destroy on timer.
Sry for my English , im new at English
Are you using deltaTime?
I cant, because velocity movement system writen in unity physics package
Oh yeah, still that issue.
Are you still using this code?
physicsVelocity.Linear += inputs * tankMovementData.Speed * DeltaTime;
Because here you ADD to the velocity, every time the system runs
That means it will go faster and faster with every frame.
And when you build the game, it can get really high FPS.
No , thats code of my tank
Bullet velocity has been set on start and there is not any update loop
perhaps the collider of your wall is wrong - if bullet is colliding with it the moment it spawns, or colliding with something else? tank?
@mint iron i have filtered collid of tank, and checked the collision position. Thats on wall
I think the problem come from server build, thats so fast
I have not any problem on editor
What happens if you set the velocity to 0?
In that case it should not move, and thus not hit the wall.
@tawdry tree yes, thats hit ground on start, and if i remove gravity, bullet destroy by timer
scary profile pic...
Me? @analog beacon 😂
I have a fear of clowns and that looks disturbingly close to one
Then it sounds like your calcs for the 'force' variable does something odd. That or the vector/matrix math. And I'll have to admit once we got to that in school I was really happy I didn't do a more math heavy course.
I just uploaded random pic for profile @analog beacon
@tawdry tree i should test simplest example on empty project, but i think thats unity physic package issue
And i can not fix
Can you somehow get the value of the forcevariable in the build? To see if it does something weird?
Force or hit position ? @tawdry tree
The force variable, second line in the image you sent
Since it seems like the issue is velocity, which derives from that variable.
@tawdry tree ill receive force from client in byte type.
It is clamped between 15 and 30
Have you verified that to be the case?
And have you made sure that's the case in the editor?
Im clamping currentforce on network manager and i have tested on editor i can send video that showing how its work
Im share video on two states , please wait to record
First impressions: This seems to have something to do with headless (no-GUI) mode. Do you get the same result if you build non-headless?
So what happens is that it instantly detects a collision where there should be none, it didn't seem to move faster or anything.
it could be incompatibility between headless mode and DOTS physics
@tawdry tree work correctly on non-headless. thats mean i cant use this physic for bullets?
I don't know, you'd need to get answers from someone more well versed in headless and/or DOTS physics. I'd advice you to create a bug report/help thread stating that, using DOTS physics, you get different results in headless and non-headless mode.
ok thanks
is there not an entity count or component count(total sum not individual) method for the EntityManager?
nevermind it doesn't really work when I use the EntityQuery.CalculateEntityCount() anyway
After adding hybrid renderer I get this Library\PackageCache\com.unity.rendering.hybrid@0.1.1-preview\Unity.Rendering.Hybrid\LightConversion.cs(101,63): error CS1061: 'HDAdditionalLightData' does not contain a definition for 'customResolution' and no accessible extension method 'customResolution' accepting a first argument of type 'HDAdditionalLightData' could be found (are you missing a using directive or an assembly reference?) and a similar one about contactShadows. I use 2020.1a9, HDRP 7.1.2, Entities 0.1.1 and Hybrid Renderer 0.1.1. Anyone knows of a fix for this?
this came up like a week ago too with no solutions then :/
@pliant pike check entity-debugger and your EntityQuery
yeah I checked it, its 0 at the wrong time, I need a whole different way of initiliazing a blob after some GO's are converted to entity's
or maybe I just use the Enityquery-count to do the whole check 🤔
@mighty violet recent 2019.3 beta HDRP's are not supported by the current Hybrid
would expect a fix on future hybrid releases, considering Unity itself is using hybrid + hdrp with 2019.3 on their dots shooter
so at very least, we should get fixed package for 2019.3 release or so
of course you could manually fix the API change too
or take 7.1.2 from github and revert the commit that changed to the new API on HDRP
@dull copper thanks for the advice, I downgraded to 7.0.1 and it doesn't have the API mismatch so I'll stay there until there is a new version of hybrid
Where is it possible to define entity archetypes? Just when you do the entity creation? Can I define archetypes in an external file and access them later?
as far as I can tell yes, to the 2nd question
I've been building a little archetype tool for myself to build different entities rather than having to code them
since all the behaviour is automatic when you create the entities, I just have a behaviour with an IComponentData[] (among others) to define an entity with
with [SerializeReferece] and UIElements you can something fairly comprehensive
ECS is really well suited for this approach tbh
Hey guys, would someone mind telling me how to deal with the rigidbody when converting the GO to an Entity? So this is obviously not working
private Rigidbody2D rigidbody;
private void Awake()
{
rigidbody = GetComponent<Rigidbody2D>();
}
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
dstManager.AddComponentData(entity, rigidbody);
}```
- There is no 2D support (the Xyz2D classes) in DOTS physics. (can still use 3d in 2d ways)
- Conversion of those should be automatic
Do you have the DOTS physics package installed?
@tawdry tree yes I do
@tawdry tree so after attaching the rigidbody2D to a GO it should be converted automatically? And how would I access it within a system?
Pretty sure you can't use the 2D components for conversion.
Conversion of the physics stuff should be automatic the same way MeshRender/RenderMesh and the transform is.
I think you need to use a normal rigidbody, but constrain it to be unable to move on the Z axis.
thank you very much. But when I use the rigidbody I get this error The type 'Rigidbody' must be a non-nullable value type in order to use it as parameter 'T2' in the generic type or method 'IJobForEach<T0, T1, T2>' [Assembly-CSharp]
You need to use the relevant entity component, which I do not know the name of. I suggest finding a relevant sample or a tutorial.
Is this your first attempt at ECS?
Involving physics will complicate things, so if you want to learn ECS it will probably be easier to start off with just 'ECS' and self-coded logic. You can have motion without physics, you know.
The space shooter type of game is fairly simple and can be done with just ECS (and self-implemented bounding-box 'collision'). I'm not sure if it's the best place to start.
I very much recommend watching a few videos, including this one (https://www.youtube.com/watch?v=KuGRkC6wzMY) which is about 'communicating' between entities/systems.
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. ...
ye I started learning Unity DOTS with this video
In this video, learn about what's involved in migrating existing game code to the new Data-Oriented Technology Stack (DOTS), which comprises the C# Job Syste...
seems to be the newest one
If you're used to object-oriented programming, the mindset really is the hardest part. So many things you're just used to/take for granted that's wrong or just suboptimal in ECS.
A simple roadmap to learning the basic could be:
Set up basic scene in gameobjects, which converts to ECS
Add simple movement to some entities (move along some axis)
Create a player-controllable entity
Add logic to the movers, such that they move towards the player
Add shooting for player
Implement a simple 'collision' system which detects if player bullets overlap enemies, or enemies overlap player
And then you have 90% of a simple shooter kinda game. Limit movement to the 2D plane, and you got a shoot-em-up.
It will be much easier to reason about things (and ask for guidance or help) once you 'get' the basics (conversion, simple systems, probably the 'communication' between entities/systems mentioned above). I'm about to head to bed, so I'm probably not gonna be able to help you any more than that, but while not always busy, this channel tends to be helpful 🙂
thanks
http://www.dataorienteddesign.com/dodbook/ obligatory link
Data-Oriented Design
about the mindset
What is the equivalent of Quternion.Lerp() in Unity.Mathematics?
dataorienteddesign.com/dodbook/ obligatory link
i was using that source in my graduation work
i see that in math there is Lerp for float4 and quternion can be assigned by float4. Is this a valid approach to do Lerp?)
And also now i understand that i see no Quaternion.Angle analog in Unity.Mathematics
math.mul can do a whole host of operations on different data types irt angles/rotating quaternions
you may also be able to do matrix/quaternion multiplication, i think thats what i did for a rotational lerp
thx. I found nLerp in math and mul in quternion
Is there a way to get meshes working in jobs yet? Is the only current option still RenderMesh?
What’s the best way to handle configuration data that’s needed by any/all systems that is loaded at runtime?
Hi everyone. Which version fo Unity are you using?
I'm using Unity 2019.3.0a8 and everytime I install the "Entities" packages, i found this error:
Library/PackageCache/com.unity.burst@1.2.0-preview.6/Runtime/SharedStatic.cs(114,47): error CS0117: 'BurstCompilerService' does not contain a definition for 'GetOrCreateSharedMemory'
But seeing this changelog seems that my unity version does not support burst right?
https://docs.unity3d.com/Packages/com.unity.burst@1.2/changelog/CHANGELOG.html#111---2019-07-11
Thanks!
Anyone have an idea what the firstEntityIndex parameter of IJobChunk Execute() is about? Seems to be no documentation whatsoever.
@jade siren shared static was added after that editor version, you'll have to use a newer editor build or an older burst version.
@old pulsar firstEntityIndex refers to the index of the first entity in the current chunk within the EntityQuery the job was scheduled with. For example, if the job operates on 3 chunks with 20 entities each, then the firstEntityIndices will be [0, 20, 40] respectively
from com.unity.entities@0.1.1-preview\Unity.Entities\IJobChunk.cs
Hi! How should I go about saving my ecs data into a file?
@gusty comet i searched forum a bit, and there is Unity.Entities.Serialization which contains SerializeUtility with SerializeWorld() and DeserializeWorld() methods.
Here is the thread with example code (but with some err issue) https://forum.unity.com/threads/serializeworld-deserializeworld-error.688156/#post-4603228
thx!
I have a BufferFromEntity<T> that I pass into a job - getting an error that it must be marked [ReadOnly]. I'm not really sure how to get around this problem as I need it indexed by entity. Maybe I should make a concurrent dictionary or something?
can you paste the full error
Been reading, maybe this is a place to use [NativeDisableParallelForRestriction] InvalidOperationException: FillBuffersJob.Data.buffers is not declared [ReadOnly] in a IJobParallelFor job. The container does not support parallel writing. Please use a more suitable container type.
yeah exactly, its not safe by default for parallel so they stop you with this exception.
Do I need to put the [ReadOnly]/[WriteOnly] attributes on any members of a job besides native collections?
I assume not since any other fields will be unique to each batch
If I remember right spamming [ReadOnly] on everything that you dont modify actually makes the jobs faster
If you can guarantee you won't write, it can optimize for that
Similarly, if you somehow know you need never need to read, only write, it can optimize for that
If you have ever played with concurrency and threading yourself, you will likely have considered such things yourself: "Is it safe to send in this variable to that thread? But it's used over here, so if that changes..."
Locking things down drastically simplifies things without needing locks or potential deadlocks or race conditions.
I figured anything inside a job besides native collections would be assumed readonly because they are value types and won't be shared across batches.
@tawdry tree i wish i could do some of the stuff rust does or what the job system does on C++
of 100% banning accessing globals, only allowing whatever you input into the function
Even if a *parallel for job did write to a field, different batches would never be writing to the same instance of the field right?
thats what the "disableparallelforrestriction" is for
i suspect it might setup schedule dependencies based on the safety read/write access so if you don't have [ReadOnly] on a collection and it knows there are already jobs using it, you might find that it gets delayed until they're finished. But i have no proof for that 😄
it works exactly like that @mint iron
The readonly/writeonly attributes are most definitely part of the sentinel and scheduling system
the ECS library "specs" in rust does exactly the same thing
you need to declare which components (or singletons) you access on each system, and it uses that information (read/write) to schedule stuff
I understand that it works that way on collections, I just didn't know if it applied to other stuff in a job like an int or float field
i'm not aware of any special thing it does for random fields in the job struct, i think you're probably fine to leave them off; could check the generated burst assembly with/without and see if its the same? btw. unrelated, your deform library is super awesome thanks for releasing that openly.
Thanks @mint iron 🙂
how to query all entities that have no components?
right now figured out that when you remove last component on entity, this entity is not destroyed but continue to exist
probably some sort of "orphan" type query
also i wonder what is the use case when it may be useful?
intersting
placeholder for the IDs
maybe an EntityManager.UniversalQuery -> IJobChunk with GetArchetypeChunkEntityType
yes chunk iteration may work, but this pretty ugly way to iterate all chunks
I've been wondering... C# can work with pointers under the unsafe code, yeah?
Is it possible to operate on pointers of a regular array in a job?
it's possible, you might need need a NativeDisablePtrRestriction attribute in the job
Does unity even allow the usage of reference types in NariveArrays?
no
So how am I going to operate on pointers then?
Or can I just operate on the default arrays?
regular arrays stored in managed heap and may move in memory by garbage collector , native arrays in unmanaged heap what allow to use them in a job,
so if you need array in a job move you data to native array
not sure if this is what you want but you may wanna look into https://github.com/fholm/UnsafeCollections
fholm implemented most collection types using pointers so you can use them with struct components
@dry dune I plan to have all of my jobs to be completed in a context of one function. There will be no time for GC to actually work.
job is something that going to work on different CPU core outside your function
Not necessarely. By forcing the job to be completed with JobHandle.complete() or by not running the job on another core entirely (using job.run) the job will be completed before a necessary point in the main thread.
The GC can be triggered from a different thread. If you want to use managed array pointers you have to pin them
To work with pointers on managed arrays you need to pin then with fixed
byte [] a
fixed (byte* ptr = a)
Code on phones sucks
When you pin structs you need to use -> to access fields like cpp
a->speed
I'm trying to calculate/draw lines between a NativeArray of points based on their distance from eachother. I got a crappy version working by looping over the points in an IJobParallelFor and testing the distance between the current point and all the others. If a point was less than some max distance away, I added a float4x4 to a NativeQueue that stored the transformation for a quad to connect the two points. Unfortunately the only way to draw the quads was to dequeue each matrix and draw it with Graphics.DrawMesh. I want to use Graphics.DrawMeshInstanced, but to do that I need a native array or slice of float4x4s so I can memcpy it into a managed Matrix4x4 array. NativeQueue didn't give access to an array. I tried using a NativeList, but from my testing you cannot add to it from an IJobParallelFor. Does anyone have any ideas on how to calculate and store the connections in a way that lets me efficiently draw them?
Does burst work with addressables?
@sonic oyster not really, its all classes. But you can store references in a native friendly form if you need to have them as part of a prefab. For example, use IConvertGameObjectToEntity to pass the runtime key from GameObject AssetReference into ECS. The runtime key is all you need to be able to load an asset from a system/entity prefab.
I need to make a way to make modable mapgen
And its a struct with [BurstCompile] attribute
When i load it with codedom or roslyn dynamically the job works, but burst doesnt work on it.
@rugged wagon you could try NativeStream - it can read/write in parallel and has an ToNativeArray() method.
@mint iron Thanks, it looks like that could be the answer. Is there any documentation on it? Google has been struggling to find official info on the less common collections and I'm not seeing anything besides a single forum post
Ah it actually might not be the best solution if, to get the array, I have to allocate a new one. I wish it had some sort of AsNativeArray<T>() method. Looks really helpful for other stuff tho.
Could I get a pointer to the beginning of the stream and then memcpy the contents into a correctly sized native array? I don't really know how to use pointers so maybe that isn't possible idk.
I think NativeStrean().AsReader().ReadUnsafePtr(int size) can work if you want to get the contents of the NativeStream
it returns a byte* so you can likely increment the pointer by its end offset and copy it to a destination
Excuse my ignorance @coarse turtle , but what's the point of a size argument if the method just returns a pointer to a single byte? I don't know too much about pointers besides that they are addresses to a location in memory (sorry)
so here's an example, let's say you wanted to store an integer as bytes towards an address
an int is 4 bytes, so you would split the integer into 4 bytes and store them sequentially to a byte pointer
so byte* intStart would store the address that represents your integer
and if you do intStart++ you can grab the second byte that represents the integer
so a simple way to grab the entirety of the contents of the pointers is
byte* some_pointer = some_int;
for (int i = 0; i < sizeof(int); i++) {
some_pointer++;
var segment = *some_pointer;
}
// Typically if you concatenate/serialize all the contents of the pointer you can reconstruct your original intended data type
Very cool, thanks for the explanation! So incrementing a pointer moves it forward one byte in memory?
So doing:
double* doubleStart;
doubleStart++;
Would move it forward the size of a double, not a byte?
yeah the ++ operator on a pointer moves it to the next address
Thanks again, I'll check it out. I cobbled some utility methods together a while ago for copying between native/managed arrays of normal math types and mathematics types so I bet I could convert them to copy between a native stream using the byte pointer.
// Copies a native float4x4 slice into a managed Matrix4x4 array. Array lengths MUST be the same.
public unsafe static void MemCpy(this NativeSlice<float4x4> source, Matrix4x4[] destination)
{
fixed (void* managedArrayPointer = destination)
{
UnsafeUtility.MemCpy
(
destination: managedArrayPointer,
source: source.GetUnsafePtr(),
size: destination.Length * (long)UnsafeUtility.SizeOf<Matrix4x4>()
);
}
}
Is it possible to call Graphics.DrawMesh from inside of a job?
i think only the mainthread
In general, what should I be handling in a job?
there's always going to be some overhead surrounding setting up multithreading
lots of math that happens very frequently, def going to benefit
small things not so much, if you're unsure you'd probably just have to profile it yourself to spot the difference, not that it's easy with the current tools at our disposal irt debugging
okay
What would be the standard on implementing animations on your 2D pure ecs game?
Self-implemented something or other.
Can't be more specific because honestly I have no idea. You want to essentially flip through a number of sprites, so I guess some shader magic (on a spritemap) could do the trick? Outright swapping the texture sounds expensive, but doable.
Yeah, just looking for insight, atm what I have figured is swapping the materials maintexture but I have to admit I feel overwhelmed by it
Have you done some google-fu? I imagine at least one obscure coding-blog has written about doing pure ECS 2D animation in Unity.
Been going at it. Guess it's time to keep with the google-te
for 2D animations what I do is
CommandBuffer + custom quad + array of texture frames (this usually lives in a blob array)
with small pieces of animation info like playback context, playback rate, which frame of the animation to use (assuming its a sprite based animation and not IK)
Effectively all you're doing from a component system is filling up the command buffer with material property blocks so you can change the texture every set frame to animate your sprite
theres this thread https://forum.unity.com/threads/200k-dynamic-animated-sprites-at-80fps.695809/ which may help
guy posted the sourcecode too
theres also this tutorial https://unitycodemonkey.com/video.php?v=t1f8ZreCuuQ
i followed the tutorial, but if you dont go the custom shader route(which is incompatible with the renderpipelines) I think you're limited to using just drawmesh instead of drawmeshinstanced and the limits are a bit poor by ecs standards, i think at 1000 sprites is where performance drops off for me
guessing this all changes when the next entities package is released, supposed to have support for materialproperty block changing? drums fingers
I need that update so bad
poor by ecs standards
1000 sprites is where performance drops off
Isn't it lovely to be in such a situation, though? And with the reasonable expectation that you can improve upon that, as better support arrives?
for sure
How do you think - it is ok to make separate systems for every character ability even if they have something in common? I don't have other idea but this will provide some duplicated code.
Wasn't the new update supposed to be out like last week ?
yes 😬
El, That sounds highly redundant. If nothing else, put reused code in helper/static classes/jobs/base systems(inheritance).
My instincts say that making systems, especially if they do similar things, is not proper ECS, though.
@tawdry tree static methods are completely fine and very recomended
Think about your data, and your behavior, and what is general and shared. You can probably make a neat table of "this ability does X+Y, that ability does just X, this one does X+Z, that one just G, etc" Damage, for example, is likely to be very common.
I meant that making systems for every kind of ability sounds not ECS, not statics (edited comment for clarity)
making systems for every ability is actually a thing do. I did something similar on my end for a spell system
different "parts" of the spell was in components and you could compose things dynamically
That's one system for each component or set of components, though. Not for the abilities themselves, which under ECS, is purely 'subjective'/not real (ie. exists not in the pattern, only in the experience of the users)
ah true. In my case the spells were a template i would "spawn", and then their components do stuff
mostly done for projectile type spells, which was what the system was created for
tho you could do stuff that wasnt projectiles by doing stuff like adding auras in AOE or auto-attaching to stuff
The case is that, i have ship with weapons
- front cannon - with one bullet spawner
- side cannon - with multiple bullets spawners on both sides
Player shots with selected weapon. For front cannon is easy just spawn bullets from spawners.
For side cannon is more complicated, because i would like to shot from this side (subset of spawners) where closest enemy is.
For now I have only system that spawns bullets from all spawners within weapon. And thinking now where to apply that logic to spawn only from subset of spawners.
you add that to the spawners themselves
the "tracking" spawners have a component to do the tracking
and to select which of all the spawners actually shoot, thats something you do from the logic of the Ship itself
If you analyze most RPG abilities, they tend to be some combination of damage/healing, status effects, AoEs, and creating projectiles (or other objects) that apply those. Depending on the game, you might also have IFF/target selection (can or cant target this or that)
@compact hound for a complex multi-object stuff, its best to have something set as "brain"
and the other stuff is just dumb stuff
+1 to that
for erxample the front cannon
is just a BulletSpawner that has Active component
and the side cannons are BulletSpawner + Active + Tracking
the "brain" on the ship itself sets/unsets the Active component to turn the spawners on and off
and also sets the tracking target on the side cannons
Make a system where each cannon can have stats(components) and something to trigger a system to do the thing (ref. the entity interaction Unite talk)
The brain vblanco talks about would be what does the interaction here, triggering the others
something i implemented in my own ECS shanenigans on C++ is a way to send "events" up and down the entity parent chain
and utility stuff like "FindComponentInChildren"
i have currently on ship entity
- inventory that holds selected weapon
- dynamic buffer of weapons (front cannon, side cannon)
Weapon have
- Weapon
- dynamic buffer of spawners
On player input i put shot component on selected weapon, and shooting system spawns bullets from all spawners
seems good
but im struggling where to put this side cannon logic to spawn only on some of the spawners
no issue, you just add the whole "tracking" thing on the spawners
Could put on a component to group them, and have the brain make only one group fire at once. That could also scale up to something bigger, like a large, say, hexagonal enemy station.
well, thats what the Weapon is, no?
i think he has 3 levels of hierarchy
Ship -> Weapon -> Spawners
spawners could have something like LeftSide, RightSide to group them
that Side stuff is not something you normally put in components
in fact, those spawners dont really need data
but shooting system should have if logic to determine that?
that data can be stored in the weapon
weapon don't have link to spawners, entity holds dynamic buffer of them
does Used By Systems in the EntityDebugger actually show useful info? I dont fully understand as it seems like it just shows every system
then add it. A weapon should hold link to its spawn points, no?
system takes weapon, and dynamic buffer of spawners, but even if i add some list to weapon component then what? Multiple lists for each side? But simple front cannon dont need it
i like this bug 😄
@safe lintel honestly, I dont really use the Use By Systems in the Entity Debugger 😐 Also I think there's just too much to scroll through when you do see a system
@coarse turtle yeah trying to nail down usage of a particular entity and Use by systems seems rather useless
Yea the filters are way more useful on the system side and the entity side
this is my current weapon entity
how are you setting that up btw?
is that jsut a monobehaviour witha bunch of specific components on it?
@compact hound have all that whole "side weapon" stuff on the Weapon
nvm you already have that
I think i will just add side tag on spawners and add if on shooting system. Don't have better idea for now
I'm totally confused about collision filter in Unity Physics. I call distance query to find all entities with specified type in some area. And i have 2 physics category names that i added (A and B for example). I tried set any variants in input of CalculateDistance() method and of collision filter on entities, but all i got is strange errors like
IndexOutOfRangeException: Index 1768838447 is out of range of '5' Length in Library/PackageCache/com.unity.physics@0.2.4-preview/Unity.Physics/Collision/Geometry/BoundingVolumeHierarchyBuilder.cs:571
and
TypeLoadException: Recursive type definition detected
The collision masks should be bitflags, I believe, so you need to use bitwise operators (<< and >>?) on them if you calculate that. Haven't use DOTS physics myself yet, so I dunno.
Yeap, i understand bitmasks. For example, if i set my custom "Layer" in 2nd position (in unity physics it's Category names) and i want to collide with it i need to set 2nd bit to 1. So if i want to collide only with my custom layer i can use 2u value, which is already result of 1 << 1 (am i right?).
But in unity physics package we have "belongsTo" and "collidesWith" masks which aren't clear for me
1768838447 does not sounds like a bitmask made from a couple categories, but I might be misinterpreting the error.
BelongsTo -> which catergory(ies) to do I belong to
CollidesWith -> which category(ies) do I collide with
Say you have Default, environment, player, creatures.
Player belongs to Default, Creatures, Player, collides with default, world, creatures
A trigger for player could belong to nothing, collide with player
Static map belongs to environment only, no collides
Dynamic map (falling stones, logs) belong to default, environment
Enemies are default, creatures, collide with default, environment, creatures
Something like that?
Essentially, you can have one-way detected collisions. I assume you need the collidesWith flag to be affected by anything in that category.
Say you have two rolling balls, A and B, each with their own category.
They are similar in weight and stuff, and are rolled towards each other.
If either does not collide with the world, it will fall through
If neither collide with each other, they pass through each other
If only one(A) collides with the other(B), presumably A will be affected by B's inertia, but not the other way
At least, that's what I'm assuming. Pretty sure sparse use of the flasgs can help perf. The primary is just to not put anything where it doesn't need, for belongsTo, though. Other than that, you could just use masks based on what they belong to? 🤷
Has someone here experimented with distance calculations in Unity.Physics already? If so, did you figure out what the rigid transform is for in the ColliderDistanceInput? Is that the transformation from one collider CS to the other's?
And is there already a convenient method for generating Physics.Collider data from UnityEngine.Colliders?
Should I conform everything that I can to readonly or writeonly in a job?
For instance, ```csharp
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(0, mouseX, 0));
}
}```
And what kind of benefits does doing this provide me if I should?
it helps the system scheduling, i dont think its necessary on playerPos/mousexy unless they were nativearrays or componentdata etc
in my luddite understanding, if it knows multiple systems can read from and not need to write to a particular query, it can parallelize some of that work, if they all needed readwrite then you may have systems waiting on other systems to complete their workload and not as fast as it could be(though its unavoidable, if you can help it out here and there you can squeeze out as much perf as possible)
So there's nothing wrong with adding it there necessarily?
I really wish there were a way to fix these errors
I have to restart runtime everytime they show up because my player phases through the ground when these show up
and I might have to restart 6-7 times before it runs okay
Is the new Entities package out yet?
no.. 😦
yeah, I'm unclear on how WriteOnly benefits scheduling. In what scenario does writeonly permit concurrency where default readwrite does not?
WriteOnly is only there for completion, as it's implicit if ReadOnly isn't used
Like there's no point to actually marking things WriteOnly, just ReadWrite (no attribute) and ReadOnly
Hello Everyone!
Quick Question.
What is the best Approach to WriteOnly to the same DynamicBuffer from multiple systems?
@quaint snow to not do it or make sure the systems never run at the same time?
Hi @pliant pike ,
the perpose of my question is i dont want to lose performance by making my systems run in synchronously.
my first opinion about this is creating a NativeContainer which support parallel writes for each system and then collect them from another system at the end.
I also thought about creating entities that Handle the data to be buffered, then collect them and put them in the dynamic buffer after all systems concerned.
but this will prevent me from using burst and even worst ill create sync points by creating entities and adding those Datas.
I dont understand what exactly you are doing, do you mean a single job system run on multiple threads or multiple job systems, because you can do it multithreaded on a single job system
you just have to make sure the dynamic buffer wont be accessed from multiple threads, like I have entity's which have buffers and the job only works on that entity's buffers so its all self contained and doesn't result in race conditions
in this case i think i just have to declare my jib as unsafe.
but in my case im there is possiblity of race conditions.
im accessing the same Dynamic Buffer from Multiple Systems
yeah I dont think its even possible to write to a nativearray at the same time with multiple jobs safely
How do I go about using the new inputSystem in ECS? I've been currently using a singleton pattern like this https://hatebin.com/julsfekogz and a job that propagates it like this one https://hatebin.com/uhpnrbdvtf
Should I split the overworld input? Do I un-singletonize it=
That depends on how huge overworld input is gonna be
And if there is gonna be other class input
atm it's just two bools and a moveVector
the two bools are quite unrelated to the moveVector so I'm gonna split it up either way
Yeah i would split it up and just set to the job the bools directly
An I doing something wrong? Everything is fine in play and editor but when I build the game every entity has it's transform reset to zero
New project, create cube, convert to entity then build and it always resets
no idea
Are you making sure you have the package for your target platform when building?
Ah. Prob not.
I thought that was only for non standard platforms
Did not realize there was a windows and Linux one. I'll try that when I get back. Thanks
i dont believe those do anything yet.
the transform zero is a bug, if you try disabling srp batcher it might fix it, otherwise the fix is either in an upcoming entities release or unity release but neither are out yet
Hi! I've been making a simple rpg maker-like collision system and I'll love your input on it https://hatebin.com/rtbfyfvzyz
Is hybrid renderer required for ECS? Because I'm sorta at a standstill on coding more of my game until it works (if it's required). I'm on 2019.3.b7
no
What's the hybrid renderer for then? The description says its used for drawing meshes using DOTS... How does it make an entity and a visible mesh without it?
well you would use old gameobjects for your rendering representation. if you need a pure ecs entity rendered without gameobjects then the hybridrenderer would be required for you
it works