• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by zenislev · Dec 02, 2009 at 07:40 PM ·

How to increase score incrementally over time?

So, I have a system whereby NPCs will chase a player character. My goal is to setup scoring so that, while they are chasing, a score value will increase by 100 every 5 seconds, per NPC.

I've tried this code for scoring, attached to the NPCs and only called when they are in chase mode:

function Score(){

 if( !ProtectMode.protectMode ){
     return;
 }

 else if( ProtectMode.protectMode ){
     ProtectMode.scoreProtect += ProtectMode.scoreIncreaseRate * Time.deltaTime;
 }

}

...which references variables in the following script (ProtectMode.js), attached to a GUIText component of an empty GameObject for output:

@script RequireComponent(GUIText)

static var protectMode : boolean = true;

static var scoreProtect : float = 0; static var scoreIncreaseRate : float = 500;

function Update () { guiText.text = "PROTECT:" + parseInt(scoreProtect); }

The GUIText works fine, and the score increases when NPCs are chasing, but I expected this to add just 1 to the score every 5 seconds (because scoreIncreaseRate = 500). Instead, it looks like the score is increasing by at least 1 every frame. What's gone wrong?


EDIT: Sorry this isn't in a comment; I wanted to format this code.

This is what I came out with after trying while loop:

function Score(){

 if( !ProtectMode.protectMode ){
     return;
 }

 else if (ProtectMode.protectMode){

     while(true){

     ProtectMode.scoreProtect += scoreAmount;
     yield WaitForSeconds (5.0);

     }
 }

}

The score still increases every frame, instead of as it should. Is this maybe because I'm calling Score() from within Update(), or because I've written it horribly?

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image duck ♦♦ · Dec 03, 2009 at 10:14 AM 0
Share

"Is this maybe because I'm calling Score() from within Update(), or because I've written it horribly?" .... errr, a bit of both :-)

Please see my new answer below, for an explanation about how to do this with a coroutine!

3 Replies

· Add your reply
  • Sort: 
avatar image
3
Best Answer

Answer by duck · Dec 02, 2009 at 07:49 PM

If you want the score to increase in discrete steps of a fixed amount, each 5 seconds, you could implement something like this:

// put these with your var declarations private var nextScoreTime : float; private var scorePeriod = 5; private var scoreAmount = 1;

// put this in your Update() loop: if (Time.time > nextScoreTime && ProtectMode.protectMode) { ProtectMode.scoreProtect += scoreAmount; nextScoreTime += scorePeriod; }

Or, look up Coroutines as they are designed to do this sort of thing.

Comment
Add comment · Show 7 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image zenislev · Dec 02, 2009 at 08:47 PM 0
Share

You again;) Thanks a lot. This works as you said, but seems to get confused when picking up multiple chasers: if there are already NPCs chasing, attracting more messes up the total score, doubling it or adding the wrong amounts. Weird.

I apologise for not explaining properly; ins$$anonymous$$d of a fixed increase, I would like each NPC to have its own independent count, adding 100 as soon as it enters chase mode and 100 every 5 seconds after that. $$anonymous$$y fault.

avatar image zenislev · Dec 02, 2009 at 08:48 PM 0
Share

Coroutines look useful for this. Would it be as simple as starting the same score function as above with StartCoroutine, replacing nextScoreTime += scorePeriod with yield WaitForSeconds(5.0) and repeating?

avatar image duck ♦♦ · Dec 02, 2009 at 08:59 PM 0
Share

Yep pretty much. Although if you're using Unity's Javascript, you don't need to use StartCoroutine, you can just call the function.

avatar image zenislev · Dec 02, 2009 at 09:35 PM 0
Share

Quality. Do you know how I would set the function to repeat?

avatar image equalsequals · Dec 02, 2009 at 10:38 PM 0
Share

put it in a while loop:

while(true) { val++; yield WaitForSeconds(0.5) }

Show more comments
avatar image
2

Answer by duck · Dec 03, 2009 at 10:14 AM

Right, if you want to do it using a Coroutine, your "Score" function needs to look like this:

function Score(){
    while(true) {
        if (ProtectMode.protectMode)
        {
            ProtectMode.scoreProtect += scoreAmount;
        }
        yield WaitForSeconds (5.0);
    }
}

There's no need for the part you had where it returns if protectMode is false. And you should only call this once, from your Start() function - not every frame in your Update() function. The reason for this is that once called, this function ticks over like a little engine automatically from then onwards, indefinitely monitoring the state of "protectMode" (until your game stops).

Also, notice that I've put the check for "protectMode" inside the while loop. This means that if "protectMode" ever gets changed back to false, the score will stop increasing, but the loop will continue to run - so it will work even if you change protectMode to false, and then later back to true.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image zenislev · Dec 04, 2009 at 06:18 PM 0
Share

O$$anonymous$$, I made a mistake implementing this first time round, but it's all running well now. Thanks Duck.

Is there a way to measure the time since the function was first called, and start the scoring intervals from that point? Since the score still likes to update every 5 seconds for all of them at once; that might be the only way to achieve the scoring effect I talked about^^.

avatar image
-1

Answer by Ashkan_gc · Dec 03, 2009 at 04:48 AM

using System.Collections;

IEnumerator socring () { while (true) { ProtectMode.scoreProtect += scoreAmount; yield return new WaitForSecond (5.0f); } }

void Start () { StartCoroutine (scoring); }

the code is untested and typed here but should work with correct spelling. you should attach this code to all of your NPCs it's a good idea to use static variables for score if you need to access the score from many objects

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image duck ♦♦ · Dec 03, 2009 at 10:18 AM 0
Share

This is a c# script, whereas the the original poster is using Javascript. Also, you're calling the coroutine from Update, which would mean a new coroutine would get spawned every frame.

avatar image Ashkan_gc · Dec 03, 2009 at 04:40 PM 0
Share

i corrected the code. you are right.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

No one has followed this question yet.

Related Questions

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

How to import the object from server to unity 2 Answers

Can someone help me fix my Javascript for Flickering Light? 6 Answers

Setting Scroll View Width GUILayout 1 Answer

Material doesn't have a color property '_Color' 4 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges