Whats Happening:
It works for the most part except after some time after using the offline coin count is always 0. Im am trying to make it so the player cant just change their system time to try to get more money faster. I also am not trying to do this by connection to server for time check. Does anyone see whats going wrong?
If statement is in awake:
if (PlayerPrefs.GetInt("offlineCheck").Equals(1))
{
ButtonCanvas.gameObject.SetActive(false);
OfflineCanvas.gameObject.SetActive(true);
PlayerPrefs.SetInt("offlineCheck", 0);
// year not the same
if (!PlayerPrefs.GetInt("year").Equals(System.DateTime.Now.Year))
{
// Add 24 Hour Coins
if (PlayerPrefs.GetInt("year") < System.DateTime.Now.Year)
{
offlineCoinCount = PlayerPrefs.GetInt("OfflineCoinsVal") * (24 * 60);
} else {
offlineCoinCount = 0;
}
}
else
{ // same Year
// month not the same
if (!PlayerPrefs.GetInt("month").Equals(System.DateTime.Now.Month))
{
// Add 24 Hour Coins
if (PlayerPrefs.GetInt("month") < System.DateTime.Now.Month)
{
offlineCoinCount = PlayerPrefs.GetInt("OfflineCoinsVal") * (24 * 60);
} else {
offlineCoinCount = 0;
}
}
else
{ // Same Month
// day not the same
if (!PlayerPrefs.GetInt("day").Equals(System.DateTime.Now.Day))
{
// Add 24 hours?
if (PlayerPrefs.GetInt("day") < System.DateTime.Now.Day)
{
offlineCoinCount = PlayerPrefs.GetInt("OfflineCoinsVal") * (24 * 60);
} else {
offlineCoinCount = 0;
}
}
else
{ // Same Day
// hour not the same
if (!PlayerPrefs.GetInt("timeHour").Equals(System.DateTime.Now.Hour))
{
// Add Coins
if (PlayerPrefs.GetInt("timeHour") < System.DateTime.Now.Hour)
{
offlineCoinCount = PlayerPrefs.GetInt("OfflineCoinsVal") * (((System.DateTime.Now.Hour - PlayerPrefs.GetInt("timeHour")) * 60) - (System.DateTime.Now.Minute - PlayerPrefs.GetInt("timeMin")));
} else {
offlineCoinCount = 0;
}
}
else
{ // Same hour
// min not the same
if (!PlayerPrefs.GetInt("timeMin").Equals(System.DateTime.Now.Minute))
{
// Add coins
offlineCoinCount = PlayerPrefs.GetInt("OfflineCoinsVal") * (System.DateTime.Now.Minute - PlayerPrefs.GetInt("timeMin"));
}
else
{ // Same min
}
}
}
}
}
}
Rest of Code for this anti-time cheat
private void OnApplicationQuit()
{
saveDateTime();
PlayerPrefs.SetInt("offlineCheck", 1);
//offlineCoinCount = 0;
}
private void OnApplicationFocus(bool focus)
{
saveDateTime();
PlayerPrefs.SetInt("offlineCheck", 1);
//offlineCoinCount = 0;
}
private void OnApplicationPause(bool pause)
{
saveDateTime();
PlayerPrefs.SetInt("offlineCheck", 1);
//offlineCoinCount = 0;
}
public void saveDateTime()
{
//Player Restart Game
//////
/// Check Time for coin bonus
////
if (PlayerPrefs.GetInt("year").Equals(System.DateTime.Now.Year))
{ // Same Year
if (PlayerPrefs.GetInt("month").Equals(System.DateTime.Now.Month))
{ // Same Month
if (PlayerPrefs.GetInt("day").Equals(System.DateTime.Now.Day))
{ // Same Day
if (PlayerPrefs.GetInt("timeHour").Equals(System.DateTime.Now.Hour))
{ // Same Hour
if (PlayerPrefs.GetInt("timeMin").Equals(System.DateTime.Now.Minute))
{ // Same Minute
}
else
{ // Different Minute
// Update if new Minute is higher than old
if (PlayerPrefs.GetInt("timeMin") < System.DateTime.Now.Month)
{
PlayerPrefs.SetInt("timeMin", System.DateTime.Now.Minute);
}
}
}
else
{ //Different Hour
// Update if new hour is higher than old
if (PlayerPrefs.GetInt("timeHour") < System.DateTime.Now.Month)
PlayerPrefs.SetInt("timeHour", System.DateTime.Now.Hour);
PlayerPrefs.SetInt("timeMin", System.DateTime.Now.Minute);
}
}
else
{ // Different Day
// Update if new day is higher than old
if (PlayerPrefs.GetInt("day") < System.DateTime.Now.Month)
{
PlayerPrefs.SetInt("day", System.DateTime.Now.Year);
PlayerPrefs.SetInt("timeHour", System.DateTime.Now.Hour);
PlayerPrefs.SetInt("timeMin", System.DateTime.Now.Minute);
}
}
}
else
{ // Different Month
// Update if new month is higher than old
if (PlayerPrefs.GetInt("month") < System.DateTime.Now.Month)
{
PlayerPrefs.SetInt("month", System.DateTime.Now.Year);
PlayerPrefs.SetInt("day", System.DateTime.Now.Year);
PlayerPrefs.SetInt("timeHour", System.DateTime.Now.Hour);
PlayerPrefs.SetInt("timeMin", System.DateTime.Now.Minute);
}
}
}
else
{ // Different Year
// Update if new year is higher than old
if (PlayerPrefs.GetInt("year") < System.DateTime.Now.Year)
{
PlayerPrefs.SetInt("year", System.DateTime.Now.Year);
PlayerPrefs.SetInt("month", System.DateTime.Now.Year);
PlayerPrefs.SetInt("day", System.DateTime.Now.Year);
PlayerPrefs.SetInt("timeHour", System.DateTime.Now.Hour);
PlayerPrefs.SetInt("timeMin", System.DateTime.Now.Minute);
}
}
}
Related
I am facing an issue with my timer. The issue is, timer goes negative after reaching the specified time limit and the next levels never unlocks. This only happens whenever I change my timespan to 24 hours. When I am using seconds or minutes the timer stops when it reaches to zero (0) and make the button interactable again. I have also tested it on 1 hour and it works fine.
IEnumerator TimeUpdate()
{
if (bonus != null)
{
if (PlayerPrefs.GetInt("Bonus", 0) == 0)
{
bonus.interactable = true;
showTimer.gameObject.SetActive(false);
PlayerPrefs.SetString("BONUS_END_TIME", "");
StopAllCoroutines();
}
else
{
bonus.interactable = false;
showTimer.gameObject.SetActive(true);
}
}
while (true)
{
chkbonustime();
DateTime dt = DateTime.Now;
string bonusendtime = PlayerPrefs.GetString("BONUS_END_TIME", "");
DateTime dateComplete;
if (bonusendtime != null)
{
dateComplete = DateTime.Parse(bonusendtime);
DateTime ENDTIME = dateComplete.Add(TimeSpan.FromHours(24));
TimeSpan ABC = ENDTIME - dt;
showTimer.text = ABC.Hours + " : " + ABC.Minutes + " : " + ABC.Seconds;
}
// Debug.Log();
yield return new WaitForSeconds(1);
}
}
public void chkbonustime()
{
string bonusendtime = PlayerPrefs.GetString("BONUS_END_TIME", "");
if (!bonusendtime.Equals(""))
{
DateTime dateComplete = DateTime.Parse(bonusendtime);
DateTime xyz = DateTime.Now;
TimeSpan timespan = xyz - dateComplete;
Debug.Log(timespan.Seconds);
if (timespan.Hours >= 24)
{
// if (PlayerPrefs.GetInt("Bonus", 0) == 1)
// {
PlayerPrefs.SetInt("Bonus", 0);
bonus.interactable = true;
showTimer.gameObject.SetActive(false);
PlayerPrefs.SetString("BONUS_END_TIME", "");
StopAllCoroutines();
// }
// else
// {
// bonus.interactable = false;
// showTimer.gameObject.SetActive(true);
// }
}
//else
// return false;
// PlayerPrefs.SetString("BONUS_END_TIME", "");
}
else
{
// return false;
}
}
Hours is only between 0-23, you likely want TotalHours or TotalDays.
I have a timer that runs in the background and at the end of the level i want to show the leaderboard. i want to take this timer and convert it to 00:00 format 00 (Minutes) : 00 (Seconds) (i.e 01:40). How is that possible? I just need to do the calculations and the convertion when the Level ends.
This is what i have now. i start the timer normally
void Update()
{
if(timerIsRunning)
{
mainGameTimer += Time.deltaTime;
}
}
and now to add the timer in the 00:00 format i need to pass it as float but read it as string in the leaderboard
public void ShowResult()
{
int min = Mathf.FloorToInt(mainGameTimer / 60);
int sec = Mathf.FloorToInt(mainGameTimer % 60);
users.Add(new User(userName, score , timeScore));
users.Sort(delegate (User us1, User us2)
{ return us2.GetScore().CompareTo(us1.GetScore()); });
int max = users.Count <= 10 ? users.Count : 10;
for (int i = 0; i < max; i++)
{
//leaderListName[i].text = users[i].GetName() + "- " + users[i].GetScore() + "-" + Mathf.RoundToInt(users[i].GetTimeScore()) + "Sec";
leaderListName[i].text = users[i].GetName();
leaderListscore[i].text = users[i].GetScore().ToString();
leaderListtime[i].text = users[i].GetTimeScore().ToString();
}
}
class User
{
string name;
int score;
float timeScore;
public User(string _name, int _score , float _timeScore)
{
name = _name;
score = _score;
timeScore = _timeScore;
}
public string GetName() { return name; }
public int GetScore() { return score; }
public float GetTimeScore() { return timeScore; }
}
Instead of doing your own calculations you can use TimeSpan to convert to a time format. Input will need to be of type double:
double mainGameTimerd = (double)mainGameTimer;
TimeSpan time = TimeSpan.FromSeconds(mainGameTimerd);
string displayTime = time.ToString('mm':'ss");
This is the piece of code I usually use
//Calculate the time in minutes and seconds.
int minutes = (int)levelDuration / 60;
int seconds = (int)levelDuration % 60;
//Update the duration text.
durationText.text = minutes.ToString() + ":" + ((seconds < 10) ? ("0") : ("")) + seconds.ToString();
I have been told I should not be using Updates when I don't need to use them. I am not sure when to not use them, but I am trying to figure it out.
I want to have an event, "Wave", run for 20 seconds and then switch to a random "Wave" and run for another 20 seconds and keep repeating this cycle.
Game Manager:
void Start()
{
StartFireWaves();
}
public void StartFireWaves()
{
StartCoroutine(wm.SelectWave());
}
Wave Manager:
public IEnumerator SelectWave()
{
float waitFor;
float diff = 0;
diff = nextWaveAT - Time.time;
if (diff <= 0f)
{
SpawnFlames();
waitFor = Random.Range(15, 20);
}
nextWaveAT = nextWaveAT + waitFor;
yield return new WaitForSeconds(waitFor);
}
SpawnFlames:
void SpawnFlames()
{
float val = Random.value;
if (val < .25f)
{
Wave1();
}
if (val >= .25f && val < .5f)
{
Wave2();
}
if (val >= .5f && val < .75f)
{
Wave3();
}
else
{
Wave4();
}
}
I am assuming this is how it should work, but it doesn't seem to keep "updating" or running. It just runs once and then nothing happens.
Use Coroutine with multiple nested while loops to do this. The first while loop is to make it run forever until stopRunningWaves() function is called. The second while loop is used to run the wave for x amount of time then jumps back to the first while loop.
bool keepRunningWaves = false;
IEnumerator startingRunningWaves(float second = 20)
{
if (keepRunningWaves)
{
yield break;
}
keepRunningWaves = true;
while (keepRunningWaves)
{
float timer = 0;
int randWave = Random.Range(1, 5);
while (timer < second)
{
if (!keepRunningWaves)
{
yield break;
}
if (randWave == 1)
{
Debug.Log("Running Wave 1");
Wave1();
}
else if (randWave == 2)
{
Debug.Log("Running Wave 2");
Wave2();
}
else if (randWave == 3)
{
Debug.Log("Running Wave 3");
Wave3();
}
else if (randWave == 4)
{
Debug.Log("Running Wave 4");
Wave4();
}
timer += Time.deltaTime;
yield return null;
}
//Reset Timer for next run
timer = 0;
yield return null;
}
keepRunningWaves = false;
}
void stopRunningWaves()
{
keepRunningWaves = false;
}
To test it, use 3 seconds to do it so that you will save your time:
StartCoroutine(startingRunningWaves(3));
Hello guys here I am trying to make a bowling game. What I want is to pop up image of Strike when ball hits strike or spare image when hits spare.
please help me out your help will be appreciated.
please answer me as soon as possible.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class ScoreDisplay : MonoBehaviour {
public Image strick;
public Text[] rollTexts, frameTexts;
public void FillRolls (List<int> rolls) {
string scoresString = FormatRolls (rolls);
for (int i = 0; i < scoresString.Length; i++) {
rollTexts[i].text = scoresString[i].ToString();
}
}
public void FillFrames (List<int> frames) {
for (int i = 0; i < frames.Count; i++) {
frameTexts[i].text = frames[i].ToString();
}
}
public static string FormatRolls (List<int> rolls) {
string output = "";
for (int i = 0; i < rolls.Count; i++) {
int box = output.Length + 1; // Score box 1 to 21
if (rolls[i] == 0) { // Always enter 0 as -
output += "-";
strick.enabled = true;
Debug.LogError("Better Luck Next Time");
} else if (box % 2 == 0 && rolls[i-1]+rolls[i] == 10) { // SPARE anywhere
output += "/";
Debug.LogError("Its Spare");
} else if (box >= 19 && rolls[i] == 10) { // STRIKE in frame 10
output += "X";
Debug.LogError("Congo you got Strick");
} else if (rolls[i] == 10) { // STRIKE in frame 1-9
output += "X ";
Debug.LogError("Its Strick");
} else {
output += rolls[i].ToString(); // Normal 1-9 bowl
Debug.LogError("Try Your Hard");
}
}
return output;
}
}
What you could do is put the image as a child of an empty gameobject,
this will turn it into a gameObject which you can easily instantiate in your code using the Instantiate(object,position,rotation) function.
You can declare a public GameObject, drag your prefab (Gameobject with your image as child) into the inspector then use Instantiate on it, I recommend doing this because then you have more control over your gameobject after it's been instantiated.
for (int i = 0; i < rolls.Count; i++) {
int box = output.Length + 1; // Score box 1 to 21
if (rolls[i] == 0) { // Always enter 0 as -
output += "-";
Instantiate(GameObjectYouWantToInstantiate, location, rotation);
//strick.enabled = true;
Debug.LogError("Better Luck Next Time");
} else if (box % 2 == 0 && rolls[i-1]+rolls[i] == 10) { // SPARE anywhere
output += "/";
Debug.LogError("Its Spare");
} else if (box >= 19 && rolls[i] == 10) { // STRIKE in frame 10
output += "X";
Debug.LogError("Congo you got Strick");
} else if (rolls[i] == 10) { // STRIKE in frame 1-9
output += "X ";
Debug.LogError("Its Strick");
} else {
output += rolls[i].ToString(); // Normal 1-9 bowl
Debug.LogError("Try Your Hard");
}
}
Use Destroy(Strick) when you want to destroy it.
Want to do a loop of picture slideshow to start from a specific time and then to end at another specific time.
Also, how to set the DateTime picker to select minutes/hours?
//Under start button
if (rbtnDateTime.Checked == true)
{
DateTime startDate = dateTimePicker1.Value.Date;
DateTime stopDate = dateTimePicker2.Value.Date;
//Given time interval in seconds
if (mtxtSlideShowInterval.Text != "")
{
int interval = Convert.ToInt16(mtxtSlideShowInterval.Text);
while ((startDate = startDate.AddSeconds(interval)) <= stopDate)
{
timerSlideShow.Enabled = true;
timerSlideShow.Start();
}
timerSlideShow.Stop();
timerSlideShow.Enabled = false;
}
}
//Under timer_tick event
//Infinite Loop
else
{
if (listBoxPicturesInAlbum.SelectedIndex ==listBoxPicturesInAlbum.Items.Count - 1)
{
listBoxPicturesInAlbum.SelectedIndex = 0;
}
else
{
listBoxPicturesInAlbum.SelectedIndex++;
}
}
I would be rid of the while loop you have, and take a few steps.
First, you'll need a field to mark your current index:
int currentImageIndex = 0;
Second, you'll set your timer.Interval.
timer.Interval = int.Parse(mtxtSlideShowInterval.Text) * 1000;
Third, your timer_tick can include something like this:
if (DateTime.Now < dateTimePicker2.Value.Date)
{
listBoxPicturesInAlbum.SelectedIndex = currentImageIndex;
pictureBox.Image = Image.FromFile((string)listBoxPicturesInAlbum.SelectedValue);
currentImageIndex = (currentImageIndex + 1) % listBoxPicturesInAlbum.Items.Count;
}