- Home /
Destroy only selected object
My script selects an object with a certain tag but when destroying the object it destroys other objects with the same tag that have not been selected. How could I change this so that it only destroys the object that has been selected? Hope this makes sense.
var selected = false;
var deleteSound : AudioClip;
function Update (){
if(Input.GetMouseButtonDown(0)){
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, hit, 10.0)){
if(hit.collider.tag == "placedObject"){
selected = true;
Wait(hit.collider.renderer);
}
}
}
if(Input.GetKeyDown(KeyCode.C) && selected == true){
var placedObject = GameObject.FindWithTag("placedObject");
Destroy(placedObject);
audio.PlayOneShot(deleteSound);
selected = false;
}
}
function Wait(rend : Renderer){
var originalColor = rend.material.color;
rend.material.color = Color.yellow;
yield WaitForSeconds(2);
rend.material.color = originalColor;
selected = false;
}
if(hit.collider.tag == "placedObject")
{
placedObject = hit.gameObject;
selected = true;
Wait(hit.collider.renderer);
}
Answer by Kiwasi · Jul 07, 2014 at 11:27 PM
FindWithTag (line 23) will return one GameObject with the tag. Hence you will be destroying one random object every time you push C.
You would be better off caching the result of your raycast, like so. Please forgive any typos, JavaScript is not my language of choice:
// On line 3
var SelectedGameObject : GameObject;
// On line 13
SelcetedGameObject = hit.collider.gameObject;
// Replace lines 23 and 24 with
Destroy (SelectedGameObject);
Good luck. Let me know if you have any further problems
Your answer
Follow this Question
Related Questions
Destroy all objects with tag "enemy"? 2 Answers
help with game error 0 Answers
changing objects color through a raycast? 1 Answer
Deselect a selected object? 2 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers