Quick question: is there a way to have a variable reference another variable of a simple type (int, float, etc.)?
My current, limited understanding is that all = and passing operations on objects are by reference and on simple types are by value.
What I’m trying to do is have friendly-named variables in the editor, but having them easily accessible in the code by array index. I would like to have one construct’s variables reference the other so they stay in sync.
Thanks.
I just came across a documentation page that lists a function argument “ref float currentVelocity”. Reference variables (at least for function calls) are possible in javascript! Can someone fill in how to set this up in Unity’s javascript (“function blah(myVar : ref float)”?) and if reference variables are possible outside of function arguments? Thanks in advance.
They’re possible in .NET, but to my knowledge there’s no support in JS.
The workaround is to create a “wrapper” class, say, CameraWrapper, and pass that. The reference inside the wrapper class will point to the same Camera no matter how it gets passed around.
What this need really all stemmed from is wanting to create reference variables to items in float arrays. If this is possible in C#/Boo, maybe I’ll look into those for doing some front end to the back end. Please post if you have a JS alternative. Thanks.
All objects are always passed by reference in .Net. Structs and primitive types are passed by value by default.
There is currently no syntax in Unity Javascript to specify that a function parameter should be passed by reference, but it is supported when calling a .Net function defined in another language (such as c#) that requires a boxed reference.
Also as suggested above, you could define a wrapper class and pass that around instead of the values directly:
class FloatRef {
public float value;
}
var aref = FloatRef();
aref.value=2.0;
This may confuse matters more than it helps, but who knows.
I believe everything is passed by value in javascript, and that objects are object references.
So the reason it looks like it’s passed by reference is that the object referred to can be changed, but in fact what’s being passed is a referenc, passed by value. This does make the “Why do objects and primitives get treated differently?” question a little easier though.
Attached are a couple of links about the difference between value types and reference types in .Net:
Reference and Value Types (KnowDotNet.com)
Type Fundamentals (MSDN Magazine)