- Home /
Non stopping point - counter
Hey, guys. I am trying to make a point counter for my game and the logic is every time a canvas is enabled add 1 point. But the problem is that with my script it doesnt stop unless the canvas goes off. How can I take this parameter?Here is the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class test : MonoBehaviour {
public Text scoreText;
public int point;
void Update () {
scoreText.text = point + " x3";
if (gameObject.activeSelf){
point++;
}
}
}
Answer by Vicarian · Sep 13, 2018 at 03:12 PM
A better way to do this would be to avoid using Update(). Instead, use the OnEnable callback:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class test : MonoBehaviour {
public Text scoreText;
public int point;
void OnEnable() {
scoreText.text = point + " x3";
if (gameObject.activeSelf) {
point++;
}
}
}
If you have many Canvas elements in your scene, you'll quickly murder your performance with all the Update calls. It also avoids managing the logic if a canvas has been "scored," if you can disable and re-enable the Canvas.
edit: above answer is probably ideal for OP's situation, leaving $$anonymous$$e for posterity.
Sure, you'd just keep track of whether that canvas should be scored or not.
private bool shouldScore = true;
void Update () {
// Check if we're active and we should allow this canvas
// to add a point
//
if (this.shouldScore && gameObject.activeSelf){
point++;
scoreText.text = point + " x3";
// This will prevent it from firing again, but you will need
// to modify this if you want this canvas to ever be scored again
//
shouldScore = false;
}
}