Hello,
I have been trying to create a simple enemy AI for a first person shooter. For some reason my AI script causes a lot of lag. Here is the script:
var players:GameObject[];
var player:GameObject;
var speed:float;
var hitrange:float = 1.5;
var enemyprefab:Transform;
var healthkitprefab:Transform;
var ammokitprefab:Transform;
var plr:plrstats;
var enemy:enemystats;
var best:int = 0;
var current:int;
var x:int = 0;
var startpos:Vector3 = Vector3.zero;
var canhit:boolean = true;
var isspawned:boolean;
function Start()
{
isspawned = false;
startpos = transform.position;
enemy = gameObject.GetComponent(enemystats);
}
function Update () {
if (!isspawned)
{
spawn();
return;
}
x++;
players = GameObject.FindGameObjectsWithTag("Player");
for(var plr:GameObject in players)
{
current = Vector3.Distance(transform.position, plr.transform.position);
if (current > best)
{
player = plr;
best = current;
}
}
if (player == null) return;
if (Vector3.Distance(transform.position, player.transform.position) > hitrange && !canhit)
{
canhit = true;
}
if (Vector3.Distance(transform.position, player.transform.position) < hitrange)
{
if (!canhit) return;
plr = player.GetComponent(typeof(plrstats));
plr.Damage(20);
canhit = false;
}
if (enemy.isdead)
{
plr = player.GetComponent(typeof(plrstats));
plr.points += 10;
var bonus:Transform;
bonus = Instantiate(enemyprefab, startpos, Quaternion.identity);
bonus.name = "enemy";
var x = Random.Range(1,20);
if(x == 1){bonus = Instantiate(healthkitprefab, transform.position, Quaternion.identity); bonus.name = "healthkit";}
if(x == 2){bonus = Instantiate(ammokitprefab, transform.position, Quaternion.identity); bonus.name = "ammokit";}
GameObject.Find("pointer").guiText.text = "+";
GameObject.Destroy(gameObject);
}
}
function FixedUpdate()
{
if (player == null) return;
if (canhit)
{
transform.rotation = Quaternion.Slerp(transform.rotation,Quaternion.LookRotation(player.transform.position-transform.position), speed);
rigidbody.AddForce((transform.position-player.transform.position).normalized*speed*Time.deltaTime);
}
}
function spawn()
{
yield WaitForSeconds(3);
isspawned = true;
}
There is over 10 enemies on the map when the game is running, each enemy has one of these attached. The lag doesn’t appear until the enemies are spawned. When I took the things from the fixed update and put them in update the lag was replaced by the enemies not moving as they should. Could the lag be caused by fixedupdate?
How could I prevent the lag?
Thank You.