How to_ Enter Password to enter cell code

Ive seen it on other games. I know what it is I want to do, but I dont know what it is called or how to look it up.

I want to have it where if the reader puts the correct 3-digit code they can enter, if incorrect- get sent to an alternative state.

(I typically hat asking for help, but I am unsure of what wording to use when searching on the googles)

1 Like

What games was this featured in and could you post an image of it. I’m sure that we can figure it out.

1 Like

I’m not sure whether this is for Unity or not, but it feels like it might be related to the Text101 game.

You could consider a input field. An alternative might be to have something tell the user to enter * followed by the code. Then, in your code you could store each key press in an array, but only the last 4, then check to see if the last 3 digits after the * are equal to your code. The first approach may well be a bit simpler if you are not overly familiar with code, or go for the second if you want to stretch yourself a bit :slight_smile:

Hope this helps, oh and let me know if this was for Unity / Text101 and I’ll move the post for you.

1 Like

what the-!? i thought this was in the text 101 forum…

i think i had too many links open and got a bit confused. but yes, this is fr the text adventure class.

i just wanted the reader to have the ability to enter a 3 digit code into the keypad. if they got it correct they go on to state_1, and if they entered anything other than the correct one (an incorrect entry) they’d see state_2 (whatever it is i set those to be)

ill look up the input.field codes on msdn(even though im on a mac…)

hopefully, in a few hours, ill have everything i need to just write the code in real quick (the flow chart is my sketch pad for the whole thing.)

THANKS AGAIN!
if it works, ill fix it to [SOLVED] when/wherever the post ends up :smiley:

Aha! I’ll move it across, you will still be able to find it under you posts.

The link to the InputField Unity documentation was in my reply by the way.

I have thrown together this quick example for you, it covers the basics and you can improve on it enormously, but it will get you started. I have created it in a separate scene so there is less going on, give me a shout if you have any problems. :slight_smile:



GameController.cs

using UnityEngine;
using UnityEngine.UI;

public class GameController : MonoBehaviour
{

    // private field to hold our secure code
    private string _secureCode;

    // public field to reference our security panel (InputField)
    public InputField _securityPanel;

    // public field to reference our message to our user (Text)
    public Text _message;

    /// <summary>
    /// Initialise
    /// </summary>
    private void Start()
    {
        Initialise();
    }

    /// <summary>
    /// Initialises GameController
    /// </summary>
    private void Initialise()
    {
        _secureCode = "41RM";   // enter code of your choice
    }

    /// <summary>
    /// Checks to see if the entered code and secure code match
    /// </summary>
    public void CheckSecurityCode()
    {
        string attemptedCode = _securityPanel.text;

        if(attemptedCode == _secureCode)
        {
            _message.text = "The code is correct, the door opens!";
        }
        else
        {
            _message.text = "The code is wrong!  Bells are ringing... you have alerted the guards!";
        }
    }
}

Hope this helps…


Updated Wed Jan 04 2017 17:57

GitHub Repository - see Example_Projects / UI / InputField - Unity 5.4.1f1

1 Like

Hey Rob, I liked the youtube video very much. (oddly, the lack of sound made it easier to follow)

I started to follow the directions (but also, very slowly) and trying to understand what to write, where and when.

I always come to the conclusion that its just a matter of writing it over and over until memorizing or understanding the syntax.

Here is a paste of my first Text101 prior to the video that lets you build on it

http://pastebin.com/tkub28JR

Im still messing around with the images/sprites situation, but my concern is with the InputPasscode. im at the point where you put it in the start function(syntax?) around 5:15 on the video you provided, but since I would like this to come up at a later state-not at the start, and certainly not always on scree- I thought that it needed to be at an else if statement, but when I tried that it (obviously, now) doesnt work.

Thank you, again for your input :wink:

Hey, it was posted in one of the Text101 “try my games” section. (or at least thats what I see on the bottom of my screen when on this site) if I find it again, I will reply here with the link.

Hi,

Glad to hear the video was useful, I removed the sound because it was mainly me typing, clicking the mouse, coughing, and the odd passer by crashing around in the kitchen :slight_smile:

