- Home /
Destroying an instatiated game object with a script attached creates problems for the rest of instatiated game objects with the same script
Hi, I'm trying to make a tower defense game and I'm having issues with the units (enemies) spawned. (sorry for the long post and for my English)
I'm using a gameobject (called Spawn) to instatiate units into the scene, these units have an AI script attached (for A* pathfinding) that allows them to find the shortest path between the starting point and the end point. In case i place an obstacle in the middle of the route the script recalculates the path and finds a way around that obstacle so the units can keep moving towards the end point without stopping anywhere.
Everything works fine until the moment the first unit gets destroyed (by reaching the end point). When it gets destroyed the rest of the units won't recalculate the path if i place an obstacle and i will get an error (MissingReferenceException: The object of type 'AstarAI' 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.)
when I'm placing an obstacle. The obstacle though does appear on the scene and the grid does update (including the newly placed obstacle), it's just the units that don't update their path.
From what i understand along with the game object the script is also getting destroyed leaving the rest of the units "scriptless" (though the still find the correct/updated path if i spawn a new one) and i'm not sure if this is a logic problem or coding one.
Below some code hoping that it will help someone to understand.
From the spawn game object:
public class Spawn : MonoBehaviour {
public GameObject monsterToSpawn;
private GameObject spawnMonster;
void Update()
{
if (Input.GetKeyDown("space"))
{
spawnMonster = Instantiate(monsterToSpawn, transform.position, Quaternion.identity) as GameObject;
}
From the unit (AI):
public class AstarAI : MonoBehaviour
{
//The point to move to
public Transform target;
//The point to start moving from (Spawn position)
public Transform startPos;
private Seeker seeker;
//The calculated path
public Path path;
//The AI's speed per second
public float speed = 2;
//The max distance from the AI to a waypoint for it to continue to the next waypoint
public float nextWaypointDistance = 0.02f;
//The waypoint we are currently moving towards
private int currentWaypoint = 0;
public void Start()
{
seeker = GetComponent<Seeker>();
//Start a new path to the targetPosition, return the result to the OnPathComplete function
seeker.StartPath(startPos.transform.position, target.position, OnPathComplete);
}
public void OnPathComplete(Path p)
{
// Debug.Log("Yay, we got a path back. Did it have an error? " + p.error);
if (!p.error)
{
path = p;
//Reset the waypoint counter
currentWaypoint = 0;
}
}
//Recalculates the path after an obstacle has been placed.Gets called immidietly when you create the wall.
public void OnEnable()
{
AstarPath.OnGraphsUpdated += RecalculatePath;
}
public void RecalculatePath(AstarPath ap)
{
seeker.StartPath(transform.position, target.position, OnPathComplete);
}
public void FixedUpdate()
{
if (path == null)
{
//We have no path to move after yet
return;
}
if (currentWaypoint >= path.vectorPath.Count)
{
Debug.Log("End Of Path Reached");
Destroy(gameObject);
currentWaypoint++;
return;
}
//Direction to the next waypoint
Vector3 dir = (path.vectorPath[currentWaypoint] - transform.position).normalized;
dir *= speed * Time.fixedDeltaTime;
this.gameObject.transform.Translate(dir);
//Check if we are close enough to the next waypoint
//If we are, proceed to follow the next waypoint
if (Vector3.Distance(transform.position, path.vectorPath[currentWaypoint]) < nextWaypointDistance)
{
currentWaypoint++;
return;
}
}
}
The error message appears right after the first unit gets destroyed and i place a wall. When i click on it, it sends me to the
public void RecalculatePath(AstarPath ap)
{
seeker.StartPath(transform.position, target.position, OnPathComplete);
}
part where the recalculation of the path happens.
Again, i don't know if this is a coding problem or a logic one.
Any help will be appreciated.
Thanks for your time and sorry for the long post.
P.S if anyone knows of a good tutorial that explains game logic etc for Tower Defense games (preferable 2D ones) please link it here so i can read it.
Your answer
Follow this Question
Related Questions
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
How do I make objects disappear as they are touched? 1 Answer
Is there a way for me to find the walkable edges of my traversable game map? 0 Answers
How to minimize directional changes of A* autopathing movement? 0 Answers
Cannot destroy Component while GameObject is being activated or deactivated 2 Answers