A Score that Adds as Time Goes

Hey guys, this is my first post but I know not to just go and ask for a script yet I think this would be beneficial to me and the community. I have been searching the internet and thinking of how to write this script for days. I’m not really sure where to start or if anyone knows of something like this. All I would like the script to do is show a score in the GUI/HUD somewhere and count up over time. For instance, lets say the player has been playing for 5 seconds so there score could be five or one or whatever you would like to count by and then at twenty it could be twenty or four. I think you get the idea but I would be happy to explain more.
Thank You,
Bennet

Here is a script for a very basic scoring system.

var score : int = 0;

while(1==1)
   {
      yield WaitForSeconds (1);
      score += 1;
      GUI.Label(Rect(25,56,253,23),"score");
}

I haven’t tested this in Unity but it should work.

Ok I’ll test it and tell you, thank you so much.
EDIT
Just checked it, and it doesn’t work. The error was something related to the fact you can’t have a GUI component without the “function OnGUI()” if you know how to fix it please tell me. I tried putting “function OnGUI()” above the while statement and adding brackets but it said I can’t make the function a courutine or something like that. Obviously I’m a novice coder and some more help would really help.
Thanks,
Bennet

This code, in C#, will probably do close to what you want. You will need to drag and drop the scripts from your project to a game object in your hierarchy. Code is mostly self-documenting if you take the time to read the public methods. You will want to wire up the Levelling to the Scoring, the TrickleScoring to the Scoring, and the ScoreDisplay to the TrickleScoring via the Inspector before you run it.

This code will track the players score, up and down, with the public methods AdjustScore on the Scoring script. If you have wired everything up correctly in the Inspector, the score will then trickle up from whatever the current score is to the new score value. You can adjust how fast it trickles, and by what units, by simply adjusting those parameters in the Inspector.

TrickleScoring.cs

// (c) Copyright 2011 by Infinite Monkey Factory, LLC -- All Rights Reserved.
// http://www.imf.la/
//
// See the document "TERMS OF USE AND LICENSE" included in the project folder
// for licensing details.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using UnityEngine;
using System;

/// <summary>
/// Tracks the player's score, increments it when necessary.
/// </summary>
[RequireComponent(typeof(Levelling))]
[RequireComponent(typeof(Scoring))]
public class TrickleScoring : MonoBehaviour, IGameScore
{
    private const string MsgScoreAdjustedBy = "ScoreAdjustedBy";
    private const string MsgScoreAdjustedTo = "ScoreAdjustedTo";
    private const string InvokedScoreAdjustment = "ScoreAdjustment";

    public event ScoreAdjustedHandler ScoreAdjusted;
    public int[] m_unitDivisors;

    public float m_trickleStepDelay;

    public MonoBehaviour m_scoringScript;
    private int m_score;

    public AudioClip m_trickling;
    public bool m_shouldTrickle;

    private int m_destinationScore;

    void Reset()
    {
        m_trickling = null;
        m_shouldTrickle = true;
        m_trickleStepDelay = 0.05f;
        m_unitDivisors = new int[] { 1000, 100, 10 };
    }

    private void OnScoreAdjusted(int score, int points)
    {
        SendMessage(MsgScoreAdjustedTo, score, SendMessageOptions.DontRequireReceiver);
        SendMessage(MsgScoreAdjustedBy, points, SendMessageOptions.DontRequireReceiver);
        if (ScoreAdjusted != null)
        {
            ScoreAdjusted(score, points);
        }

    }

    void Start()
    {
        (m_scoringScript as IGameScore).ScoreAdjusted += TargetScoreAdjusted;
        m_score = (m_scoringScript as IGameScore).Score;
    }

    public int Score
    {
        get
        {
            return m_score;
        }

    }

    private void TargetScoreAdjusted(int score, int points)
    {
        m_destinationScore = score;
        if (m_shouldTrickle == false)
        {
            m_score = score;
        }
        else
        {
            if (m_score != score)
            {
                m_destinationScore = score;
                Invoke(InvokedScoreAdjustment, 0.0f);
            }

        }

    }

    private void PlayTricklingEffect()
    {
        audio.PlayOneShot(m_trickling);
    }

    private void AdjustScoreBy(int points)
    {
        m_score += points;
        PlayTricklingEffect();
        Invoke(InvokedScoreAdjustment, m_trickleStepDelay);
        OnScoreAdjusted(m_score, points);
    }

