Time for action – warning the player
A single script attached to our objects in space will warn the player as the objects approach.
- We start by creating a new script and name it
Alarm
. - This script starts with a single variable. It will hold the distance value at which the sound will start to fade in.
public float warningDist = 100f;
- Next, we create the
Update
function. It starts by checking for an Audio Source component and exiting the function early if there isn't one. Theaudio
variable holds the reference to the attached Audio Source component.public void Update() { if(audio == null) return;
- The function continues by calculating the distance to the player. Because the player never moves, we can just use the position's distance to the origin to make it simpler. We also use
sqrMagnitude
, which is the square of the length of the vector, because it is significantly faster to calculate. If the object is outside the range, the volume is set to0
and the function is exited.float...