Chun Tao Lin
Chun Tao Lin

Reputation: 25

How to destroy a game object in Unity

I am having trouble trying to destroy my player. I have a script attached to my platforms, that if it collides with the player start a timer, and when the timer is done, destroy gameobject(which is the platform itself). I also want to have it so if the player happens to be on the platform by the time it runs out, the player also is destroyed. So I created a bool, but I am having trouble writing a destroy just player if bool is true.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DestroyAddPlatform : MonoBehaviour {

    //This will be used to set the seconds
    public float timeLeft = 3f;
    bool playerOn = false;
    private float PlayerGameObject;


    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }

    //How you declare a Coroutine Function.
    IEnumerator destroyer(){
        //wait for the timeLeft in seconds.
        yield return new WaitForSeconds (timeLeft);

        //Then destroy the object this script is attached to
        Destroy (gameObject);
    }

    //A timer that will start the coroutine
    void destroyTimer(){
        //coroutine calls the destroyer function, its a function that runs independently.
        StartCoroutine ("destroyer");

        //At this point tell it to add in a new platform. 
    }

    //This function will be in accordance to a collision.
    void OnCollisionEnter2D (Collision2D other){

        if (other.gameObject.CompareTag ("Player"))
            //If the object is the player, run
            destroyTimer ();//Start the destroy timer funciton.
    }   

}

Upvotes: 0

Views: 9608

Answers (2)

sight
sight

Reputation: 375

OnCollisionEnter with the player store the player's gameobject in a variable PlayerGameObject.

OnCollisionExit with player set the

PlayerGameObject = null;

Then check when the timer is done if

if(PlayerGameObject != null)
{
    Destroy(PlayerGameObject);
}

Upvotes: 1

Muhammad Faizan Khan
Muhammad Faizan Khan

Reputation: 10561

You can do it with destroy method. Simply make a script and attached to an object (who will never destroyed in game). Then assign your player object to that script and use the destroy method.

public  var Player : GameObject;
//call this method at desired event
    function DestroyPlayer(){
        Destroy(Player);
    }

Upvotes: 0

Related Questions