I am trying to destroy 2d object when clicked on it Heres my code if (Input.GetButton("Fire1")) Destroy(this.gameObject); But if i have 2 instance of object, both gets destroyed when i click on one object. How do i just destroy one object instance that i click
Ok and the other object is having that same script right? If yes that is the problem. You have to "catch" object you clicked on. Lets say, every time you click on object you have to check which one is clicked and then destroy that one. Try to add different "Tag" to each object, and then when you click on one check which "Tag" is it, and then destroy GameObject with that "Tag". Did you understand what i said?
No I have a 2d object called apple which has this script. I put this object on scene and then i duplicate it to make 2 apples But now when i click on one apple both apple gets delete. How to make only delete the apple i click on it
First: Code you showed remove from that script and put it in separate script and then that script attach for example, to Background game object. Tag of first apple should be "FirstApple" and Tag of the second one should be "SecondApple". Script on Background should have something like this Code (CSharp): void Update() { if (Input.GetMouseButtonDown(0)) { RaycastHit hitInfo = new RaycastHit(); bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo); if (hit) { if (hitInfo.transform.gameObject.tag == "FirstApple") { //FindGameObjectsWithTag FirstApple //destroy that object } else { //FindGameObjectsWithTag SecondApple //destroy that object } } } }
isnt there a better way to do this? If i wana have 30 apples does that mean i need to create 30 tags??
Yes, try without tags: Code (CSharp): void Update() { if (Input.GetMouseButtonDown(0)) { RaycastHit hitInfo = new RaycastHit(); bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo); if (hit) { Destroy(hitInfo.transform.gameObject); } } }
Hi! Create prefab of your apple, add two of them to the scene and after click use code Code (CSharp): function OnMouseEnter () { if (Input.GetKeyDown ("Mouse 0")) { Destroy (gameObject); } }` or Code (CSharp): function OnMouseDown () { Destroy(gameObject); } Add this script to your apple prefab.
OnMouseDown is only called on objects that contain a Collider http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html