Menu
CoddyTech

Recap: Input Swap

Part of the Building Real Games section of Coddy's Unity journey. Lesson 48 of 60.

This chapter read the keyboard, the mouse and the project's actions with the Input System. The bubble wand still uses the old Input class: port it call by call.

challenge icon

Challenge

Medium

Port the bubble wand to the Input System; the old Input class throws here.

  1. Add using UnityEngine.InputSystem; and InputAction fields moveAction and jumpAction, set in Start() with InputSystem.actions.FindAction.
  2. Walk by moveAction.ReadValue<Vector2>(), its y along z.
  3. Swap the Jump tests for WasPressedThisFrame(), IsPressed() and WasReleasedThisFrame(), and the click for Mouse.current.leftButton.wasPressedThisFrame.

Press Play, blow a bubble and pop it. Then Check.

Try it yourself

using UnityEngine;

public class Wand : MonoBehaviour
{
    public float speed = 4f;
    public float growRate = 1f;
    public float maxSize = 1.5f;
    public GameObject bubblePrefab;

    private Transform bubble;

    void Update()
    {
        Vector3 move = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
        transform.position += move.normalized * speed * Time.deltaTime;

        if (Input.GetButtonDown("Jump"))
        {
            bubble = Instantiate(bubblePrefab, transform.position + Vector3.up * 1.5f, Quaternion.identity).transform;
        }
        if (Input.GetButton("Jump") && bubble != null)
        {
            float size = Mathf.Min(bubble.localScale.x + growRate * Time.deltaTime, maxSize);
            bubble.localScale = Vector3.one * size;
        }
        if (Input.GetButtonUp("Jump") && bubble != null)
        {
            Debug.Log("Bubble: " + bubble.localScale.x.ToString("F1"));
            bubble = null;
        }

        if (Input.GetMouseButtonDown(0))
        {
            GameObject[] bubbles = GameObject.FindGameObjectsWithTag("Bubble");
            foreach (GameObject b in bubbles) Destroy(b);
            Debug.Log("Popped " + bubbles.Length);
        }
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Building Real Games

Practice on your own: Unity playground