-1

i ve 15 objects in my scene, and when using raycast it takes the first objects near the camera, even if you clike the last objects it will destroy the first one. here is my code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;


public class SecondD : MonoBehaviour
{
    Ray _ray;
    RaycastHit _raycastHit;
    Camera _camera;
    // Start is called before the first frame update
    void Start()
    {
        _camera = Camera.main;
    }

    // Update is called once per frame
    void Update()
    {

        if(Input.GetMouseButtonDown(0))
        {
            ShootRay();
        }
    }
    private void ShootRay()
    {
        _ray = _camera.ScreenPointToRay(Input.mousePosition);
        if(Physics.Raycast(_ray, out _raycastHit))
        {
            Destroy(GameObject.FindWithTag("Objects"));
        }
    }
}
derHugo
  • 83,094
  • 9
  • 75
  • 115
  • With that code yes. Firstly you arent destroying what you hit. You just find the first object in the hierarchy with that tag. Second. If you want to find more objects with the raycast. You need to use a different kind of raycast. Have a look at the documentation – BugFinder Feb 27 '22 at 22:09

1 Answers1

0

You are using FindWithTag which will just return to you any object from the scene with the given tag that is encountered first.

You rather want to actually use the object you have hit with your raycast:

private void ShootRay()
{
    var ray = _camera.ScreenPointToRay(Input.mousePosition);
    if(Physics.Raycast(_ray, out var raycastHit))
    {
        if(raycastHit.transform.CompareTag("Objects"))
        {
            Destroy(raycastHit.transform.gameObject);
        }
    }
}

In general for this purpose instead of tags you should rather use Layers and make your raycast only hit that specific layer (something you can't do with tags).

// Adjust via the Inspector
[SerializeField] private LayerMask hitLayer;

...

    if(Physics.Raycast(_ray, out var raycastHit, float.PositiveInfinity, hitLayer))
    {
        Destroy(raycastHit.transform.gameObject);
    }

If you also want to hit multiple objects at the same time you rather want to use Physics.RaycastAll and iterate (foreach) over the results.

derHugo
  • 83,094
  • 9
  • 75
  • 115