I am creating game and I need to track some statistics. I want to track total played time (since the user started game and till the moment he definitely ended game).
I have a "continue" option from main menu, so if someone turned game off and then started it and selected "Continue" - it means that I need to increment the old playedTime because, it is not new player.
How can I track this total played time? I cannot use Editor Scripts because I need this to be available just from the game build (player will start game with .exe, not from Unity)
You can store the realtimeSinceStartup on an ApplicationQuit, for example in the playerprefs. Something like this should do the trick:
using UnityEngine;
public class TimeStatistics : MonoBehaviour
{
public float TotalTime
{
get
{
float totalTime = Time.realtimeSinceStartup;
if(PlayerPrefs.HasKey("totaltime"))
totalTime += PlayerPrefs.GetFloat("totaltime");
return totalTime;
}
}
void OnApplicationQuit()
{
PlayerPregs.SetFloat("totaltime", this.TotalTime);
}
}
Make sure the script always exists, otherwise you wont get an OnApplicationQuit!
Related
I am about half way done with the firs prototype of my new game-idea, and I am tring to implement a spawner that randomly spawns one of 3 enemy prefabs. This enemy spawning hasn't been working very well for me, as I have always found little problems here and there. One of these problems was major and caused Unity to crash every time I pressed Play ind the editor. I wasn't sure what the problem was, and so I Build the game I tried running the build, and it crashed as well. Then eventually I scraped my spawner and tried a new one. This one also crashed Unity every time, so I tried to spawn a random sphere with no components to it, and this seems to be working perfectly fine.
While running the game In the Unity Editor, I simultaneously open the task manager to see what was going on. It told me Unity was running like a charm, although it used about 1.5 gigs of Ram. Is it a lot? TBH, I don't know if that's the reason it keeps crashing, but I wouldn't know why it takes these amounts of ram. As soon as I deactivated the spawner it stopped crashing, so is it the spawner? I personally don't think so because I was able to spawn the sphere without the game crashing, but as soon as I try to spawn the enemies breaks down.
-> edit: The game doesn't really crash, it just starts loading into infinity, forcing me to end the application and reopen it hands why I am not able to provide any error codes.
Here is the spawner script I used:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour
{
public GameObject[] enemyPrefabs;
public float spawnRate = 1.0f; //The frequency at which enemies spawn.
private float nextSpawn = 0.0f; //used to trigger the next spawn
void Update()
{
//Make enemy spawn on a countdown timer
if (Time.time > nextSpawn)
{
nextSpawn = Time.time + spawnRate; // Trigger next spawn
Debug.Log("Spawn");
//Spawn the enemy in the same place as the spawner
GameObject piClone = Instantiate(enemyPrefabs[Random.Range(0, enemyPrefabs.Length)], transform.position, transform.rotation) as GameObject;
}
}
}
I'm trying to start a couroutine that triggers an animation then waits for 10 seconds and goes into another anim.
I have a simple IEnumerator that goes between 2 anim stages and has a small wait between each one.
When I run the scripts the first time it does wait 10 seconds to start (trapActivate) and then waits 10 seconds to start (trapInactivate) but the animations after that just play one after another without waiting the 10 seconds they should be waiting between anim states.
Not sure what the issue could be.
I looked up a a lot of threads of people having issues because they where starting their couritne inside their Update function but I'm not doing that so not really sure what else could be causing that.
I already tried changing the wait time and no matter how long they are after the first wait they just start playing one after another.
I can see them jumping between each other in the animator
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AnimateEveryNTime : MonoBehaviour
{
private Animator animator;
public void Start() {
StartCoroutine(playAnimation());
Debug.Log("Couroutine");
animator = GetComponent<Animator>();
}
public IEnumerator playAnimation() {
yield return new WaitForSeconds(10f);
// Insert your Play Animations here
animator.SetTrigger("trapActivate");
yield return new WaitForSeconds(10f);
animator.SetTrigger("trapInactive");
}
}
Here is a pic of my animator layout:
enter image description here
Your image shows the type of the two parameters is Bool not Trigger. The interest thing is SetTrigger can also work for Bool parameters and set their values to true. So you need delete them and create new parameters with the type Trigger and same names.
I've been studying c sharp as part of my games course and my teacher has left and they cant find a replacement so I'm really struggling with coding my demo game. I’ve got a problem with my doors in my game and I was wondering if anyone knew how u can get it to work because I haven’t really got a clue when it comes to coding. Basically what I’ve got is my doors are shut then when I start my game they open and then shut but I need a code that will make sure it says shut until I’m in the trigger point but all the YouTube clips haven't been working and it says it’s got problems with it. I know what I want it to do I just don’t know how to put that into action.
This is my code but I don't think it does anything:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DoorAnimation: MonoBehaviour
{
Animator animator;
int isOpeningHash;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
animator = GetComponent<Animator>();
isOpeningHash = Animator.StringToHash("isOpening");
bool isOpening = animator.GetBool(isOpeningHash);
bool OpenPressed = Input.GetKey("e");
bool CloseDoor = Input.GetKey("left shift");
if (!isOpening && OpenPressed)
{
animator.SetBool(isOpeningHash, true);
}
if (isOpening && OpenPressed)
{
animator.SetBool(isOpeningHash, false);
}
}
}
First of all, make 2 animations(and turn off the loop or it will loop for eternity) for the opening and closing of door. Don't make Bools for the animator. It's basically useless. At the top of a script declare a bool called as open and set it equal to false(if the door is closed from start). Check if E is pressed and open is set to false(the door is closed), play the opening animation, set open to true and if left shift is pressed and open is set to true(the door is open) play the closing animation, set open to false. You can play animations if a certain key is pressed like this https://answers.unity.com/questions/1362883/how-to-make-an-animation-play-on-keypress-unity-ga.html
This should do your job :)
I am trying to display player tutorial when the user 1st starts the game using playerpref and want the game to be paused, the problem i am facing is that Time.timescale=0 is not pausing the game when placed inside start (tutorialCanvas gets displayed), but works when is called by a button(Pause button).
Following is the code I use
void Start()
{
if (PlayerPrefs.HasKey ("test4") ==false ) {
tutorialCanvas.SetActive (true);
Time.timeScale = 0;
}
}
Time.timeScale = 0 is really messed up for me so what i could recommend you is that if you just want to pause something like pausing a movement of a character then you can try it like this :
GameObject PlayerScript;
if(Input.GetKey(KeyCode.P)){
//lets disable the playermovement script only not the whole object
PlayerScript = GetComponent<PlayerMovement>().enabled = false;
}
I've been stucked there also so i made an alternative way. And you can also visit this one. If you want a free of that asset you can get it here
I had this issue recently, although it was only doing it on a build, and not in the editor. Changing timeScale to something like 0.0001f would fix it, but that wasn't a great solution. Creating an input settings asset (under Camera -> Player Input -> Open Input Settings) seemed to have fixed it for the builds.
I am new in C#, anyone can help me solving this. I am creating game in Unity and have integrated admob (interstitial) in Gameover state. Now it works well, however it looks much annoying for showing insterstitial ads everytime user reach the gameover screen. So here I think it's good to add some delay time within the ads showing. As far I got some simple logic but it doesn't work as I need, not sure.
Here is my code, for example I want it to have 2 minutes delay, so at gameover it won't execute the interstitial ads if it doesn't reach the delay time. The counter should keep counting continously. If the counter reach more 2 minutes and the next gameover screen appear, the ads should show up and the counter restarting counting from zero.
// For timer Admob
public int counter = 0;
public bool timer = true;
void Update()
{
if (timer == true)
{
counter++;
}
}
And in my gameover screen
if (counter >= 120) // delay for 2 minutes
{
<<my custom code to show admob>>
timer = true;
counter = 0;// set the counter to zero and restarting count
}
else
{
timer = true; // it will keep counting
}
Really apreciated for help
I think Update() is called every frame (probably around 30 - 60 times per second) so delay need to be much higher, also to make your game not frame dependant use Time.deltaTime.
http://docs.unity3d.com/ScriptReference/Time-deltaTime.html
Edit: Also in shown code, to timer variable you are never assigning false so looks like it's redundant. You're comparing variable delayAdmob in an if statement, but where do you change or declare it?