Passing Parameters by Reference and using In/Out Parameter Modifiers
In Parameter Modifier
Typically the default parameter modifier is in
for input. The method must take in an input value. Since this is the default, we don’t use a keyword then. It’s implied that is what the parameter modifier is. So it would look like:
private void Jump(in float jumpHeight);
but we just type:
private void Jump(float jumpHeight);
The in
parameter modifier makes the parameter immutable. This means once the parameter/object is created, you cannot change it.
Ref Parameter Modifier (Passing Parameters by Reference)
ref
means you're passing a parameter by reference. The ref
keyword stands for reference and it means the parameter’s original version of the value can be changed and it can be input or output. To elaborate:
- If your
ref
parameter is an object (class, struct, Vector3, etc.), and you change any of the fields inside of that object, those changes will be reflected back to the caller of the method. - If you re-assign a different value to your
ref
parameter, the caller's variable will also be re-assigned.
Out Parameter Modifier
An out
parameter is a ref
parameter and it must output a value. If you re-assign a different value to your ref
parameter, the difference is the caller’s variable MUST be re-assigned somewhere in the method before returning.
So TryGetComponent<ShootController>(out ShootController)
is gauranteed to assign a value to your new variable that we call controller
, in the example below:
if (player.TryGetComponent(out ShootController controller))
controller.AddAmmoCount(5);
In this different example (TryGetComponent<T>(out T)
),
- If it finds the component, it’ll set your variable to the appropriate reference of the component it found.
- If it does not find the component, it’ll set your variable to
null
.
So out
is very useful if you want to:
- Ensure a variable will be initialized no matter what.
- Return 2+ variables/values from 1 method. (You can have as many out parameters as you wish. Typically, these are written as the last parameters of the method, in the comma-separated list of parameters).