Hello, I was trying for a few hours to get my instantiated hat to be destroyed, I have tried many methods. For example:
function Hair(){
Hair1 = GameObject.FindGameObjectsWithTag("Hair1");
Destroy(Hair1);
}
Doesn’t work, along with all of the other fail attempts. So I was wondering if anyone here knew what I could try. I can give you part of the code in which you need, and that may help. Thanks in advance if anyone can help! 
var HairNumber : int = 0;
var HairArray : Transform[];
var HairBone : Transform;
function Update(){
if(HairNumber < 0){
HairNumber = 1;
}
if(HairNumber > 1){
HairNumber = 0;
}
}
function OnGUI(){
if(GUI.Button(Rect(10,460,100,100),"Hair")){
Hair();
}
}
function Hair(){
HairNumber +=1;
if(HairNumber == 1){
Instantiate(HairArray[0], HairBone.position, HairBone.rotation);
}
if(HairNumber == 2){
Instantiate(HairArray[1], HairBone.position, HairBone.rotation);
}
}
2 Answers
2
Using Destroy with Hair1 = GameObject.FindGameObjectsWithTag("Hair1"); can’t work because FindGameObjectsWithTag returns an array. So you need to loop through the array and destroy each object in it. By the way, following the Unity convention of always using lowercase for variables and uppercase for methods and classes will make your code easier to understand.
I hate it when I can’t destroy my instantiated hat, it’s always so easy to burn the base ball caps and my bowler has proved susceptible to concussion grenades.
If you instantiated it then its name with be “Hair1(Clone)” - the best option would be to attach a script to the hair that acts as a singleton - then it will be easy to find (and you could make it so that other things that were instantiated with the same script destroyed the previous one too).
#PartFinder.js
import System.Collections.Generic;
var partName : String;
var thereCanBeOnlyOne = true;
static var parts = new Dictionary.<String, GameObject>();
function Awake()
{
if(thereCanBeOnlyOne && parts.ContainsKey(partName))
Destroy(parts[partName]);
parts[partName] = gameObject;
}
static function FindPart(name : String) : GameObject
{
return parts.ContainsKey(name) ? parts[name] : null;
}
Then either set thereCanBeOnlyOne true in the inspector or find your objects fast (much faster than FindGameObject) using:
PartFinder.FindPart("hat");
Good point - I should read the damn question properly (that comes of being up to late).
– whydoidoit