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
Related
The cards with the Button component and an onClick listener require numerous erratic clicks to trigger and fail to invoke after just one click.
The first two cards will always invoke via the first click. Afterwards, the other cards often require multiple clicks (between 2 and 7 clicks) before their listener is invoked, and they are flipped over. This occurs at random as sometimes even the first three pairs will flip after just one click, and then the rest won´t.
If I wait for a set time of five seconds, the next card I click will turn over with just one click. So the issue appears to depend on the interval between clicks, as opposed to the number of clicks. Although this behaviour is inconsistent, as clicking just once on a new card and then waiting those 5 seconds doesn´t always work and the card will stay unflipped; assuming because I clicked too soon.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class GameController : MonoBehaviour
{
[SerializeField] private Sprite bgImage;
public Sprite[] puzzles;
public List<Sprite> gamePuzzles = new List<Sprite>();
public List<Button> btns = new List<Button>();
private bool firstGuess, secondGuess;
private int countGuesses;
private int countCorrectGuesses;
private int gameGuesses;
private int firstGuessIndex, secondGuessIndex;
private string firstGuessPuzzle, secondGuessPuzzle;
void Awake()
{
puzzles = Resources.LoadAll<Sprite>("Sprites/Cards");
}
void Start()
{
GetButtons();
AddListeners();
AddGamePuzzles();
Shuffle(gamePuzzles);
gameGuesses = gamePuzzles.Count / 2;
}
void GetButtons()
{
GameObject[] objects = GameObject.FindGameObjectsWithTag("Puzzle Button");
for (int i = 0; i < objects.Length; i++)
{
btns.Add(objects[i].GetComponent<Button>());
btns[i].image.sprite = bgImage;
}
}
void AddGamePuzzles()
{
int looper = btns.Count;
int index = 0;
for (int i = 0; i < looper; i++)
{
if (index == looper / 2)
{
index = 0;
}
gamePuzzles.Add(puzzles[index]);
index++;
}
}
void AddListeners()
{
foreach (Button btn in btns)
{
btn.onClick.AddListener(() => PickAPuzzle());
}
}
public void PickAPuzzle()
{
string name = UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject.name;
Debug.Log("You are clicking a button named" + name);
if (!firstGuess)
{
firstGuess = true;
firstGuessIndex =
int.Parse(UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject.name);
firstGuessPuzzle = gamePuzzles[firstGuessIndex].name;
btns[firstGuessIndex].image.sprite = gamePuzzles[firstGuessIndex];
}
else if (!secondGuess)
{
secondGuess = true;
secondGuessIndex =
int.Parse(UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject.name);
secondGuessPuzzle = gamePuzzles[secondGuessIndex].name;
btns[secondGuessIndex].image.sprite = gamePuzzles[secondGuessIndex];
countGuesses++;
StartCoroutine(CheckIfThePuzzlesMatch());
}
}
IEnumerator CheckIfThePuzzlesMatch()
{
yield return new WaitForSeconds(2f);
if (firstGuessPuzzle == secondGuessPuzzle && firstGuessIndex != secondGuessIndex)
{
yield return new WaitForSeconds(1f);
btns[firstGuessIndex].interactable = false;
btns[secondGuessIndex].interactable = false;
btns[firstGuessIndex].image.color = new Color(0, 0, 0, 0);
btns[secondGuessIndex].image.color = new Color(0, 0, 0, 0);
CheckIfTheGameIsFinished();
}
else
{
yield return new WaitForSeconds(1f);
btns[firstGuessIndex].image.sprite = bgImage;
btns[secondGuessIndex].image.sprite = bgImage;
}
yield return new WaitForSeconds(1f);
firstGuess = secondGuess = false;
}
void CheckIfTheGameIsFinished()
{
countCorrectGuesses++;
if (countCorrectGuesses == gameGuesses)
{
Debug.Log("Game Finished");
}
}
void Shuffle(List<Sprite> list)
{
for (int i = 0; i < list.Count; i++)
{
Sprite temp = list[i];
int randomIndex = Random.Range(i, list.Count);
list[i] = list[randomIndex];
list[randomIndex] = temp;
}
}
}
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);
}
public class green : MonoBehaviour
{
private AudioSource source;
public AudioClip sound;
static int result = 0;
// Use this for initialization
void Start()
{
StartCoroutine("RoutineCheckInputAfter3Minutes");
Debug.Log("a");
}
IEnumerator RoutineCheckInputAfter3Minutes()
{
System.Random ran = new System.Random();
int timeToWait = ran.Next(1, 50) * 1000;
Thread.Sleep(timeToWait);
source = this.gameObject.AddComponent<AudioSource>();
source.clip = sound;
source.loop = true;
source.Play();
System.Random r = new System.Random();
result = r.Next(1, 4);
Debug.Log("d");
yield return new WaitForSeconds(3f * 60f);
gm.life -= 1;
Debug.Log(gm.life + "값");
source.Stop();
Debug.Log("z");
if (gm.life >= 0)
{
StartCoroutine("RoutineCheckInputAfter3Minutes");
}
}
// Update is called once per frame
public void Update()
{
if (result == 1 && gm.checkeat == true)
{
Debug.Log("e");
gm.life += 1;
Debug.Log("j");
Debug.Log(gm.life + "값");
source.Stop();
gm.checkeat = false;
StopCoroutine("RoutineCheckInputAfter3Minutes");
StartCoroutine("RoutineCheckInputAfter3Minutes");
}
if (result == 2 && gm.checkshit == true)
{
Debug.Log("f");
gm.life += 1;
Debug.Log("o");
Debug.Log(gm.life + "값");
source.Stop();
gm.checkshit = false;
StopCoroutine("RoutineCheckInputAfter3Minutes");
StartCoroutine("RoutineCheckInputAfter3Minutes");
}
else if (result == 3 && gm.checksleep == true)
{
Debug.Log("g");
gm.life += 1;
Debug.Log(gm.life);
Debug.Log(gm.life + "값");
source.Stop();
gm.checksleep = false;
StopCoroutine("RoutineCheckInputAfter3Minutes");
StartCoroutine("RoutineCheckInputAfter3Minutes");
}
}
}
public class gm : MonoBehaviour
{
static public int life = 0;
static public bool checkeat = false;
static public bool checkshit = false;
static public bool checksleep = false;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void eating(string eat)
{
Debug.Log(life + "값");
checkeat = true;
}
public void shitting(string shit)
{
Debug.Log(life + "값");
checkshit = true;
}
public void sleeping(string sleep)
{
Debug.Log(life + "값");
checksleep = true;
}
}
when i click a button , program stops for a while and then works... i think it is because of thread or something...
please share your opinion..
.when i click a button , program stops for a while and then works... i think it is because of thread or something...
please share your opinion..
Stop using :
Thread.Sleep(timeToWait);
This stalls the entire thread, in this case Unity completely from running.
Since your using routines anyway, use this instead :
yield return new WaitForSeconds(timeToWait);
And change this line :
int timeToWait = ran.Next(1, 50) * 1000;
To this :
int timeToWait = ran.Next(1, 50);
I want to play three sounds simultaneously, but second sound must play after one seconds, third sound after two seconds. I have this code:
private void Play()
{
AxWindowsMediaPlayer player1 = new AxWindowsMediaPlayer();
player1.CreateControl();
AxWindowsMediaPlayer player2 = new AxWindowsMediaPlayer();
player2.CreateControl();
AxWindowsMediaPlayer player3 = new AxWindowsMediaPlayer();
player3.CreateControl();
player1.URL = "sounds\\1.wav";
player1.Ctlcontrols.play();
System.Threading.Thread.Sleep(1000);
player2.URL = "sounds\\2.wav";
player2.Ctlcontrols.play();
System.Threading.Thread.Sleep(1000);
player3.URL = "sounds\\3.wav";
player3.Ctlcontrols.play();
Why all this sounds are playing in one time after two seconds?
I ended up using SharpDX (available via NuGet packages SharpDX
and SharpDX.XAudio2.
An example of its usage can be found in one of my GitHub projects: 2DAI
You can hear the various sounds overlapping in this screen recording as well.
Playing a sound:
var backgroundMusicSound = new AudioClip(#".\Assets\Sounds\Music\Background.wav" /*Sound path*/, 1.0 /* Volumne*/, true /*Loop Forever?*/)
backgroundMusicSound.Play();
The class that I pieced together:
public class AudioClip
{
private XAudio2 _xaudio = new XAudio2();
private WaveFormat _waveFormat;
private AudioBuffer _buffer;
private SoundStream _soundstream;
private SourceVoice _singleSourceVoice;
private bool _loopForever;
private bool _isPlaying = false; //Only applicable when _loopForever == false;
private bool _isFading;
private string _wavFilePath; //For debugging.
private float _initialVolumne;
public AudioClip(string wavFilePath, float initialVolumne = 1, bool loopForever = false)
{
_loopForever = loopForever;
_wavFilePath = wavFilePath;
_initialVolumne = initialVolumne;
var masteringsound = new MasteringVoice(_xaudio); //Yes, this is required.
var nativefilestream = new NativeFileStream(wavFilePath,
NativeFileMode.Open, NativeFileAccess.Read, NativeFileShare.Read);
_soundstream = new SoundStream(nativefilestream);
_waveFormat = _soundstream.Format;
_buffer = new AudioBuffer
{
Stream = _soundstream.ToDataStream(),
AudioBytes = (int)_soundstream.Length,
Flags = BufferFlags.EndOfStream
};
if (loopForever)
{
_buffer.LoopCount = 100;
}
}
public void Play()
{
lock (this)
{
if (_loopForever == true)
{
if (_isPlaying)
{
if (_isFading)
{
_isFading = false;
_singleSourceVoice.SetVolume(_initialVolumne);
}
return;
}
_singleSourceVoice = new SourceVoice(_xaudio, _waveFormat, true);
_singleSourceVoice.SubmitSourceBuffer(_buffer, _soundstream.DecodedPacketsInfo);
_singleSourceVoice.SetVolume(_initialVolumne);
_singleSourceVoice.Start();
_isPlaying = true;
return;
}
}
var sourceVoice = new SourceVoice(_xaudio, _waveFormat, true);
sourceVoice.SubmitSourceBuffer(_buffer, _soundstream.DecodedPacketsInfo);
sourceVoice.SetVolume(_initialVolumne);
sourceVoice.Start();
}
public void Fade()
{
if (_isPlaying && _isFading == false)
{
_isFading = true;
(new Thread(FadeThread)).Start();
}
}
private void FadeThread()
{
float volumne;
_singleSourceVoice.GetVolume(out volumne);
while (_isFading && volumne > 0)
{
volumne -= 0.25f;
volumne = volumne < 0 ? 0 : volumne;
_singleSourceVoice.SetVolume(volumne);
Thread.Sleep(100);
}
Stop();
}
public void Stop()
{
if (_loopForever == true)
{
if (_singleSourceVoice != null && _isPlaying)
{
_singleSourceVoice.Stop();
}
_isPlaying = false;
_isFading = false;
}
else
{
throw new Exception("Cannot stop overlapped audio.");
}
}
}
It should also be notes that loading the sounds can be a heavy process, so if you are doing it a lot then you might want to cache them as I did:
private Dictionary<string, AudioClip> _audioClips { get; set; } = new Dictionary<string, AudioClip>();
public AudioClip GetSoundCached(string wavFilePath, float initialVolumne, bool loopForever = false)
{
lock (_audioClips)
{
AudioClip result = null;
wavFilePath = wavFilePath.ToLower();
if (_audioClips.ContainsKey(wavFilePath))
{
result = _audioClips[wavFilePath];
}
else
{
result = new AudioClip(wavFilePath, initialVolumne, loopForever);
_audioClips.Add(wavFilePath, result);
}
return result;
}
}
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;
}