Prevent one from doing action if one is activated (C# UNITY) - c#

Good Day, I just want to ask if how can I do these.
I need to prevent one action from doing something if the another action is activated and vice versa . Here's the code i have written so far.
if (hit == "spr_player")
{
betOnPlayer = true;
if (betOnBanker)
{
Debug.LogError("You already bet on the banker cannot bet on the player"); ;
}
else
{
if (betOnPlayer)
{
bet[0] = chip;
chips_bet[0].enabled = true;
Chips(chip, 0);
Debug.LogError("Betting on the player");
}
else
{
Debug.LogError("You can not bet on the Player");
}
}
}
else if (hit == "spr_banker")
{
if (betOnPlayer)
{
Debug.LogError("You already bet on the banker cannot bet on the player");
betOnBanker = true;
}
else
{
if (betOnBanker)
{
bet[4] = chip;
chips_bet[4].enabled = true;
Chips(chip, 4);
Debug.LogError("Betting on the banker");
}
else
{
Debug.LogError("You can not bet on the Banker");
}
}
}
But the problem here is that I couldn't get to switch it on off . Could someone point out what I am doing wrong.

I guess your program is that first click is select target, second click is bet.
And when you set the flag to someone, you should also unset another one.
if (hit == "spr_player")
{
if (betOnPlayer)
{
// bet on player
}
else
{
betOnPlayer = true;
betOnBanker = false;
}
}
else if (hit == "spr_banker")
{
if (betOnBanker)
{
// bet on banker
}
else
{
betOnPlayer = false;
betOnBanker = true;
}
}
Another answer:
string currentSelect = "";
void Update() {
if(YOUR_INPUT_EVENT) {
if (hit == "spr_player")
{
if (currentSelect == "Player")
{
// bet on player
}
else
{
currentSelect = "Player"
}
}
else if (hit == "spr_banker")
{
if (currentSelect == "Banker")
{
// bet on banker
}
else
{
currentSelect == "Banker"
}
}
}
}

Related

How do I deactivate all the virtual buttons in Vuforia after pressing just one?

Good afternoon!
I'm trying to make a simple AR quiz game that requires virtual buttons to answer. The game goes on if the correct button is pressed.
The question is: how do I deactivate all the virtual buttons when a virtual button is pressed?
I've looked at nearly every topic regarding this, but can't figure it out how to make this work.
At this point I can press all the buttons but only once.
Thanks in advance (and sorry for my bad English)!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Vuforia;
public class PushToDebug : MonoBehaviour, IVirtualButtonEventHandler
{
public string vbName;
public AudioSource audi;
void Start()
{
//Register with the virtual buttons TrackableBehaviour
VirtualButtonBehaviour[] vrb = GetComponentsInChildren<VirtualButtonBehaviour>();
audi = GetComponent<AudioSource>();
for (int i = 0; i < vrb.Length; i++)
vrb[i].RegisterEventHandler(this);
}
public void OnButtonPressed(VirtualButtonBehaviour vb)
{
vbName = vb.VirtualButtonName;
if (vbName == "VB1")
{
Debug.Log("Button 1 is pressed!");
audi.Play();
vb.GetComponent<VirtualButtonBehaviour>().enabled = false;
}
else if (vbName == "VB2")
{
Debug.Log("Button 2 is pressed!");
audi.Play();
vb.GetComponent<VirtualButtonBehaviour>().enabled = false;
}
else
{
Debug.Log("Button 3 is pressed!");
audi.Play();
vb.GetComponent<VirtualButtonBehaviour>().enabled = false;
}
}
public void OnButtonReleased(VirtualButtonBehaviour vb)
{
if (vbName == "VB1")
{
Debug.Log("Button 1 is released!");
}
else if (vbName == "VB2")
{
Debug.Log("Button 2 is released!");
}
else
{
Debug.Log("Button 3 is released!");
}
}
}
Thank you for your reply!
For some weird reason it doesn't just work.
I added Debug.Log("DeactivateButtons is called!"); and this method wasn't called at all.
Looks like you are disabling only one button when pressed whereas others remain active. You can add a function to check if any of the buttons are pressed so that you can deactivate them.
Or since you are finding the name of the button when pressed, then you can probably create 3 variables such as:
var VB1 = GameObject.Find("VB1");
var VB2 = GameObject.Find("VB2");
var VB3 = GameObject.Find("VB3");
if(VB1 != null && VB2 != null && VB3 != null){
VB1.GetComponent<VirtualButtonBehavior>().enabled = false;
VB2.GetComponent<VirtualButtonBehavior>().enabled = false;
VB3.GetComponent<VirtualButtonBehavior>().enabled = false;
}
Now to integrate the above to your code, perhaps under OnButtonPressed() function; you can add:
public void OnButtonPressed(VirtualButtonBehaviour vb)
{
vbName = vb.VirtualButtonName;
if (vbName == "VB1")
{
Debug.Log("Button 1 is pressed!");
audi.Play();
vb.GetComponent<VirtualButtonBehaviour>().enabled = false;
DeactivateButtons();
}
else if (vbName == "VB2")
{
Debug.Log("Button 2 is pressed!");
audi.Play();
vb.GetComponent<VirtualButtonBehaviour>().enabled = false;
DeactivateButtons();
}
else
{
Debug.Log("Button 3 is pressed!");
audi.Play();
vb.GetComponent<VirtualButtonBehaviour>().enabled = false;
DeactivateButtons();
}
}
public void DeactivateButtons()
{
var VB1 = GameObject.Find("VB1");
var VB2 = GameObject.Find("VB2");
var VB3 = GameObject.Find("VB3");
if(VB1 != null && VB2 != null && VB3 != null){
VB1.GetComponent<VirtualButtonBehavior>().enabled = false;
VB2.GetComponent<VirtualButtonBehavior>().enabled = false;
VB3.GetComponent<VirtualButtonBehavior>().enabled = false;
}
}

Is it possible to have a while loop slowed?

Rewrite: I'm writing a program to get a better understanding of C# and taking user input in. Right now I'm using WFA in C# with a textbox where I put the text of what I want pasted/typed out. Then I have two other boxes that have an interval input and a amount input. Everything worked perfectly fine until I added the amount input, I've added a while loop to a timer that is used to type/paste the text. However, for some reason that I'm not sure of.. The program disregards any input for the interval.
I have it basically setup like this
private void timerPaste_Tick(object sender, EventArgs e)
{
interval = Int32.Parse(interNum.Text);
timerPaste.Interval = interval;
if (typeModebool == true && pasteModebool == false)
{
while (amount > 0) //Need to find a way to make GUI responsive during while loop.
{
SendKeys.Send(textBox1.Text);
SendKeys.Send("{Enter}");
amount--;
}
timerPaste.Enabled = false;
amount = Int32.Parse(amountSetBox.Text);
}
if (pasteModebool == true && typeModebool == false)
{
while (amount > 0) //Need to find a way to make GUI responsive during while loop.
{
Clipboard.SetText(textBox1.Text);
SendKeys.Send("^{c}");
SendKeys.Send("^{v}");
SendKeys.Send("{Enter}");
amount--;
}
timerPaste.Enabled = false;
amount = Int32.Parse(amountSetBox.Text);
}
}
something like that..?
timerPaste.Elapsed += OnTickEvent;
private async void OnTickEvent(Object source,EventArgs e)
{
interval = Int32.Parse(interNum.Text);
timerPaste.Interval = interval;
if (typeModebool == true && pasteModebool == false)
{
while (amount > 0) //Need to find a way to make GUI responsive during while loop.
{
SendKeys.Send(textBox1.Text);
SendKeys.Send("{Enter}");
amount--;
}
timerPaste.Enabled = false;
amount = Int32.Parse(amountSetBox.Text);
}
if (pasteModebool == true && typeModebool == false)
{
while (amount > 0) //Need to find a way to make GUI responsive during while loop.
{
Clipboard.SetText(textBox1.Text);
SendKeys.Send("^{c}");
SendKeys.Send("^{v}");
SendKeys.Send("{Enter}");
amount--;
}
timerPaste.Enabled = false;
amount = Int32.Parse(amountSetBox.Text);
}
}
I actually was able to fix this, the problem was that the while loop listened to the timer the first time, then after that just started going off on it's own. I switched it to a if, with an else statement and everything works as intended now.
int i = 0;
private void timerPaste_Tick(object sender, EventArgs e)
{
if (typeModebool == true && pasteModebool == false) //Check what mode is being used
{
if (i < amount) //If runs until i == amount
{
SendKeys.Send(textBox1.Text);
SendKeys.Send("{Enter}");
amount--;
}
else
{
timerPaste.Enabled = false;
}
}
if (pasteModebool == true && typeModebool == false)
{
if (i < amount)
{
Clipboard.SetText(textBox1.Text);
SendKeys.Send("^{c}");
SendKeys.Send("^{v}");
SendKeys.Send("{Enter}");
amount--;
}
else
{
timerPaste.Enabled = false;
}
}
}

Need help figuring out repeatable equals and addition operator events

I am building a UWP calculator app using the MVVM pattern and I have just about everything figured out except how to get the equals button to calculate repeatedly and have my operator buttons work correctly. I can do one or the other, but I can't figure out how to do both. The code below works for a repeatable equals button, but the plus operator will yield the wrong answer when adding multiple values.
If I take out the second switch statement and change the variables back to using one Output variable then I can get the plus operator to work, but the equals button will fail when it repeats.
I am sure it is just a matter of adding a nested if statement or the addition of a bool somewhere, but I'm stumped! Please help. I've removed the non essential buttons and operators. Any other helpful suggestions on my code would be appreciated too.
Thank you!
public class ComputareViewModel : ViewModelBase
{
#region Private Fields
private double resultNumber = 0;
private double xResultNumber;
private double yResultNumber;
private string _outputValue = "0";
bool isOperationPerformed = false;
bool EqualsRepeated = false;
public ComputareViewModel()
{
}
public string OutputValue
{
get
{
return _outputValue;
}
set
{
_outputValue = value;
OnPropertyChanged("OutputValue");
}
}
public void OnNumberBtnClick(object sender, RoutedEventArgs args)
{
if ((_outputValue) == "0" || (isOperationPerformed))
_outputValue = "";
isOperationPerformed = false;
Button numberBtnClick = (Button)sender;
if ((string)numberBtnClick.Content == ".")
{
if (!_outputValue.Contains("."))
{
OutputValue = OutputValue + numberBtnClick.Content;
}
}
else
{
OutputValue = OutputValue + numberBtnClick.Content;
}
}
public void OnOperatorBtnClick(object sender, RoutedEventArgs args)
{
Button operatorBtnClick = (Button)sender;
if(isOperationPerformed == false)
{
if (xResultNumber != 0)
{
OnEqualsBtnClick(this, new RoutedEventArgs());
operationPerformed = (string)operatorBtnClick.Content;
isOperationPerformed = true;
EqualsRepeated = false;
}
else
{
operationPerformed = (string)operatorBtnClick.Content;
xResultNumber = Double.Parse(OutputValue);
isOperationPerformed = true;
}
}
else
{
//Do nothing.
}
}
public void OnEqualsBtnClick(object sender, RoutedEventArgs args)
{
if (EqualsRepeated == false)
{
if (double.TryParse(OutputValue, out yResultNumber))
switch (operationPerformed)
{
case "+":
{
OutputValue = (xResultNumber + yResultNumber).ToString();
break;
}
}
isOperationPerformed = true;
EqualsRepeated = true;
}
else
{
// If equals has already been clicked
if (EqualsRepeated == true)
if (double.TryParse(OutputValue, out xResultNumber))
switch (operationPerformed)
{
case "+":
{
OutputValue = (xResultNumber + yResultNumber).ToString();
break;
}
}
}
isOperationPerformed = true;
}
}
There are some logical problems in your code. First, after OnEqualsBtnClick is called, isOperationPerformed is true, if you want to call the OnOperatorBtnClick, it will always go to the else part and do nothing. Second, if you repeat click euqal button, xResultNumber is not 0, if you want to call OnOperatorBtnClick, it will then call the OnEqualsBtnClick, but EqualsRepeated is true now, so you should change EqualsRepeated to false. At last, xResultNumber is the value of last calculation, you should set it to 0 in OnEqualsBtnClick method.
So you can change your code like this:
public void OnOperatorBtnClick(object sender, RoutedEventArgs args)
{
Button operatorBtnClick = (Button)sender;
EqualsRepeated = false;
if (isOperationPerformed == false)
{
if (xResultNumber != 0)
{
OnEqualsBtnClick(this, new RoutedEventArgs());
operationPerformed = (string)operatorBtnClick.Content;
isOperationPerformed = true;
EqualsRepeated = false;
}
else
{
operationPerformed = (string)operatorBtnClick.Content;
xResultNumber = Double.Parse(OutputValue);
isOperationPerformed = true;
}
}
else
{
//Do nothing.
}
}
public void OnEqualsBtnClick(object sender, RoutedEventArgs args)
{
if (EqualsRepeated == false)
{
if (double.TryParse(OutputValue, out yResultNumber))
switch (operationPerformed)
{
case "+":
{
OutputValue = (xResultNumber + yResultNumber).ToString();
break;
}
}
isOperationPerformed = true;
EqualsRepeated = true;
}
else
{
// If equals has already been clicked
if (EqualsRepeated == true)
if (double.TryParse(OutputValue, out xResultNumber))
switch (operationPerformed)
{
case "+":
{
OutputValue = (xResultNumber + yResultNumber).ToString();
break;
}
}
}
isOperationPerformed = false;
xResultNumber = 0;
}

Show Unity Ads Every 5 times scene is loaded. (Unity 3D)

I want to show ads in my 2D game every 5 times the scene is loaded. I tried this:
void Update ()
{
if(GameObject.Find ("Main Camera").transform.position.x == -23) {
showNumber += 1;
if(showNumber == 5) {
if(Advertisement.isReady()){
Advertisement.Show();
}
}
if(showNumber > 5) {
showNumber = 1;
}
}
}
How do I make the number only change only once so it would only change once when the main camera's position is -23. Right not it changes every frame.
Edit
void OnTriggerEnter(Collider other) {
DontDestroyOnLoad (gameObject);
if(other.name == "Main Camera") {
showNumber +=1;
if(showNumber == 5) {
if(Advertisement.isReady()){
Advertisement.Show();
}
}
if(showNumber > 5) {
showNumber = 0;
}
}
}
Solution: Put the showNumber +=1 oder showNumber++ into
void Start()
{
showNumber +=1;
}
I think it would be easier if you write this value to a textfile and then read it from this textfile, all in the start event and not the update.
Start is called once and the update is called every frame.
Quick and dirty Edit: Place a trigger zone on your desired postion.
Then call an OnTriggerEnter method.
void OnTriggerEnter(Collider other) {
showNumber +=1;
if(showNumber == 5) {
if(Advertisement.isReady()){
Advertisement.Show();
}
}
Edit: Your problem is that showNumber +=1; is called like 30-60 times, depending on your computer.
You could add a bool variable to check if it's a new entry on that point.
bool alreadyEntered = false;
void Update ()
{
if(GameObject.Find ("Main Camera").transform.position.x == -23 && alreadyEntered == false) {
showNumber += 1;
alreadyEntered = true;
if(showNumber == 5) {
if(Advertisement.isReady()){
Advertisement.Show();
}
}
if(showNumber > 5) {
showNumber = 1;
}
}
}
Save the Show Number in player prefs.
private int showNumber{
get{
return PlayerPrefs.GetInt("showNumber");
}
set{
PlayerPrefs.SetInt("showNumber",value);
}
}
void OnTriggerEnter(Collider other) {
showNumber +=1;
if(showNumber == 5) {
if(Advertisement.isReady()){
Advertisement.Show();
showNumber = 0;
}
}

Music player freeze a bit when pressing next button too fast

Based on:
C# windows form & using WMPLib
The Problem:
when pressing next or prev button too fast, the apps will freeze a bit (uncontrollable).
The Code:
private void next_event()
{
_paused = false;
if (list[current_index].Rows.Count != 0 && _playing == true)
{
if (option.random.Checked == true)
{
nextRandom(1);
}
else if (option.order.Checked == true)
{
if (list[current_index].Rows.IndexOf(_musicData[_NowPlaying]) == list[current_index].Rows.Count - 1)
{
setNowPlaying((Guid)list[current_index].Rows[0].Cells["Key"].Value);
}
else
{
setNowPlaying((Guid)list[current_index].Rows[list[current_index].Rows.IndexOf(_musicData[_NowPlaying]) + 1].Cells["Key"].Value);
}
}
seek_bar.Value = 0;
play();
}
}
private void prev_event()
{
_paused = false;
if (list[current_index].Rows.Count != 0 && _playing == true)
{
if (option.random.Checked == true)
{
nextRandom(2);
}
else if (option.order.Checked == true)
{
if (list[current_index].CurrentRow.Index == 0)
{
setNowPlaying((Guid)list[current_index].Rows[list[current_index].Rows.Count - 1].Cells["Key"].Value);
}
else
{
setNowPlaying((Guid)list[current_index].Rows[list[current_index].Rows.IndexOf(_musicData[_NowPlaying]) - 1].Cells["Key"].Value);
}
}
seek_bar.Value = 0;
play();
}
}
private void play() // play
{
button3.Text = "Pause";
dmp_status.Text = "Playing...";
_paused = false;
if (list[current_index].Rows.Count != 0)
{
if (File.Exists(_musicData[_NowPlaying].Cells["FileLocation"].Value.ToString()))
{
if (_playing == true) wmp.controls.stop();
if(wmp != null) wmp.close();
wmp = new WMPLib.WindowsMediaPlayer();
wmp.PlayStateChange += new WMPLib._WMPOCXEvents_PlayStateChangeEventHandler(PlayStateChange);
seek_bar.Value = 0;
setNowPlayingLabel(_musicData[_NowPlaying]);
if (!_musicData.ContainsKey(_LastPlaying)) _LastPlaying = Guid.Empty;
setNowPlayingColor(_musicData[_LastPlaying],_musicData[_NowPlaying]);
//wmp.URL = list[current_index].CurrentRow.Cells["FileLocation"].Value.ToString();
wmp.URL = _musicData[_NowPlaying].Cells["FileLocation"].Value.ToString();
wmp.controls.play();
wmp.settings.rate = wmp_rate;
wmp.settings.volume = volume_pos;
if (_playing == false) _playing = true;
}
else
{
next_event();
}
}
}
The Question:
I have hard time figuring why they need a delay(freeze) before playing each music, this making a problem when user press next button consecutively.
I think it is due to reentry. Happened when subsequent events are fire while the first event hasn't complete. To prevent this:
// add this line to your class member
private Object syncRoot = new Object();
// add this block to your next_event() method
if (!Monitor.TryEnter(syncRoot)) return;
try {
// add your existing code here
}
finally {
Monitor.Exit(syncRoot);
}

Categories