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.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Issues with creating score count

Discussion in 'Scripting' started by unity_TMJLD3-jMWzVyA, Apr 12, 2020.

  1. unity_TMJLD3-jMWzVyA

    unity_TMJLD3-jMWzVyA

    Joined:
    Jan 14, 2020
    Posts:
    4
    void Update()
    {
    if(invulPeriod>0)
    {
    invulPeriod-=Time.deltaTime;
    if(invulPeriod<=0)
    {
    gameObject.layer=correctLayer;
    if (spriteRenderer!=null)
    {
    spriteRenderer.enabled=true;
    }
    }
    else
    {
    if(spriteRenderer!=null)
    {
    spriteRenderer.enabled=!spriteRenderer.enabled;
    }
    }
    }

    if(health<=0)
    {
    Die();
    }
    }
    private void Die()
    {
    if(gameObject.layer==9)
    {
    Debug.Log("Killed enemy");
    killCount++; //this part doesnt work
    Debug.Log(killCount);
    }
    Destroy(gameObject);
    }

    private void OnBecameInvisible()
    {
    if(health<=0)
    {
    Destroy(gameObject);
    }
    }

    void OnGUI()
    {
    GUI.Label(new Rect(100,100,100,50),"Score: "+killCount);
    }
    }
    I am trying to make a score count for my game. However, the kill count does not increment, it stays at one.
    Layer 9 is the enemy layer. "Killed enemy" is outputted to the log every time one dies. Also, the GUI label stays at 0 for some reason. Any suggestions? Sorry if this is basic, I'm new to unity/c#.
     
    providejahwill likes this.
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    Where is the variable "killCount" defined? To me it appears like this script is a script that is attached to every "enemy" GameObject in the scene. Is that correct? If so there's a few problems:
    • You have an independent "killCount" variable for each enemy object, rather than a single global counter. Therefore killCount will never go above 0 or 1 because you are destroying the enemy object when it dies, and each enemy only keeps track of its own death, not the deaths of the other enemies.
    • Your OnGUI code will draw a GUI Label on the same spot of the screen, for every enemy in the scene. All of these labels will cover each other on the screen.
    Try creating something like a "ScoreBoard" object, of which you only have one in the scene, and use that as a central place to count enemy deaths (and any other "score" you want to keep track of).
     
    Last edited: Apr 12, 2020
  3. unity_TMJLD3-jMWzVyA

    unity_TMJLD3-jMWzVyA

    Joined:
    Jan 14, 2020
    Posts:
    4
    Thanks a lot that was a good tip! I ended up using this video to get it working.
     
    providejahwill likes this.