Skip to content

Instantly share code, notes, and snippets.

@AnhPham
Created April 23, 2014 08:19
Show Gist options
  • Save AnhPham/11206783 to your computer and use it in GitHub Desktop.
Save AnhPham/11206783 to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections;
using System;
public class SSSendScore : MonoBehaviour
{
[SerializeField]
float m_WaitTime = 10;
protected long m_CurrentScore;
protected bool m_IsWaiting;
private static SSSendScore m_Instance;
public static SSSendScore Instance
{
get
{
if (m_Instance == null)
{
GameObject go = new GameObject("SendScore");
DontDestroyOnLoad(go);
m_Instance = go.AddComponent<SSSendScore>();
}
return m_Instance;
}
}
public void UpdateScore(long score)
{
if (score > m_CurrentScore)
{
m_CurrentScore = score;
if (!m_IsWaiting)
{
Run ();
}
}
}
protected virtual void SendScore(long score)
{
Debug.Log ("[Virtual] Send Score: " + score);
}
protected void Awake ()
{
if (m_Instance == null)
{
m_Instance = this;
DontDestroyOnLoad (gameObject);
}
else
{
Destroy (gameObject);
}
}
protected void Run()
{
StartCoroutine (IERun ());
}
private IEnumerator IERun()
{
m_IsWaiting = true;
yield return new WaitForSeconds (m_WaitTime);
SendScore (m_CurrentScore);
m_IsWaiting = false;
}
}
@AnhPham
Copy link
Author

AnhPham commented Apr 23, 2014

In some games, you must to touch a 'coin' to get money, then send score to a ranking server. If quantity of coins is big, send so many requests in a short time is a bad implementation.

I made this script to optimize it. After updating score, it will wait about 10 seconds before sending score to server. When the counting down finishes, the last score will be sent to server. You can customize this 'Wait Time' value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment