My script lets me take over another object(possessable) by destroying the first person prefab (spirit) and switching the new object’s controls on. I can “unpossess” an object by instantiating a prefab of the spirit and disabling the possessed object. This is repeatable.
BUT, after the first time the “spirit” is destroyed, and I possess then possess and unpossess the object again, there are clones of the “spirit” running around. Despite being tagged as spirit, they will not be destroyed.
How can I destroy the prefab clones? (preferably by still using the tag “spirit”).
This code is attached to the possessable objects:
//FOR IT TO WORK:
//Possessable item has this script
//Possessable item has a trigger
//Spirit Gameobject is tagged as "Spirit" (as well as children?)
//Disable Camera and FPSInput Controller script
private var insideSpiritTrigger: boolean = true;
var spiritPrefab : GameObject;
var PossessableCamera : GameObject;
var PossessableInput : FPSInputController;
insideSpiritTrigger = false;
//Define the Spirit
var Spirit : GameObject[];
var SpiritPrefab : GameObject[];
SpiritPrefab = GameObject.FindGameObjectsWithTag("Spirit");
Spirit = GameObject.FindGameObjectsWithTag("Spirit");
private var spirit : GameObject;
function Start(){
spirit = GameObject.Find("Spirit");
}
//If in trigger, then "insideSpiritTrigger" is true
function OnTriggerEnter (spirit : Collider){
if(spirit.tag=="Spirit")
insideSpiritTrigger = true;
}
function OnTriggerExit (spirit : Collider){
if(spirit.tag=="Spirit")
insideSpiritTrigger = false;
}
function Update() {
//when trigger is true and E is pressed, destroy spirit
if ( (insideSpiritTrigger == true) && (Input.GetKeyDown(KeyCode.E)) ) {
//destroy spirit
for (var spirit in Spirit){
Destroy(spirit);
}
//activate possessable
PossessableInput.enabled = true;
PossessableCamera.active = true;
}
//if possessed
if ( (PossessableInput.enabled == true) && (Input.GetKeyDown(KeyCode.Q)) ) {
//deactivate possessable
PossessableInput.enabled = false;
PossessableCamera.active = false;
//bring back Spirit
var createSpirit : GameObject = Instantiate(spiritPrefab, transform.position + Vector3(0,5,-3), transform.rotation);
}
}