Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 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 zchantie · May 18, 2015 at 10:15 AM · physics2draycasting

How to use Raycasting 2D to mouse click and delete objects?

So I'm using the code below right now. The goal is to be able to click & destroy objects on screen with a mouse.

Right now I get this error: "Missing Reference Exception: The object of type 'GameObject' 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."

I know this is because the destroy command isn't specific enough but what should I be destroying? Or alternatively, I've heard about "pooling" objects and right now my spawner spawns the objects from a pool but how do I get rid of those objects upon clicking without destroying? Any help on this would be great.

 using UnityEngine;
 using System.Collections;
 
 public class ClickTest : MonoBehaviour {
     // public GameObject red, red2, yellow, yellow2, MainCamera;
     // Use this for initialization
     
     public int health = 1;
     
     void Update () {
         if (Input.GetMouseButtonDown(0)) {
             Debug.Log("Pressed left click, casting ray.");
             CastRay();
         }       
     }
     
     void CastRay() {
         Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction, Mathf.Infinity);
         if (hit.collider !=null&&hit.transform==transform) {
             Debug.Log (hit.collider.gameObject.name);
             health --;
         }
         if (health <= 0) {
             Die ();
         }
     }
     void Die() {
         Destroy (gameObject);
         
     }
 }
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

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by Headworker · May 18, 2015 at 10:23 AM

First: I assume your raycast does work? Is the Debug.Log showing properly?

Second: There is an error in your script. Die() destroys the clicker, not the target object. Attach the script to the camera. Change your code to something like (untested):

your destroyable gameobject needs to have a script attached to it, ideally with a public method DamageMe() for instance. If this script is named Destroyable, something like this can work:

 ...
 // Script on the mouse
      if (hit.collider !=null) 
      {
          Debug.Log (hit.collider.gameObject.name);
          if (hit.collider.getComponent<Destroyable>() != null)
          {
               hit.collider.getComponent<Destroyable>().DamageMe()
          }

   

//Script on the Object to destroy

 public class Destroyable: MonoBehaviour 
 {
     int Health = 5; //Example
     
          public void DamageMe()
          {
              health--;
              if (health <= 0)
              {
                  Die();
              }
          }
          
          void Die(gameObject go)
          {
             Destroy(go);
          }

}

Third: If you use a pooling system, the command to disable an object and recycle it for reuse depends entirely on the pooling system. Most System however simply disable the gameobject like this.

  void Die(gameObject go)
  {
  go.setActive(false);
  }

}

This formatting is killing me...

Comment
Add comment · Share
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

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

Is it possible to raycast during edit mode? 1 Answer

RaycastHit2D.collider always null? 0 Answers

[Solved] How to touch/activate 2D objects? 1 Answer

Can RaycastHit2D.point be inside a BoxCollider2D if raycast was performed from outside that collider? 1 Answer

Raycasting not behaving as expected? 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