- Home /
How to destroy Instantiated objects (C#)(not last instantiated one)
Hello!I have a problem with my project. In global I'm trying to recreate something like Terraria or Starbound(just for fun) and currently I can place blocks while pressing mouse0 but how do I destroy objects when I press on them with mouse0.Currently I have place/destroy code in one script:
using UnityEngine;
using System.Collections;
public class Place : MonoBehaviour {
public GameObject Block;
private GameObject instantiatedObj;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetMouseButton(0)){
Vector2 mousePos = camera.ScreenToWorldPoint(new Vector2(Input.mousePosition.x,Input.mousePosition.y));
instantiatedObj = (GameObject)Instantiate(Block, mousePos ,Quaternion.identity);
}
if(Input.GetMouseButton(1)){
//works only for last instantiated obj
Destroy(instantiatedObj);
}
}
}
The destroy function is working only for the last instantiated obj and I need it to work for all instantiated objects.Please help me!
it's going to be inefficient to store references to the objects, you should use a raycast from the mouse location into the scene to find the block, check out this question http://answers.unity3d.com/questions/141529/getting-gameobject-from-raycast-hit.html
Your answer
Follow this Question
Related Questions
2D C# destroy a GameObject on collision 2 Answers
Distribute terrain in zones 3 Answers
Create destroyed prefab 1 Answer
destroying gameobject from other script 1 Answer
Increase score upon an enemy's death 2 Answers