- Home /
How to increase score by one per second when you are holding an object
Hello. I'm working on a game in which there are 2 ways of scoring. 1- 1point/sec while holding a ball. 2- 5 points if you drop the ball in a basket. I have multiple questions in this but I'd like to focus on the 1pt/sec part for now.
Here's my code (sorry it's pretty sloppy, I'm kind of new):
public int score;
private bool hasBall;
private float startTime;
void Start()
{
score = 0;
hasBall = false;
startTime = Time.time;
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "ball")
{
//Destroy(other.gameObject);
other.gameObject.transform.parent = gameObject.transform;
hasBall = true;
}
else
hasBall = false;
}
void Update()
{
if (Input.GetKeyDown("space"))
print("throwBall");
if(hasBall)
score = (int)(Time.time - startTime);
Debug.Log("Score: " + score);
}
This works for giving me 1 point per second, but it doesn't recognize when I pick it up as the start time. My debug log often will say I have "Score: 5" the first second I pick it up.
Answer by Maui-M · Feb 17, 2014 at 06:12 PM
Delta time will give you the time passed since the previous frame/update. Use that to get how long the ball has been held. Whenever its been held for over a second add that to the score and subtract it from your time counter.
public int score;
private bool hasBall;
private float heldTime = 0.0f;
void Start()
{
score = 0;
hasBall = false;
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "ball")
{
//Destroy(other.gameObject);
other.gameObject.transform.parent = gameObject.transform;
hasBall = true;
}
else
hasBall = false;
}
void Update()
{
if (Input.GetKeyDown("space")){
print("throwBall");
heldTime = 0.0f;
}
if(hasBall){
heldTime += Time.deltaTime;
if(heldTime >= 1){
score += (int)heldTime;
heldTime -= (int)heldTime;
}
}
Debug.Log("Score: " + score);
}
Thank you so much for the quick reply! It works great! Wish I could upvote it but I don't have 15 rep yet =/ just started on this. Wish I could link this to my Stack Overflow account so I could.
@Rs31412 ,below the thumbs up/down icons, do you see another option to 'select this as answer'?
just found it! Thanks! Need to get used to this site! Thanks!
Answer by CagatayAkyazi · Jan 26, 2019 at 12:55 AM
THANX a lot five years after but:))) it helped me a lot... thnx again
Your answer
Follow this Question
Related Questions
Scoring System 3 Answers
I want my score to reset back to 0 but keep my highscore saved 3 Answers
Scoring help ! 1 Answer
Associate time and distance for a score system 3 Answers
How to save score for survival time? 1 Answer