I can send variables to another script, but how do I return them?

s2 = GameObject.FindObjectOfType();
s2.DoSomething (myint);

My class is “s2” so I’m sending myint to that class function, so that’s not problem, but what if I want to return a variable? For example, let’s say I am sending a “score” variable and I want another classes function to change the score then send it back to the original function.

I’m coming from Adobe Director where I Can just set a global variable and be done with it, but this is clearly a little more taxing!

When ur setting void as the return type of the function, you’re specifying that the function doesn’t return a value. If you want it to return an int, give it a return type of int.

public int DoSomething (int score)
{
    //do fancy things with score
    return score;
}

If the method you’re sending to is what you want to return the variable, it’s the same as any method in C# programming.

Say, for instance, ‘DoSomething’ was written like this:

int DoSomething(int myint) {
   int b = myint + 2;
   return b;
  }

Then, with your ‘s2’ … you could do:

int returnedInt = s2.DoSomething(myint);

Hope that helps :slight_smile:

And for something more advanced, if you wanted to return multiple objects, you have 2 options:

  1. Make a struct type and return that

or

  1. Use the “out” keyword for multiple parameters:
public bool DoSomething(int score, out int newScore, ref int highScore)
{
  newScore = score + 10;
  highScore = Mathf.Max(highScore, newScore);
  return true;
}

EDIT: Was too clever for my own good. Fixed to change highScore to “ref” instead of “out”, which means it’s used as both input and output.

Very good tip – you forgot to ensure the path returns ‘bool’ though :wink: heh.

:stuck_out_tongue: Fixed!

Cool :slight_smile: heh