Menu
CoddyTech

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 icon

Challenge

Medium

Give PlaceLamp a parameter so each lamp stands in its own place.

  1. Change the method's first line to void PlaceLamp(float x), and its position to new Vector3(x, 1, 0).
  2. In Start(), change the calls to PlaceLamp(-3);, PlaceLamp(0); and PlaceLamp(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

Practice on your own: Unity playground