Time for action – the player is over here
With a very short script, we can easily allow all our enemies know the location of the player:
Start by creating a new script in the
Scripts
folder of the Project window. Name itPlayerPosition
.This script will start with a single static variable. This variable will simply hold the current position of the player. Because it is static, we will be able to easily access it from the rest of our scripts.
public static Vector3 position = Vector3.zero;
For the next lines of code, we make use of the
Start
function. This function is automatically called when a scene is first loaded. We use it so that theposition
variable can be filled and used as soon as the game starts.public void Start() { position = transform.position; }
The last segment of code simply updates the
position
variable in every frame to the player's current position. We also do this in theLateUpdate
function so that it is done after the player has moved. TheLateUpdate
function is called at...