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 Lolligirl · Nov 16, 2016 at 05:23 AM · raycastunity5raycastingpickup

Raycasting to pick up an item problem

Hello! I am having an issue with raycasting and picking up an item: my code only gets to "a!" in the console, and then throws an error. Physics.Raycast is supposed to take in a Vector3 origin, Vector3 direction, and a float maxDistance, but it does not accept my "out hit" as a direction. I've also tried ray.direction as the direction, but it still does not work. Can someone please point me in the right direction of what I'm doing wrong here? :)

 using UnityEngine;
 using System.Collections;
 
 public class ItemPickup : MonoBehaviour {
 
     private InventoryScript inventory;
     public float raycastLength = 5f;
 
     void Start () {
         inventory = GameObject.FindGameObjectWithTag("InventorySystem").GetComponent<InventoryScript>();
     }
 
     void Update () {
         // Create variables for the ray and the possible hit.
         Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         RaycastHit hit;
         Debug.Log("a!");
 
         if (Physics.Raycast(ray, out hit, raycastLength)) //PROBLEM LIES HERE
         {
             Debug.Log("b!");
             // We hit something! Check if we can pick it up.
             if (hit.collider.gameObject.tag == "Pickupable")
             {
                 Debug.Log("Found item!");
                 if (Input.GetKeyDown("e"))
                 {
                     // Add the item to the inventory and destroy it in the world.
                     inventory.item++;
                     Destroy(hit.collider.gameObject);
                 }
             }
         }
     }
 }
 
Comment
Add comment · Show 1
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 roman_sedition · Nov 16, 2016 at 02:54 PM 0
Share

What error are you getting? It looks like it should work, unless the raycastLength isn't long enough, have you tried to draw the ray?

1 Reply

· Add your reply
  • Sort: 
avatar image
1

Answer by Ambrose998800 · Nov 16, 2016 at 05:51 AM

Tested your script, there's no problem in my case. Prints a! and b!.

Try once my pickup script, that is working very well and is almost the same (take out the InvWindow check)...

 using UnityEngine;
 using System.Collections;
 
 public class Focus : MonoBehaviour {
 
     private GameObject InvWindow;
     private LayerMask Mask = 1;
     public RaycastHit Hit;
     public GameObject Item;
 
     void Awake()
     {
         InvWindow = GameObject.Find("InvWindow");
     }  
 
     void Update()
     {        
         if (Physics.Raycast(transform.position, transform.forward, out Hit, 10.0f, Mask.value))
         {
             Item = Hit.collider.gameObject;            
             if (Hit.distance <= 1.5f && InvWindow.active == false)
             {
                 Item.SendMessage("PickUp", true, SendMessageOptions.DontRequireReceiver);
             }
         } 
     }
 
 }
Comment
Add comment · Show 4 · 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 Lolligirl · Nov 16, 2016 at 04:39 PM 0
Share

@Ambrose998800 Thank you very much for that solution! The only problem is that now, for some reason, when I hover over many different parts of the code, I get the error message "The name '$$anonymous$$onoBehaviour' does not exist in the current context." It only does this for the .cs files opened for any scene in this project; my other projects do not do this. The problem stops if I delete all the files in the project directory except the Assets and ProjectSettings folder, but then I have to re-set up all of my assets in the scene. Do you have any idea which file may be causing this error? :)

alt text

avatar image Ambrose998800 Lolligirl · Nov 16, 2016 at 04:56 PM 1
Share

If the class is called "public class Focus : $$anonymous$$onoBehaviour {", you need to name your script the same way; in that case: Focus.cs

If you want to name it PickUp.cs, change the line to: "public class PickUp: $$anonymous$$onoBehaviour {"

Edit_1: just tried to reproduce that message, it's not fixed by changing the name of the script, is it?

Edit_2: I forgot, if you want to use the Send$$anonymous$$essage function in my script, you need a second script on every item object that gets the collider that will be hit by the PickUp-script:

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class Item_Basic : $$anonymous$$onoBehaviour {
          
     //Basic item variables                   
     public string Name;
     public float ID; 
     public Sprite Icon;
 
     public float Weight;
 
     private Inventory Inv;
     private Rigidbody Rb;
     private AudioSource Soundsource;
 
     void Start()
     {
 
         //Assign inventary script
         Inv = GameObject.Find("PlayerScriptSpace").gameObject.GetComponent<Inventory>();
         
         //Create or assign rigidbody
         if (gameObject.GetComponent<Rigidbody>() == false)
         {
             Rb = gameObject.AddComponent<Rigidbody>(); 
         }
         Rb = gameObject.GetComponent<Rigidbody>();
         if (Rb.mass <= 1.0f)
         {
             Rb.collisionDetection$$anonymous$$ode = CollisionDetection$$anonymous$$ode.Continuous;
         }
         Rb.mass = Weight;
     }
 
     void PickUp()
     {
                  
         if (Input.GetButtonDown("PickUp Object"))
         {
 
             //Put off renderer
             if (this.gameObject.GetComponent<Renderer>() == true)
             {
                 this.gameObject.GetComponent<Renderer>().enabled = false;
             }
             if (this.gameObject.transform.childCount != 0)
             {
                 foreach(Transform Child in this.gameObject.transform)
                 {
                     Child.gameObject.GetComponent<Renderer>().enabled = false;
                 }
             }
 
             //$$anonymous$$ake object follow player
             this.gameObject.transform.parent = GameObject.Find("Player").gameObject.transform;
             this.gameObject.transform.localPosition = Vector3.zero;
                      
             //Add or remove object from inventary list
             Inv.UpdateItemList();
 
         }
     }
 }
avatar image Lolligirl Ambrose998800 · Nov 17, 2016 at 06:52 PM 0
Share

Thank you very much for showing me this code; remembering to assign a RigidBody component, for example, is very useful! :)

By the way, I fixed the odd problem I was having by deleting the project files and folders except for "Assets," "Library," and "ProjectSettings." It was the same problem this guy was having. Thanks again!

Show more comments

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

6 People are following this question.

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

Related Questions

How do i get local Hit position of Raycast on a collider 1 Answer

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

What's an easy way to align a UI element with a Raycast? 0 Answers

Raycasting doesn't hit terrains 0 Answers

What's wrong with my RayCastHit2D? 0 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