Hi,
I don’t know what I’m doing wrong - possibly a lot - but I’m trying to write a simple score system for the little game I’m doing in the online course ‘Create with Code’. For that I’m actually using the system presented there in the chapter 5 (Lesson 5.2 - Keeping Score - Unity Learn), but as my game is a bit different - a very simple sidescroller - I tried to implement these things into my system but something is wrong. First, I do not get the score to update and second, I just broke the game. I wrote and rewrote it last night for hours and hours and I know it’s messy, but I can’t find a way out. Help would really be appreciated.
P.
using TMPro;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public TextMeshProUGUI gameOverText;
public float verticalInput;
public float speed = 10.0f;
public ParticleSystem EnergyExplosion;
public ParticleSystem DustExplosion;
public bool gameOver = false;
private AudioSource playerAudio;
public AudioClip moneySound;
public AudioClip explodeSound;
public ParticleSystem explosionParticle;
private SpawnManager SpawnManager;
public int pointValue;
void Start()
{
SpawnManager = GameObject.Find("SpawnManager").GetComponent<SpawnManager>();
playerAudio = GetComponent<AudioSource>();
}
void Update()
{
verticalInput = Input.GetAxis("Vertical");
transform.Translate(Vector3.up * verticalInput * Time.deltaTime * speed);
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.layer == 9)
{
playerAudio.PlayOneShot(explodeSound, 1.0f);
gameOver = true;
Destroy(gameObject);
Instantiate(explosionParticle, transform.position, explosionParticle.transform.rotation);
gameOverText.gameObject.SetActive(true);
}
else if (other.gameObject.layer == 8)
{
EnergyExplosion.Play();
playerAudio.PlayOneShot(moneySound, 1.0f);
Destroy(other.gameObject);
SpawnManager.UpdateScore(pointValue);
}
}
}
===================================================
using UnityEngine;
using TMPro;
public class SpawnManager : MonoBehaviour
{
public TextMeshProUGUI scoreText;
private int score;
public GameObject[] enemyPrefabs;
private float spawnRangeY = 10;
private float spawnPosZ = -5;
private float startDelay = 1;
private float spawnInterval = 0.5f;
private PlayerController PlayerController;
void Start()
{
InvokeRepeating("SpawnRandomEnemy", startDelay, spawnInterval);
PlayerController = GameObject.Find("Player").GetComponent<PlayerController>();
score = 0;
UpdateScore(0);
}
void SpawnRandomEnemy()
{
int enemyIndex = Random.Range(0, enemyPrefabs.Length);
Vector3 spawnPos = new Vector3(-8, Random.Range(-spawnRangeY, spawnRangeY), spawnPosZ);
if (PlayerController.gameOver == false)
{
Instantiate(enemyPrefabs[enemyIndex], spawnPos, enemyPrefabs[enemyIndex].transform.rotation);
}
}
public void UpdaScore (int scoreToAdd)
{
score += scoreToAdd;
scoreText.text = "Score: " + score;
}
}