Frequently Used Code Samples

Note: if you are looking for tutorial scripts, please goto tutorials page and search

Just C# Methods

CreateAudioSource()

Load AudioSource to GameObject via script from ..\Asset\Resources folder. Place in script on gameobject.

            
    private AudioSource CreateAudioSource(string filenamenoextension)
    {
        AudioSource audio = this.gameObject.AddComponent<AudioSource>();
        audio.clip = Resources.Load<AudioClip>(filenamenoextension);
        return audio;
    }
                
            

CreateAudioSource()

A global static file version. Load AudioSource to GameObject via script from ..\Asset\Resources folder.

            
    private AudioSource CreateAudioSource(GameObject go, string filenamenoextension)
    {
        AudioSource audio = go.AddComponent<AudioSource>();
        audio.clip = Resources.Load<AudioClip>(filenamenoextension);
        return audio;
    }
                
            

PlayerMoveRotate()

Move player forward and backward. Rotate player left and right.

            
    private void PlayerMoveRotate()
    {
        //move, rotate (WASD, Arrows, LeftAnalog Gamepad)
        float vert = Input.GetAxis("Vertical");
        float horz = Input.GetAxis("Horizontal");
        this.transform.Translate(Vector3.forward * vert * 3.5f * Time.deltaTime);
        this.transform.localRotation *= Quaternion.AngleAxis(horz * 120f * Time.deltaTime, Vector3.up);
    }
                
            

PlayerMoveLook()

First person move and look controls (like a 1st person shooter). The camera must be set/positioned as a child object of the player.

            
    private void PlayerMoveLook()
    {
        //move control (WASD, Arrows, LeftAnalog Gamepad)
        float V = Input.GetAxis("Vertical");
        float H = Input.GetAxis("Horizontal");
        this.transform.Translate(Vector3.forward * V * 3.5f * Time.deltaTime);
        this.transform.Translate(Vector3.right * H * 3.5f * Time.deltaTime);

        //look control (Mouse movement)
        float mX = Input.GetAxis("Mouse X");
        float mY = Input.GetAxis("Mouse Y");
        Vector2 mouseLook = new Vector2(mX, mY);
        mouseLook = Vector2.Scale(mouseLook, new Vector2(120.0f, 120.0f));
        this.transform.localRotation *= Quaternion.AngleAxis(mouseLook.x * Time.deltaTime, Vector3.up);
        Camera.main.transform.localRotation *= Quaternion.AngleAxis(-mouseLook.y * Time.deltaTime, Vector3.right);
    }
                
            

MouseClickPoint()

Get hit info for mouseclick in a 3D scene.

            
    private bool MouseClickPoint(out RaycastHit hit)
    {
        if (Input.GetMouseButtonDown(0) == true)
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            return Physics.Raycast(ray, out hit);
        }
        return false;
    }
                
            

Whole C# Scripts

PlayerMoveLook.cs

Attach script to player gameobject with camera child/located at player's center.

            
using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class PlayerMoveLook : MonoBehaviour
{
    #region --- helper ---
    private enum enumMouseButton
    {
        primary = 0,
        secondary = 1,
        middle = 2,
    }
    #endregion

    public float Movespeed = 5.0f;
    public float Turnspeed = 120f;
    public float Jumpforce = 8.0f;
    public Camera childCam = null;
    private Rigidbody rb = null;

    private void Start()
    {
        rb = this.GetComponent<Rigidbody>();
        Cursor.lockState = CursorLockMode.Locked;
        if (childCam == null)
        {
            Debug.LogError(string.Format("{0}.cs property 'ChildCam' is not defined. Please make camera a child object of the player and define ChildCam in inspector window.", this.name));
        }
    }

    private void Update()
    {
        //move forward (arrows, WASD, gamepad)
        float vert = Input.GetAxis("Vertical");
        this.transform.Translate(Vector3.forward * vert * Movespeed * Time.deltaTime);

        //strafe (arrows, WASD, gamepad)
        float horz = Input.GetAxis("Horizontal");
        this.transform.Translate(Vector3.right * horz * Movespeed * Time.deltaTime);

        //look (player looks up,down / camera look left,right)
        float mX = Input.GetAxis("Mouse X");
        float mY = Input.GetAxis("Mouse Y");
        Vector3 mouselook = new Vector3(mX, mY);
        mouselook = Vector3.Scale(mouselook, new Vector3(Turnspeed, Turnspeed));
        this.transform.localRotation *= Quaternion.AngleAxis(mouselook.x * Time.deltaTime, Vector3.up);
        if (childCam != null)
        {
            childCam.transform.localRotation *= Quaternion.AngleAxis(-mouselook.y * Time.deltaTime, Vector3.right);
        }

        //jump (space)
        if (rb != null)
        {
            if (Input.GetKeyDown(KeyCode.Space) == true || Input.GetMouseButtonDown((int)enumMouseButton.primary) == true)
            {
                rb.AddRelativeForce(Vector3.up * Jumpforce, ForceMode.VelocityChange);
            }
        }

        //cursor lock
        if (Input.GetKeyDown(KeyCode.Escape) == true)
        {
            Cursor.lockState = CursorLockMode.None;
        }
        else if (Input.GetKeyDown(KeyCode.Return) == true)
        {
            Cursor.lockState = CursorLockMode.Locked;
        }
    }
}
                
            

