Menu
CoddyTech

Recap: Input Swap

Part of the Building Real Games section of Coddy's Unity journey. Lesson 47 of 56.

challenge icon

Challenge

Medium

This bubble wand was written for the old Input class. It works in a project set to Both, but this project is set up like a new Unity 6 project (Active Input Handling: Input System Package): press Play and the first Input call throws an InvalidOperationException. Port it to the Input System, keeping everything it does:

  • The arrows or WASD walk the wand across the lawn at speed units per second, no faster on a diagonal.
  • Pressing Jump blows a bubble 1.5 units above the wand. While Jump is held, that bubble grows by growRate per second, up to maxSize. Letting go logs its size, such as Bubble: 0.8.
  • A left click pops every bubble and logs how many, such as Popped 3.

Use the project's Move and Jump actions and Mouse.current, and leave no Input. call in the script. Press Play and try 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);
        }
    }
}

All lessons in Building Real Games