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:

  1. Start by creating a new script in the Scripts folder of the Project window. Name it PlayerPosition.
  2. 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;
  3. 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 the position variable can be filled and used as soon as the game starts.
    public void Start() { position = transform.position; ...

Get Unity Android Game Development by Example Beginner's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.