- Home /
Make Script Component Do Things Even When Game Is Closed
I want to add a lives system like candy crush in my game. I want to use an InvokeRepeating() function to add lives to an int called lives every second, but when the game is off it can't add lives because the game object is destroyed.
Is there any way to make a script or game object active even when the game is off? If there is no way to do this, I might put something like this in feedback.
I have not made my script yet but this is what it my script might look like:
using UnityEngine;
using System.Collections;
public class LivesManager : MonoBehaviour {
void addLife () {
PlayerPrefs.SetInt("Lives", Playerprefs.GetInt("Lives") + 1);
}
void Start () {
PlayerPrefs.SetInt("Lives", 0);
InvokeRepeating("addLife", 1, 1);
}
}
I agree with you two. When you joined the game. You compute the offline time and refresh the num. Then you start your InvokeRepeating("addLife", 1, 1) . It's O$$anonymous$$/
Answer by Hellium · Jul 29, 2016 at 08:35 PM
Do you realize what you are asking ? It's like asking your car to continue to go while it is "turned off".
Save the date when the game is "paused" or quitted using OnApplicationFocus
Compute the duration the game has been turned off
Compute the lives to add to your counter depending on the previous duration
If I do that, it will add lives when a game is off, but it won't add lives when the game is on. Do you know if there is any way to do it even when the game is on.
Uhm, what's the problem when you use both things at the same time?
Take a look at my example over here. It does implement exactly the behaviour of candy crush. However it's written in UnityScript since the OP of the other question used UnityScript.
Answer by PCSorcery10 · Aug 01, 2016 at 04:04 AM
Try using a method called Awake(). Might not be exactly what you are looking for, but hopefully it will work.