Having some trouble getting something working here. I want to pass a Vector3 to the necessary classes I create within a character controller, so if the currentPosition Vector3 is updated in one place, it is updated everywhere. Currently I am attempting to do so like this:
_currentPosition = new Vector3(transform.position.x, transform.position.y, transform.position.z);
_abilities = new AbilityHandler(ref abilitySettings, ref _input, ref _state, ref _currentPosition);
So I’m passing in the new Vector3 with the ref keyword. However, when the value is modified in one place, it doesn’t seem to reflect the changes in another. Why is this and is there a way around this?
I pass in the ref to the constructor of the class, and then I store the ref in the Vector3 _currentPosition from the AbilityHandler class
This seems to work with other data structures, but I’ve been having issues with the Vector3. The InputHandler and AbilitySettings structures (which are custom classes) work just fine
Vector3s are value types, like integers and floats. You can pass it into the function / constructor using the ref keyword, and then change the value of that parameter and the change will be reflected in the calling class, but when you assign it to _currentPosition you’re making a copy of that value, not a reference to it. Since InputHandler and AbilitySettings are reference types, then it’s only the reference being copied, not the object, and things work how you expect them to work.
It’s worth noting that you don’t have to use the ‘ref’ keyword for those reference objects at all- they’ll work regardless. The point of using ‘ref’ for reference types is that if you were to assign a new object to one of the parameters pass in that way, that will change the reference for the original variable in the calling class as well. That’s apparently not needed here.
OK… so ref in old versions of C# just don’t work that way.
C# 7 introduced some expanded uses of ref that you ‘might’ be trying to use? But as far as I know unity doesn’t support C# 7 currently. It only started supporting .Net 4.6 shortly ago, and I think it only did so with C# 6 support.
Even if it did, the new features of ‘ref’ don’t support field’s being set to refs as far as I know. It really only added ‘ref returns’ and ‘ref locals’:
You say:
If they’re classes, classes work different than structs. Classes are ref types by default and are always referenced.