- Home /
OnTriggerEnter2D is being called multiple times....
I'm new to Unity so sorry in advance if this is a basic question, I attached a variable that should add by 1 every time OnTriggerEnter2D is triggered. It however is not adding by 1 but adding constantly. Can please tell me what I'm doing wrong?
Here is where I'm calling it
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();
}
}
and this is where its going
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);
}
}
You could probably work this out just by adding some logging so you can see when the targetHit and scoreCount variables are changing, and to what.
It looks to me like targetHit is probably incrementing as you want it to, but you are adding it to the score on every frame (assu$$anonymous$$g that scoreIncreasing is true). It seems unlikely that that's what you want to do. Just changing line 23 to an =
ins$$anonymous$$d of a +=
might fix it.
Your answer
Follow this Question
Related Questions
Child Trigger event on parent Script 1 Answer
OnTriggerEnter2D Not Working 1 Answer
OnTriggerEnter2D is not being called 1 Answer
score display not showing 1 Answer