Adding image data to the InstructionStep model

From our CSV data, images will be referenced by name. The app will look in the Resources folder for the files. We could use an image URL instead (and that is provided as another column in the CSV data), but, just in case wikiHow changes its article we don't want that to break this book.

The image name is the fourth column in your database (index 3). We can capture it when the file is loaded.

To InstructionStep.cs, add the following:

    public string ImageName; 
private const int ImageColumn = 3;

And then add this to the InstructionStep constructor function:

            if (values.IndexOf(item) == ImageColumn) { 
                ImageName = item; 
            } 

Now we create a UI element component. In your Scripts/UIElements/ folder, create a C# script named ImageGraphic and write the following:

File: ImageGraphic.cs 
using UnityEngine; 
using UnityEngine.UI; 
 
[RequireComponent(typeof(RawImage))] 
public class ImageGraphic : InstructionElement { 
    protected override void InstructionUpdate(InstructionStep step) { 
        if (!string.IsNullOrEmpty(step.ImageName)) {
GetComponent<LayoutElement>().enabled = true; GetComponent<RawImage>().texture = Resources.Load(step.ImageName) as Texture; } else { GetComponent<RawImage>().texture = null;
GetComponent<LayoutElement>().enabled = false; } Canvas.ForceUpdateCanvases(); } }

The script is very similar to the ones we wrote for title, body, and step text. The difference is what we do inside the InstructionUpdate function for an image. If the current step includes an image, we load it as a texture. If not, we clear any image textures that may already be in the UI. We also enable or disable the LayoutElement component to show or hide it as necessary.

Afterwards, we call ForceUpdateCanvases on the canvas to ensure Unity takes the changes right away, in the current frame.

Save the file and add the ImageGraphic script to the Image Graphic UI object in Hierarchy.

In Hierarchy, select the Image Graphic (Instruction Canvas/ Instruction Panel/ Content Panel/ Image Graphic) and drag the ImageGraphic script into Inspector.

OK, now we can import the image files.

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

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