58 lines of C# code to create 5000 “magic” cubes.

I’ve been learning a lot over the last three weeks about terrain generation and manipulation of terrain data. So I thought it was about time to actually cover the basics!

 

Cube Controller

using UnityEngine;

public class CubeController : MonoBehaviour
{
    public Rigidbody rb; 
    private float maxRaycastDistance = 0.5f;
    public float jumpVelocity;
    public Color cubeColour;

    public Color RandomColor()
    {
        return new Color(Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f));
    }

    void Start()
    {
        jumpVelocity = Random.Range(10f, 30f);
        rb = GetComponent<Rigidbody>();
        cubeColour = RandomColor();
        GetComponent<MeshRenderer>().material.color = cubeColour;
    }

    void FixedUpdate()
    {
        if (Input.GetKey(KeyCode.Space) && isGrounded())
        {
            Vector3 jumpVel = new Vector3(0, jumpVelocity, 0);
            rb.velocity = rb.velocity + jumpVel;
        }
        float hor = Input.GetAxis("Horizontal");
        float vert = Input.GetAxis("Vertical");
        Vector3 movement = new Vector3(hor * Time.deltaTime, 0, vert * Time.deltaTime);
        rb.MovePosition(transform.position + movement);
    }

    bool isGrounded()
    {
        return Physics.Raycast(transform.position, Vector3.down, maxRaycastDistance);
    }
}

 

Cube Generator 

using UnityEngine;

public class CubeGenerator : MonoBehaviour
{
    public GameObject myPrefab;
    float spread = 50f;

    void Start()
    {
        Vector3 spawn = new Vector3(512f, 50f, 512f);

        for (int i = 0; i < 5000; i++)
        {
            float random = Random.Range(-spread, spread);
            GameObject thing = Instantiate(myPrefab, (spawn + new Vector3(random, random, random)), Quaternion.identity) as GameObject;
        }
    }
}