Regarding the code you’ve pasted up, I see you have implemented the Start() method from my example, you don’t need to have two of these, simply add the Initialise() method call to you existing Start() method (I’m actually surprised this didn’t error).

void Start() {
    Initialise();
    myState = States.cell;
}

In the example the only thing which is called from the Start() method is the Initialise() method, which in turn populates the value for the secure code - you could potentially do this anywhere at the start of your game, even at the top of your script, as long as it occurs before you need to compare the value. I I prefer to have a method like this which is responsible for setting things up at the start of a game.

So, what I think you are saying is the problem is that the InputField is showing in your game before you really want it to, e.g. it’s asking for the code before you arrive at that specific state and story text.

So, what you could do is place the InputField control, along with it’s dependants into a panel object. Then, at the start of the game, hide it. When you arrive to the relevant part of the story, un-hide it. You may have to figure out the best place to position it, but that shouldn’t be too hard, just drop it in the scene initially below where the longest part of the text in your story appears.


Steps:

  • Add a UI.Panel GameObject to the Scene

  • Click on the Color property within the Image component of Panel and set the Alpha of Panel to 0

  • Rename Panel to SecurityPanelContainer within the Hierarchy

  • Within the _Hierarchy, _Drag SecurityPanelContainer into Canvas, making it a child of Canvas

  • Within the Hierarchy drag SecurityPanel into the SecurityPanelContainer, making it a child of SecurityPanelContainer

  • Update GameController.cs as follows;


using UnityEngine;
using UnityEngine.UI;

public class GameController : MonoBehaviour
{

    // private field to hold our secure code
    private string _secureCode;

    // private field to reference eour security panel
    private InputField _securityPanel;

    // public field to reference our security panel container (Panel)
    public GameObject _securityPanelContainer;

    // public field to reference our message to our user (Text)
    public Text _message;

    /// <summary>
    /// Initialise
    /// </summary>
    private void Start()
    {
        Initialise();
    }

    /// <summary>
    /// Initialises GameController
    /// </summary>
    private void Initialise()
    {
        _securityPanelContainer.SetActive(false);       // container is now set it inactive and is hidden 
        _securityPanel = _securityPanelContainer.GetComponentInChildren<InputField>();  // grab the InputField
        _secureCode = "41RM";   // enter code of your choice
    }

    /// <summary>
    /// Checks to see if the entered code and secure code match
    /// </summary>
    public void CheckSecurityCode()
    {
        string attemptedCode = _securityPanel.text;

        if(attemptedCode == _secureCode)
        {
            _message.text = "The code is correct, the door opens!";
        }
        else
        {
            _message.text = "The code is wrong!  Bells are ringing... you have alerted the guards!";
        }
    }

    /// <summary>
    /// Update
    /// </summary>
    private void Update()
    {
        if(Input.GetKeyDown(KeyCode.C))
        {
            _securityPanelContainer.SetActive(true);    // container is now set to active and appears
        }
    }
}

  • Within the Hierarchy select GameController

  • From the Hierarcy, drag the SecurityPanelContainer GameObject into the Security Panel Container field within the Game Controller script component


When the game runs, the UI.Panel is hidden, as are all of it’s child objects.
Press “C” on the keyboard and it will re-appear

Enter the code 41RM as before to get the “success” message, or something else for the “failed” message.

You can extrapolate the parts of the code you need from this example. The pressing “C” is effectively your if statement to see if you are at the correct state, if you are - show the panel.

I have committed these changes to the git repository so you can grab the full project, unfortunately I didn’t have time this evening to produce another video - if you need any further help let me know.

1 Like

I’ve done quite a bit (even though my question is still with something early on in the instructions)
you say:

Rename Panel to SecurityPanelContainer within the Hierarchy

Within the Hierarchy, _Drag SecurityPanelContainer into _Canvas, making it a child of Canvas

Within the Hierarchy drag SecurityPanel into the SecurityPanelContainer, making it a child of SecurityPanelContainer

But no matter what I do Panel (Rename to SecurityPanel) it never has the dropdown menu, but then again, i thought i renamed Panel to SecurityPanelContainer… Unless you meant rename InputField as SecurityPanel and drag THAT into SecurityPanelContainer?

