Advertisement
Guest User

Untitled

a guest
Apr 19th, 2019
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.39 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class EnemyPathing : MonoBehaviour
  6. {
  7.     // new serialized field to drop the root prefab into
  8.     [SerializeField] Transform path;
  9.  
  10.     // Doesn't need to, and really shouldn't be serialized any more
  11.     [SerializeField] float moveSpeed = 2f;
  12.     List<Transform> waypoints = new List<Transform>();
  13.     int waypointIndex = 0;
  14.  
  15.    
  16.  
  17.     void Start()
  18.     {
  19.         // Simple iteration of the children transforms and adding them to the list
  20.         // if they're not in order (0), (1), (2) in the hierarchy, they wont be in the list, either.
  21.         for (int i = 0; i < path.childCount; i++)
  22.         {
  23.             waypoints.Add(waypoints[i]);
  24.         }
  25.  
  26.        
  27.         transform.position = waypoints[waypointIndex].position;
  28.        
  29.     }
  30.  
  31.  
  32.     private void Move()
  33.     {
  34.         if (waypointIndex <= waypoints.Count - 1)
  35.         {
  36.             var targetPosition = waypoints[waypointIndex].transform.position;
  37.             var movementThisFrame = moveSpeed * Time.deltaTime;
  38.             transform.position = Vector2.MoveTowards(transform.position, targetPosition, movementThisFrame);
  39.  
  40.             if (transform.position == targetPosition)
  41.             {
  42.                 waypointIndex++;
  43.             }
  44.         }
  45.         else
  46.         {
  47.             Destroy(gameObject);
  48.         }
  49.     }
  50.  
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement