- Home /
How to combine old AI script with a new one
So I was wondering how I could put this script:
public GameObject thePlayer;
public GameObject theEnemy;
public float enemySpeed = 0.01f;
public bool attackTrigger = false;
public bool isAttacking = false;
void Update()
{
transform.LookAt(thePlayer.transform);
if (attackTrigger == false)
{
enemySpeed = 0.01f;
theEnemy.GetComponent<Animation>().Play("walk_in_place");
transform.position = Vector3.MoveTowards(transform.position, thePlayer.transform.position, enemySpeed);
}
if (attackTrigger == true && isAttacking == false)
{
enemySpeed = 0;
theEnemy.GetComponent<Animation>().Play("attack");
StartCoroutine(InflictDamage());
}
}
void OnTriggerEnter()
{
attackTrigger = true;
}
void OnTriggerExit()
{
attackTrigger = false;
}
IEnumerator InflictDamage()
{
isAttacking = true;
yield return new WaitForSeconds(1.1f);
GlobalHealth.currentHealth -= 5;
yield return new WaitForSeconds(0.2f);
isAttacking = false;
}
}
Into This:
void Start()
{
target = PlayerManager.instance.player.transform;
agent = GetComponent<NavMeshAgent>();
}
// Update is called once per frame
void Update()
{
float distance = Vector3.Distance(target.position, transform.position);
if (distance <= lookRadius)
{
agent.SetDestination(target.position);
theEnemy.GetComponent<Animation>().Play("walk_in_place");
if (distance <= agent.stoppingDistance)
{
//attack
FaceTarget();
}
}
}
void FaceTarget ()
{
Vector3 direction = (target.position - transform.position).normalized;
Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 5f);
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, lookRadius);
}
}
Answer by LTonon · Jan 11, 2020 at 05:04 PM
This sounds like a weird question, but I guess you could accomplish this by:
Adding all the variables from script1 into script2;
Remove the content of the Update function in script1 (lines 9 - 21) and create a new function into script2. Then you'd just have to call this new function inside the Update in script2 (or just paste the content into the Update without creating a new function);
Everything else could be pretty easily added into the script2, just copy and paste;
Couldn't you just add both scripts components to your Game Object that requires AI?
Your answer
![](https://koobas.hobune.stream/wayback/20220612221406im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Is the Player Being Looked at 1 Answer
EnemyAI C# Error 1 Answer
How to make an AI like slender ? 1 Answer
AI Following Problem 1 Answer
enemy doesn't follow the player 2 Answers