Recap: Input Swap
Part of the Building Real Games section of Coddy's Unity journey. Lesson 47 of 56.
Challenge
MediumThis 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
speedunits 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
growRateper second, up tomaxSize. Letting go logs its size, such asBubble: 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
2Buttons and Screens
Buttons and onClickLambdasWiring in the InspectorPanels On and OffHealth BarsRecap: Upgrade Shop5Saving with PlayerPrefs
Save a NumberLoad with a DefaultHigh ScoreSave SettingsRecap: Coins in the Bank3The Game Manager
One Script Runs the GameThe SingletonGame StatesSwitching on the StateRecap: Round Manager6Project: Endless Runner
Three LanesObstacles Ahead9The New Input System
Two Input SystemsKeyboard and MousePressed This FrameInput ActionsRecap: Input Swap