My Score doesn't add up
Apparently, my score is not working as it should be, but it's not working for some reason. for example the score doesn't add up whenever I defeat an enemy, does anyone know how to fix this?
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Enemy : MonoBehaviour { public GameObject refToBase; public GameObject refToGameManager; public float moveSpeed; public string Enemystate; private Transform target; public Rigidbody2D RB; public BoxCollider2D BoxCollider2D; // Start is called before the first frame update void Start() { moveSpeed = 0.3f; target = GameObject.FindGameObjectWithTag("Threat").GetComponent(); RB = GetComponent(); BoxCollider2D = GetComponent(); }
// Update is called once per frame
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, target.position, moveSpeed * Time.deltaTime);
if (this.GetComponent<SpriteRenderer>().bounds.Intersects(refToBase.GetComponent<SpriteRenderer>().bounds))
{
refToBase.GetComponent<Base>().LifeNum -= 1;
}
}
public void OnTriggerEnter2D(Collider2D collision) {
if (collision.gameObject.GetComponent<Base>() != null)
{
Death();
refToBase.GetComponent<Base>().LifeNum -= 1;
}
if (collision.gameObject.tag == "Cannonball")
{
refToGameManager.GetComponent<GameManager>().ScoreCount += 10;
Debug.Log(collision.gameObject.tag == "Cannonball");
}
}
public void Death()
{
Destroy(this.gameObject);
}
}
public class GameManager : MonoBehaviour { public bool gameHasEnded = false; public string gameState = "Play"; public bool isplayable = true; public GameObject refToBase, refToPlayer, refToEnemy, refToEnemy2, refToCannon, refToCannonball; public TextMesh ScoreText; public int ScoreCount = 0; // Start is called before the first frame update void Start() { ScoreText.GetComponent(); refToCannon = GameObject.Find("Cannon"); }
// Update is called once per frame
void Update()
{
ScoreText.text = "Score: " + ScoreCount.ToString();
if (isplayable == true)
{
Time.timeScale = 1;
}
if (gameHasEnded == true)
{
gameState = "Stop";
refToPlayer.GetComponent<Player>().PlayerState = "Stop";
refToCannon.GetComponent<Cannon>().CannonState = "Stop";
refToCannon.GetComponent<Cannon>().isplayable = false;
isplayable = false;
Time.timeScale = 0;
if (Input.GetKey(KeyCode.R))
{
Restartgame();
}
}
}
void Restartgame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613043848im_/https://answers.unity.com/themes/thub/images/avi.jpg)