Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Noshiz · Feb 12, 2016 at 01:43 PM · scripting problemgameobjectaidestroypathfinding

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.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

3 People are following this question.

avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges