I'm making a game. it has a login panel and rememmer me button. i keep the info on regedit. when I click rememmer me button it works and when I start game after click button it gets my info like id and pass but when I start again it deletes my id and pass on regedit. So it get just one time. I couldn't find the problem or fix way. Can you help me? Thank you.
Here is my codes:
void Start()
{
if(PlayerPrefs.GetInt("BeniHatirla")==1)
{
Debug.Log("start "+PlayerPrefs.GetInt("BeniHatirla"));
BeniHatirlaGetir();
}
}
Here is the method ı called in start:
public void BeniHatirlaGetir()
{
isim = PlayerPrefs.GetString("BeniHatirlaIsim");
sifre = PlayerPrefs.GetString("BeniHatirlaSifre");
Debug.Log("kullanici "+isim+sifre);
BeniHatirlaUniSlider.value = 1;
Debug.Log("Ogrenm Durumu"+PlayerPrefs.GetInt("OgrenimDurumuBelirleme"));
switch (PlayerPrefs.GetInt("OgrenimDurumuBelirleme"))
{
case 1:
OrtaOkulKadiTextBox.text = isim.ToString();
OrtaokulKsifreTextBox.text = sifre.ToString();
LoginPanelleri[0].SetActive(true);
break;
case 2:
LiseKadiTextBox.text = isim.ToString();
LiseKsifreTextBox.text = sifre.ToString();
LoginPanelleri[1].SetActive(true);
break;
case 3:
UniversiteKadiTextBox.text = isim.ToString();
UniversiteKsifreTextBox.text = sifre.ToString();
LoginPanelleri[2].SetActive(true);
break;
}
}
And here is the rememmer me button:
public void BeniHatırlaButon()
{
PlayerPrefs.SetInt("BeniHatirla", 1);
switch (PlayerPrefs.GetInt("OgrenimDurumuBelirleme"))
{
case 1:
PlayerPrefs.SetString("BeniHatirlaIsim", OrtaOkulKadiTextBox.text.ToString());
PlayerPrefs.SetString("BeniHatirlaSifre", OrtaokulKsifreTextBox.text.ToString());
break;
case 2:
PlayerPrefs.SetString("BeniHatirlaIsim", LiseKadiTextBox.text.ToString());
PlayerPrefs.SetString("BeniHatirlaSifre", LiseKsifreTextBox.text.ToString());
break;
case 3:
PlayerPrefs.SetString("BeniHatirlaIsim", UniversiteKadiTextBox.text.ToString());
PlayerPrefs.SetString("BeniHatirlaSifre", UniversiteKsifreTextBox.text.ToString());
break;
}
}
If you're running some debugger, it may be missing out on when it actually saves the values to disk. From the documentation for PlayerPrefs:
By default Unity writes preferences to disk during OnApplicationQuit(). In cases when the game crashes or otherwise prematuraly exits, you might want to write the PlayerPrefs at sensible 'checkpoints' in your game. This function will write to disk potentially causing a small hiccup, therefore it is not recommended to call during actual gameplay.
So if you are exiting the application prematurely through debugging it may be that you just need to call PlayerPrefs.Save() right after you try to write the values.
Related
I'm a complete Newbie to the world of programming, yet I really wish to learn a lot as quick as possible and now came up to a problem that I can't find to solute just via researching and "learning- by doing" (Trying around).
Basically I'm trying to work on a small console- based TextAdventure in C Sharp (With VisualStudios) Now I came to a Case- Switch (Offering the User some Options to read and walk through), but I wish to add a Y/N Confirmation in case the User decides to take a different path. For now it's only for the starting point of the story:
Does the User want to go into "The Wilds", "The City", "The Farm". Something as simple as that just in addition: "Are you sure (Y/N)?" leading the No to return the given choices.
Thank you all in advance and stay healthy!
Menu mainMenu = new Menu(prompt, options);
int selectedIndex = mainMenu.Run();
switch (selectedIndex)
{
case 0:
EnterTheWorld();
break;
case 1:
VisitTheMemorial();
break;
case 2:
TakeYourLeave();
break;
default:
break;
}
}
private void TakeYourLeave()
{
WriteLine("\nYou are about to take your leave... Are you sure ? (Y/N)");
ReadKey();
Environment.Exit(0);
}
private void VisitTheMemorial()
{
Clear();
//FILLER//
WriteLine("You may proceed by the press of any button.");
ReadKey(true);
RunMainMenu();
}
private void EnterTheWorld()
{
string prompt = "Where would you like to start your journey?";
string[] options = { "The Slums", "The Wilds", "The City", "The Farm" };
Menu startMenu = new Menu(prompt, options);
int selectedIndex = startMenu.Run();
BackgroundColor = ConsoleColor.White;
switch (selectedIndex)
{
case 0:
ForegroundColor = ConsoleColor.Black;
WriteLine("\n ||Small Description||Are you sure to take this path? (Y/N)");
break;
case 1:
ForegroundColor = ConsoleColor.Green;
WriteLine("\n ||Small Description||Are you sure to take this path? (Y/N)");
break;
case 2:
ForegroundColor = ConsoleColor.Red;
WriteLine("\n ||Small Description||Are you sure to take this path? (Y/N)");
break;
case 3:
ForegroundColor = ConsoleColor.Yellow;
WriteLine("\n ||Small Description|| Are you sure to take this path? (Y/N)");
break;
}
In this case, you need to take care of a few things:
Make sure that the entire switch-statement logic is in a while-loop, as such:
while (True) {
int selectedIndex = mainMenu.Run();
switch (selectedIndex)
{
case 0:
EnterTheWorld();
break;
case 1:
VisitTheMemorial();
break;
case 2:
TakeYourLeave();
break;
default:
break;
}
}
Check with your function if the input given is "No", if such, then immeditely return so your function exits before any navigation
private void VisitTheMemorial()
{
userInput = readKeyFunction();
if (userInput == "no") {
return;
}}
Finally, if the user doesn't select no, just do nothing and let the function go on
It is best to handle the 'Are you sure?' inside the menu.Run(), and return a value to the selectedIndex after the confirmation. Also avoid using while loop at the main flow in this case.
Note: you have to think in a modular way. Consider your Menu class as a module which handles user choice. The main flow does not have to bother about the confirmation by the user, it just have to process the final result of the user.
Another suggestion: Use enums instead of integers wherever possible for multiple choices.
So I'm working on a Switch-Case menu for my program but I'm having multiple issues (I'm probably missing something real obvious here)
So first off I'm trying to implement a while loop to make it possible to return to the menu after executing any of the case methods. However when trying to implement a while loop it doesn't seem to recognise my bool variable for some reason.
Secondly I'm not quite sure how to make it so the user can return to the start menu after they've done what they want to do in the case they've chosen, this probably has a real easy solution, but I just can't find one.
[code]
private string[] säten = new string[24];
private int Antal_passagerare = 0;
public void Run()
{
bool continue = true;
while(continue)
{
string menu = (Console.ReadLine());
int tal = Convert.ToInt32(menu);
switch(tal)
{
case 1:
Add_passagerare;
break;
case 2:
break;
case 3:
break;
}
}
}
[/code]
Your problem is that your local variable name conflicts with the C# keyword (or statement) continue which controls the flow of a loop (e.g. for, foreach, while, etc). Another control flow keyword is break.
You must rename the local variable. But because of the flow control keywords you can drop the local variable (see below). Also use Int32.TryParse to avoid your program from crashing, if the user inputs a non numeric value. In this context you can see the statements continue and break at work:
// Start an infinite loop. Use the break statement to leave it.
while (true)
{
string userInput = Console.ReadLine();
// Quit if user pressed 'q' or 'Q'
if (userInput.Equals("Q", StringComparison.OrdinalIgnoreCase)
{
// Leave the infinite loop
break;
}
// Check if input is valid e.g. numeric.
// If not show message and ask for new input
if (!(int.TryParse(userInput, out int numericInput))
{
Console.WriteLine("Only numbers allowed. Press 'q' to exit.");
// Skip remaining loop and continue from the beginning (ask for input)
continue;
}
switch (numericInput)
{
case 1:
break;
case 2:
Add_passagerare();
break;
case 3:
break;
}
}
I am creating a dialog system on unity where the user has options to select from and either gets a response via a text field or gets more options to choose from.
At first i have 3 options. These 3 options belong to a script and another 2 options belong to another which are both running simultaneously. Each option has an int index(first option = 0 , second option = 1 etc..). I have made it so that if i press on option 1, the index becomes 3 to go to the fourth option.
As i have put everything in Update to wait for key input by user, whenever the user presses Enter, it gets executed from both of the scripts so it enters both statements at once.
Whats happening basically when i select option 1, im getting the response of option 4 instantly because when i press enter it gets executed from both scripts
How can i make it so that when i press enter for option 1 it ignores the other statement please. Screenshots below.
if (Input.GetKey (KeyCode.Return)) {
if (indexConversation == 0) {
Debug.Log("first Option");
// GameObject.Find("Scripts2").SetActive(true);
telResponse.text = "Response 1";
Conv1Controller.Conv1showConversation = true;
indexConversation = 3;
Debug.Log (indexConversation);
} else if (indexConversation == 1) {
Debug.Log("second Option");
telResponse.text = "Response 2";
StartCoroutine(responseTwoFollowedbySix ());
}
else if (indexConversation == 2) {
Debug.Log("third Option");
telResponse.text = "Response 3";
StartCoroutine(responseThreeFollowedbyFourFollowedbySeven ());
}
showConversation = false;
}
The other script (option 4 and 5)
if (Input.GetKey(KeyCode.Return))
{
if (DialogueController.indexConversation == 3)
{
Debug.Log("Fourth Option");
telResponse.text = "Response 4";
}
if (DialogueController.indexConversation == 4)
{
Debug.Log("Option 5");
telResponse.text = "Response 5";
}
//Conv1showConversation = false;
}
Considering your first script has a indexConversation variable and your second script seems to refer to it using DialogueController.indexConversation, I feel like this variable is a public static int one. In this situation you could simply do something like this:
First script
[SerializeField]
private YOUR_OTHER_SCRIPT_CLASS otherScript;
if (Input.GetKey(KeyCode.Return))
{
showConversation = false;
switch(indexConversation)
{
case 0:
Debug.Log("first Option");
telResponse.text = "Response 1";
Conv1Controller.Conv1showConversation = true;
indexConversation = 3;
Debug.Log (indexConversation);
break;
case 1:
Debug.Log("second Option");
telResponse.text = "Response 2";
StartCoroutine(responseTwoFollowedbySix ());
break;
case 2:
Debug.Log("third Option");
telResponse.text = "Response 3";
StartCoroutine(responseThreeFollowedbyFourFollowedbySeven ());
break;
default:
otherScript.ReturnKeyPressed();
break;
}
showConversation = false;
}
Here I added a variable to reference your other script and used a switch instruction to avoid the many if and else if.
Also if the value of indexConversation is not 1, 2 or 3, you ask for your other scrip to do something.
Other script
public void ReturnKeyPressed()
{
switch(DialogueController.indexConversation)
{
case 3:
Debug.Log("Fourth Option");
telResponse.text = "Response 4";
break;
case 4:
Debug.Log("Option 5");
telResponse.text = "Response 5";
break;
default:
break;
}
}
In this script, there is no more if (Input.GetKey(KeyCode.Return)) since the input detection will be made in the first script and send to this script if needed.
P.-S.
As #Programmer said, you should never use OnGUI() for anything else than debugging. This method is really heavy as it's called many times per frame (which is useless) and you can use Unity UI System to work with UI easily.
As #Nabren suggested, if your system is more complexe than this simple case, you should really change the way it's made and have an input manager class that get inputs and send them to the appropriate scripts.
Hope this helps,
You should really think about storing your conversations into a Model that have a link to responses and responses can link to specific "FollowUp" conversation. This way you can write the script as agnostic as possible. You just give it a response and it knows how to handle it. Each response would get its own "ResponseView" Script which takes in a response model and could add button listeners or key listeners for press events and then upon receiving the correct input would load the next conversation using its current response model. Writing specific methods in code to tell your responses where they need to go is very very fragile and will not scale well at all.
I am making a very simple multiple choice console game. I have created a finite state machine using enums and if else states all within a while loop (while game = true).
The issue is, inside of the class level.level1 (contains level info) it needs to change myState to the new state which is in the main program, but it can't impact it. Any ideas on how to make this happen? I'm stumped.
var game = true;
while (game = true)
{
State myState = State.intro;
//first level
if (myState == State.intro)
{
level.Intro();
}
else
{
if (myState == State.contact1)
{
Console.WriteLine("Wroked");
}
in the level class:
Console.WriteLine(name + " What are you doing, I need your help!");
Thread.Sleep(1000);
Console.WriteLine("\nA. Who is this? \nB. How are you doing this?\nC. How do you know my name?");
var res = Console.ReadLine();
char response = res[0];
switch (response)
{
case 'a':
State myState = State.contact1;
break;
case 'b':
Console.WriteLine("\nright");
break;
case 'c':
Console.WriteLine("\nleft");
break;
}
There's obviously more code than this, but that's the important part. you can see full code here:
https://gist.github.com/MajorMojo/700936c02f1430de44b4559f0579917d
https://gist.github.com/MajorMojo/5bba21cb977a4b768029e765a0d74886
you either need to pass a game object into the level class or make some static variables.
I would do the first one and have a GameEngine class that is created by main and maintains the overall state of the game. It can have a SetState method (or State property). Pass the GameEngine object into the level when you create it.
I would suggest starting with a basic intro to programming tutorial. The C# one isn't too bad: https://msdn.microsoft.com/en-us/library/aa664628(v=vs.71).aspx
You're missing a lot of basic concepts. It would be a lot easier for you to pick them up by working through a complete tutorial than by asking individual questions here.
I tried this:
if(PauseButton.Image != global::GripAIConsole.Icons.Resume)
{
PauseButton.Image = global::GripAIConsole.Icons.Resume;
ToolTipMainWin.SetToolTip(PauseButton, "Resume / Step <F4>");
}
And it doesn't work. I would have thought it was comparing pointers internally to see if they were pointing at the same place.
You are working with resources, so if you want to make sure the reference is right, compare using the static method Object.ReferenceEquals(). As ChrisF said, you should not use this to determine application logic. Using a simple bool variable is much better (and slightly more performance friendly).
I would define the possible states with an enum:
public enum State {
Stopped,
Pausing,
Running
}
And then define a state property or variable:
State _state;
then Change the states as follows:
void ChangeState(State newState)
{
_state = newState;
switch (newState) {
case State.Stopped:
PauseButton.Image = global::GripAIConsole.Icons.Pause;
ToolTipMainWin.SetToolTip(PauseButton, "Start game <F5>");
break;
case State.Pausing:
PauseButton.Image = global::GripAIConsole.Icons.Resume;
ToolTipMainWin.SetToolTip(PauseButton, "Resume / Step <F4>");
break;
case State.Running:
PauseButton.Image = global::GripAIConsole.Icons.Pause;
ToolTipMainWin.SetToolTip(PauseButton, "Pause <F4> / Stop game <F6>");
break;
}
}
... or whatever your logic requires.
This is much cleaner and understandable. A picture has to do with the GUI, not with the logic. Inferring the state of the logic from things displayed on the forms is weird.