I’m making a RTS Game, and currently I’m working on the Ai for shoting, destroying etc… I have Prefabs of the Enemy and of the Player Object. The Problem is that my Player Object AI does, if the Enemy gets destroyed and it reaches the clone of the Enemy , just stop, says “MissingReferenceException: The object of type ‘Transform’ has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.” and doesn’t shoot or work anymore. If it first reaches the clone of the Enemy it doesn’t target the clone but the Original object. i ran out of ideas - Pls Help. here is the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Attack : MonoBehaviour
{
public GameObject projectile;
public bool attackE;
public Transform enemy;
public float attackRange;
public LayerMask whatIsGround,whatIsEnemy;
bool alreadyAttacked;
public float timeBetweenAttacks;
// Start is called before the first frame update
void Awake()
{
enemy = GameObject.Find("Enemy").transform;
}
// Update is called once per frame
void Update()
{
attackE = Physics.CheckSphere(transform.position, attackRange, whatIsEnemy);
if (attackE) Fire();
}
public void Fire()
{
if (!alreadyAttacked)
{
Vector3 enemyDirection = enemy.position - transform.position;
///Attack code here
Rigidbody rb = Instantiate(projectile, transform.position, Quaternion.identity).GetComponent<Rigidbody>();
rb.AddForce(enemyDirection * 32f, ForceMode.Impulse);
///End of attack code
alreadyAttacked = true;
Invoke(nameof(ResetAttack), timeBetweenAttacks);
}
//Make sure enemy doesn't move
}
private void ResetAttack()
{
alreadyAttacked = false;
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, attackRange);
}
}