After my enemy reaches 0hp (I kill him) the game freezes and I get and error 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.
UnityEngine.Transform.set_localScale (UnityEngine.Vector3 value) (at <480508088aee40cab70818ff164a29d5>:0)
EnemyAI.FixedUpdate () (at Assets/Scripts/EnemyAI.cs:82).
Here is my script. Btw I am very new to Unity and scripting I followed Brackeys tutorial.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Pathfinding;
public class EnemyAI : MonoBehaviour
{
public Transform target;
public float speed = 200f;
public float nextWaypointDistance = 3f;
public Transform EnemyGFX;
Path path;
int currentWaypoint = 0;
bool reachedEndOfPath = false;
Seeker seeker;
Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
seeker = GetComponent<Seeker>();
rb = GetComponent<Rigidbody2D>();
InvokeRepeating("UpdatePath", 0f, .5f);
}
void UpdatePath()
{
if (seeker.IsDone())
seeker.StartPath(rb.position, target.position, OnPathComplete);
}
void OnPathComplete(Path p)
{
if (!p.error)
{
path = p;
currentWaypoint = 0;
}
}
// Fixed used in physics etc.
void FixedUpdate()
{
if (path == null)
return;
if(currentWaypoint >= path.vectorPath.Count)
{
reachedEndOfPath = true;
return;
}else
{
reachedEndOfPath = false;
}
Vector2 direction = ((Vector2)path.vectorPath[currentWaypoint] - rb.position).normalized;
Vector2 force = direction * speed * Time.deltaTime;
rb.AddForce(force);
float distance = Vector2.Distance(rb.position, path.vectorPath[currentWaypoint]);
if (distance < nextWaypointDistance)
{
currentWaypoint++;
}
if (force.x >= 0.01f)
{
EnemyGFX.localScale = new Vector3(-8f, 8f, 1f);
}
else if (force.x <= -0.01f)
{
EnemyGFX.localScale = new Vector3(8f, 8f, 1f);
}
}
}