Hello,
am trying to implement a simple score counter event. Have a space shooter game and everytime a spawned enemy is killed (one bullet = ine kill) I would like to increment the score. But for some reason th score in the game is not changing/working. Maybe someone could help me with this issue?
In the game I am spawning the enemies (from prefabs) in front of some distance of the player.
GameController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameController : MonoBehaviour
{
public Player3DScript player;
public GameObject enemyPrefab;
//score
int score = 0;
public Text scoreText;
void Update()
{
if (player != null)
{
enemySpawnTimer -= Time.deltaTime;
if (enemySpawnTimer <= 0)
{
enemySpawnTimer = enemySpawnInterval;
GameObject enemyInstance = Instantiate(enemyPrefab);
enemyInstance.transform.SetParent(transform);
enemyInstance.transform.position = new Vector3(
Random.Range(spawnLevelLimitLeft, spawnLevelLimitRight),
-2.5f,
player.transform.position.z + enemySpawnDistance
);
enemyInstance.GetComponent<Enemy>().OnKill += OnEnemyKilled;
Debug.Log("Am in UPDATE Game Controller OnEnemyKilled()");
}
foreach (Enemy enemy in GetComponentsInChildren<Enemy>())
{
if (player.transform.position.z >= enemy.transform.position.z + 10f)
Destroy(enemy.gameObject);
}
}
}
void OnEnemyKilled()
{
score += 1;
scoreText.text = "Score: " + score;
Debug.Log("Am in Game Controller OnEnemyKilled() ");
}
}
Enemy.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour {
public delegate void KilledHandler();
public event KilledHandler OnKill;
void OnTriggerEnter2D(Collider2D otherCollider)
{
if (otherCollider.tag == "PlayerBullet" || otherCollider.tag == "Player")
{
Destroy(gameObject);
Destroy(otherCollider.gameObject);
if (OnKill != null)
{
Debug.Log(Am in -> onKill()");
OnKill();
}
}
}
}
The text field is a simple Text object in canvas.
When I start the game I only see the Debug.Log under:
Debug.Log(“Am in UPDATE Game Controller OnEnemyKilled()”);
Also when I kill an enemy, nothing changes. No other Debug.Log uppears.
Any help is really welcome :).