HELP! How do I add image to each states for my text adventure game?

( Sorry for my bad english) So I’m following the text 101 tutorial of the Complete C# Unity Game Developer 2D course and I want to add images to my game. I want the image to be displayed and change every state but it fails. I tried doing it myself but it doesn’t show anything in the game screen
Hers’s my code:

AdventureGame.cs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
//using UnityEngine.UIElements;

public class AdventureGame : MonoBehaviour
{
    [SerializeField] Text textComponent;
    [SerializeField] State startingState;
    public SpriteRenderer spriteRenderer;

    
    State state;

    void Start()
    {
        state = startingState;
        textComponent.text = state.GetStateStory();
    }

    void Update()
    {
        ManageState();
    }
   
    private void ManageState()
    {
        var nextState = state.GetNextState();
        for(int i=0;i<nextState.Length;i++)
        {
            if (Input.GetKeyDown(KeyCode.Alpha1+i))
            {
                state = nextState[i];
                spriteRenderer.sprite = state.GetStateImage();
            }
        }
    spriteRenderer.sprite = state.GetStateImage();
    textComponent.text = state.GetStateStory();
    }
}


State.cs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
//using UnityEngine.UIElements;

[CreateAssetMenu(menuName = "State")]
public class State : ScriptableObject
{
    [TextArea(10,14)] [SerializeField] string storyText;
    [SerializeField] State[] nextState;
    public Sprite storyImage;
    public string GetStateStory()
    {
        return storyText;
    }
    
    public State[] GetNextState()
    {
        return nextState;
    }

    public Sprite GetStateImage()
    {
        return storyImage;
    }
}

Hi,

Welcome to our community! :slight_smile:

I’ve skimmed your code, and you are already on the right track. Instead of SpriteRenderer, try the Image type. In AdventureGame, connect the Image component to the imageComponent variable (or whatever you name it), the same way you did with the Text component.

Arrange the Image component within the Canvas container because it is a UI element like Text.

Did this help?


See also:

Thank you very much!!!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms