This is the script I am using currently I am trying to make an AI that will follow the nearest player in a multiplayer game. I honestly cannot figure out what to do from here, please help!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ZombieAI : MonoBehaviour {
public Transform player;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Vector3.Distance(GameObject.FindGameObjectsWithTag("Player").position, this.transform.position) < 10000)
{
Vector3 direction = GameObject.FindGameObjectsWithTag("Player").position - this.transform.position;
direction.y = 0;
this.transform.rotation = Quaternion.Slerp(this.transform.rotation, Quaternion.LookRotation(direction), 0.1f);
if(direction.magnitude > 1)
{
this.transform.Translate(0,0,0.0152f);
}
}
}
}
Try using a NavMesh It’s very easy to do especially in you situation and has obstacle avoidance heres a tutorial: The NavMesh Agent - Unity Official Tutorials - YouTube
first of all findobjectswithtag is very heavy on the CPU its a last resort sort of thing. If you are doing this every frame and on every zombie. you will lag!!! really you should be keeping them in a list or array somewhere on a masterscript so that all the zombie scripts don’t have to keep looking them up.
here is a function that would return the closest player gameobject (if you REALLY want to use FindObjectsWithtag).
I would reccomend at least putting it on a timer so its called every couple seconds instead of everyframe.
public GameObject[] players;
float timer = 0;
public GameObject closest;
public GameObject getclosest(){
int i;
float dd;
float dist;
int close = 0;
players = GameObject.FindGameObjectsWithTag ("Player");
i = players.Length;
dist = 10000f;
while(i>0){i--;
dd=Vector3.Distance(transform.position,players*.transform.position);*
-
if(dd<dist){close=i;dist=dd;}}*
-
return players [close];*
-
}*
-
void Update () {*
-
timer -= Time.deltaTime;*
-
if (timer < 0) {*
-
timer += 2;*
-
closest=getclosest();*
-
}*
-
//do whatever you want to closest player here*
-
transform.position = Vector3.MoveTowards (transform.position, closest.transform.position, .5f);*
-
}*