Coin toss

Hal Brooks
2 min readAug 25, 2021

--

Objective: Allow player to toss a single coin.

Since the player will throw the coin, open the Player C# script and create three new variables.

Variables for coin toss.

SerializeField allows the assignment of the Coin prefab to _coinPrefab and audio file Coin_Drop to _coinClip using Unity inspector, as shown below. The Boolean _coinThrown will be used to allow a single coin toss by the player, defaulting to false.

Player script variable assignment

In void Update() add the following code to check that player has not previously thrown the coin, i.e. _coinThrown is false, and if the right mouse button is clicked. The Coin prefab is a Coin game object with a child coin that that needs the components shown below. The transform position and rotation should be (X 0, Y 0, Z 0). The scale is (X 0.15, Y, 0.015, Z 0.15).

Coin child of Coin game prefab.

Cast a ray from the main camera to the mouse position at the time of right click and if Physic.raycast hits a collider the location is stored in hit.

Code in void Update allowing the coin toss in Player script.

The coin is placed at hit.point, i.e. the mouse position, and a sound clip is played at this point. AudioSource.PlayClipAtPoint creates a transient audio clip at hit.point and removes it after the clip finishes. Changing _coinThrown to true prevents the player from throwing another coin since _coinThrown must be false to execute this code.

The small gold coin is placed at the mouse cursor when right clicked.

The article uses assets from The Great Fleece by GameDevJon from the Unity Asset Store.

--

--

No responses yet