I need help with my restart button ..when I reload a scene all processes will stop.
//start
void Start()
{
if (NoAnsweredQuestion == null || NoAnsweredQuestion.Count == 0)
{
NoAnsweredQuestion = question.ToList<Question>();
}
SetcurrentQuestion();
StartCoroutine("CountDownTimer");
}
//Setcurrentquestion
void SetcurrentQuestion()
{
int randomQuestionIndex = Random.Range(0, NoAnsweredQuestion.Count);
currentQuestion = NoAnsweredQuestion[randomQuestionIndex];
factText.text = currentQuestion.fact;
correctAnswerText.text = currentQuestion.answered;
}
//transition
IEnumerator TransitiontoNextQuestion()
{
NoAnsweredQuestion.Remove(currentQuestion);
yield return new WaitForSeconds(delaybetweenquestion);
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
this my restart button of my game
public void restart()
{
WWWForm form = new WWWForm();
WWW www = new WWW(restartBegGrammarIAQ, form);
Application.LoadLevel(Application.loadedLevel);
}
Related
Guys When I gave it something tagged with pizza first coroutine doesn't stop How Can I stop it?
Please help me guys I couldn't find the way. What should I do? Btw I am new sorry for bad posting:/
I'm trying to make a pizza restaurant game. So customer will sit then waitforpizza coroutine will start if we give tag with pizza waitforpizza coroutine should start then eatpizza will start but my waitforpizza doesn't stop.
IEnumerator EAT, PAY, WAIT;
private void Start()
{
EAT = EatPizza();
WAIT = WaitForPizza();
PAY = WaitForTheCase();
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Pizza"))
{
canEat = true;
}
if (other.gameObject.CompareTag("Out"))
{
Destroy(this.gameObject);
}
}
void Update()
{
if (isEating)
{
if (Vector3.Distance(transform.position, agent.destination) <= 1f)
{
anim.SetTrigger("sit");
isEating = false;
}
}
if (!isEating && !isPaying && !isOut && !canEat)
{
StartCoroutine(WaitForPizza());
}
if (!isEating && !isPaying && !isOut && canEat)
{
StopCoroutine(WAIT);
StartCoroutine(EatPizza());
}
if (isPaying)
{
isEating = false;
anim.SetTrigger("walk");
agent.destination = checkoutTarget.position;
if (Vector3.Distance(transform.position, agent.destination) <= 1f)
{
anim.SetTrigger("wait");
if (ifCashier)
{
//throw money
isPaying = false;
isOut = true;
}
if (!ifCashier)
{
StartCoroutine(WaitForTheCase());
}
}
}
if (isOut)
{
anim.SetTrigger("walk");
isEating = false;
isPaying = false;
agent.destination = outTarget.position;
}
if (canEat)
{
StopCoroutine(WAIT);
}
}
IEnumerator WaitForTheCase()
{
anim.SetTrigger("wait");
yield return new WaitForSeconds(randomFloatWait);
angry.SetActive(true);
isEating = false;
isPaying = false;
isOut = true;
}
IEnumerator EatPizza()
{
angry.SetActive(false);
StopCoroutine(WaitForPizza());
happy.SetActive(true);
yield return new WaitForSeconds(randomFloatWait);
happy.SetActive(false);
isEating = false;
isPaying = true;
isOut = false;
}
IEnumerator WaitForPizza()
{
while (!canEat)
{
yield return new WaitForSeconds(randomFloatWait);
angry.SetActive(true);
isEating = false;
isPaying = false;
isOut = true;
}
}
First, define WAIT as Coroutine then when you want to start waiting use WAIT = StartCoroutine(WaitForPizza()); and when you want to finish it use StopCoroutine(WAIT);.
I am making a badminton simulator in unity, where the opponent is a set of video clips. I am trying to add some delay to my update method so theres some time between two clips of the opponent. However this delay only applies to the video clips and not the shuttle that arrives from behind the video.
My Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Video;
public class Video_Player : MonoBehaviour
{
public VideoPlayer activeCam, otherCam;
public List<VideoClip> playlist = new List<VideoClip>();
public GameObject shuttle;
VideoClip nextClip;
private bool Timer;
void Start()
{
Shuffle(playlist);
// play the first video in the playlist
PrepareNextPlaylistClip();
SwitchCams(activeCam);
Timer=false;
// setup an event to automatically call SwitchCams() when we finish playing
activeCam.loopPointReached += SwitchCams;
otherCam.loopPointReached += SwitchCams;
shuttle.SetActive(false);
}
void Update()
{
if (playlist.Count == 0)
return;
if(!Timer)
{
StartCoroutine(CountDown(5));
if (nextClip == null && activeCam.time >= activeCam.clip.length - 0.1)
{
PrepareNextPlaylistClip();
shuttle.SetActive(false);
}
if(activeCam.time >= 1.0f && activeCam.time <= 2.95f)
{
Debug.Log("start:"+activeCam.time);
shuttle.SetActive(true);
}
else
//if(activeCam.time >= 2.95f || activeCam.time <= 1.0f)
{
Debug.Log("end:"+activeCam.time);
shuttle.SetActive(false);
}
}
}
void SwitchCams(VideoPlayer thisCam)
{
activeCam = otherCam;
otherCam = thisCam;
activeCam.targetCameraAlpha = 1f;
otherCam.targetCameraAlpha = 0f;
Debug.Log("new clip: " + nextClip.name);
nextClip = null;
}
void PrepareNextPlaylistClip()
{
nextClip = playlist[0];
otherCam.clip = nextClip;
otherCam.Play();
playlist.RemoveAt(0);
}
//delay couroutine
IEnumerator CountDown(float delay)
{
Timer = true;
yield return new WaitForSeconds(delay);
Timer= false;
}
// randomize the video playlist
public static void Shuffle<T>(IList<T> playlist)
{
int n = playlist.Count;
while (n > 1)
{
n--;
int k = Random.Range(0, n);
T value = playlist[k];
playlist[k] = playlist[n];
playlist[n] = value;
}
}
}
Forgive me if I'm misunderstanding your code but rather than having it all in Update() couldn't you just have it in an IEnumerator like this?
void Start()
{
Shuffle(playlist);
// play the first video in the playlist
PrepareNextPlaylistClip();
SwitchCams(activeCam);
activeCam.loopPointReached += SwitchCams;
otherCam.loopPointReached += SwitchCams;
shuttle.SetActive(false);
//Run the function on start
StartCoroutine(Function());
}
IEnumerator Function()
{
while(true)
{
if(playlist.Count == 0)
{
//If you have no clips left exit out of the loop
break;
}
if(nextClip == null)
{
//If you have clips left load the next clip
shuttle.SetActive(false);
PrepareNextPlaylistClip();
}
yield return new WaitForSeconds(1); //This is your delay
//Execute the code you want to run after the delay here
}
}
How can I stop the NoAnsweredQuestion.Count when I click on a button...
Problem:
When I click on the reset button, the NoAnsweredQuestion.Count is still counting go to the maximum limit
Random:
private void SetcurrentQuestion()
{
int randomQuestionIndex = Random.Range(0, NoAnsweredQuestion.Count);
currentQuestion = NoAnsweredQuestion[randomQuestionIndex];
factText.text = currentQuestion.fact;
correctAnswerText.text = currentQuestion.answered;
}
This is my limit:
public void ContinueTransition()
{
if (NoAnsweredQuestion.Count == 10)
{
FinalScore.SetActive(true);
}
else
{
StartCoroutine(TransitiontoNextQuestion());
updatequestion();
}
}
Reset button:
public void Restart()
{
var form = new WWWForm();
var www = new WWW(restartBegGrammarIAQ, form);
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
Time.timeScale = 1f;
GameIsPaused = false;
}
Add NoAnsweredQuestion.Clear() in your restart method and it should work
I'd like to know how I can pause and unpause menu from the same button using the mouse pointer when I click on it.
Lets say I have this. C#
void Update () {
if (Button_Pause.OnPointerClick()) {
if(!active){
PauseGame();
}
else{
ResumeGame();
}
active = !active;
}
}
public void PauseGame()
{
Button_Pause = Button_Pause.GetComponent<Button> ();
Canvas_PauseMenu.enabled = true;
Button_Exit.enabled = true;
Button_Pause.enabled = true;
}
public void ResumeGame()
{
Canvas_PauseMenu.enabled = false;
Button_Exit.enabled = false;
Button_Pause.enabled = false;
}
In the first line, where I call the OnPointerClick I'm just guessing because I don't know what to do. What I've searched around, using click to show something it's having a TimeScale or something like that.
¿Can anyone help moi? Please.
Add a listener for your button and in your pause script set timescale to zero to pause the game
[SerializeField] private Button MyButton = null; // assign in the editor
void Start() { MyButton.onClick.AddListener(() => { pause();});
}
void pause(){
if (Time.timeScale == 1)
{
Time.timeScale = 0;
}
else
{
Time.timeScale = 1;
}
}
I managed to solve the issue. It might not be efficient but it does what I need.
I created 2 buttons in the same place. Those buttons are represented with different sprites (Pause & Play). "Pause" is visible since the start. When I click on it, the menu pops up, the "Pause" stop being active and the "Play" sprite button activates and pops up too. When I click on it, I unpause and goes back to the "Pause" sprite visible in the screen.
void Start () {
Canvas_PauseMenu = Canvas_PauseMenu.GetComponent<Canvas> ();
Button_Pause = Button_Pause.GetComponent<Button> ();
Button_Resume = Button_Resume.GetComponent<Button> ();
Canvas_PauseMenu.enabled = false;
Button_Resume.enabled = false;
Button_Resume.gameObject.SetActive (false);
}
// Update is called once per frame
public void PauseTest () {
if(!active){
PauseGame();
}
else{
ResumeGame();
}
}
public void BackToMainMenu()
{
Application.LoadLevel (0);
}
public void PauseGame()
{
Canvas_PauseMenu.enabled = true;
Button_Exit.enabled = true;
Button_Pause.enabled = false;
Button_Pause.gameObject.SetActive (false);
Button_Resume.enabled = true;
Button_Resume.gameObject.SetActive (true);
active = true;
Time.timeScale = 0;
}
public void ResumeGame()
{
Canvas_PauseMenu.enabled = false;
Button_Exit.enabled = false;
Button_Pause.enabled = true;
Button_Pause.gameObject.SetActive (true);
Button_Resume.enabled = false;
Button_Resume.gameObject.SetActive (false);
active = false;
Time.timeScale = 1;
}
I have the following code which creates a main menu :
public class EscapeGUI : MonoBehaviour {
public GUISkin MySkin;
public bool pauseToggle = false;
public bool showGUI = false;
public bool levelLoaded = false;
static string filePath;
private List<string> list = new List<string>();
private string line;
void Update() {
if (!levelLoaded) {
showGUI = true;
Time.timeScale = 0;
Debug.Log ("NO LEVEL LOADED");
} else {
if (Input.GetKeyDown (KeyCode.Escape)) {
pauseToggle = !pauseToggle;
if (pauseToggle) {
Time.timeScale = 0;
showGUI = true;
} else {
Time.timeScale = 1;
showGUI = false;
}
}
Debug.Log("FILEPATH IS " + filePath);
Debug.Log("LEVEL IS LOADED");
}
}
void OnGUI() {
if (showGUI) {
GUI.skin = MySkin;
GUILayout.BeginArea (new Rect (Screen.width / 4, Screen.height / 4, 400, Screen.width / 2));
GUILayout.BeginHorizontal ();
if (levelLoaded){
if (GUILayout.Button ("Resume")) {
Time.timeScale = 1;
showGUI = false;
pauseToggle = false;
}
}
GUILayout.EndHorizontal ();
GUILayout.BeginHorizontal ();
if (levelLoaded){
if (GUILayout.Button ("Restart")) {
Application.LoadLevel (0);
showGUI = false;
pauseToggle = false;
Time.timeScale = 1;
levelLoaded = true;
Debug.Log ("Game is restarted with this level: " + filePath);
}
}
GUILayout.EndHorizontal ();
GUILayout.BeginHorizontal ();
if (GUILayout.Button ("Load")) {
filePath = EditorUtility.OpenFilePanel("Select JSON file",Application.streamingAssetsPath,"txt");
Debug.Log ("Game is loaded with this level: " + filePath);
StreamReader reader = new StreamReader(filePath);
while ((line = reader.ReadLine()) != null)
{
list.Add(line);
//Debug.Log(line);
}
//Do this as soon as the JSON is checked and found to be OK.
GameObject.Find("Preserved Variables").SendMessage("setFilePath", filePath);
Time.timeScale = 1;
levelLoaded = true;
showGUI = false;
pauseToggle = false;
}
GUILayout.EndHorizontal ();
GUILayout.BeginHorizontal ();
if (GUILayout.Button ("Quit")) {
Application.Quit();
}
GUILayout.EndHorizontal ();
GUILayout.EndArea ();
}
}
}
A game is created by importing a JSON file (in the code its just txt for testing, i have not implemented the JSON part yet), in this JSON file the game flow will be described.
So basically when a player clicks load, I want the game to be playable and then when he clicks restart because of the 'Application.LoadLevel (0);' code everythings gets deleted, thus I don't know anymore what the current file (level) it was.
So I created an empty gameobject called 'Preserved Variables' and I put a C# script component in this, the script looks like this:
public class PreservedVariables : MonoBehaviour {
public string filePath;
public static PreservedVariables instance;
void Awake() {
if(instance){
Destroy(this);
} else {
DontDestroyOnLoad(this);
instance = this;
}
}
void setFilePath(string fp) {
filePath = fp;
}
string getFilePath() {
return filePath;
}
}
Now the problem is that when I run this and ingame i click 'load', i select my file and so far everything is good. But then when I click "restart" I get the following 2 problems:
1) the main menu shows me only the 'load' and 'quit' as it is only supposed to show when there is no game loaded (so this only happens at startup), however i think this will be fixed by fixing nr.2 (see below)
2) As soon as i click restart after loading a file, the gameobject 'Preserved Variables' is made again but this time it does not have a script component attached. (the original gameobject has its FilePath updated correctly though).
If I may I would like to ask an extra small question to this, how do I exactly retrieve the filepath variable again from the empty gameobject 'Preserved Variables' so that I can use it in my restart code?