Unity C#浮点值在“OnCollisionEnter2d”

时间:2017-03-27 09:05:26

标签: c# unity3d

首先看看我的代码

using UnityEngine;
using System.Collections;
public class Layer : MonoBehaviour {

    public float health=150f;
    void OnCollisionEnter2D(Collision2D beam){
        if (beam.gameObject.tag == "Box") {
            Destroy (gameObject);
        }

        Projectile enemyship = beam.gameObject.GetComponent<Projectile> ();   // Retrieving enemyship
        if (enemyship) {
            Destroy (gameObject);
            health = health - 100f; // its value is decreasing only once
            Debug.Log (health);
            if (health < 0f || health == 0f) {
                Destroy (enemyship.gameObject); // this line not executing
            }
        }
    }

}

在上面的代码中,健康值只减少一次,但OnCollisionEnter2D正常工作。这意味着在第一次碰撞时,健康值减少100f并且变为50f但是当它第二次碰撞时它的值仍然是50f。我一直在寻找3小时的解决方案。请帮帮我

我正在添加更多内容。当我按下太空时,我正在发射一个抛射物(激光)。所以当激光击中两次物体时应该被摧毁

1 个答案:

答案 0 :(得分:0)

好吧首先,你做错了就是你的碰撞逻辑毫无意义。你的碰撞物体是&#34;让我们说一个凡人物品&#34; ,无论什么时候它都必须&#34;死&#34; 健康状况低于或等于0,但每当它与标记为Box或类型为Projectile的组件发生碰撞时,您就会销毁它。
要解决此问题,请先根据这些条件降低运行状况,然后检查是否要销毁该对象。

示例代码:

public float health = 150f;

void OnCollisionEnter2D(Collision2D beam)
{
    float damage = 0f; // current damage...
    if (beam.gameObject.tag == "Box") 
    {
        // Destroy (gameObject); // do not destroy, just remove health
        damage = health; // reduce health to 0
    }
    else
    {
        Projectile enemyship = beam.gameObject.GetComponent<Projectile> ();   
        if (enemyship) 
        {
            // Destroy (gameObject); // again do not destroy.. just reduce health
            damage = 100f;
        }
    }

    health -= damage;
    Debug.Log (health); // print your health

    // check if dead
    if (health < 0f || health == 0f) {
        Destroy (gameObject); // this line not executing
    }
}