Cant make a enemy script for looking at the player
Options
so i made an enemy script but there is some errors
code:
using System.Collections; using System.Collections.Generic; using UnityEngine; using Photon.Pun; using Photon.Realtime; public class Enemy : MonoBehaviourPunCallbacks { public static Enemy instance; public float health; public float damageToPlayer; public float rangeToAttack; public float timeBetweenAttacks; public bool lookAtPlayer; public int playerCount; [HideInInspector] public ActualPlayerController nearestPlayer; ActualPlayerController[] players; float nextAttackTime; [HideInInspector] public PhotonView view; private void Awake() { instance = this; } private void Start() { nextAttackTime = timeBetweenAttacks; view = GetComponent<PhotonView>(); } private void Update() { if (PhotonNetwork.CurrentRoom.PlayerCount != 2 || PhotonNetwork.IsMasterClient == true) { return; } players = FindObjectsOfType<ActualPlayerController>(); float distanceOne = Vector3.Distance(transform.position, players[0].transform.position); float distanceTwo = Vector3.Distance(transform.position, players[1].transform.position); if (distanceOne < distanceTwo) { nearestPlayer = players[0]; } else { nearestPlayer = players[1]; } if (nearestPlayer == null) { return; } if (lookAtPlayer) { transform.LookAt(nearestPlayer.transform.position); } if (Vector3.Distance(transform.position, nearestPlayer.transform.position) < rangeToAttack) { if (nextAttackTime < Time.time) { nextAttackTime = Time.time + timeBetweenAttacks; Attack(); } } } public void TakeDamage(float damage) { health -= damage; if(health <= 0) { Destroy(gameObject); } } public virtual void Attack() { } }
the error is:
IndexOutOfRangeException: Index was outside the bounds of the array
at Enemy.cs:44
so the error line is the
float distanceTwo = Vector3.Distance(transform.position, players[1].transform.position);
0