Connecting the model with the controller and UI

Let's see this in action before populating our list with real data. We just need to make a few changes to the InstructionsController script. Namely, the controller will be responsible for telling the model to load its data, get the current instruction step, and display it on the screen.

At the top of the class, we will add variables for the titleText and bodyText UI objects. These will be populated using the Inspector. We also have a currentInstructionModel variable.

File: InstructionsController.cs 
public class InstructionsController : MonoBehaviour { 
    public Text stepText; 
    public Text titleText; 
    public Text bodyText; 
 
    private int currentStep; 
    private InstructionModel currentInstructionModel = new InstructionModel(); 
 

MonoBehaviour allows us to define an Awake() function, which will be run at the very beginning of initialization of our app, before any of the Start() functions are called. In the Awake() function, add a call to tell the model to load its data:

    void Awake() { 
        currentInstructionModel.LoadData(); 
    } 

And then CurrentInstructionUpdate() can do its thing with the current step data:

    private void CurrentInstructionUpdate() { 
        InstructionStep step = currentInstructionModel.GetInstructionStep(currentStep); 
        stepText.text = "Step " + currentStep; 
        titleText.text = step.Title; 
        bodyText.text = step.BodyText; 
    } 
 

Finally, we should check the boundary conditions of the currentStep value since we know it can't go below 0, or be greater than or equal to the size of the steps list:

    public void NextStep() { 
        if (currentStep < currentInstructionModel.GetCount() - 1) { 
            currentStep++; 
            CurrentInstructionUpdate(); 
        } 
    } 
 
    public void PreviousStep() { 
        if (currentStep > 0) { 
            currentStep--; 
            CurrentInstructionUpdate(); 
        } 
    } 

Save the files.

Back in Unity, don't forget to populate the Instruction Controller's Title Text and Body Text slots with your UI elements. The resulting Instructions Controller component is shown ahead:

Now when you press Play in Unity, you can step forward and back through our mock instructions, within the limits of 0 to 2, as shown ahead:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset