【问题标题】:How to destroy a game object in Unity如何在 Unity 中销毁游戏对象
【发布时间】:2018-04-17 23:36:16
【问题描述】:

我在试图摧毁我的播放器时遇到了麻烦。我有一个附加到我的平台的脚本,如果它与玩家发生冲突,则启动一个计时器,当计时器完成时,销毁游戏对象(即平台本身)。我也想拥有它,所以如果玩家在它用完时恰好在平台上,那么玩家也会被摧毁。所以我创建了一个 bool,但如果 bool 为真,我将无法编写一个仅销毁的播放器。

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.
    }   

}

【问题讨论】:

  • 您可以添加您尝试过的代码吗?到这篇文章
  • 如果您不向我们提供具体问题以及导致该问题的代码,我们将无法帮助您。您还确定unityscript 标签是相关的吗?该语言正在逐步淘汰以支持 c#,如果您真的在使用它,我建议您切换,如果您已经在使用 c#,请删除标签:-)。
  • 我已经发布了我的代码并删除了 unityscript 标签

标签: unity3d


【解决方案1】:

OnCollisionEnter 与玩家一起将玩家的游戏对象存储在一个变量 PlayerGameObject 中。

OnCollisionExit 与玩家设置

PlayerGameObject = null;

如果是,则检查计时器何时完成

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

【讨论】:

    【解决方案2】:

    您可以使用destroy 方法来实现。只需制作一个脚本并附加到一个对象(在游戏中永远不会被摧毁)。然后将您的播放器对象分配给该脚本并使用 destroy 方法。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-06
      相关资源
      最近更新 更多