Write a Method
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 39 of 85.
You have been calling methods for a while: Debug.Log, PlaceCrate, and Unity calls your Start() and Update(). Writing your own works the same way:
void Shout(string word)
{
Debug.Log(word + "!");
}void says the method does a job and gives nothing back. Shout is its name. Inside the parentheses are its parameters: variables that the caller fills in. Shout("Hello"); runs the method with word holding "Hello", and Shout("Run"); runs it again with "Run".
A method with no parameters still needs its empty parentheses: void Jump(), called as Jump();. A method can take several parameters, split by commas: void PlaceTile(int column, int row).
Challenge
MediumGive PlaceLamp a parameter so each lamp stands in its own place.
- Change the method's first line to
void PlaceLamp(float x), and its position tonew Vector3(x, 1, 0). - In
Start(), change the calls toPlaceLamp(-3);,PlaceLamp(0);andPlaceLamp(3);.
Press Play: three lamps stand in a row, 3 apart. Then Check.
Try it yourself
using UnityEngine;
public class LampRow : MonoBehaviour
{
void Start()
{
PlaceLamp();
PlaceLamp();
PlaceLamp();
}
void PlaceLamp()
{
GameObject lamp = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
lamp.name = "Lamp";
lamp.transform.position = new Vector3(0, 1, 0);
lamp.transform.localScale = new Vector3(0.3f, 1, 0.3f);
lamp.GetComponent<Renderer>().material.color = new Color(0.3f, 0.3f, 0.35f);
}
}
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