#archived-dots
1 messages ยท Page 56 of 1
I see, let me check this out
facepalm nope, me being a fool, didn't install a render pipeline, standard isn't supported by graphics package
ok ๐
Yeah, URP or HDRP for DOTS ๐
Thank you for the assistance though!
Yeah, its been a minute since I created a new project instead of working on the same one, slipped my mind that was a requirement
Reasonably so imho. I don't remember that requirement being stated anywhere in the editor elements of things so easy to miss.
this feels poetic - open ecs network racing sample
Loading Entity Scene failed because the entity header file couldn't be resolved. This might be caused by a failed import of the entity scene. Please take a look at the SubScene MonoBehaviour that references this scene or at the asset import worker log in I:\Documents\Demos\ECS Network Racing Sample\Logs. scenePath=Assets/Scenes/Subscenes/Garage.unity guid=9803f74949f661b4cb495cc790f62801
I had that error too a while back. Don't remember how I fixed it.
oh mate, it's a constant thing
i just found it amusing first thing i saw opening their sample
heh, fair
Unity.Entities.IBaker.AddDebugTrackingForComponent (Unity.Entities.Entity entity, Unity.Entities.TypeIndex typeIndex) (at Library/PackageCache/com.unity.entities@1.0.0-pre.15/Unity.Entities.Hybrid/Baking/Baker.cs:1282)```
this one was less expected o_O
i remember someone mentioning this on forums a couple of weeks ago
Can anyone comment on what is going on during "ImportOutOfDateAssets" during RefreshV2 while recompiling? Using superluminal it says that it is almost 25 seconds (20 being to "SwapContext")
firstly, are you making asset changes?
no, just adding a comment in a script and then compile
which takes roughly 80 seconds, but working with some profiling tools it seems the compilation time itself is roughly 5 seconds
yeah, wasting a lot of time so finally decided to jump into profiling, though my experience is limited
UnloadDomain 40 sec of that
how big is your project?
pretty big, 8 gb assets, project folder 40gb total
though I duplicated the project, tore out most all of the assets (meshes and textures) and didn't seem to have a significant impact
I wouldn't be surprised if it were time due to compilation since the architecture is a mess but since profiling says the compile times are low I am looking at what else could cause it, though I may be approaching the data incorrectly
i was more curious about scripts
do you have a lot of statics
is your project split into asmdef
Yes, quite a few asmdef
I am struggling to measure the direct cost of each of the asmdef assembly loads
ok so beast of a machine
(that said single thread not cores matters much more here)
unfortunately, no idea ๐ฆ
yeah, when I get some time I am swapping out
any idea how big of an impact? this threadripper average clock is like 4 ghz, i see 5.2 ghz benches for 13 series.
i'm using a 3900x which is more cores than ST (it's ok though)
so i can't really say
but i doubt it's magically going to fix you down to a few seconds from 80
one day domain reload will be a thing of the past. ๐
Rename all, Domain -> Environment
unity on .net 7.0
just imagine
I feel like they should migrate their whole engine to .net
pretty sure they're doing that (but .net 6)
since that's the LTS version
multi year job though
yeah, I heard that's smth that is target for 2023
but just scripting though
not actual engine
you want them to rewrite their c++ engine in .net?
or do you just mean the c# front end?
yeah
They already rewrite some parts
yes its taken 5 years to rewrite tiny parts of engine
in dots
for the benefit of probably running slower?
eh user scripting end is enough ๐
i don't even want to know how long the c++ side of unity needs to compile ๐คฃ
maybe they should migrate their front end to c++ ๐คฃ
Dots racing sample is out?
yeah came out yesterday
Can someone explain how its possible that we can destroy entities during a query ? Even without buffering ?
Does entities iterates backwards over the chunks/entities to make that work ? ^^
What do you mean?
EntityManager.Destroy(EntityQuery)?
nice, those samples are so low key released. nothing in the forum (?)
yeah there
I mean entity destruction in general.
like :
Entities.ForEach(...){
manager.Destroy(entity);
}.WithStructuralChanges();
This iterates over entities and destroys them at the same time.
How does entities manage that ? Normally its not possible to iterate forward over a collection and to delete items from it at the same time ^^
Or do queries iterate backwards ?
WithStructuralChanges causes them to copy to a new entity array
its basically
foreach(var entity in query.ToEntityArray(Temp))
manager.destroy(entity)
oh thanks for posting the link ๐ haven't looked at the thread for 2 days lol
Ahhh thats interesting ^^ thanks.
Would it also be possible to iterate backwards over entities ? Wouldnt this allow us to delete/add/remove entities during a query without extra copies ?
using a query for destroy is very different - it's very efficient
Since backwards iterations are usually used for this purpose
Ah i see, thats nice ^^
And on a single entity basis ? Would it be possible to do backwards iteration + destroy ?
Atleast in theory it should be possible, right ?
I don't think you will see any significant performance improvements, the memory copy is very fast
No its not about performance, im just curious if that works ^^ without copy stuff into a new entity array
I'm sure there's a way to shoehorn it in, but there's probably not much point
(especially since Entities.ForEach is deprecated in 1.0+)
It is ? ๐ฎ havent updated yet, whats the alternative ?
Either use a job, or a query
Whyyy ? I loved the entities.foreach syntax ๐ฆ
e.g.
foreach (var (component1, component2) in SystemAPI.Query<RefRO<Component1Type>,RefRO<Component2Type>>())
{
//logic...
}
It was changed to support nested loops iirc
And I think it makes more sense syntax wise in C#, with closures being an issue in the language normally
it was changed because it's super slow
I thought it was re-compiled to generated code anyways?
I never looked into how it worked
That's pretty interesting
yeah i mentioned it a while ago thinking about this
going to be hard to analyze and strip certain dependencies
Yep sounds tricky but would be pretty cool
So the old Entities.ForEach cannot tell the difference between enabled and disabled components
not sure if this is a bug or intentional
I wouldn't be surprised if it's not supported given it's being deprecated, but I never tested it
I don't think this is the correct channel for that, try asking in the graphics channels
Are querydescription obsolete now ?
Are aspects a replacement ? What are aspects ? Dont understand their purpose yet
Query descriptions are replaced by SystemAPI.QueryBuilder(), which is more concise.
Aspects are groupings of (optional) components and methods that act on those components, and can be queried as you would any other type of component.
Thanks, feels like they added several layers of abstractions and new concepts to it. Not sure if i like it, feels so... Complex right now
A lot of the stuff is functionally identical, just the syntax is cleaned up. A lot of the new stuff is completely optional (e.g. aspects)
The only thing "removed" is scheduling inline jobs using Entities.ForEach, which now requires a job struct
(which is actually less abstract than before, at least in the case of IJobChunk)
The only other "big" thing that was changed significantly that I can think of right now is the baking system, since runtime gameobject conversion was removed. Impact depends on how much you were using that
Hmm, guess you are right. Probably just feels overwhelming since so much syntax changed
Yes there's definitely a few things to "re-learn" ๐
Has anyone experienced something like this before? Note the lid, it has a small cube on it that is just a child collider + mesh. When I attach the lid to the box, they are connected via Fixed joint, no transform parenting. Whenever the box falls on the lid, it does that jump. I assume it's because of the joint? I removed that small cube on the lid, so it's just a flat lid. The behavior is the same. How can I reduce this issue with the joint?
Hi guys, I got a new problem on a android device with subscene. In the editor when I load to the battle scene, sub scene in the battle scene work well, but on the android device it totally disappeared. Does anyone know the reason?
Noted: I'm using DOTS ver 1.0.0 pre 12, and unity ver 2022.2.1.f1
your subscene is open in this picture
does it work when closed
because at the moment you're just rendering it as a gameobject
yep, I just open to capture the demo
what srp and what graphics api?
vulken or opengl 3?
(i think those are the current android ones right)
have you tried a devleopment build
I'm using URP and Vulkan graphic API
I just tried a development build, but it still doesn't work
ah, I'm using IL2CPP for scripting backend mode
Am I asking dumb questions, or does no one really know the answers?
๐คทโโ๏ธ i've never used a joint
ooo the dynamic occlusion in graphics is much better than it used to be
supports shadows now, can't fault it so far (well except if you turn off burst it has constant safety warnings)
really curious about large scale performance
but sir, just think about it. They made burst for C#, they rewrote their 2d physics from C++ to Burst.
They made UI Toolkit for C#.
And .net is moving towards cross platform, which suits Unity needs very well.
burst is really just a wrapper for llvm
can just run it direct on the c++!
then unreal can buy them out
Hey dudes, what is the proper way to handle it?
Request: Path finding from a source to a target point.
They are added to a list/queue.
How can I add these requests to job list and schedule them(job system)?
For example after there are n requests, then schedule them using job system?
or consider time, after n seconds check that request list and then schedule and run them ?
Request Queue: Request 1 (source 1, target 1),Request 2 (source 2, target 2),...,Request N (source N, target N)
Output: Path Result (Request 6), Path Result (Request 1), Path Result (Request 3), ..
Wouldn't you just have a NativeList or DynamicBuffer of requests and check length or time since last scheduling then make the job and schedule/scheduleparallel?
thanks, so my way is correct?
Consider time or count and compare it with a threshold, then schedule them,..
I'm still "just" a student and I generally hesitate to claim hard truth in any matters. It's just the way I would do it off the top of my head ๐
But yeah, for "gather X until Y limit then do Z" is quite normal in that fashion
Me too ๐คฃ logical
Perfect
Now, I think how I should choose those thresholds (time and count)
๐ It depends on hardware
I think count is the 'better' threshold generally speaking but yeah, it depends on what your exact needs are, the hardware you're running on and as always regarding performance: profiling if its that important ๐
Speaking of profilers and performance, here's a great talk on how "just use a profiler" doesn't necessarily help you solve the problem: https://youtu.be/r-TLSBdHe1A
Performance clearly matters to users. For example, the most common software update on the AppStore is "Bug fixes and performance enhancements." Now that Moore's Law has ended, programmers have to work hard to get high performance for their applications. But why is performance hard to deliver?
I will first explain why current approaches to evalu...
I think it should be dynamic
Because this game does not run it only in my pc
The benefits of code: if you have condition A and condition B, you can make condition C based on the two ๐
is it possible to SetName inside a Baker?
Does anyone know off the top of their head of this physicsCollider.Value.Value.SetCollisionFilter(negatedFilter); will affect just that collider instance, or the shared collider held by all instances?
Is it valuable to add [ReadOnly] attributes for fields/containers of nested struct types used in jobs?
JobA -->
Fields
NestedStructB
Container1 --> [ReadOnly] attribute
and ReadOnly containers I mean NativeArray<>.ReadOnly is efficient like NativeArray itself without ReadOnly?
I think I read somewhere earlier in this chat that things marked ReadOnly outside of the job itself has no influence on what the job sees/knows - but I'm not sure, especially not about nested structures.
It is not outside. It is nested
OK, perfect
What is the proper way to create and return a native container from a private method and then dispose it?
PopulateAndGetContainer(out var container);
//...
container.Dispose();
var container = new NativeArray<>(,);
PopulateContainer(ref var container);
//...
container.Dispose();
var container = GetContainer();
It does not work because it is value type, copy it
you don't, use a singleton component instead
if it's not shared, the second approach from you should be fine too
where you just use ref
Oh wat ๐
InvalidOperationException: Can't call GetSingletonEntity() on queries containing enableable component types.
Why u can't do this?
It's not supported
No plan to support it in future?
No plans as of now. It would require adding a lot of sync points to block and make sure singleton foo was both present and enabled where currently it just being present suffices and requires no blocking
as a workaround
you can either create/obtain singleton during OnCreate phase just once
oh wait
on queries
nvm any of that
๐
hm what use case has enableable comps on singletons?
simple workaround could be singleton + bool field
he mentioned queries
so it's probably not singleton
it's singleton entity in query
i had never considered it but after hearing it i thought of some ideas
like current application state
like you can have 10 of these components but if 9 are always disabled you can swap what is passed
ah like merging several singletons into 1?
think, difficulty level
you could pre-bake 10 different versions
and just enable 1
depending on level/settings/etc
i'm not saying i'd do it this way, just what popped into my head when i read it
finally someone else brought up my issue with ECS right now :
https://forum.unity.com/threads/decoupling-in-ecs.1376892/#post-8684067
if anyone has good solutions plz contribute
I've heard that Unity will release some free course for learning DOTS/ECS on UnityLearn, did they communicate a release date for that ?
I have so many packages I think I have the opposite problem
Maybe i just dont get how to decouple then
I don't think you're alone
my biggest issue is that i lack the terminology to explain it properly
and i dont want to be rude or anything but what am i supposed to answer to Monarchs reply : "an interface?"
I guess we need to separate coupling here into 1 or both way
I think a stat system is a very low level concept that should depend on nothing
But an equipment system that builds upon it, is it OK for that to depend on the stat system?
No idea, I could write equipment system that wasnt coupled to my stat system simply by having it create start entities without and knowledge of what they are
But should I worry about this level of decoupling? Maybe.
But probably not
I think an equipment system jobs of goes hand in hand with the underlying stat system
So I think of this problem more as a hierarchy of 1 way dependencies instead of a complete removal
My 30 seconds thought while on a tram
Another example I guess is rival, I can easily plug my own camera and input systems into it
i see. but i think it really depends on the packages. maybe in your cases its alright to have this coupling. But abilities that can be affected by physics, ai and movement for example are way too intertwined here
you would make your abilities dependent on all of those other packages...
with aliasing ComponentData you could decouple everything
Well Ai I think depends on most things
But the underlying library doesn't need to be coupled to it
That assumes every package had the same data requirements
You can kind of use write groups for this as well
Actually write groups in a way are a direct solution to solve this
thats what i meant in the forumthread with we need some way to translate between ComponentData then
but only if you control all packages right?
No?
Whole point of write groups is the library can depend on a component it doesn't know about
oh damn i need to read up on it again. i never got the real usecases for them. aside from making systems ignore certain component combinations
Say you have component a in your library and the default system to write to it from b, a user has another library and wants to use their component c instead of b to write to a, they can write group and the b to a system will ignore this component c
Anyway brb 90min gym
yes but the user has to reimplement the whole system for his component right?
what i want is that the system runs exactly as before but the users component is used in place of the packages component. as well as the packages component. like they are internally treated as the same component.
Believe that's called generics ๐
Actually you kind of explain why my Ai system is implemented entirely with generics
So I guess this is not a problem I am unfamiliar with
but even with generics it means you need to run multiple generic systems instead of just one
ah ok yes my case is a little different. i get what you mean
But I think you're detailing exactly what my thought process was at the time
but yes if the whole physics package was written in a generic way and lets the user Create his own Component to use for Velocity for example that would work.
its just not something that is ever going to happen
I don't really understand physics logic here though
Are you expecting someone to implement their own physics system
I guess that's the question
no but i expect someone to have systems in multiple packages that could modify Velocity for example
id need to tell all those packages that "MyUserDefinedVelocityComponent" is what they need to use as their internal Velocity component
if all of those systems have generic systems in place for "output and input" to the Package boundaries then you can make it work.
Can't you just have a barrier to copy to and from this component
sry man i dont want to keep you from getting buff. you dont have to reply right now ^^
Actuality this is what I do with my orca system. I use a custom transform in a single array instead of entity components
yes but do we want to do that for every package boundary
Oh I'm on my bike waiting for class to start
Just wait till you realise you need to tag your components for ghosts and netcode
oh god im actually so afraid of even looking at netcode... i dont want to see my AI solution go up in flames
Well the good news is if it's just Ai that's likely nearly all server side
It's more abilities and stuff that need to be network considered
yes thats right but even serverside my architecture might be bad. i rely on the fact that i do alot of scheduling on mainthread but all of the work on workers. i think most servers want to run multiple serverinstances of singlethreaded code on one processor.
recieved this error message with this code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Entities;
using Unity.Collections;
using Unity.Mathematics;
public class CameraSync : MonoBehaviour
{
private Entity ECam;
public GameObject GCam;
void Update()
{
if (ECam == null)
{
EntityQuery CamQuery = new EntityQueryBuilder(Allocator.Temp)
.WithAll<CameraData>()
.Build(World.DefaultGameObjectInjectionWorld.EntityManager);
if (CamQuery.CalculateEntityCount() == 1)
{
ECam = CamQuery.ToEntityArray(Allocator.Temp)[0];
}
}
else
{
var CamComp = SystemAPI.GetComponent<CameraData>(ECam);
GCam.GetComponent<Camera>().orthographicSize = CamComp.Zoom;
GCam.transform.position = (float3)CamComp.Pos;
}
}
}
``` Is it failing due to the entity query?
edit: im an idiot nevermind
i would guess that SystemAPI is not available in monobehaviours. i assume the codegen only works inside systems
oh clever, so i should just add a wrapper from inside a systembase that i can then call from a monobehaviour?
no you should use getcomponent from entitymanager
ah ok thanks a ton!
So this is the Burst compiler?
is WhateverEntity == null the proper way to check if an entity is blank, or is there a better way?
entity.null
ah so WhateverEntity = entity.null? Thanks a ton!
EntityManager.Exists(Entity) if in the main thread
ah ok thanks!
which is equivalent to EntityManager.GetSharedComponent for jobs? Something like ComponentLookup but for shared components.
hmm im on the main thread in a monobehaviour but Exists(WhateverEntity) is returning true, but then when i go to use GetComponentData() it tells me the entity does not exist, this is all within the same frame, odd
switched to using the Entity.Null and it is working now, thanks yall!
This will stop working if you destroy the entity
for now i dont need to delete the entity, i'll cross the bridge once i come to it, atleast Entity.Null works for now!
80% of the time if there's a feature you want i've probably already implemented it in my library ๐
Thanks
there's even a version in there that lets you access managed shared components in jobs (not bursted) via scd index
if you dont want the full library
checkout
SystemStateExtensions and EntityManagerExtensions
on how to create it
/// <summary> System responsible for sending a join request and waiting for the connection before moving us into game. </summary>
[BurstCompile]
[UpdateInGroup(typeof(ClientStateSystemGroup))]
public partial struct ClientJoinGameStateSystem : ISystem, ISystemStartStop
{
[BurstCompile]
public void OnCreate(ref SystemState state)
{
StateAPI.Register<ClientState, StateJoinGame, ClientStates>(ref state, "join-game");
}
[BurstCompile]
public void OnStartRunning(ref SystemState state)
{
var ep = NetworkEndpoint.LoopbackIpv4.WithPort(BovineLabsBootstrap.Port);
SystemAPI.GetSingletonRW<NetworkStreamDriver>().ValueRW.Connect(state.EntityManager, ep);
ClientAPI.UIEnable(ref state, "load-screen");
}
[BurstCompile]
public void OnStopRunning(ref SystemState state)
{
ClientAPI.UIDisable(ref state, "load-screen");
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
this.WaitForConnection(ref state);
this.WaitForGhost(ref state);
}
[SuppressMessage("ReSharper", "MemberCanBeMadeStatic.Local", Justification = "SystemAPI")]
private void WaitForGhost(ref SystemState state)
{
var query = SystemAPI.QueryBuilder().WithAll<GhostOwnerComponent, Player, LocalPlayer>().Build();
if (query.IsEmptyIgnoreFilter)
{
return;
}
ClientAPI.StateSet(ref state, "in-game");
}
I've been leaning into cleaning up syntax of my game library with SystemAPI like syntax to hide a lot of the behind the scenes
what do you think?
pretty nice ๐
just opened my project and it appears my subscene is broken, is this normal or a bug or something else? (also i can still see the entities in the subscene in scene view, albeit using the default unlit pink texture...)
try reimport entities package (right click import)
ok ill try that!
wait what do i have to right click, as im right clicking on the package in the package manager and nothing is being pulled up
in your project folder
ah ok, ill go hunt for it!
ok i reimported entities and it really did not like it
upon restarting unity it seems to have fixed my subscene though, so thanks a ton!
I'm trying to use AssetDatabase.FindAssets(filter) and want to look for a scriptable object that inherits from a class. Is that possible?
Oh, I see, it's because it was generic class, that's why it wasn't coming up.
yeah it's often handy to just inject an empty non-generic base for finding
settings<T> : settings
settings : scriptableobject
Yup. That's exactly what I did ๐
Whipped up an abstract class and it all works now
does GetExistingSystemManaged<>() pass by reference or by value?
Reference
ok thanks for the info!
It`s class
ah, guessing all classes get passed by reference then?
Yes
ok thanks a ton!
is there a dots version of Gizmos.DrawWireCube()?
no
ah that is unfortunate, thanks for the info!
What the
somehow
having Dynamic PhysicsBody causes
DrawMeshInstanced does not support the shader 'Universal Render Pipeline/Lit' because it does not read any instanced properties. Try switching to DrawMeshInstancedProcedural if the shader is doing procedural instancing.
I don't get it
if I disable PhysicsBody
no error
btw, is there any explanation to this?
there is no render mesh
only full recreation of object helped
which is odd
Why does this struct in the Rival OnlineFPS sample have OnSystemCreate and OnSystemUpdate methods?
public struct FirstPersonCharacterUpdateContext
{
// Here, you may add additional global data for your character updates, such as ComponentLookups, Singletons, NativeCollections, etc...
// The data you add here will be accessible in your character updates and all of your character "callbacks".
[ReadOnly]
public ComponentLookup<WeaponVisualFeedback> WeaponVisualFeedbackLookup;
[ReadOnly]
public ComponentLookup<WeaponControl> WeaponControlLookup;
public void OnSystemCreate(ref SystemState state)
{
WeaponVisualFeedbackLookup = state.GetComponentLookup<WeaponVisualFeedback>(true);
WeaponControlLookup = state.GetComponentLookup<WeaponControl>(true);
}
public void OnSystemUpdate(ref SystemState state)
{
WeaponVisualFeedbackLookup.Update(ref state);
WeaponControlLookup.Update(ref state);
}
}
What.
Oh yeah I thought that's what OnCreate and OnUpdate were named with ISystem.
But no they're called OnCreate and OnUpdate even with ISystem.
This OnSystemCreate really means "on FirstPersonCharacterPhysicsUpdateSystem create."
FirstPersonCharacterPhysicsUpdateSystem's OnCreate calls it:
[BurstCompile]
public void OnCreate(ref SystemState state)
{
_characterQuery = KinematicCharacterUtilities.GetBaseCharacterQueryBuilder()
.WithAll<
FirstPersonCharacterComponent,
FirstPersonCharacterControl>()
.Build(ref state);
_context = new FirstPersonCharacterUpdateContext();
_context.OnSystemCreate(ref state);
_baseContext = new KinematicCharacterUpdateContext();
_baseContext.OnSystemCreate(ref state);
state.RequireForUpdate(_characterQuery);
state.RequireForUpdate<NetworkTime>();
state.RequireForUpdate<PhysicsWorldSingleton>();
}
And its OnUpdate calls _context.OnSystemUpdate(ref state);.
It's a way to handle the getting/updating of componentLookups defined in the context struct, but all in one place. That context struct needs to be built by 2 different systems, so it saves you from writing that logic in multiple places when adding new lookups
Oh yeah it's used by FirstPersonCharacterVariableUpdateSystem too.
hmm if i have an authoring component on a gameobject that has a child gameobject, I cant access the resulting entity that comes from the child gameobject in my parent's baker?
getting InvalidOperationException: Entity Entity(16:1) doesn't belong to the current authoring component.
out works as well
Usually, how do you choose batch count in IParallelJobFor, Schedule?
Thread count, core count?
depends entirely on your data set
batch count is != thread count
if you wanted even load you'd do length / thread count
generally you'd use either 1 or some somewhat arbitrary high value like 128 or 512
1 if your per index cost is really high, otherwise you won't notice much different as long as you don't use too low or too high a value
merry christmas all ๐
i love how my ui works
do you use some sort of pattern?
tertle makes it up #7
i use my state flags to control active panel / popups
which i recently just added history support to so i can pop/forward/back UI states
i use uitoolkit
and each panel is it's own system
each panel can control subpanels etc without new systems
up to the panel
let me show you the most basic panel
{
/// <inheritdoc />
protected override string StateName => "menu";
/// <inheritdoc />
protected override TypeIndex StateInstanceComponent => TypeManager.GetTypeIndex<UIMenu>();
/// <inheritdoc />
protected override void OnLoad(VisualElement panel)
{
var playButton = panel.Q<Button>("play");
var joinButton = panel.Q<Button>("join");
var optionsButton = panel.Q<Button>("options");
playButton.clicked += this.PlayButtonOnClicked;
joinButton.clicked += this.JoinButtonOnClicked;
optionsButton.clicked += this.OptionsButtonOnClicked;
}
private void PlayButtonOnClicked()
{
ClientAPI.StateSet(ref this.CheckedStateRef, "host-game");
}
private void JoinButtonOnClicked()
{
ClientAPI.StateSet(ref this.CheckedStateRef, "join-game");
}
private void OptionsButtonOnClicked()
{
ClientAPI.StateSet(ref this.CheckedStateRef, "options");
}
private struct UIMenu : IComponentData
{
}
}```
my menu panel, 3 buttons
when OnLoad is called?
{
if (this.panelElement == null)
{
var assets = this.EntityManager.GetComponentObject<UIAssets>(SystemAPI.ManagedAPI.GetSingletonEntity<UIAssets>());
var asset = assets.Assets[this.stateKey];
Assert.IsNotNull(asset, $"No UI asset set for {this.StateName}");
this.panelElement = asset.CloneTree();
this.panelElement.name = this.StateInstanceComponent.ToString();
this.panelElement.pickingMode = PickingMode.Ignore;
this.panelElement.AddToClassList(RootClassName);
this.OnLoad(this.panelElement);
this.localization = new UILocalization(new LocalizedStringTable(assets.StringLocalization), this.panelElement); // TODO
}
this.OnShow(this.panelElement);
this.AddToParent(this.documentSystem, this.panelElement, this.Priority);
}```
first time onstartrunning executes
oh, you load uxml through subscene?
but yes, everything i load is through subscenes
all my data / settings are baked
My goal here is to tie existing UI patterns (MVP/MVVM) with ECS World as Model
while also keeping modularity and no need for baking
what you're seeing here is my model
and i don't believe in using ecs without baking ^_^
no I mean
not Baking as Conversion
but baking as making it prehardcoded in editor
I want a possibility to load additional UI logic through runtime, potentially
allthough I never even considered using subscenes to load UI ๐
or just replace / edit it with uss
now that you showed me, I think that's the way
allthough I want to have some OOPish generic logic behind creation and keep it all in one system
that's far from true now with content management
I haven't really looked into it yet
sooo, here's what I thought of for now:
- I load UI data through subscene.
- Each UI panel will have it stored on some component
- Then as entities with those are loaded, main (and hopefully the only) UI system will query over them and instantiate panels into runtime data using some virtual method
- As panel instantiated, entity gets a tag
Instantiatedand is ignored by system
@rotund token do I need to do any extra to serialize VisualTreeAsset in a subscene?
I never really thought of how you store managed data in subscene
no its just a unity asset
you can store it on a managed icomponentdata
public class UIAssets : IComponentData
{
public VisualTreeAsset[] Assets;
public Guid StringLocalization;
}```
[Serializable]
public class UIDataContainer : IComponentData
{
public VisualTreeAsset source;
}
ah yeah, so I though
๐
i'm a huge fan of uitoolkit with entities
can I serialize type somehow?
type of what
Type that needs to be instantiated
sorry is it a icd or just a general managed type
Just general
you could serialize a fully qualified name and just look it up at runtime, or serialize stabletypehash and look it up via typemanager
Does TypeManager works with non-ICD types?
TypeManager.GetTypeInfo(type).StableTypeHash
ComponentType.FromTypeIndex(TypeManager.GetTypeIndexFromStableTypeHash(hash)).GetManagedType()
but I don't have T in this case
var type = TypeManager.GetTypeIndex(typeof(UIDataContainer));
var hash = TypeManager.GetTypeInfo(type).StableTypeHash;
var index = TypeManager.GetTypeIndexFromStableTypeHash(hash);
var kek = TypeManager.GetType(index);
so, should be like this
oh yeah that works as wlel
๐ค
or maybe I should just serialize monob attached to entity
damn, I need to figure a convinient way to serialize specific class
I would love to see your project or at least one that uses ECS and UIToolkit @rotund token
^ i posted yesterday how my API is shaping up for UI and game states
but i am considering releasing this game UI at some point
i just have a small licensing issue on 1 part of code, that i can probably safely conditionally compile out
I've also been experimenting with entities with UI Toolkit and happy with my progress so far. There are five entities here: 3 buttons, 1 label, and 1 container for the buttons. Each entities holds a visual element component, a input component (updated per frame), and additional components as needed (e.g. tweening).
you took it even further than me by making your UI entities; that's interesting
i just took a shower and was thinking about AI and I've just realized the biggest issue my AI system had, the effort of getting data into it, has been solved by aspects in 1.0 and now i want to go work on that again...
are the official unity tutorials uploaded somewhere for dots? Like the "flocking " demo?
https://github.com/Unity-Technologies/EntityComponentSystemSamples
is probably the closest thing
Thank you! That's exactly what I was looking for
@rotund token welp, sadge.
StableHash solution only works on component data.
And no, you can't attach any managed class to entities anymore it seems
what can't you attach
i attach animators/stuff np
but yeah wasn't certain about stablehash
not sure how manged components serialize tbh
i guess not with stable hash then ^_^'
just used the fully qualified reference like normal serializers do then?
ArgumentException: Unknown Type:UI.MainMenuPresentation All ComponentType must be known at compile time. For generic components, each concrete type must be registered with [RegisterGenericComponentType].
as soon as I add this object to SubScene
without even closing it
it gives me this error
public class MainMenuBaker : Baker<MainMenuAuthoring>
{
public override void Bake(MainMenuAuthoring authoring)
{
AddComponentObject(new UIDataContainer
{
source = authoring.asset,
type = UIDataContainer.Convert(authoring.Type)
});
}
}
it's triggered from AddCOmponentObject
from
Convertmethod
public static ulong Convert(Type type)
{
var index = TypeManager.GetTypeIndex(type);
return TypeManager.GetTypeInfo(index).StableTypeHash;
}
which is just this
in other words, some random class is not registered in TypeManager that's why it throws
I guess the other way around
Make type IComponentData
I wonder how inheritance works with this one
hmm
making Abstract class ICD fixed error
allthough need to check whether it works as intended in runtime
not good. Loading such object causes Editor to throw hundreds of errors
if you make some abstract class inherit ICD and then inherit from this abstract class, it makes Editor go nuts and require restart as soon as you load game
making the type ICD directly fixes it
why would you make an abstract icd
I'm experimenting with different implementations
I want as less boilerplate as possible
I need to tie VisualTreeAsset and specific type with it
as in, View and it's logic
hmm
yeah, I guess
serializing as string would make more sense
or not?
hmmm
why would it not?
I might want to attach those to Entities as comp
because I want cross reference resolved somehow inside
for example, presentation A wants to know about presentation B and etc
itd be as supported as your source field
idk how to design it properly
should I store those managed objects inside 1 system
or attach them to components?
i still don't understand why systems aren't used for the logic
because there is no logic
^
public class MainMenuPresentation : BasePresentation , IComponentData
{
[SerializeField] private BasePresentation settings;
[SerializeField] private BasePresentation play;
private void StartTheGame()
{
EntityManager.SetGameState<GameState.Aim>();
SetEnable(false);
play.SetEnable(true);
}
private void OpenSettings()
{
settings.SetEnable(true);
}
protected override void OnInit(VisualElement root)
{
root.Q<Button>("QuickPlayButton").RegisterCallback<ClickEvent>(_ => StartTheGame());
root.Q<Button>("SettingsButton").RegisterCallback<ClickEvent>(_ => OpenSettings());
}
}
All it looks like mostly
I instantiate them this way
protected override void OnUpdate()
{
using var buf = new EntityCommandBuffer(Allocator.Temp);
foreach (var (uiData, e) in SystemAPI.Query<UIDataContainer>().WithNone<UIInstantiated>()
.WithEntityAccess())
{
var typeIndex = TypeManager.GetTypeIndexFromStableTypeHash(uiData.type);
var type = TypeManager.GetType(typeIndex);
Debug.Log(type);
buf.AddComponent<UIInstantiated>(e);
try
{
var presentation = (BasePresentation)Activator.CreateInstance(type);
presentation.OnCreate(uiData.source, World);
_presentations.Add(presentation);
}
catch (Exception exception)
{
Debug.LogException(exception);
}
}
buf.Playback(EntityManager);
}
so you just re-invented monobehaviours
why not just do your UI on gameobjects/monobehaviours like unity does then?
tying logic between monoB and World is pain
Is worker count limited to core count?
So, if it is 7 cores, execution time is aournd 1/7 by using all worker jobs.
worker count is hard limited to 128
this is defined in JobsUtility
/// <para>Maximum job thread count.</para>
/// </summary>
public const int MaxJobThreadCount = 128;```
Can't it change?
So, why I see just 7 workers in profiler editor
worker 0,..,6
ok sorry i guess that's max worker count
/// <para>Current number of worker threads available to the Unity JobQueue.</para>
/// </summary>
public static int JobWorkerCount
{
get => JobsUtility.GetJobQueueWorkerThreadCount();
set
{
if (value < 0 || value > JobsUtility.JobWorkerMaximumCount)
throw new ArgumentOutOfRangeException(nameof (JobWorkerCount), string.Format("Invalid JobWorkerCount {0} must be in the range 0 -> {1}", (object) value, (object) JobsUtility.JobWorkerMaximumCount));
JobsUtility.SetJobQueueMaximumActiveThreadCount(value);
}
}```
I have created a job schedule with 20 jobs (array length is 20)
you probably want this
but it only uses 7 workers
because your cpu only has 8 cores
Is worker count limited to core count?
So, if it is 7 cores, execution time is aournd 1/7 by using all worker jobs.
so, the answer is yes?
For example my 20 jobs, every job takes 100ms
assuming main thread is not chipping in then on 7 cores that's going to take 300ms
total time is around 500-600 ms
i see 23 for example
I think I know the secret to bringing DOTS to the masses: Prebuilt systtems
Colliders/Trigger Colliders/ETC/ Get all the generic sysetms ready
Then have a few core projects like FPS/Space shooter/2d platformer/3d platformer
I mean DOTS/ECS prebuilt FPS might beat Unreal at their niche FPS market
or maybe just fix all bugs with baking and editor ๐
also give us a bit of 2d tools
at very least renderer
I'm on .51, I don't have bugs.
๐
For real tho, systems are things I get done and almost never want to touch again
Ok, that's all I got, cya
what is your cpu?
once ecs is stable and in a few years, it will be more akin to plug and play when it comes to systems
Hey people. I was wondering if it's possible to refer components by the interfaces they implement in ecs? For example querying components that implement a certain interface and passing them to a job?
querying by an interface is not possible
not in the straight forward way. it can go in roundabout way with implementing generic systems that have an interface as constraint
Hm... Okay. Another newbie question then. Can ECS components have array fields?
you can nest Native collections
Okay. Then what's the point of dynamic buffers? Is it because collections in components have to have a constant size?
well, collections indeed have to have constant size
but since native containers are just pointers
that's no problem
buffers were used before you could nest collections into comps
Aah, I see. Thanks.
they still are used
In what situation?
well, it's simply easier to manage collections that way
if you nest array into icd
you'll have to ensure its created
you can use nativearrays in compdatas now?
and that is either new system or instantiation pipeline
since 1.0
interesting I should get to updating soon
I see. Thanks for the explanation!
sir, what is ClientAPI?
And how do you resolve panel switching?
I am at a point, when I need my game to change current UI panel
and I'm not sure of a way to do so
I use my state system
To actually visually do it, I just remove / add it to hierarchy
Is that some kind of built in feature or your own code?
It should be 20, why the number is 7?
_jobHandle = job.Schedule(inputPoints.Count, 1);
_jobHandle.Complete();
inputPoints length is 20
That's not how the array length field works
It's just a while loop and requests work for this job until there is none left
If you click on it take a picture of the popup
It is empty, OK
Eh what
Click find pathfinding job
If I execute 20 jobs in parallel, shouldn't I see 20 blocks?!
How can I see they run
arent the workers your cpu threads, so its 20 jobs shared out through 7 threads
Thanks just wanted to check something
Yes, but I want to see these 20 jobs in the profiler. can't?
There is only 1 job
yeah that's what I thought schedule is just one
hm for calculating rootmotion its obviously the delta position/rot between frames, however when it comes to the looping point of say frame 30 back to frame 0, and the delta becomes a negative "snapback" value, how should/would this part be handled?
Are nullable types and value tuples OK in jobs? performance wise? or define custom struct?
and what is execution time of a burst friendly code over that code on jobs? the ratio approximate
EXETIME(no job) / EXETIME(job)
?
@robust scaffold rootmotion of an animation can be derived from the difference in each frame a model translates on the root bone;
think in an animation clip from 0-30 frames a model can walk forward a total distance of say 30 units.
in a dcc program it will snap back to frame 0 when you play the position and positionally move back to whatever position frame zero was.
in a game engine the model's position change from frame to frame is not applied to the root bone and instead to the rig or gameobject, and obviously when it reaches frame 30 and loops to 0, the negative translation from 30 units to 0 units isnt used, some sort of calculation is made to continue the movement seamlessly.
A conditional where if the next unit is less than current, skip delta?
maybe, could also use the previous delta or average it over all frames but just doesnt feel correct? the old animation package just reads the delta change from the stream with no regard to what frame during runtime so maybe they are precalculating something when they convert clips to blobs? not sure
If I have a list of assets in a scriptable object. How can I bake that in? Say I want that list of assets to be registered as prefabs and their GetEntity(prefab) counterpart get stored either on buffer or components somewhere. How can I do this?
Can I write in elements of a native array? Is it thread safe?
if you use index, yes
Can I print them inside job?
sure, Debug.Log works
index is 0...n and based on how many elements you schedule for the job
Does ECS compare shared components via their IEquatable interface, or does it do it in-house?
By compare, I mean decide if they will be together or in separate chunks.
IEquatable needs to be implemented, at least that was the case when i used them, no in house thingy.
during authoring gameobject fields get turned into entities that can then be used in baking via GetEntity() right? So then if i have an array of gameobjects will authoring turn them into entities aswell, and could i then iterate over them with GetEntity() in a forloop during baking to get an Entity array?
update: yep it works real well!
interface if managed, by value if unmanaged
Thanks. I had to discard IEquatable because it actually overwrote the fields (not considered by IEquatable interface) and merged entities together into the same chunk even though the values were different.
ahem, you are the one who implements it
and how it compares two
I'm actually curious how Unity compares by value 2 unmanaged structs
because
.net does it through reflection
in managed context
Assuming unmanaged blittable, it's easy. Compare the byte equivalents. A struct with reference fields requires reflection for a deep comparison though.
not really
I mean
for some reason microsoft chose to use reflection after all
How else can you compare reference fields by value then?
Unless you hardcode resolve the references of course.
@robust scaffoldoh sir, could you send your physics clamping system?
Last time I saw you mentioned it was just job. And I couldn't figure where it was meant to be scheduled
yeah, this is where source gen comes in
I insert the constraining job right before the physics data export.
hold on
but doesn't it affect resolving of physics?
or it doesn't matter?
in a sense, what if for some reason before physics ticks smth modifies z velocity
Of course it affects the physics. It zeros out the Z and XY rotations.
Assuming that all objects are initially 2D, this job will enforce 2D physics
I thought you insert right after world imported
If you started with 3D physics, then this job will cause unexplained effects as it forces everything to have 0 Z positions and 0 XY angular.
The key part of this is that I dont actually change rotation quat. XY euler angles. Assuming that initial velocity along angular directions of XY is 0. If it for some reason or externally from physics causes XY rotations, this job doesn't enforce 2D on it because converting quat to euler in and back to quat is very expensive.
It seems to work well enough for me. I have not observed any Z positions nor XY euler rotations in any physics collisions. However, I am just using basic spheres and cubes for all my collisions
but, why not do that before physics are resolved though?
so it's 3D proof
as in, if physics objects are imported with z/xy velocities, they will be nullified
Because all the graphical presentation systems occur after physics. If physics for some reason resolves a 3D positions or rotation, the graphics will render it as such.
Yes, the next frame's execution of the job will immediately clamp the position at least to 2D but that's 1 frame of strange glitching. Doing it after prevents that. Although if you want to enforce 2D input and output, just run the job twice.
So far, I havent experienced anything that requires pre-constraining job because I ensure that all gameobjects at bake are in 2D locations when creating them in editor.
I highly recommend giving rolling your own physics engine a shot. Just 2d is enough. It's very educational.
I don't have enough time for such things
It doesn't need to work, well you should at least get circles bouncing off each other, but it really illuminates the black box that is physics.
It only takes a week or two to get spheres bouncing off each other. None of the complex line cast and most penetration axis required for squares and polygons to function
https://johanhelsing.studio/posts/physics-01-balls Here's a physics engine written in bevy which is ECS as well.
I really don't have enough time for this ๐
I have been hammering my head against this goal for days now: I want interpolated movement but predicted collisions. What I think is required is a permanently predicted entity but custom interpolated movement. Using ghost prediction smoothing doesnt seem to change anything.
hmmm, I'm trying to think of a good way to implement this part of UI system
I need to be able to create specific trigger entities from anywhere in ECS and have UI react on that.
Right now the only thing that comes to mind: message system. Some system create entity with component and message "MainMenu"
And then this message is sent to all UI systems and they react through their own hardcoded or not way.
But I feel like there is much better solution
I dont know if my experience with making my entity debugger is of any relevance but I just used change filters everywhere. Primarily structural and one or two value change filters for event and refresh triggering.
well, it's not really about value changes
rn it's simple panel switch
from nothing to MainMenu, from Play overlay to Death overlay
and etc
smth that is not triggered by player input
but rather game logic
I think the closest in my entity ui is enabling and disabling systems in the system list. I just redraw the UI values every frame for that.
For example, graying out large sections of the list "recursively" if a parent system group is disabled. I just call the Refresh delegate every frame.
this kind of thing is better be done through events tbh
but that's not my case either
There's change filters on the big ticket items like rebuilding the entire list structure but for something like showing and hiding panels, that's just a boolean toggle. Negleible performance cost.
Ya gotta think outside of DOTS and ECS for UI design and back to OOS. Delegates, callbacks, and events.
yeah, and rn I think of merging it somehow
well, not really merging
but jsut making a bridge
of some sort
Here's where I process clicking on any entities within the entities list.
you can use _entityView.selectedItem
or selectedIndex
instead of initial check
Selected item may result from a callback from the system list view as well I found. At least there was an error on that. And this is a callback.
Using selected item or selected index will require checking every update for changes vs this delegate being called when something does change
You still have to check for null.
Ugh, happy?
yeah, that feels better for me ๐
hmmm
I Just had an idea
what if I use a similiar to browser http requests
Here's the bridge between DOTS and the UI
Where get query is basically an interface for EQB.
so some game logic requests "main-menu" address
Every UI panel which have this adress defined will be opened, while everything else closed
That's basically just setting the root visual element's class.
And then on the CSS assign visibility properties to various elements using a class inheritance.
oh no no no
this caused me tons of perfomance issues
I simply remove VE from UIDocument root
so it's not rendered at all
and there is no need for visiblity classes
If it's not displayed, it shouldn't be rendered anyways
of any sort
but it's still catching callbacks
this was a case for me back in 2021 or 2020
don't really remember
I dont know, that wasn't my experience with the current UI toolkit at least. I set something's display to none and it completely disappears. That's how I toggle the chunk info box on the side. It doesnt just go invisible, all visual elements resize properly as if the VE no longer exists.
And that chunk info box is very expensive. Lots of custom CSS and other fuckery to get all the elements to work properly. If it just went invisible, there would still be a very slight but measurable performance cost when I hover over and click on where it used to be. But it doesnt.
Should I turn off memory leak and safety check, job debugger when building or it is done automatically?
Automatically. Generally, just don't touch the safety options.
Thanks, so it is turned off.
What about memory leak?
Because it has overhead
all safety is editor only
or debug only, not sure
in release build you are free to crash your pc however you want
๐
Is there any word on when / if graphics will support some of the 2D only features, like sorting groups?
๐ฅฒ
I have such a strange issue that has randomly cropped up. For some reason one of my prediction systems is reading some old value for a synchronized component, even though the system that writes the player's input to that component is reading the correct value...
I'm guessing I broke something since if I revert to a much earlier version it works, but I can't for the life of me figure out what is going wrong
Are there some kind of special considerations for systems in the PredictedSimulationSystemGroup when adding required components for updates?
I can't find anything in the docs...
Anyone know if you can bake an array of GameObjects?
I tried iterating through the objects, calling GetEntity and adding them to a NativeArray<Entity> but it ended up adding my SceneSystem Entity instead of my GameObject's Entity, like it's not evaluating my GetEntity the same way.
Ideas?
for some context, I'm making an array of possible enemies, which I could (and now have to) seperate into all individual attributes.
But i'd like some easier way to just reference my list of possible prefabs
The list of possible prefabs as game objects or as entities?
As Entities preferable, but if there is a different way than baking to turn a GO into an Entity, then list of GO would be good too
I bake prefabs this way
store them in serialized array on other GO
and then process it in baker
you can attach your own temp tag, that will remove Prefab tag during baking
All right, so I decided to make HTTP like system for my UI to connect it with ECS
I wonder how it'll work out
what are you baking your array into?
into entities
stored in? a nativearray? or static class?
entities are stored in a world
you can only store references to them
right but what do you store your references in? I tried to store mine in a native array, and it stored a reference ti my SceneSystem instead of my prefab's entity
in a component on other entity
allthough
in my particular case I don't store anything
they are ready as they are loaded, I just query them in systems
If you call GetEntity it should give you the entity for that game object which was registered with the dependency system
I do, but when I store the reference in a NativeArray<Entities> and fetch it in a System to instantiate, It's a reference to "SceneSystem" instead of my other object.
But if I store it as an individual Entity entry, it works fine.
I'm not sure if storing it in a NativeArray is supported, I would always go with a DynamicBuffer. Maybe containers work too some way, I've never tried ๐คทโโ๏ธ
I'm trying that now (although I think i tried some variation of it at first)
Getting a Null reference when trying to Add. Is there some baker special way to initialize the buffer?
yeah there is. AddBuffer. whoops
It doesn't work with a generic "AddBuffer<Entity>()"
I guess I need to make an IBufferElement that just stores an Entity
Yeah that won't work, since Entity is not an IBufferElementData. Just make a struct implementing IBufferElementData with an Entity field ๐
Also I would check if storing native containers during baking is allowed. I would guess no, unless they added some fancy special serialization for it
Yeah Iโm guessing no as wel lol.
Iโm out of time to test, gtg xmas stuff.
Thanks for the help!
What command buffer should I use if I want to destroy entities? The example I'm looking at uses BeginInitializationEntityCommandBufferSystem but that doesn't seem right...
Anybody experience regular crashes with 2022.2.. i jumped from 2021 with entities 0.51 to 2022.2 and after getting everything ported and working with entities 1.0 i'm getting editor crashes quite often
It depends on when you want to destroy them
last one was system out of memory but i've not had time to check where it's coming from, just thought i'd ask if it was a known thing for others
I'm on 2022.2 and the editor very rarely crashes for me
latest version 2022.2 1f1?
I found a more up-to-date example that uses commandBuffer = SystemAPI.GetSingleton<EndSimulationEntityCommandBufferSystem.Singleton>().CreateCommandBuffer(state.WorldUnmanaged).AsParallelWriter(), which sounds right for me
Yep
I usually use EndSimulationEntityCommandBufferSystem, but it depends on when you want them destroyed
for creating entities would you use BeginInitializationEntityCommandBufferSystem or BeginSimulationEntityCommandBufferSystem ?
I guess if it has physics it should be the initialization one since simulation is after?
(for context, I'm spawning projectiles from a weapon)
Why is entities package in preview after several years?
Entities overview | Entities | 1.0.0-pre.15 - Unity - Manual
I use unity 2021
To use the Entities package, you must have Unity version 2022.2.0b8 and later installed.
How can I be sure a job runs in less than 4 frames, so, I can allocate native fields of the job as temp job?
I cannot understand.
How that certainty
For example, in one pc, it lasts 60ms in another one 130ms!!!
i think i read here someone had written an inspector for colliders - anybody done the same for joints/constraints?
Either frame count (don't do this)
Or use persistent memory for long running jobs
Note you can't use entity data in long running jobs, they have a 1 frame limit. You need a copy.
That would be me
I have not done joint's though (I just never use them)
When I call Complete method, it interrupts main thread until completion. So, it takes one frame, it can be executed slowly or fast but in one frame, right?
Complete stalls the frame until job is done
Yes
Interesting thanks
Lot's of good stuff in there, i wish i had the time to dive more into this
Any simple way to access the currently selected entity?
ie scene view / hierarchy selected
i previously used for example this to select an entity:
Unity.Entities.Editor.EntitySelectionProxy.SelectEntity(World, myEntity);
Still works you just need internal access
Is there a way to cast a native array into a native list with capacity the size of the original native array?
Finally tracked down the oddest error. Netcode throws an index out of bounds error if a ghost component not replicated (no ghost fields) but specified as a server/client only prefab is due to the assembly reference not having Networking.Transport in the list of references.
That's gonna eliminate all my cleaning systems now that I can get netcode to do it for me using attributes.
For anyone else, if you see this error: error NetCode: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index') at Unity.NetCode.Generators.NetCodeSourceGenerator.Generate(GeneratorExecutionContext executionContext, IDiagnosticReporter diagnostic), check the asmref of the script the component is located in and make sure all the netcode references are included, even if none of the components within it are serialized.
@light badgerIf you're still around, do you use remote predicted player prediction in your rival samples anywhere?
probably a stupid question, but how would i add a component to an entity?
using Unity.Entities;
public class MySystem : ComponentSystem
{
protected override void OnUpdate()
{
// Get the EntityManager
EntityManager entityManager = World.EntityManager;
// Create an entity
Entity entity = entityManager.CreateEntity();
// Add a component to the entity
entityManager.AddComponent<MyComponentData>(entity);
}
}```
ah ok thanks a ton!
Wait, don't know the context, which version are you on? If it's just adding a component to an entity 
ComponentSystem and World.EntityManager are really not the recommended approaches. - they be old
If you're on 0.51 I would say:
partial class MySystem : SystemBase {
protected override void OnUpdate()
{
// Create an entity
Entity entity = EntityManager.CreateEntity();
// Add a component to the entity
EntityManager.AddComponent<MyComponentData>(entity);
}
}
and if you're on 1.0:
[BurstCompile]
partial struct MySystem : ISystem {
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
// Create an entity
Entity entity = state.EntityManager.CreateEntity();
// Add a component to the entity
state.EntityManager.AddComponent<MyComponentData>(entity);
}
}
on 1.0, still using a systembase, i should really switch over to ISystem lol, thanks so much for the info!
Yea I haven't updated either, my b
just curious, what is the differences between system base and i system, i know one is a struct and one isnt, but apart from that are there any other major differences?
ISystem can be burst compiled
oh cool, thanks for the info!
aha i see ISystem doesn't have RequireForUpdate<>(), is there an ISystem version of it?
Yup, everything that SystemBase has as part of this. is part of SystemState, which is why you have it on every OnCreate, OnStartRunning, OnUpdate, OnStopRunning, OnDestroy :3
so. state.RequireForUpdate<T> does the trick
ok that makes sense, thanks so much!
guessing i would replace GetExistingSystemManaged<>() with GetExistingSystem<>() in order to grab it from somwhere else?
Yes and no. Depends on your usage. As you can kinda split up GetExistingSystem usage into two catogories. One is systemhandling. (So causing it to update and killing it etc.) and the other is one we try to discourage people from doing. Which is accessing data from other systems. For this you will still need GetExistingSystemManaged. GetExistingSystem will let you do SystemHandling, as in you get back a SystemHandle, which can do Updates and you can add Component to etc.
ok got it, cause basically i have 2 systems currently where 1 handles map making, and the other system is the player and every now and again it tells the first system to load or unload a certain chunk, is that a good usage? but thanks so much for the info!
You can easily do that by having you MapSystem query for the existence of a component ChunkRequest or alternativly. You can have a singleton on said system:
partial struct MapSystem : ISystem {
public unsafe struct MapData : IComponentData {
public NativeArray<int> Data;
public bool* ShouldUpdateChunk;
public void DoUpdate(){*shouldUpdateChunk = true}
}
public void OnCreate(ref SystemState state) {
state.EntityManager.AddComponent(state.SystemHandle, new MapData{Data = new NativeArray(64*64, Allocator.Persistent)});
}
public void OnUpdate(ref SystemState state) {
var mapDataRef = SystemAPI.GetSingletonRW<MapData>();
// use MapData here
}
}
ooh yes! I could always a 3 native arrays of int2 as a singleton, 1 for chunk generation, 1 for chunk loading, and 1 for chunk unloading, and just have the map maker system thingy work through them every frame then make them all empty again! Thanks a ton!
ISystem is valid even on 0.51 btw
Well aware, but without IJobEntity, and with EntitesForEach - both things that will hurt ya in tha butt if you want to upgrade ๐
IJobEntity is also a thing in 0.51
But not for ISystem
I was the one who did ISystem support for IJobEntity, but I did it after cutoff, so if it worked before, it was probably not intentaional ๐
But EntitiesForEach does work. Ironically.. Which it doesn't do for 1.0 - So I wouldn't wanna be the person updating from 0.51 to 1.0 with ISystem, as the code changed a fair amount inside, before EFE no IJE, now IJE no EFE :3
just got this error message but SystemApi.HasComponent<>() only takes 1 argument and not 2?
Where are you using SystemAPI
- as the error says, it needs to be in a method that has 'ref SystemState' as a parameter
oh whoops, i assumed it meant the method on that line, not the parent method, thanks a ton!
very confused, line 115 is empty?
could this be due to code gen doing something weird perhaps?
wait nope im an idiot, dont worry!
also can i add a ref SystemState state as a singleton so i can access it externally/internally(in a static method that will be called externally)?
that is a very bad idea
and you can't store direct ref
but you can store system handle
which will give you ref through UnamangedWorld
system handle component is created for each system
oh ok fascinating, so how would i get this system handle component then, and could i then create a singleton of it, or is that also not a good idea lol?
in ECS, your systems should never access other systems
this leads to sphagetti
which hurts bad in ECS
so should i instead just put everything inside 1 system then?
you should make systems that don't rely on any other
but isntead, rely on data (components)
ok fascinating, are the SystemState state things the same for each system or are they different in some way?
it's same for every system, but each has it's own
oh ok fascinating
but how do i get the data onto the components without either needing everything to be in 1 system, or having systems doing stuff in other systems
well, if logic is way too merged with another - make it one system
but generally
every little bit can be split into different systems
it really isnt, 1 system for the player, 1 system for the map, the player asks the map if it is allowed to move where it is trying to move, the map then tells it yes or no, the map system is also responsible for generating the map,
i cant see a way to avoid spaghetti, if i dont have my 2 smaller systems talking to eachother, then i have to have 1 huge unreadable system which would also be spaghetti...
that's a wrong approach
you musn't rely system on other
so if player needs to know whether he can move to specific area or not
there should be a system that does it
technically, that system will probably be part of pathfinding
but the map knows everything about the map, and the player knows everything about the player, the player needs to interact with the map somehow, i thought static methods in the map system was a good approach, how else could i do it?
map is data
yes, but something has to read that data, and it may aswell be the same thing that writes it, right?
otherwise i would have to have 2 static methods on 2 system bases that are exactly the same, and that really doesn't seem right
i know im doing something terribly wrong somewhere, but i dont see any other way somehow...
yeah
that's wrong view on ECS
or more, OOP view that tries to use ECS
think of ECS this way
all systems are in specific order
each system processes 1 specific logic
and result of their processing - data in world is modified
system don't store any data
they only process data in world
data on the other hand
none of my systems currently store data, atleast as far as i can tell
is accessible to anything
EntityManager can access you any component in any time
so systems can work together on same set of data
while doing different thing
yes but data needs to be read in a specific way, which means either duplicating static methods everywhere or having 1 system use a method from another system, right?
then how would i read my data?
through systems
jobs
or entity manager
in Unity ECS, no data should be static
unless maybe it's some sort of unique per PC configuration of some sort
which is read only
and is not used in systems
but that would require duplicating code so many times, i would be copy and pasting 10 lines so often, when instead i could just use 1 method, isn't code meant to be reused?
I think your issue is that you don't need to duplicate code because systems/jobs basically do database queries and work on each row returned.
Say you want your player character to have movement. You'd implement a PlayerMovementSystem or something. That system acts on your player and the data associated with your player entity. It handles all the movement for the player, but only that.
If you want a general MovementSystem that acts for the player and all other entities that should move, that's fine too. Coded slightly differently but you still have only that one section of code, just run with different parameters (i.e. once per entity it matches)
yes, but i need to read the data, which requires either a static method from another system, or copy and pasting the same code over and over and over, right?
You read it via your foreach or job. ๐
im afraid i really dont understand
what kind of duplication are you even talking about?
duplication of code for reading the data, that could easilly be housed in a single static method
well i have been so far somehow
You can read static data in a static method but non-static data needs non-static access
I still would like to see
what kind of duplicated code are we even talking about
I feel like there is something very very wrong with what you do ๐
Only owning clients are predicted; remote players are interpolated
ye, almost certainly
i have a map system with a bunch of static methods for how to read certain components and then my player system uses these static methods to read components, i suppose i could have them not be in a system, cause they are static methods, but it really makes it more readable to put all map stuff in the map system
I think showing us some of that code might help
sure
just show them
https://hastebin.com/mezopepecu.csharp this is my map system
You... plan on keeping OnUpdate empty...?
dont worry, i do plan to add some stuff there, it is very unfinished
im currently porting a monobehaviour & gameobject simple infinite world thing into ecs hence why things seem a bit barren and missing
yep, this is exactly what you should avoid
you are doing OOP inside ECS
store data inside components
ok ye i can do that, im sorry about that thing, but for the static methods, are they decent?
I see no reason to have the static methods in the first place.
They're only static because your NativeLists are static, no?
nah, the methods are static so i can easilly use them from other systems, the native lists being static was just for some basic ideas testing, ill make the lists not static and in a component eventually
If you need to access them in another system, put them on a singleton component (Settings or Config or something maybe) and access them through that.
I don't have any experience in 1.0 so for specifics, Issue is probably the better candidate ๐
you can put methods on components, really?
I meant put the lists in a component.
Public fields.
oh ye, that would make sense, ill do that at some point, thanks
also are my static methods ok, or should i also do them differently somehow?
no, you are breaking ECS pattern horribly. You are not supposed to do that
what should i do instead?
store that data on components
store what data?
what you want to read from other systems
i dont want to read anything from the other systems, unless im missing somthing?
what your map even represents?
Is it tile map?
ye i guess a tile map is the best way to describe it
Then you can store all those arrays inside component
what arrays?
that represent your map
native lists
that is already stored in components...
then why do you need static methods to obtain them?
so im not copy and pasting code over and over? I try to reuse code when possible using static methods usually
why do you need to copy paste code over and over in the first place?
so that everything that needs to read the data can, hence why static methods make it much easier to read and understand
This is btw pattern that is also used in OOP that is broken
SRP
single responsibility
if you need other systems to use same code - that means you share responsibilit between other systems
what should i use instead though, as the only alternative i can see to using static methods would be to use spaghetticode copy and pasting?
But you don't need code everywhere that's duplicated if the data is stored in components and read as necessary where it is used?
i just want a clean and simple way to read the component data, the only way i can see to do that would be static methods, i dont understand any other way that wouldn't involve spaghetti copy and pasting, im sorry im really not getting this
OK, let's do something else.
If you have data on components, how would you access that data?
using my static methods
I suggest you read here ๐ https://docs.unity3d.com/Packages/com.unity.entities@1.0/manual/components-intro.html
they make my code easier to read, i learned from past projects that not using static methods becomes a pain very quickly, and jumping all over the place is not fun, so i use static methods that are easy to understand with clear and concise names,
static methods is not clean way
it's very dirty way in ECS pattern
i shall try
the static methods, if you dont want me to use them, then i have to take the code out of the static method and start copy and pasting it around my code like sprinkles on a cake
i realise i have already read this, and i dont see that im doing anything horribly against what is said there if i remember right
make data easy to understand and grab, reduce copy and pasting, reduce jumping around, make code easier and quicker to understand
no no no, explain game logic behind
listen i understand im clearly doing something wrong, perhaps instead of trying to get me to understand why it is wrong, instead tell me what i can do to make my code better
game logic behind what?
behind your methods
what do they do
in game sense
why do they even exist
well each one has one specific thing it does, got any specific ones you want to know, or should i just start listing?
just explain in game sense
as in
this method moves player by 1 unit in Y axis
or smth like this
i usually use the names to do this, i try have the name of the static method describe what it does, are some of them unclear?
am i missing something?
well, they seem technical
Chunk makes no sense in game sense
unless it's literally some kind of big stone ๐
ok, so what do your methods do with chunk?
depends on the method
and why can't you access them through SystemAPI.GetSingleton<GameMap>().MyChunk(ind);?
im afraid i do not understand, what is GameMap and what is MyChunk(ind)? Is it a dictionary?
the current way i get access to my chunks is via a dictionary stored in a component that can be easily used from anywhere as far as i can tell
just pseudoname for types you use
yeah, except it's not burst compatible
why not?
you can't use static data in burst
unless it's some primitives
and they must be readonly
i dont have any static data, (atleast wont very soon), only static methods
im really doubtful im ever going to understand why this is a bad idea, so perhaps you could atleast list some alternative ways instead?
your static methods access static data
SystemAPI.GetSingleton<GameMap>().MyChunk(ind);
store data on component
for now, i plan to put all that static data up top into a component soon
then where else can i put it???
you can only use static methods for math, like math. package
EntityManager.AddComponentData(yourEntity, yourData);
that is the data, im talking about the way of reading it
where do i put the way of reading it, if not in a static method?
to read you do
EntityManager.GetComponentData<YourData>(yourentity);
first of all, why do you need a specific way of reading in the first place?
you can make helper functions inside component itself
if it's that specific
or you can store data in a way that is obvious and simple enough
to read without any additional logic
cause otherwise i would be copy and pasting it all over like sprinkles, and i was taught to reuse code if possible instead of just copying and pasting...
Remember, logic must be held only withing System and never be accessible to other
ooh fascinating, ill look into that