G
G
GmDvlpr2020-01-07 15:09:40
Unity
GmDvlpr, 2020-01-07 15:09:40

Unity object destruction, what to do?

I am creating an android game in which objects appear and when you tap on them, they are destroyed.
I use void OnMouseDown(), then I write in it that I need to destroy the object

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Hitenemy : MonoBehaviour
{
    public GameObject man;
    GameObject enemy;
    public Text score;
    public int count = 0;
    void Start()
    {
        StartCoroutine(Spawn());
    }

    
    void Update()
    {
        
    }

    IEnumerator Spawn()
    {
        while (true)
        {
            man.transform.position = new Vector2(Random.Range(-2.21f, 2.195f), Random.Range(-4.354f, 2.498f));
           enemy= Instantiate(man);
            yield return new WaitForSeconds(1.5f);

            //   Destroy(enemy);
            // yield return new WaitForSeconds(1.5f);
        }
    }

    private void OnMouseDown()
    {
        enemy=GameObject.FindWithTag("Player");
        Destroy(enemy);
        count++;
       score.text = count.ToString();
    }
}

Then I bind the script to the 3d object from which I removed the mesh renderer
. When I start the game, wherever I click, the score will increase, and the objects will be deleted as soon as they appear, but I want me to click on the objects, and not on the 3d an object.
I tried to attach a script to the camera, but nothing is pressed there at all

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
freeExec, 2020-01-07
@freeExec

In the place of pressing, you need to do a Reycast to determine if there is something there or if it is an empty place.

G
GavriKos, 2020-01-07
@GavriKos

Or, as freeExec said , or - hang a script on EVERY object (provided that it has a collider), and destroy not the mythical Player, but this particular object - Destroy(gameObject)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question