Hi,
I have the following code that spawns an object at a location when a trigger is entered. I also want to destroy the object when the trigger is left. At the moment the code doesnt work because the prefab is an FBX and gets called FBX(clone) when instantiated in the scene. How would I destroy the object? I’m thinking make the object children of the original trigger when instantiated but I’m not sure how.
Any ideas?
Thanks
var prefab : GameObject;
function OnTriggerEnter(myEnter:Collider){
if (myEnter.gameObject.name == "MainCam"){
var spawn : GameObject = Instantiate(prefab, transform.position, transform.rotation);
Debug.Log("triggered");
}
}
function OnTriggerExit(myExit:Collider){
if (myExit.gameObject.name == "MainCam"){
Destroy(prefab);
Debug.Log("untriggered");
}
}
You have it all setup to work, just destroy the gameObject “spawn” instead of “prefab”.
var prefab : GameObject;
function OnTriggerEnter(myEnter:Collider){
if (myEnter.gameObject.name == "MainCam"){
var spawn : GameObject = Instantiate(prefab, transform.position, transform.rotation);
Debug.Log("triggered");
}
}
function OnTriggerExit(myExit:Collider){
if (myExit.gameObject.name == "MainCam"){
Destroy(spawn);
Debug.Log("untriggered");
}
}
if you wanted to make a child gameObject and have the prefab instantiate at it you can rewrite the code like this.
var prefab : GameObject;
var targetSpawn : GameObject; //This is where the child game object should be placed
function OnTriggerEnter(myEnter:Collider){
if (myEnter.gameObject.name == "MainCam"){
var spawn : GameObject = Instantiate(prefab, targetSpawn.transform.position, targetSpawn.transform.rotation);
Debug.Log("triggered");
}
}
function OnTriggerExit(myExit:Collider){
if (myExit.gameObject.name == "MainCam"){
Destroy(spawn);
Debug.Log("untriggered");
}
}
The above code should work. I did not test it…
also I don’t recommend using prefab as a variable, I suggest you call it something else more to suit what it is, such as bullet, projectile or enemy if it is an enemy…
Thanks,
I think I will change the name of the variable.
If i change the code to
Destroy (spawn);
(which I assume would be the easier option), it says unknown identifier ‘spawn’. Is this because the variable ‘spawn’ was declared inside another set of squiggly brackets? How would I work around this?
Also I tried the (targetSpawn.transform.position) approach and it didn’t put the instantiated object into the heirarchy of the targetSpawn. 
Cheers
Sorted it.
i was missing the var spawn outside the function bit.
var buildings : GameObject;
private var spawn : GameObject;
function OnTriggerEnter(myEnter:Collider){
if (myEnter.gameObject.name == "MainCam"){
spawn = Instantiate(buildings, transform.position, transform.rotation);
Debug.Log("triggered");
}
}
function OnTriggerExit(myExit:Collider){
if (myExit.gameObject.name == "MainCam"){
Destroy (spawn);
Debug.Log("untriggered");
}
}
Thanks