Dev Day 70: Working with Return Methods and Arrays in Unity3D
Objective: Create 5 positions that a GameObject will be randomly set to at the start of the game.
Step 1: Within Unity, create a Cube 3D GameObject in the Hierarchy window and rename it to Player. Then create a C# Script in the Project window called Player and attach it to the Player GameObject.
Step 2: In the Player script, create a public array of type Vector3 named position.
Step 3: Either within Unity or within the Player script, assign 5 different positions to the position array.
Step 4: In the Player script, create a private int method called GetRandom(), and set the return to a random range within the position array between 0 and the length of the array, or 5.
Step 5: Create a private Vector3 method called GetPosition() with an int variable called index as its parameter and the return set to the position array with the index variable as its array ID.
Step 6: At the top of the Player script, create a new public variable of type int called randomIndex.
Step 7: Within the Start() method, have the randomIndex variable and assign it the GetRandom() method. This will assign a random array ID value to the randomIndex variable. Then have the transform.position equal to the GetPosition() method with the randomIndex variable as its parameter to call the random ID in the array and assign the ID’s Vector3 value to the GameObject’s position.
Save the script, go back into Unity, and when the scene is played, the Player GameObject will move to a random position.