【问题标题】:OnTriggerEnter2D is being called multiple timesOnTriggerEnter2D 被多次调用
【发布时间】:2015-12-14 06:06:43
【问题描述】:

我是 Unity 的新手,如果这是一个基本问题,请提前抱歉,我附加了一个变量,每次触发 OnTriggerEnter2D 时该变量应加 1。然而,它不是加 1,而是不断地加。请告诉我我做错了什么?

这就是我所说的

public class MonsterTarget : MonoBehaviour {
 public Resetter Resetting;
 public ScoreCount ScoreHit;
 public float targetHit = 0;


 // Use this for initialization
 void Start () {

 }

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

 }

 public void OnTriggerEnter2D(Collider2D col)
 {
     targetHit ++;
     Resetting.Reset();

 }

}

这就是它要去的地方

public MonsterTarget monTarget;

 public Text scoreText;
 public Text highScoreText;

 public float scoreCount;
 public float highScoreCount;

 public bool scoreIncreasing;

 // Use this for initialization
 void Start () {
     if(PlayerPrefs.HasKey("HighScore"))
         {
         highScoreCount = PlayerPrefs.GetFloat("HighScore");
     }
 }

 // Update is called once per frame
 void Update () {
     if (scoreIncreasing)
     {
         scoreCount += monTarget.targetHit;//RIGH HERE IS WHERE IM CALLING IT
     }

     if (scoreCount > highScoreCount)
     {
         highScoreCount = scoreCount;
         PlayerPrefs.SetFloat("HighScore", highScoreCount);
     }

     scoreText.text = "Score: " + Mathf.Round(scoreCount);
     highScoreText.text = "High Score: " + Mathf.Round(highScoreCount);

 }

}

【问题讨论】:

    标签: unity3d triggers 2d


    【解决方案1】:

    “脚本系统可以检测碰撞发生的时间并使用 OnCollisionEnter 函数启动动作。但是,您也可以使用物理引擎简单地检测一个碰撞器何时进入另一个碰撞器的空间而不产生碰撞。一个碰撞器配置为触发器(使用 Is Trigger 属性)不表现为实体对象,只会让其他碰撞器通过。当碰撞器进入其空间时,触发器将调用触发器对象脚本上的 OnTriggerEnter 函数。"

    来自http://docs.unity3d.com/Manual/CollidersOverview.html

    我认为可能是,因为你的对象在触发空间内,所以它一直被调用。

    当碰撞体进入其空间时,触发器将在触发器对象的脚本上调用 OnTriggerEnter 函数。

    这可能意味着targetHit ++; 在您的对象通过其他对象的碰撞空间时不断被调用。

    我建议尝试OnCollisionEnter2D(),因为这样你的对象会发生碰撞但不会相互穿过。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-08
      • 2010-10-24
      • 2011-10-18
      相关资源
      最近更新 更多