PlayerMoveJump()

Player can move, turn, and jump. The jump has a fall arc that is stronger than the rise.

            
using UnityEngine;

public class PlayerMoveJump : MonoBehaviour
{
    public float Movespeed = 3.5f;
    public float Turnspeed = 120f;
    public float Jumpforce = 8f;
    public float Fallmultiplier = 2.5f;
    public float Jumpmultiplier = 3.0f;
    private Rigidbody rb = null;
    private bool onGround = false;
    private int numJumps = 0;

    private void Start()
    {
        rb = this.GetComponent<Rigidbody>();
    }

    private void Update()
    {
        //move
        float vert = Input.GetAxis("Vertical");     // -1..0..1
        this.transform.Translate(Vector3.forward * vert * Movespeed * Time.deltaTime);

        float horz = Input.GetAxis("Horizontal");
        this.transform.Rotate(Vector3.up, horz * Turnspeed * Time.deltaTime);

        //jump
        if (Input.GetKeyDown(KeyCode.Space) == true)
        {
            if ((numJumps == 0 && onGround == true) || (numJumps == 1 && onGround == false))
            {
                rb.AddRelativeForce(Vector3.up * Jumpforce, ForceMode.VelocityChange);
                numJumps += 1;
            }
        }
        //jump higher
        if (rb.velocity.y > 0 && Input.GetKey(KeyCode.Space) == false)
        {
            rb.velocity += Vector3.up * Physics.gravity.y * Jumpmultiplier * Time.deltaTime;
        }
        //fall faster
        if (rb.velocity.y < 0)
        {
            rb.velocity += Vector3.up * Physics.gravity.y * Fallmultiplier * Time.deltaTime;
        }
    }

    private void OnCollisionEnter(Collision collision)
    {
        onGround = true;
        numJumps = 0;
    }

    private void OnCollisionStay(Collision collision)
    {
        onGround = true;
    }

    private void OnCollisionExit(Collision collision)
    {
        onGround = false;
    }
}
                
            

CameraFollow2D.cs

Camera will maintain offset from the 'follow' object, staying in it's 2D plane

            
using UnityEngine;

public class CameraFollow2D : MonoBehaviour
{
    public GameObject Follow = null;
    private Vector3 offset;

    private void Start()
    {
        offset = Follow.transform.position - this.transform.position;
    }
    private void LateUpdate()
    {
        this.transform.position = Follow.transform.position - offset;
    }
}
                
            

CameraRotateTarget.cs

Camera moves and looks around target point in 3D space

            
using UnityEngine;

public class CameraRotateTarget : MonoBehaviour
{
    public float ScrollSpeed = 8.0f;
    public float TurnSpeed = 120.0f;
    public Transform RotateCenter = null;

    private void Update()
    {
        if (Input.mouseScrollDelta.y != 0.0f)
        {
            this.transform.Translate(Vector3.forward * Input.mouseScrollDelta.y * ScrollSpeed * Time.deltaTime);
        }

        if (Input.GetKey(KeyCode.LeftAlt) == true)
        {
            float x = Input.GetAxis("Mouse X");
            this.transform.RotateAround(RotateCenter.position, Vector3.up, TurnSpeed * x * Time.deltaTime);

            float y = Input.GetAxis("Mouse Y");
            this.transform.RotateAround(RotateCenter.position, Vector3.right, TurnSpeed * y * Time.deltaTime);

            this.transform.eulerAngles = new Vector3(this.transform.eulerAngles.x, this.transform.eulerAngles.y, 0.0f);
        }
    }
}
                
            

CameraFollow3D.cs

Camera can follow around an object in 3D. The gameobject should have a target to look at point and a target follow point

                
using UnityEngine;

public class CameraFollow3D : MonoBehaviour
{
    public Transform LookAt = null;
    public Transform MoveTo = null;
    public float Lookspeed = 45f;
    public float Movespeed = 1.8f;

    private void LateUpdate()
    {
        Quaternion rotTarget = Quaternion.LookRotation(LookAt.position - this.transform.position);
        this.transform.rotation = Quaternion.RotateTowards(this.transform.rotation, rotTarget, Lookspeed * Time.deltaTime);

        this.transform.position = Vector3.Lerp(this.transform.position, MoveTo.transform.position, Movespeed * Time.deltaTime);
    }
}