Skip to main content

Random walker

We will create a first GameObject and give it the functionality to randomly change it's position within a predefined range.

Create a GameObject

go to File -> GameObject -> cube to create your first GameObject
a handy definition for GameObject: A game object is the base class for all entities in unity

aa_basics_001.gif

Create a Material for our GameObject

go to Assets -> create -> Material   or  In the Assets window leftClick -> create -> Material

aa_basics_002.gif

rename it to "green"

Assign the Material to the RandomWalker GameObject

click on the RandomWalker GameObject in the Scene view or the Hierarchy

on the left, you will see now the Inspector window showing the GameObjects' properties!

in the MeshRenderer component under Materials you will find the current material(s) assigned.

assign the material you've just created.

aa_basics_003.gif

Create a Folder in the Assets Window and call it "Materials"
Drag the newly created Material 'green' into the newly created folder "Materials"

Attach a C# script to your GameObject

In the Inspector (right pane on default) scroll down and click 'Add Component'
Type the name of your new Script in this case "RandomWalker' and press the enter key.
In the Assets Window you'll see the newly created Script.

aa_basics_004.gif

Create a Folder in the Assets Window and call it "Scripts"
Drag the Script "RandomWalker" into the newly created Folder called Scripts

Edit the C# script to add random walk functionality to the RandomWalker class

When the script is created, it normally opens immediately in the IDE that is associated with Unity
in our case, that is Visual Studio Code. You can the associated editor under File -> Preferences -> External Tools

If the editor does not open, you can click with your mouse on the script in the Assets window, generally you can find all Scripts in the folder "Scripts."

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RandomWalker : MonoBehaviour
{
    public float speed = 2f; // speed of movement
    public float range = 3f; // range of movement
    private Vector3 targetPosition;

    void Start()
    {
        targetPosition = transform.position + Random.insideUnitSphere * range;
    }
    
    void Update()
 {
 		// move towards target position
        transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);
        // if target position is reached, set a new random target position
        if (Vector3.Distance(transform.position, targetPosition) < 0.1f)
        {
            targetPosition = transform.position + Random.insideUnitSphere * range;
        }  
    }
}