- Home /
Increasing an int everytime another int reaches an amount.
Hi, I'm new to Unity3d and I'm working on my first project to get to know the software and learn C#. I'm trying to make an upgrade system with points. I have a score variable (int) which is increased by 50 every time you kill an enemy and each time you have 1000 score I would like another variable (int uPoints) to be increased by 1.
The tricky part here is that when you die 3 times you are game over so score resets but i wan uPoints to keep it's value. Anyone can help me with this please? Here's my score script, it just need the uPoints line(s) of code:
using UnityEngine;
using System.Collections;
public class Score : MonoBehaviour {
public static int score = 0;
public static int uPoints = 0;
void OnTriggerEnter(Collider collider){
if(collider.gameObject.CompareTag ("Enemy")){
score += 50;
Destroy(this.gameObject);
}
}
}
Thanks!
Since those are static fields, they will keep whatever value you give them (until the game exits). You'd have to reset them to zero manually, whenever you want that to happen (for example, when the player dies X times, or possibly when changing levels or buying upgrades).
If you have code that kills the player, this reset logic probably goes in there.
Well, my score is being reset when the player is game over with the following script:
using UnityEngine;
using System.Collections;
public class gameOver : $$anonymous$$onoBehaviour {
public static bool isGameOver = false;
// Update is called once per frame
void Update () {
if (Lives.playerLives < 0) {
isGameOver = true;
Destroy(GameObject.FindWithTag("Enemy"));
Invoke("Reload", 3);
}
}
void OnGUI(){
if (isGameOver == true) {
GUI.Box (new Rect (Screen.width / 2 - 40, Screen.height / 2 - 10, 80, 20), "Game Over!");
}
}
void Reload(){
Lives.playerAlive = true;
Score.score = 0;
gameOver.isGameOver = false;
Lives.playerLives = 3;
enemySpawn.enemyNumber = 0;
Application.LoadLevel("Hud");
}
}
The only way I know of that would make uPoints be increased by one every 100 score is by doing
public int uPoints { get{ return score / 750; }}
but as soon as score would be reset, so would uPoints.
Answer by mattyman174 · Feb 21, 2014 at 02:35 AM
Use the Modulo Operator (%)
http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx
if((score % 100) == 0 && score != 0)
{
uPoints++;
}
Modulo gives the remainder after a division.
Will try! Seems perfect since it doesn't depend on the score var to have a value itself. Thanks a lot! Would rep you but I can't yet
Your answer
Follow this Question
Related Questions
How do i link a GUI text to a variable text which is a integer? 2 Answers
Multiply float by int? 2 Answers
Adding coin score to multiplied value 2 Answers
Check if a guiText = a number? 2 Answers
int +=1 won't exceed 1 2 Answers