Here’s what I see:

I was going to do it… but I kind of dont want to make so many changes that there is a point of no return(or undo)

Secondly. In my screenshots, you can see my Assets… Should I ALSO have GameController Asset? Can I just change the code in TextController? (I was under the understanding that a TextController is just a description of a GameController that is text driven… again, im very green behind the ears(new).

I suppose ill Paste my current MB content as well…

http://pastebin.com/tkub28JR

I highlighted the parts I think I need help with. (in the story there will need to be 3 ,maaaaayyyybe 4, codes to be entered.) I know this probably looks like a *&$%show, but I trying :smiley:

(On lines 50-55, as you can see, im using the sort of logic that was meant in the if then statements to see if i can push the user in a direction depending on their securitycode. As is, I dont think its working, lol.

I appreciate any/all help, as usual :hamburger:

Yes, the latter, the post above builds upon what I’d originally put together for you… so, in the first example we added a new GameObject (InputField) and renamed it to SecurityPanel. It was this object which contained the Placeholder and Text objects, and it is this which needs to be within the SecurityPanelContainer. I think part of the issues is the re-use of the word panel in the example, as it refers to both the Type of game object and also the noun in your game - my bad…

So, you are aiming for;


  • Canvas
    • SecurityPanelContainer (type of UI.Panel)
      • SecurityPanel (type of InputField)

If it helps, rename everything call SecurityPanel to KeyPad or something like that, so it makes a bit more sense for you :slight_smile:

Here’s what I see:

Yep, so in that green screenshot, delete the object called SecurityPanel, then rename InputField to SecurityPanel and you will have the correct hierarchy and names.

You don’t need to have the GameController object. As I mentioned in my other post, you can simply extrapolate the bits of code you need into your own game, the GameController object was merely for the example I put together for you. In the same way you wouldn’t need a UI.Text GameObject called Message because in your game you already have UI.Text object which displays the story to the player :slight_smile:

Both TextController and GameController aren’t really anything special in their own right, they are simply GameObjects with a script attached. It’s what’s in the script that will effect your game etc.

I really wouldn’t worry too much about how things may look just yet, what’s more important is understanding what’s going on, tidying up some code (refactoring) afterwards is another step :slight_smile:

To answer your question in comments on line 58, yes. You don’t need to actually display a message to the user in the way I did in my example if the outcome if the if...else statement is true, you could just set a variable as you have been with you states so far, e.g. myState = States.DoorUnlocked; etc.

Also, in my example I was merely using a “code is correct” / “code is incorrect” scenario, it looks like you want to give the player 3 options… so instead of using if...else statements you could use a switch statement, which may make it a little easier to read for you and to follow…


Switch Example;

switch (attemptedCode)   // pass in what you want to evaluate
{
    case _secureCode_0:
       myState = States.your_relevant_state;  // put the appropriate _state_ here
        break;
    case _secureCode_1:
       myState = States.your_relevant_state;  // put the appropriate _state_ here
        break;
    case _secureCode_2:
       myState = States.your_relevant_state;  // put the appropriate _state_ here
    default:
        myState = States.your_relevant_state;  // put the appropriate _state_ here
        break;
}

In the above, add your correct states as per my comments for each code variant.

default: can be used for the scenario where your player entered something other than the three specific cases you are testing for… so you could have another state which ends up returning a message to the player which says “I don’t know what you were thinking, but the door remains locked.” etc. Equally, you could just remove that part.

break; indicates where the block of code for each of the cases ends, so if you wanted to do something else as well as setting the state for each item (perhaps keeping a count of how many times they had got the code wrong), you could add this before the break; statement on the relevant case statement.

You can do this with if.. statements also, you just end up with something that has lots of else if.. statements, no significant differences for you at this point other than perhaps readability.


if (attemptedCode == _secureCode_0) {
   myState = States.your_relevant_state;  // put the appropriate _state_ here
} 
else if (attemptedCode == _secureCode_1) {
   myState = States.your_relevant_state;  // put the appropriate _state_ here
} 
else if (attemptedCode == _secureCode_2) {
   myState = States.your_relevant_state;  // put the appropriate _state_ here
}
else {
   // none of the above conditions were met, so perhaps you do something different
   myState = States.your_relevant_state;  // put the appropriate _state_ here
}

In the above, the else at the end of the block is the same as the default in the switch example, e.g. if none of the other conditions are met, do this…

Give me a shout if you need anything else :slight_smile:

Hey @Rob,

So I know i have been silent for a very long time, but I was doing a lot of re learning. This is the fruit of my labor so far. It still isnt working correctly, but at least I got this far. I also used GitHub, I think i messed up somewhere. I think I overwrote the master (but thats okay because I got rid of a lot of what i think was unnecessary code).

Still need to learn how to use GitHub correctly, so I am making additions to the project instead of just overwriting everything.

The Goods.

I literally cannot wait to be able to make a point-and-click adventure…

Thanks again

-mne

2 Likes

Hiya,

Glad to hear things are going well and well done on giving Git a go, that’s great progress. If you look through your revision history for the repository chances are you haven’t overwritten anything, you should still be able to get back out any specific revision from the past. :slight_smile:

If you are still interested in the input key code stuff let me know when you are ready :slight_smile:

1 Like

t worked. I spent the past (12-14?) hours reading, attempting, and installing/reinstalling of a lot of version of different apps. I essentially had to start from scratch to fix the problems, but at least now T can just copy and paste the code that T know DOES work and weed out the garbage. It was a small battle. The war is still not over. :wink:

I am Tres Tired and am about to pass out, I will update you as soon as I update my git :smiley:

(next on the list is making the panel disappear when not in use- and i know exactly where you gave me the answer to that)

-mne

1 Like

Sounds like lots of progress.

What were you having to install / uninstall?

What’s T?

Updated Sun Feb 26 2017 10:19

Ah, “T” is the keypress I’m guessing…

@Rob
At 5 am my decrepit brain was trying to type “IT WORKED!” except “t worked.” (a much less exciting and communicative way) I am awake now, and am going to get started on hiding the security panel.

-mne

1 Like

Lol… ! Gotcha… re-reading your post know that makes more senae now… hehe…

Well done for persevering, I look forward to having a go on your game and using this security panel in due course. :slight_smile:

(OFF TOPIC: Settler of Catan is by far one of the best games out there and the story of the inventor is pretty awesome. Gives hope for ALL game makers of ALL kinds out there, digital and analog. Unfortunately the type of people you need to play it are very far and few in between. I wish you much luck in your board gaming endeavors, and if you’re ever int eh states come and knock on my door for an evening of arguing and taking land from each other ;D)

OKOK-Back to the grind for real :smiley:

1 Like

Hehe… thanks for the invite… I bought the board game the other week as it was finally a better price on Amazon… what I now lack is anyone to play it with… my son is more into Rainbow Six Siege on his XBox at the moment… turns out there are no “Sad Sack One Player” instructions :smiley:

@Rob,

So Ive made and remade my repository a few times (its been messy), and this is the most up to date that I have. The keycode DID work for a short period of time, but over the course of working it into the rest of the code (IE @ Line177) I started getting errors from the Unity app.

NullReferenceException: Object reference not set to an instance of an object
TextController.CheckSecurityCode () (at Assets/Scripts/TextController.cs:56)
UnityEngine.Events.InvokableCall.Invoke (System.Object args)
UnityEngine.Events.InvokableCallList.Invoke (System.Object parameters)
UnityEngine.Events.UnityEventBase.Invoke (System.Object parameters)
UnityEngine.Events.UnityEvent`1[T0].Invoke (.T0 arg0)
UnityEngine.UI.InputField.SendOnSubmit () (at /Users/builduser/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/InputField.cs:1338)
UnityEngine.UI.InputField.DeactivateInputField () (at /Users/builduser/buildslave/unity/build

I get that its pointing to line 56, and that is where I have the CheckSecurityPanel() method, but why all of a sudden now it is not working?

Also, I know it is asking a lot, but typos aside (like the story part, in the quotes) is how I am using the string “attemptedCode” making any sense? I feel like there might be a way to declare it in the beginning so I dont have to keep using it in every method, but when I tried to give it a static keyword i just got more errors, so I put it back to normal.

I am happy that I am able to hide and show the panel, and ive done a little searching and saw maybe there is a way to use the key to toggle the bool, instead of just setting it ? (so for instance on line 72:

if 		(Input.GetKeyDown(KeyCode.C)) 						{securityPanelContainer.SetActive(true);}  // container is now set to active and appears

C will show me the panel (awesome), but now its there for eternity. Is it possible to have it where, lets say, the user enters a 3 digit code and hits enter (or presses R to return back to the previous state- circumstances permitting) and the panel then automatically hides again?
Would I need to set the enter key to toggle it back to false so it hides, and if so… is it as simple as adding another if (input…) statement?

Okay, hoping to catch ya before bed, but no worries if I missed ya.

Thanks again,

mne

(PS: this may or may not matter at all, but why does my code on github (when I open the script) look all whacky, but on the IDE look all neat? Are all those un-cleaned spaces?)

Final note added to the top of my reply : This is a lengthy response with quite a few steps… take your time! :slight_smile:


Hi,

I saw this last night but was fairly tired and didn’t think I could give my best response, so waited until this morning, sorry for the delay.

Well done for persevering with Git / GitHub, the more you use it the more straight forward it will become. If you are using the console and typing in the commands I would recommend having a look at a GUI client at some point as this will make things easier (GitKraken is free and seems fairly good, although there are others too).

One minor issue I had was that I don’t think you have included the project files in your repo, so I wasn’t able to just open it in Unity, no biggy, it was only the code file I really needed to see, so I created a copy of the Text101 project at this end and then swapped out the TextController.cs and scene files with yours to get it up and running. :slight_smile:

I don’t have the steps to repeat the problem you have explained above, so I’ve had a poke around.


TextController.cs;

  • You have a trailing comma in your States enumeration after the last item.
  • You have 53 States values, yet only 19 corresponding methods. It might be better to add them as you need them to avoid leaving items you don’t need/use (e.g. States.freedom)

Playing the Game / Reproducing the Error;

  • I chose to look at the mirror, took the mirror, then looked at the lock - I died.
  • Restarted
  • I chose to look at the lock, it told me immediately that I had entered the wrong code, it was now broken, and I died in my cell.
  • Restarted
  • I looked at the sheets, tore some off to make the bandage, took the mirror, looked at the locked, it told me immediately that I had entered the wrong code, it was now broken, and I died in my cell.

Following the code through, that is because of this method;

	void lock_1a()
	{
		text.text = "Looking in the mirrors reflection you see crusty brown fingerprints on the " +
					"numbers '1' and '0'... as well as the surrounting panel. \n\n" +
					"Press L to enter a 3 digit keycode. ";
				
		string attemptedCode = securityPanel.text;
		if 		(attemptedCode == secureCode) 			{myState = States.freedom;}
		else 											{myState =States.death_0;}
	}

Specifically, the bottom if statement, as soon as this state becomes true you are checking to see whether the attemptedCode is equal to the secureCode, which it can’t because the player hasn’t been given an opportunity to enter anything yet. Although you are checking within the Update() method to see if C has been pressed but the above method fires and puts us into the death state, before we even get chance to read the writing, or realistically have chance to press C.

So, what do we do… well, we need a way of stopping the security code validation firing before we want it to. The clue here is in your story text, “Press L to enter a 3 digit keycode.”, lets use that!

void lock_1a()
{
    text.text = "Looking in the mirrors reflection you see crusty brown fingerprints on the " +
                "numbers '1' and '0'... as well as the surrounting panel. \n\n" +
                "Press L to enter a 3 digit keycode. ";

    // activate the keycode data entry
    if (Input.GetKeyDown(KeyCode.L))
    {
        securityPanelContainer.SetActive(true);
    }
}

So, if they get to this state and press the L key we can set the securityPanelContainer as active, thus making it appear. Great!

But hang on, lets see if we are setting it to appear anywhere else also… Yes! In your first story item, in this method;

void cell_0()
{
    text.text = "Disoriented, you wake up in a cell with not a sound to be heard. " +
                "Your surroundings dictate that escape is essential for your survival. " +
                "There is a bed behind you made with filthy sheets, " +
                "a mirrior on the wall, and a locked door.\n\n" +
                "Press S to view Sheets, M to view Mirror, L to view Lock.";

    if (Input.GetKeyDown(KeyCode.S)) { myState = States.sheets_0; } // checks out
    else if (Input.GetKeyDown(KeyCode.M)) { myState = States.mirror_0; } // 
    else if (Input.GetKeyDown(KeyCode.L)) { myState = States.lock_0; securityPanelContainer.SetActive(true); }  // container is now set to active and appears
}

So, that bottom else if statement, when they view the lock without having the right items. But now that we are setting it to appear in the right place we can remove this, so, update this method to reflect this;

void cell_0()
{
    text.text = "Disoriented, you wake up in a cell with not a sound to be heard. " +
                "Your surroundings dictate that escape is essential for your survival. " +
                "There is a bed behind you made with filthy sheets, " +
                "a mirrior on the wall, and a locked door.\n\n" +
                "Press S to view Sheets, M to view Mirror, L to view Lock.";

    if (Input.GetKeyDown(KeyCode.S)) { myState = States.sheets_0; } // checks out
    else if (Input.GetKeyDown(KeyCode.M)) { myState = States.mirror_0; } 
    else if (Input.GetKeyDown(KeyCode.L)) { myState = States.lock_0; }
}

Ok, so far so good, lets see if there is anywhere else we make the panel appear. Yes! In the Update() method;

// Update is called once per frame
void Update()
{

    if (Input.GetKeyDown(KeyCode.C)) {securityPanelContainer.SetActive(true);}  // container is now set to active and appears

    // note I have not pasted the whole method here as it has all of your `if` statement logic`
}

Now, lets have a think, what we are saying here is “Every frame, regardless of the state we are in, if the player press C lets make the security panel appear”

We don’t need that now because we are going to check in the correct state for the key press (L now).

So lets remove that line completely from your Update() method. Gone!

Adding a quick horizontal break for a gasp of breath and a sip of my drink…


Ok, so now, if I run the game and choose these options, in this order;

S, T, M, B, M

I am reading the correct text and nothing is automatically submitted. I now press L and the InputField appears for me to type in.

I have noticed at this stage though that, as a player I have to now click into the InputField, assuming I could see it, so I click roughly on the green text… what might be better is to actually focus the InputField and get the cursor flashing away in there to give the player some direction… lets do that now as we have spotted it.

Back to your method lock_1a() and add this line after activating the panel;

securityPanel.Select();

So, you should now have;

void lock_1a()
{
    text.text = "Looking in the mirrors reflection you see crusty brown fingerprints on the " +
                "numbers '1' and '0'... as well as the surrounting panel. \n\n" +
                "Press L to enter a 3 digit keycode. ";

    // activate the keycode data entry
    if (Input.GetKeyDown(KeyCode.L))
    {
        securityPanelContainer.SetActive(true);
        securityPanel.Select();
    }
}

Note, we are starting to build up a few security panel related statements here, it may be worth at a later stage refactoring these into their own method and simply call that after the key is pressed, lets leave them here for now as we have a lengthy post already! :slight_smile:

Running the game again and with the same sequence of key presses now shows the security panel and places the flashing cursor in the InputField. Great!


Lets now think about how we will get the game to respond to our user entering the code. We could several ways with this, we have already chosen an InputField solution but we could have the game check per key press, or, once the code is entered and the user confirms it. For now we will do the latter as it will require a little less validation and is therefore a little easier to implement, but you could update this later to make it seem much more like pressing buttons on a real keypad.

You already have the following method, but it isn’t being used at the moment for anything, lets hijack it!

public void CheckSecurityCode()
{
    string attemptedCode = securityPanel.text;

    if (attemptedCode == secureCode)
    {
        text.text = "The code is correct, the door opens!";
    }
    else
    {
        text.text = "The code is wrong!  Bells are ringing... you have alerted the guards!";
    }
}

As it stands it is doing some validation, but if we leave it to set text.text this will instantly get changed by the Update() method because we haven’t set any different state here. That would suggest that changing the state here could be useful, and if we are going to change the state, the text would be changed by the corresponding method which handles the individual states, thus we don’t need to set the text here at all. Also, at the moment, your game logic allows for “correct code - move on” or “incorrect code - die”, as such, we can hide the security panel again in here too, because we won’t need it again after this point.

So, here we go…

public void CheckSecurityCode()
{
    securityPanelContainer.SetActive(false); // hide the panel

    string attemptedCode = securityPanel.text;

    if (attemptedCode == secureCode)
    {
        myState = States.freedom_0;
    }
    else
    {
        myState = States.death_0;
    }
} 

As you can see, as soon as we arrive here, we hide the panel, then we check the value of the submitted code and set your state accordingly. The Update() method will then respond as usual based on this state and call the appropriate method.

The only bit we haven’t handled yet is how we get from entering the code, to calling this method as we didn’t call this method from within the key press logic of the lock_1a() method. We could try that, but we would run into problems with the frequency of Update() being run and which characters had been entered at that point by the user, until they were all entered your code wouldn’t be correct, so they would keep being sent down the incorrect route. What we need is some way of handling the “I’ve finished editing this InputField” event…

…and here it is;

securityPanel.onEndEdit.AddListener(delegate { CheckSecurityCode(); });`

Before we put this into your code, lets run through it so you know what its doing…

Firstly we have securityPanel that is your InputField.
Next we have onEndEdit, this is an Unity event
We then call the AddListener() method which enables us to add a delegate, a reference pointer to a method
Finally, the method itself which we want to call CheckSecurityCode()

So, in layman’s terms… “The game will be listening for the onEndEdit event, when it is triggered it will call our CheckSecurityCode method”.

onEndEdit is triggered by pressing Enter or by clicking outside of the InputField, both of these scenarios seem appropriate for our needs.


So where do we put this statement, well, its good practice to put your event listeners at the start of you code, however we want to set it for an component that we are going to find, therefore we want to make sure we have found it first.

Looking at our Start() method we call our Initialise() method, this is the method which gets a reference to our securityPanel, so seems like the best place to me.

private void Initialise()
{
    secureCode = "100";
    securityPanelContainer.SetActive(false);       // container is now set it inactive and is hidden 
    securityPanel = securityPanelContainer.GetComponentInChildren<InputField>();  // grab the InputField

    securityPanel.onEndEdit.AddListener(delegate { CheckSecurityCode(); });
}

Ok - that was a lot of reading… so, lets have some fun…

Run the game, use the key sequence, S, T, M, B, M, then, press L, the security panel appears. Type in anything other than 100, you’re dead!

Now try that again, but this time enter 100… in the Words of Mel Gibson in Braveheart… “Freeeeeeee-Dommmmmmm”…

:slight_smile:


Some additional tidying up could be useful at this point, you have a number of other methods where you have implemented the check to see if the attemptedCode == secureCode etc (lock_0(), lock_0a()), I think there was at least one method I spotted where you give the option for the game to restart by pressing X also, but without offering that as an option to the player.

I can see that in chapter two you have another scenario where you want to use a security lock. My suggestion would be to implement the above changes, and get your code committed again to source control when you know this part is working as you want.

Then I would considering refactoring out the SecurityPanel code I mention earlier in the lock_1a() method. Place these into their own method and call it. That way all of your initial state based methods are simply telling a story and waiting for key presses for options.

If you get that sorted (for chapter one), I would then commit this to source control again, you now have a clean playing field for chapter two.

There shouldn’t be any reason why you can’t use the same approach for the next secured door. You would need to update the CheckSecurityCode() method, as current it sets states that are only relevant for the first chapter.

It would also be good to spend some time on reviewing the access modifiers on your variables and methods. I know some of this was pasted in from my other code example, but worth doing so that you know what is accessible to what, e.g. private / public.

Hope this is all of use :slight_smile:


See also;