    void ScoreAdjustment()
    {
        int pointDifference = m_destinationScore - m_score;
        int absolutePointDifference = Mathf.Abs(pointDifference);
        int sign = (int)(Mathf.Sign(pointDifference));
        if (absolutePointDifference == 0)
        {
            return;
        }

        foreach (int divisor in m_unitDivisors)
        {
            if (absolutePointDifference > divisor)
            {
                AdjustScoreBy(divisor * sign);
                return;
            }

        }

        AdjustScoreBy(pointDifference);
    }

}

Levelling.cs

// (c) Copyright 2011 by Infinite Monkey Factory, LLC -- All Rights Reserved.
// http://www.imf.la/
//
// See the document "TERMS OF USE AND LICENSE" included in the project folder
// for licensing details.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using UnityEngine;
using System;

[RequireComponent(typeof(AudioSource))]
public class Levelling : MonoBehaviour
{
    private const string MsgLevelledUp = "LevelledUp";
    private const string MsgLevelAdjusted = "LevelAdjusted";
    public delegate void LevelAdjustedHandler(int level);
    public delegate void LevelledUpHandler(int level);

    public event LevelAdjustedHandler LevelAdjusted;
    public event LevelledUpHandler LevelledUp;

    /// <summary>
    /// Audio clips to play for each level up sound.
    /// </summary>
    public AudioClip[] m_nextLevelSound;

    /// <summary>
    /// Maximum permitted level.
    /// </summary>
    public int m_maximumLevel;

    /// <summary>
    /// The list of scores required to advance to the next level.
    /// </summary>
    public int[] m_nextLevelScore;

    /// <summary>
    /// The number of required points to score to advance to the next level once the score has gone beyond the provided list of points.
    /// </summary>
    public int m_nextLevelScoreProgression;

    /// <summary>
    /// The player's current level.
    /// </summary>
    private int m_level;

    public MonoBehaviour m_scoring;
    /// <summary>
    /// The minimum level permitted.
    /// </summary>
    private const int MinimumLevel = 1;

    public int m_startingLevel;

    private void OnLevelledUp(int level)
    {
        SendMessage(MsgLevelledUp, level, SendMessageOptions.DontRequireReceiver);
        if (LevelledUp != null)
        {
            LevelledUp(level);
        }

    }
    private void OnLevelAdjusted(int level)
    {
        SendMessage(MsgLevelAdjusted, level, SendMessageOptions.DontRequireReceiver);
        if (LevelAdjusted != null)
        {
            LevelAdjusted(level);
        }

    }

    protected void Reset()
    {
        m_maximumLevel = 100;
        m_nextLevelScoreProgression = 100000;
        m_startingLevel = 1;
        m_nextLevelScore = new int[] { 0, 3000, 7000, 12000, 18000, 25000, 34000, 44000, 56000, 69000, 80000 };
    }

    void Awake()
    {
        m_level = m_startingLevel;
    }

    void Start()
    {
        (m_scoring as IGameScore).ScoreAdjusted += ScoreAdjusted;
    }

    void ScoreAdjusted(int score, int points)
    {
        CheckForLevelUp();
    }

    /// <summary>
    /// Adjust the current level by the specified number of levels. Negative
    /// values will subtract levels. Does not adjust the score to match. The
    /// new level will be clamped to within the maximum permitted level.
    /// </summary>
    /// <param name="levels">Number of levels to adjust the current level by.</param>
    public void AdjustLevel(int levels)
    {
        m_level = Mathf.Clamp(m_level + levels, MinimumLevel, m_maximumLevel);

        OnLevelAdjusted(m_level);
    }

    /// <summary>
    /// The player's current level. Specifying a new level will ensure that the
    /// new level is clamped to the maximum permitted level.
    /// </summary>
    public int Level
    {
        get
        {
            return (m_level);
        }

        set
        {
            m_level = Mathf.Clamp(value, MinimumLevel, m_maximumLevel);

            OnLevelAdjusted(m_level);
        }

    }

    /// <summary>
    /// Play the audio for level up sound.
    /// </summary>
    private void PlayNextLevelSound()
    {
        if ((m_nextLevelSound == null) || (m_nextLevelSound.Length == 0))
        {
            return;
        }

        int levelUpIndex = Mathf.Clamp(m_level, MinimumLevel, m_nextLevelSound.Length - 1) - 1;
        if (m_nextLevelSound[levelUpIndex] == null)
        {
            return;
        }

        this.audio.PlayOneShot(m_nextLevelSound[levelUpIndex]);
    }

    void ScoreAdjusted()
    {
        CheckForLevelUp();
    }

