Hello!
I have started working on a little project.
The idea is for a fantasy battlefield, two armies/groups of units will attack each other until one side wins. I have built this but it can lag and I don’t feel as though this is the best way to about it. The scripts rely on Colliders so you can imagine that is can start to struggle. I need to try and find away to have a less colliders dependent script to help reduce lag. Or maybe there is another part of the script that is affecting the lag. When there are many units on the map many of the units will take a few seconds to get going.
Each Unit has
An Animator
A Rigidbody
A Nav Mesh Agent
A Box Collider
A Sphere Collider
and the Basic_ai script
The Sphere collider acts as the aggro are for the unit, once an enemy unity enters this area the script gets this enemy as the Nav target.
Here is the script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class basic_ai : MonoBehaviour {
public int hit_points;
private float moral = 100;
public Transform current_target;
private GameObject[] targets_in_area;
private int armour_rating;
private int damage;
private NavMeshAgent nav;
private Animator anim;
private GameObject enemy_spawn;
private bool is_fighting;
private string my_enemy;
void Start()
{
nav = gameObject.GetComponent<NavMeshAgent> ();
anim = gameObject.GetComponent<Animator> ();
if (this.gameObject.tag == "ally") {
my_enemy = "enemy";
} else {
my_enemy = "ally";
}
if (this.gameObject.tag == "ally") {
enemy_spawn = GameObject.Find ("enemy_spawn");
} else {
enemy_spawn = GameObject.Find ("player_spawn");
}
current_target = enemy_spawn.transform;
}
void Update()
{
if (hit_points < 0) {
Destroy (gameObject);
}
if (is_fighting == false) {
nav.SetDestination (current_target.position);
anim.SetBool ("is_running", true);
} else {
anim.SetBool ("is_running", false);
}
RaycastHit hit;
Ray meleeRay = new Ray (transform.position + Vector3.up, transform.forward);
Debug.DrawRay (transform.position + Vector3.up, transform.forward * 25);
if (Physics.Raycast (meleeRay, out hit, 25)) {
if (hit.collider.tag == my_enemy) {
anim.SetBool ("is_attacking_side", true);
hit.collider.gameObject.GetComponent<basic_ai> ().hit_points -= 1;
is_fighting = true;
}
} else {
is_fighting = false;
anim.SetBool ("is_attacking_side", false);
}
}
void OnTriggerStay(Collider col)
{
if (col.gameObject.tag == my_enemy) {
current_target = col.gameObject.transform;
}
}
}
As you can see its very basic, but it works. I am post to ask on peoples opinion and where it can be improved.
Thank you for any insight.