N
N
nika092017-05-31 13:21:03
C++ / C#
nika09, 2017-05-31 13:21:03

How to make item pickup in Unity?

I am writing a script for collecting items, there was an option using vectors but it didn’t always work correctly, I try using raycasts, everything is fine if not one but .... When the object is reduced, it stops disappearing. Please tell me how to fix this misunderstanding or how best to do so that the items would be collected (disappeared) ???
Code snippet with raycasts:

using System.Collections;
using UnityEngine;

public class RaycastExample : MonoBehaviour {


  void Start () {
    
  }
  

  void Update () {
    if (Input.GetMouseButtonDown (0)) {
      Ray ray = Camera.main.ScreenPointToRay (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, 1));
      RaycastHit _hit;
        if (Physics.Raycast (ray, out _hit, Mathf.Infinity)) {
        if (_hit.transform.tag == "PickUp") {
          Destroy (_hit.transform.gameObject);
        }
      }
    }
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daniil Basmanov, 2017-05-31
@nika09

A few notes, firstly, there is no need to create a separate vector for the mouse position, you can immediately pass Input.mousePosition. Secondly, Physics.Raycast's maxDistance is float.PositiveInfinity by default, your Mathf.Infinity can be removed. Thirdly, it is better to use CompareTag to check tags , it works a little faster.

using UnityEngine;

public class RaycastExample : MonoBehaviour
{
    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit))
            {
                if (hit.transform.CompareTag("PickUp"))
                {
                    Destroy(hit.transform.gameObject);
                }
            }
        }
    }
}

Regarding your problem, I would suggest you connect with a debugger and check that the raycasts hit the object, perhaps your collider is too small and the beam simply does not hit it. If this is the case, then you need to either increase the collider or use Physics.SphereCast .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question