Dropping coins at target point with SFX

Coin Distraction Part 1

In our next few articles we will be working on a distraction feature. The player can toss a coin and distract the guards to sneak past them.

Pseudocode

Start off simple then we will expand on this later.

if r-click
instantiate coin at clicked position
play sound effect for coin drop

Coin Prefab

This gameobject has an audio source that plays a SFX on awake.

Player Script Drop Coin at Point

On r-click a coin will be instantiated at that point.

if (Input.GetMouseButtonDown(1))
{
RaycastHit hitInfo;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hitInfo))
{
Instantiate(_coinPrefab, hitInfo.point, Quaternion.identity);
}
}
You can see the coins on the ground

Only one

We don’t want the player to be able to throw coins endlessly. We created a bool variable to store whether the player threw his only coin or not. Below our slight update to our code in bold.

if (Input.GetMouseButtonDown(1)&& _coinThrown == false)
{
RaycastHit hitInfo;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hitInfo))
{
Instantiate(_coinPrefab, hitInfo.point, Quaternion.identity);
_coinThrown = true;
}
}

We only set the bool to true when the coin is instantiated.

Aspiring developer that’s self-learning Unity & C# to transition to a career with Unity. I got a passion for creating interactive experiences.