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 /
  • Help Room /
avatar image
0
Question by OklamWarol · Apr 02, 2021 at 08:48 PM · raycasthitdestroy objectkeycode

Destroy object with KeyCode via RaycastHit

Hi! Long story short: Player moves to an item. Once within "maxCheckDistance" (3f), see the item, promptText appear from HUD if on the same layermask. Everything works fine for now. What I want to do: When player get close to object (within range) and hit "E" as a KeyDown(KeyCode), object spotted by RaycastHit has to be destroyed.

Collider, tag and layermask were added to parent object (the one I am doing the interaction with) - image provided.

Here is the code:

 public class InteractionManager : MonoBehaviour
 {
     public float checkRate = 0.05f;
     private float lastCheckTime;
     public float maxCheckDistance = 3f;
     public LayerMask layerMask;
 
     private GameObject curInteractGameObject;
     public IInteractable curInteractable;
 
     public TextMeshProUGUI promptText;
     private Camera cam;
 
     void Start()
     {
          cam = Camera.main;
     }
     void Update()
     {
         //True every "checkrate" seconds
         if (Time.time - lastCheckTime > checkRate)
         {
             lastCheckTime = Time.time;
             //Create a ray from the center of the screen pointing in the direction the player is looking
             Ray ray = cam.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
             RaycastHit hit;
 
             //Raycast hit something?
             if (Physics.Raycast(ray, out hit, maxCheckDistance, layerMask))
             {
                 //Is it interactable? If so, set as current interactable
                 if(hit.collider.gameObject != curInteractGameObject)
                 {
                     curInteractGameObject = hit.collider.gameObject;
                     curInteractable = hit.collider.GetComponent<IInteractable>();
                     SetPromptText();
                     Debug.Log("ray hit (tag): " + hit.collider.gameObject.tag);
 
                     //If "E" is pressed while interacting, destroy object found by Raycast
                     if (Input.GetKeyDown(KeyCode.E))
                     {
                         //print("E was pressed while looking at object");
                         //Debug.Log("E was pressed while looking at object");
                         Destroy(hit.collider.gameObject);
                     }
                 }
             }
             //If not interactable
             else 
             {
                 curInteractGameObject = null;
                 curInteractable = null;
                 promptText.gameObject.SetActive(false);
             }
         }
     }![alt text][1]

Thanks in advance! :)

[1]: /storage/temp/178580-image.jpg

image.jpg (60.4 kB)
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
1
Best Answer

Answer by Hellium · Apr 02, 2021 at 10:05 PM

  void Update()
  {
      //True every "checkrate" seconds
      if (Time.time - lastCheckTime > checkRate)
      {
          lastCheckTime = Time.time;
          //Create a ray from the center of the screen pointing in the direction the player is looking
          Ray ray = cam.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
          RaycastHit hit;
 
          //Raycast hit something?
          if (Physics.Raycast(ray, out hit, maxCheckDistance, layerMask))
          {
              //Is it interactable? If so, set as current interactable
              if(hit.collider.gameObject != curInteractGameObject)
              {
                  curInteractGameObject = hit.collider.gameObject;
                  curInteractable = hit.collider.GetComponent<IInteractable>();
                  SetPromptText();
                  Debug.Log("ray hit (tag): " + hit.collider.gameObject.tag);
              }
          }
          //If not interactable
          else 
          {
              curInteractGameObject = null;
              curInteractable = null;
              promptText.gameObject.SetActive(false);
          }
      }
      if(curInteratableGameObject != null && Input.GetKeyDown(KeyCode.E))
      {
           Debug.Log("E was pressed while looking at object " + curInteratableGameObject.name, curInteratableGameObject);
           Destroy(curInteratableGameObject);
      }
  }
Comment
Add comment · Show 3 · 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
avatar image OklamWarol · Apr 03, 2021 at 09:50 PM 0
Share

Changed the "Interatable" for "Interact" and it worked! Is there a reason why it has to be out of Raycast check? I am kinda new in development and trying to learn it by myself. Thanks!

avatar image Hellium OklamWarol · Apr 03, 2021 at 09:55 PM 0
Share

I literally copy-pasted your code and move one condition outside the raycast check because you perform the latter only every checkRate seconds. Your player would need to be extremely precise to perform the Key down at the exact frame the raycast is performed.

avatar image OklamWarol Hellium · Apr 03, 2021 at 10:42 PM 0
Share

Ohhh!!!! So it is because of the checkRate seconds. I was wondering why I was able to see it sometimes but not always. Thanks for the constructive feedback, really appreciated :)

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

158 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How to destroy a spawned object that lies on my raycast 1 Answer

Why doesn't the prefab destroy ? 0 Answers

I get this error when I turn off play in the editor. Vuforia runs fine, but it always comes up. I cant find an answer. Has anyone else seen this? Its probably an easy fix. 0 Answers

Check transform changes on multiple GameObjects / re-instantiate script on existing GameObject 0 Answers

Turn on Prefab with Keycode issue 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