Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Passing Variables as reference

Discussion in 'Scripting' started by rothpletz5, Jun 27, 2021.

  1. rothpletz5

    rothpletz5

    Joined:
    Dec 2, 2020
    Posts:
    27
    In C#, variables such as floats and ints are passed into functions by value. This means that if you have the code
    Code (CSharp):
    1. int Value=5;
    2.  
    3. void Start(){
    4. DoSomething(Value);
    5. Debug.Log(Value);
    6. }
    7.  
    8. private void DoSomething(int value) {
    9.     value++;
    10. }
    , "5" will appear in the console log, as
    Value
    will not change outside of the function.

    How do I pass in an int or float by reference or do something equivalent in UnityScript, such that when
    DoSomething(Value);
    is called, Value will be increased outside of the function?
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    rothpletz5 and Vryken like this.
  3. rothpletz5

    rothpletz5

    Joined:
    Dec 2, 2020
    Posts:
    27
    Are you sure this works? I read somewhere that ref doesn’t work with unity, and I got errors when I tried this.
     
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    Don't know where you read that. It 100% works, and works in Unity. What errors did you get, and what was your code?

    Not only does it work in Unity, some of Unity's own functions use it. For example:
    https://docs.unity3d.com/ScriptReference/Mathf.SmoothDamp.html
     
    rothpletz5 likes this.
  5. rothpletz5

    rothpletz5

    Joined:
    Dec 2, 2020
    Posts:
    27
    hmm, thanks for letting me know! I tried it again, and its working great now! Not sure what I had done wrong initially...

    Anyways, what a great tool to learn! thanks for the help!
     
  6. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    There's also out, which is similar to ref, but doesn't need to be initialized before the function call and must be assigned to before the function returns. This may create better semantics for your use-case.
     
    rothpletz5 likes this.