transmit a variable by reference in JS ?

Hi

In JavaScript, I would like to set a variable as a reference to another variable.

That way if I change the value of the first variable, the value of the second one is also modified.

Can I do that ? If yes, how ?

Thanks

I don’t think you can pass value-types as reference in UnityScript (you can in C# though, so you may be able to). If you cannot in UnityScript, you might need to box the variable in a separate class. Pseudo-code:

class SharedVariable
{
	public var Value;
}

public var myReferencedVariable : SharedVariable = new SharedVariable();

function Start()
{
	myReferencedVariable.Value = 5;
}
function Update()
{
	Debug.log("Value: " + myReferencedVariable.Value); //outputs 5
	UpdateVariable(myReferencedVariable, 10);
	Debug.log("New Value: " + myReferencedVariable.Value); //outputs 10
}

function UpdateVariable(referencedVariable:SharedVariable, newValue)
{
	referencedVariable.Value = newValue;
}

Sweet.

What you posted is actually a great clean simple example of how to create and use a class in Unity.

Thanks for taking the time to post the code.

Thanks.