- Home /
Can't increase my score after OnTriggerEnter occurs.
I am trying to implement a score system and I have my score increasing by distance of 1 every 1 unit traveled, works no problem. Now I have a coin object for the player to collect, which I want to add 10 points to the current score accumulated. I've spent longer than I'd liked to admit on this simple problem. I'm newer to code and unity. Below is my two scripts for the ScoreManager and Coin object.
public class ScoreManager : MonoBehaviour
{
public Transform player;
public Text scoreText;
public int score = 0;
private int distanceScore = 0;
// Distance variables
Vector3 previousPosition;
float calculatedDistance;
// Start is called before the first frame update
void Awake()
{
previousPosition = player.position;
}
// Update is called once per frame
void Update()
{
calculatedDistance += (player.position - previousPosition).magnitude;
previousPosition = player.position;
distanceScore = Mathf.RoundToInt(calculatedDistance);
score = distanceScore;
scoreText.text = "Score: " + score;
}
}
public class Coin : MonoBehaviour
{
private int coinScore = 10;
public ScoreManager sm;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Rotate(90 * Time.deltaTime, 0, 0);
}
private void OnTriggerEnter(Collider other)
{
if (other.name == "Car")
{
Destroy(gameObject); // Destroy coin
sm.score = +coinScore;
}
}
}
Answer by unity_ek98vnTRplGj8Q · Jul 21, 2020 at 07:33 PM
This is because you are overwriting your score value every update, so even if you add some value based on picking up a coin it will be overwritten by the distance score only on the next frame. Try something like this instead ->
calculatedDistance += (player.position - previousPosition).magnitude;
previousPosition = player.position;
distanceScore = Mathf.RoundToInt (calculatedDistance);
score += distanceScore;
calculatedDistance -= distanceScore;
Now instead of overwriting the score value with the distance every frame, you are just adding to it. Then you just need to subtract from your distance every time you increase the score.
Thank you very much and thanks for the explanation as well!