Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Problem with enemies killed counter to Debug.log

Discussion in 'Scripting' started by Pellisqq, Aug 6, 2022 at 5:31 PM.

  1. Pellisqq

    Pellisqq

    Joined:
    Thursday
    Posts:
    2
    Heya!

    Im new to C# scripting and working on first project with Unity & C#. I'm trying to do a counter that adds +1 every time a bullet destroys an enemy. At the moment I can Debug.Log one enemy killed, but it doesn't add up after I kill second enemy. Any ideas how to get this fixed?


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class EnemyBeha : MonoBehaviour
    6. {
    7.     GameManager _gameManager;
    8.     [SerializeField] GameObject _player;
    9.  
    10.     float _enemyHealth = 100f;
    11.     float _enemyMoveSpeed = 2f;
    12.     Quaternion _targetRotation;
    13.     bool _disableEnemy = false;
    14.     Vector2  _moveDirection;
    15.     public float _enemiesKilled;
    16.  
    17.    
    18.  
    19.     // Start is called before the first frame update
    20.     void Start()
    21.     {
    22.         _gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
    23.         _player = GameObject.FindGameObjectWithTag("Player");
    24.        
    25.     }
    26.  
    27.     // Update is called once per frame
    28.     void Update()
    29.     {
    30.         if(!_gameManager._gameOver && !_disableEnemy)
    31.         {
    32.             MoveEnemy();
    33.             RotateEnemy();
    34.         }
    35.     }
    36.  
    37.     void MoveEnemy()
    38.     {
    39.         transform.position = Vector2.MoveTowards(transform.position, _player.transform.position, _enemyMoveSpeed * Time.deltaTime);
    40.     }
    41.  
    42.      void RotateEnemy()
    43.     {
    44.        _moveDirection = _player.transform.position - transform.position;
    45.        _moveDirection.Normalize();
    46.  
    47.        _targetRotation = Quaternion.LookRotation(Vector3.forward, _moveDirection);
    48.  
    49.        if(transform.rotation != _targetRotation)
    50.        {
    51.             transform.rotation = Quaternion.RotateTowards(transform.rotation, _targetRotation, 333 * Time.deltaTime);
    52.        }
    53.     }
    54.  
    55.     void OnCollisionEnter2D(Collision2D collision)      //Enemy object collision check
    56.     {
    57.         if (collision.gameObject.tag == "Bullet")       // With Bullet
    58.         {
    59.             StartCoroutine(Damaged());                
    60.             _enemyHealth -= 40f;                        // If bullet hits, enemyhealth -40 (total 100 at start)
    61.                
    62.             if (_enemyHealth <= 0f)                     // If health goes below 0
    63.             {
    64.               _enemiesKilled ++;                        // add +1 to _enemiesKilled
    65.               Destroy(gameObject);                      // destroy the Enemy
    66.               Debug.Log(_enemiesKilled);                // debug for testing
    67.             }
    68.  
    69.             Destroy(collision.gameObject);
    70.  
    71.      
    72.  
    73.         }
    74.         else if (collision.gameObject.tag == "Player")
    75.         {
    76.             _gameManager._gameOver = true;
    77.             collision.gameObject.SetActive(false);
    78.         }
    79.     }
    80.  
    81.     IEnumerator Damaged()
    82.  
    83.     {
    84.         _disableEnemy = true;
    85.         yield return new WaitForSeconds(0.5f);
    86.         _disableEnemy = false;
    87.  
    88.     }
    89. }
    90.  
     
  2. DragonCoder

    DragonCoder

    Joined:
    Jul 3, 2015
    Posts:
    578
    The problem is that a different instance of EnemyBeha exists for every enemy and your counter variable is a "member" variable. It's tied to the instance.

    Quick and dirty solution:
    Make the variable static. Then it is a class variable. However make sure to have it set to zero somewhere at game or scene start (in a global controller, not in the start of the EnemyBeha) because static variable retain their value throughout the whole game session (not editor session).

    Better variant:
    Use some manager object which is unique and which you access via "Singleton Pattern".
     
    Pellisqq likes this.
  3. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,111
    There's also a variant where you use ScriptableObjects, which in my opinion would be pretty nice for this situation.
     
    Pellisqq likes this.
  4. DragonCoder

    DragonCoder

    Joined:
    Jul 3, 2015
    Posts:
    578
    Hmm, that requires to assign the SOs to a serialized variable on the EnemyBeha.
    Personally I rather use SOs when requiring data that is not completely generated at playtime (like this debug variable is).
     
    Pellisqq likes this.
  5. Pellisqq

    Pellisqq

    Joined:
    Thursday
    Posts:
    2
    Oh yeah I see. Did not understand why did the counter reset. But ur message clarified me that. So when the script destroys the object it also destroyes the counter since its attached to the object.

    Thank for helping Newbie!
     
    mopthrow likes this.
unityunity