- Home /
How to destroy the clone that I click on Unity 2D
I am trying to instantiate multiple clones of an object, and when I click on one of the clones, that specific clone is destroyed. I am able to instantiate one clone and then click on that clone and then it destroys just fine, but the issue comes when their are multiple clones being instantiated.
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cloneTesting : MonoBehaviour
{
public GameObject sphere;
private GameObject cloneSphere;
private CircleCollider2D collider;
// Start is called before the first frame update
void Start()
{
collider = GetComponent<CircleCollider2D>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
cloneSphere = Instantiate(sphere, new Vector3(0.04f, 4f, 0f), transform.rotation);
}
if(Input.GetMouseButton(0))
{
checkClick(getClickPosition());
}
}
//Gets the position the click
private Vector3 getClickPosition()
{
Vector3 clickPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
clickPos.z = 0f;
return clickPos;
}
//Checks the position of the click and destroys the clone if the clone is clicked on
private void checkClick(Vector3 clickPos)
{
if (collider != Physics2D.OverlapPoint(clickPos))
{
Debug.Log("HIT!");
Destroy(cloneSphere);
}
else
{
Debug.Log("MISS");
}
}
}
I understand why its not working the way that I did it, but I don't know any other way to instantiate multiple clones, and destroy the one that I click on. Thanks
Answer by highpockets · Apr 03, 2019 at 10:15 PM
You are setting the variable cloneSphere every time you instantiate a new sphere, so if you destroy cloneSphere, you are destroying the last clone instantiated. You need to change Destroy(cloneSphere); to Destroy(Physics2D.OverlapPoint(clickPos)).gameObject); and you probably don’t want to store just the last instantiated cloneSphere . You should make a list and add the objects to the list when you instantiate them if you need to reference them