Only allowing one instance of prefab created by button press & destroying prefab on collision?

Using Javascript. I’ve got a prefab that spawns at the players location when they press Tab. I only want one to be allowed in the scene at a time and when the player enters its collider that is a trigger, the prefab instance should be destroyed.

I can barely do any coding so for the life of me I cannot figure this out. The problems I’m having are 1) how to keep more than 1 prefab instance from spawning every time I press Tab, and 2) delaying the trigger detection so that the prefab instance does not destroy as soon as it spawns (because the instance spawns on the player so the player is immediately in the trigger).

 //This code is attached to the first person controller.
var playerBody : GameObject;
var playerBodySpawn : Transform;
public var PmodeActive : boolean = false;
function Start () {
}
function Update () {
if (PmodeActive == false && Input.GetButtonDown("PMode")) {
     Instantiate(playerBody, playerBodySpawn.position, playerBodySpawn.rotation);
     PmodeActive = true;
     }
else if (PmodeActive == true && Input.GetButtonDown("PMode")) {
     PmodeActive = false;
}
}
 //This code is attached to the prefab.
var bodyCount : int;
function Start () {
bodyCount = 1;
}
function OnTriggerEnter() {
     Destroy(gameObject);
     bodyCount = 0;
     PmodeActive = false;
}

This is all I have figured out so far.

Why are you using Javascript then, it’s one form of self-torture :smile:

if (Input.GetButtonDown("PMode")) {
  PmodeActive = !PmodeActive;
  if (PmodeActive && SomePrefabScript.bodyCount == 0) {
    Instantiate(playerBody, playerBodySpawn.position, playerBodySpawn.rotation);
  }
}

I don’t know Javascript that well, if bodyCount is not public static variable already, find a way to declare it so.

As for the other problem, you could manage some collision layers from Physics settings, and set the prefab not collide with player at all. Otherwise you can make a timer variable that counts from say 1 second down to 0. In Update() you can reduce the timer by Time.deltaTime.

Check out the singleton pattern.

And C#. If you know nothing, you might as well start off learning properly.