Search Unity

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

Discussion in 'Scripting' started by redgroupclan, May 31, 2016.

  1. redgroupclan

    redgroupclan

    Joined:
    Mar 22, 2016
    Posts:
    9
    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).

    Code (JavaScript):
    1.  //This code is attached to the first person controller.
    2. var playerBody : GameObject;
    3. var playerBodySpawn : Transform;
    4. public var PmodeActive : boolean = false;
    5. function Start () {
    6. }
    7. function Update () {
    8. if (PmodeActive == false && Input.GetButtonDown("PMode")) {
    9.      Instantiate(playerBody, playerBodySpawn.position, playerBodySpawn.rotation);
    10.      PmodeActive = true;
    11.      }
    12. else if (PmodeActive == true && Input.GetButtonDown("PMode")) {
    13.      PmodeActive = false;
    14. }
    15. }
    Code (JavaScript):
    1.  //This code is attached to the prefab.
    2. var bodyCount : int;
    3. function Start () {
    4. bodyCount = 1;
    5. }
    6. function OnTriggerEnter() {
    7.      Destroy(gameObject);
    8.      bodyCount = 0;
    9.      PmodeActive = false;
    10. }
    This is all I have figured out so far.
     
  2. Zaflis

    Zaflis

    Joined:
    May 26, 2014
    Posts:
    438
    Why are you using Javascript then, it's one form of self-torture :D

    Code (JavaScript):
    1. if (Input.GetButtonDown("PMode")) {
    2.   PmodeActive = !PmodeActive;
    3.   if (PmodeActive && SomePrefabScript.bodyCount == 0) {
    4.     Instantiate(playerBody, playerBodySpawn.position, playerBodySpawn.rotation);
    5.   }
    6. }
    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.
     
  3. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Check out the singleton pattern.

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