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;
}
}
}