Key Cards in Unity

Hal Brooks
3 min readOct 2, 2021

--

Objective: Create a key card collectible that activates a mobile platform.

Player collects red key card at right, activating the platform to the left.

Create a 3D object > Cube called Collectable and adjust its scale and rotation to that shown below. Position the Collectable in the scene view so it is at waist height above the platform. The box collider is set to is trigger, and create a C# script KeyCard. Create a new material called Key_Red and place it in the Materials folder within Assets in project Window. Assign this new material to the Mesh Renderer Materials Element 0, as shown below.

Create a 3D object > TextMeshPro game object called Key as a child of Collectable, shown below. Change the text to key and the font to 4. The position is set to be on one surface of the Collectable.

Key TextMeshPro object, a child of Collectable.

Drag the Collectable game object into the Prefabs folder, afterwards create two new collectables by dragging the new prefab into the Hierarchy window.

Collectable prefab.

The KeyCard script is shown below. Since multiple KeyCards will be used in the game, an int _keyID is assigned in the inspector for each key. This article will focus on the Red Key card, _keyID = 1 or Collectable (1). The transform.Rotate command in void Update() provides a visual to attract the players attention. When the Player moves onto the key card the OnTriggerEnter function triggers and selects the response based upon the _keyID. The KeyCard script communicates to the GameManager that it HasCards[1] and destroys the Collectable.

KeyCard script on Collectable

The GameManager script, shown below, is a singleton and stores the KeyCard collection state, HasCards, for communication with the MobilePlatform.

GameManager singleton script.

The MobilePlatform script is modified to control the speed based upon the HasCards state in the game manager. The bool _activePlatform and int _mobilePlatformID are used to control the movement _speed of the platform. The _speed is initially set to zero.

In void Update() the HasCards for the _mobilePlatformID is checked if true and if the platform is currently inactive, i.e. _activePlatform false, then the _activePlatform is set to true and the _speed is set to 3.0f, enabling movement.

The Mobile_Platform starts stationary, but when the Player collects the red key card the mobile platform begins to move.

--

--

No responses yet