Search Unity

It Wont Let Me Add To This Value

Discussion in '2D' started by brobrotothegogo, Aug 17, 2019.

  1. brobrotothegogo

    brobrotothegogo

    Joined:
    Aug 17, 2019
    Posts:
    8
    when i was playing my game it should add score when i kill an enemy but its not letting me add it... Any Help?
     
  2. Green11001

    Green11001

    Joined:
    Apr 14, 2018
    Posts:
    397
    Do you have any code? Pictures? A more in depth description of the enemies/player/problem?
    In addition, have you tried logging the score and when the enemy dies?
     
  3. brobrotothegogo

    brobrotothegogo

    Joined:
    Aug 17, 2019
    Posts:
    8
    Here this is what im working with and i also figured out that my score gets deleted when i say destroy this.gameObject dont know how to fix that tho... after destroy i usely add the score += 50 but i didnt add that
     

    Attached Files:

  4. Green11001

    Green11001

    Joined:
    Apr 14, 2018
    Posts:
    397
    You might want to move your score to a gamemaster script. Essentially, how this works is that you have an object in the scene that stores all values you wont want to loose, and then you modify it when you need to. Its a lot more complicated than the other code you have put, but it should fix the problem.
    So to make this put your score variable (and any other variables that should be for the whole scene) into a different script. Make sure it is public. Then, create a gameobject in your scene called gamemaster. Make sure no other scripts will ever destroy this object as that will probably break things. Put the script in your gamemaster. Then, make a reference to this class in whatever script you may need score on (something like public gamemaster gm;), and get the score from there.
     
  5. MisterSkitz

    MisterSkitz

    Joined:
    Sep 2, 2015
    Posts:
    833
    Create a ScoreScript. Make your score variable a public static int score; declaration. You can then access this variable anywhere in any script ScoreScript.score += 50; (Assuming you wanted to add 50 points to score.)
     
  6. MisterSkitz

    MisterSkitz

    Joined:
    Sep 2, 2015
    Posts:
    833
    The reason I believe your points disappear when the object is destroyed is because the script is attached to that enemy. Therefore, it's destroying your score with the enemy.
    You could hide your enemy as an alternative:
    Code (CSharp):
    1. enemy.GetComponent<Renderer>().enabled = false;
    2. enemy.GetComponent<Collider2D>().enabled = false;
    Depending on your setup whether this is the best course of action or not though. Personally, I prefer to keep the score script separate from other scripts by use of static variables. You can either make it a static class and remove MonoBehavior or keep MonoBehavior and attach it to something like an empty game object or even the main camera. (Assuming you never disable your main camera. That would screw up the script as well)