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
MediumFinish Score: a coin is worth 1 point and a gem 5.
- In
Score(int coins, int gems), findreturn 0;. - 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
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector7Loops and Methods
Repeat with forLoops Inside LoopsWrite a MethodMethods That AnswerArraysRecap: Staircase2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground