Unity C# Input & Collision Examples

Trigger Events

Detect when object enters trigger zone

void OnTriggerEnter(Collider other)
    {
        Debug.Log("Object entered: " + other.name);
    }

Check for specific name

void OnTriggerEnter(Collider other)
    {
        if (collision.gameObject.name.Contains("Player"))
        {
            Debug.Log("Player entered!");
        }
    }
Collision Events

Detect when object collides

void OnCollisionEnter(Collision collision)
    {
        Debug.Log("Collided with: " + collision.gameObject.name);
    }
Keyboard Input

Detect key press

void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Debug.Log("Space pressed!");
        }
    }
Axis Input

Basic movement with axes. Horizontal and Vertical are pre-named by Unity but you can make your own.

public float speed = 5f;
    
    void Update()
    {
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        transform.Translate(new Vector3(h, 0, v) * speed * Time.deltaTime);
    }
Button Input

Jump with button

void Update()
    {
        if (Input.GetButtonDown("Jump"))
        {
            Debug.Log("Jump button pressed!");
        }
    }
Mouse Input

Detect mouse clicks

void Update()
    {
        if (Input.GetMouseButtonDown(0))  // Left click
        {
            Debug.Log("Left clicked!");
        }
    }

Mouse movement for camera

public float sensitivity = 2f;
    
    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X");
        float mouseY = Input.GetAxis("Mouse Y");
        transform.Rotate(-mouseY * sensitivity, mouseX * sensitivity, 0);
    }
Custom Input Setup