I have a singleton in the same world that I update every OnUpdate on my system.
OnCreate holds:
state.RequireForUpdate<Singleton>();
Then OnUpdate gets it RW:
SystemAPI.GetSingletonRW<Singleton>().ValueRW;
Then I call some function that is going to do lastIndex++ at some point.
This is extremely simplified but I basically do:
public struct Singleton: IComponentData, IDisposable
{
int lastIndex;
public Singleton(...)
{
lastIndex = -1;
}
public ChangeVal() { lastIndex++; }
....
Well. LastIndex ALWAYS holds a -1.
Is there anything in C# or ECS that I’m wrong about?
Gonna take a guess that you’re doing something like this:
var v = SystemAPI.GetSingletonRW<Singleton>().ValueRW;
v.ChangeVal();
You need to use ref.
ref var v = ref SystemAPI.GetSingletonRW<Singleton>().ValueRW;
v.ChangeVal();
Or invoke the method on ValueRW
:
SystemAPI.GetSingletonRW<Singleton>().ValueRW.ChangeVal();
You were right. It’s a struct, the copy is returned. I stored ValueRW on a variable.
But you can’t do:
ref var v = ref SystemAPI.GetSingletonRW<Singleton>().ValueRW;
It returns an error:
Cannot initialize a by-reference variable with a value
I had to use “var” because it returns a ref already
That’s the correct way to assign a ref local.
I suspect you missed the ref
before SystemAPI.
That doesn’t make sense. Using a ref expression means you can assign it to either a normal local or a ref local, you don’t have to use a normal local (var
/ Singleton
).
Thanks
Yeah, I missed the right side ref, silly me.
What I meant is that ValueRW already returns ref XXX.
So Using ref again to both sides is having a ref ref. Is that ok?
That’s not what’s happening. The expression itself is a ref expression, but to express intent to use it as a ref, the ref
keyword needs to be used, e.g. ref ... = ref value
, Method(ref value)
. It’s not “adding another ref” or anything. The var
keyword also doesn’t capture ref
information, which is why it needs to be explicit, i.e. ref var
which is equivalent to ref Singleton
.