    /// <summary>
    /// Checks for completion of the current level and advances to the next
    /// level if the score is high enough.
    /// </summary>
    public virtual void CheckForLevelUp()
    {
        // if we have reached the maximum level, do nothing
        if (m_level >= m_maximumLevel)
        {
            return;
        }

        // check for the next required score
        int nextLevelScore = 0;
        // if there are no more scores in the level score progression array
        //      switch over to linear progression
        //      otherwise, use the non-linear progression
        if (m_level >= m_nextLevelScore.Length)
        {
            nextLevelScore = (m_level - m_nextLevelScore.Length + 1) * m_nextLevelScoreProgression;
        }
        else
        {
            nextLevelScore = m_nextLevelScore[m_level];
        }

        // if we have the required score to level up, advance to the next level
        if ((m_scoring as IGameScore).Score >= nextLevelScore)
        {
            m_level = Math.Min(m_level + 1, m_maximumLevel);
            PlayNextLevelSound();

            OnLevelledUp(m_level);
        }

    }

}

ScoreDisplay.cs

using UnityEngine;
using System;


public class ScoreDisplay : MonoBehaviour
{
    public MonoBehaviour m_scoringScript;
    public Levelling m_levellingScript;
    public GUISkin m_skin;

    void Reset()
    {
        m_skin = null;
        m_scoringScript = null;
        m_levellingScript = null;
    }

    /// <summary>
    /// Displays the player's score in a simple user interface
    /// </summary>
    void OnGUI()
    {
        if (m_skin != null)
        {
            GUI.skin = m_skin;
        }

        GUI.Label(new Rect(25, 25, 200, 25), String.Format("Score: {0:N0}", (m_scoringScript as IGameScore).Score));
        GUI.Label(new Rect(Screen.width - 200, 25, 200, 25), String.Format("Level: {0:N0}", m_levellingScript.Level));
    }

}

Scoring.cs

// (c) Copyright 2011 by Infinite Monkey Factory, LLC -- All Rights Reserved.
// http://www.imf.la/
//
// See the document "TERMS OF USE AND LICENSE" included in the project folder
// for licensing details.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using UnityEngine;
using System;

public class Scoring : MonoBehaviour, IGameScore
{
    private const string MsgScoreAdjustedBy = "ScoreAdjustedBy";
    private const string MsgScoreAdjustedTo = "ScoreAdjustedTo";

    public event ScoreAdjustedHandler ScoreAdjusted;

    /// <summary>
    /// The player's current score.
    /// </summary>
    private int m_score;

    public int m_startingScore;

    public bool m_clampToMinimumScore;
    public int m_minimumPermittedScore;
    public bool m_clampToMaximumScore;
    public int m_maximumPermittedScore;

    private void OnScoreAdjusted(int score, int points)
    {
        SendMessage(MsgScoreAdjustedTo, score, SendMessageOptions.DontRequireReceiver);
        SendMessage(MsgScoreAdjustedBy, points, SendMessageOptions.DontRequireReceiver);
        if (ScoreAdjusted != null)
        {
            ScoreAdjusted(score, points);
        }

    }

    protected void Reset()
    {
        m_startingScore = 0;
        m_clampToMaximumScore = false;
        m_clampToMinimumScore = true;
        m_minimumPermittedScore = 0;
        m_maximumPermittedScore = 1000000000;
    }

    protected void Awake()
    {
        m_score = m_startingScore;
    }

    public int Score
    {
        get
        {
            return m_score;
        }

        set
        {
            int previousScore = m_score;
            m_score = value;
            
            OnScoreAdjusted(m_score, m_score-previousScore);
        }

    }

    /// <summary>
    /// Adjust the score by the specified number of points. Negative values
    /// will subtract points.
    /// </summary>
    /// <param name="points">Number of points to adjust the current score by.</param>
    public void AdjustScore(int points)
    {
        m_score += points;
        if (m_clampToMinimumScore == true)
        {
            m_score = Mathf.Max(m_score, m_minimumPermittedScore);
        }

        if (m_clampToMaximumScore == true)
        {
            m_score = Mathf.Min(m_score, m_maximumPermittedScore);
        }

        
        OnScoreAdjusted(m_score, points);
    }

}

IGameScore.cs

using System;

public interface IGameScore
{
    int Score { get; }
    event ScoreAdjustedHandler ScoreAdjusted;

}

ScoreAdjustedHandler.cs

using System;

public delegate void ScoreAdjustedHandler(int score, int points);

I’m probably just being a noob but does this actually make your score go up as the clock runs or is it a general level up script. Sorry I’m pretty bad in C Sharp.
EDIT
I now understand how the scripts work yet I was unable to figure out the configuration in the inspector.