Working With Method Parameters in Unity3D

Pete Thomasberger
3 min readJul 24, 2021

Objective: Change the color of a cube to red when the Space key is pressed by passing parameters from one method to another method.

Step 1: In Unity, create a 3D Cube in the Hierarchy window.

Step 2: Create a C# Script called Player and attach it to the Main Camera in the Hierarchy window.

Step 3: Within the Player script, create a new public variable of type GameObject named cube and save the script.

Step 4: Go back into Unity, select the Main Camera GameObject in the Hierarchy window, and drag the Cube GameObject into the Cube slot in the Player (Script) component in the Inspector window.

Step 5: In the Player script, create a new private method with no return called ColorChange().

Step 6: Within the () of the ColorChange() method, add a GameObject parameter called obj, and then add a Color parameter called colorToAssign.

Step 7: Within the Update() method, create an if statement stating that if the Space key is pressed, call the ChangeColor() method and assign the cube variable to the obj parameter, and assign Color.red to the colorToAssign parameter.

Now that the cube variable is assigned to the obj parameter, the Mesh Renderer of the Cube GameObject can be accessed through the obj parameter.

Step 8: Within the ChangeColor() method, access the Renderer component of the Cube GameObject by using GetComponent. Then access the material and color and assign the colorToAssign parameter which is now referencing Color.red.

Save the script, go back into Unity, and when the Space key is pressed, the Cube will turn red.

--

--