Search Unity

Destroy Tagged items

Discussion in 'Scripting' started by ShatterGlassGames, Mar 19, 2020.

  1. ShatterGlassGames

    ShatterGlassGames

    Joined:
    Jan 14, 2016
    Posts:
    135
    Hi, I need some help with one of my interaction scripts. I would like to know a way i can destroy a tagged item but without having to declare a GameObject variable. Below is the script i attached to my fps player camera.


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class CollectItemSaphire : MonoBehaviour
    6. {
    7.     public AudioClip[] CollectSound;
    8.     public GameObject InteractIcon;
    9.     public float interactDistance = 2.0f;
    10.  
    11.     void Update()
    12.     {
    13.         Ray ray = new Ray(transform.position, transform.forward);
    14.         RaycastHit hit;
    15.         if (Physics.Raycast(ray, out hit, interactDistance))
    16.         {
    17.             if (hit.collider.CompareTag("ItemSaphire"))
    18.             {
    19.                 InteractIcon.SetActive(true);
    20.                 if (Input.GetButtonDown("Interact"))
    21.                 {
    22.                     int r = Random.Range(1, CollectSound.Length);
    23.                     AudioSource.PlayClipAtPoint(CollectSound[r], transform.position);
    24.                     ScoringSystem.TheScoreSaphire += 1;
    25.                     //the code to destroy the game object i'm hitting with my ray goes here.
    26.                 }
    27.             }
    28.         }
    29.         else
    30.         {
    31.             InteractIcon.SetActive(false);
    32.         }
    33.     }
    34. }
     
  2. Chocolade

    Chocolade

    Joined:
    Jun 19, 2013
    Posts:
    933

    Code (csharp):
    1.  
    2. Destroy(hit.transform.gameObject);
    3.  
     
  3. ShatterGlassGames

    ShatterGlassGames

    Joined:
    Jan 14, 2016
    Posts:
    135
    Thank you very much. That did the job.