Menu
CoddyTech

Methods That Answer

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 40 of 85.

Some methods do a job. Others work something out and hand the answer back, like a calculator. For those, the type of the answer goes where void was:

int Double(int n)
{
    return n * 2;
}

int before the name says this method gives back an int. return hands the value back to the caller and ends the method, so lines after it in the same method do not run.

The call then stands for the answer, wherever you put it:

int big = Double(21);          // big is 42
Debug.Log("Twice 5 is " + Double(5));

A method that gives back a value must reach a return with a value of its type; C# refuses to run the script otherwise.

challenge icon

Challenge

Medium

Finish Score: a coin is worth 1 point and a gem 5.

  1. In Score(int coins, int gems), find return 0;.
  2. Replace it with return coins + gems * 5;.

Press Play: the Console shows Score: 23 for 3 coins and 4 gems, and the bar grows. Then Check.

Try it yourself

using UnityEngine;

public class ScoreBoard : MonoBehaviour
{
    void Start()
    {
        int score = Score(3, 4);
        Debug.Log("Score: " + score);
        transform.localScale = new Vector3(1, score / 5f, 1);
    }

    // A coin is worth 1 point and a gem is worth 5.
    int Score(int coins, int gems)
    {
        return 0;
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground