Canvases does not show up

Hi there,

My laptop crashed while adding scene manager and when I reopen the file I get this error:

The .meta file Assets/Scripts/GameManager.cs.meta does not have a valid GUID and its corresponding Asset file will be ignored. If this file is not malformed, please add a GUID, or delete the .meta file and it will be recreated correctly

I’ve tried to regenerate project files but I still could not see the canvases in Scene view and I get this error when I compile the codes again:

NullReferenceException: Object reference not set to an instance of an object
Quiz.DisplayAnswer (System.Int32 index) (at Assets/Scripts/Quiz.cs:81)
Quiz.Update () (at Assets/Scripts/Quiz.cs:58)

any suggestions about how to continue through the course? :sweat_smile: :sweat:

using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;

public class Quiz : MonoBehaviour
{
    [Header("Questions")]
    [SerializeField] TextMeshProUGUI questionText;
    [SerializeField] List<QuestionSO> questions = new List<QuestionSO>();
    
    QuestionSO currentQuestion;

    [Header("Answers")]
    [SerializeField] GameObject[] answerButtons;
        int correctAnswerIndex;
    bool hasAnsweredEarly;

    [Header("Button Colors")]
    [SerializeField] Sprite defaultAnswerSprite;
    [SerializeField] Sprite correctAnswerSprite;

    [Header("Timer")]
    [SerializeField] Image timerImage;
    Timer timer;

    [Header("Scoring")]
    [SerializeField] TextMeshProUGUI scoreText;
    ScoreKeeper scoreKeeper;

    [Header("ProgressBar")]
    [SerializeField] Slider progressBar;

    public bool isComplete;


    void Start()
    { 
        timer = FindObjectOfType<Timer>();
        scoreKeeper = FindObjectOfType<ScoreKeeper>();
        progressBar.maxValue = questions.Count;
        progressBar.value = 0;
          
    }

     void Update()
    {
        timerImage.fillAmount = timer.fillFraction;
        if(timer.loadNextQuestion)
        {
            hasAnsweredEarly = false;
            GetNextQuestion() ;
            timer.loadNextQuestion = false;
        }
        else if(!hasAnsweredEarly && !timer.isAnsweringQuestion)
        {
            DisplayAnswer(-1);
            SetButtonState(false);
        }
    }

    public void OnAnswerSelected(int index)
    {
        hasAnsweredEarly=true;
        DisplayAnswer(index);
        SetButtonState(false);
        timer.CancelTimer();
        scoreText.text = "Score: " + scoreKeeper.CalculateScore() + "%";

        if(progressBar.value == progressBar.maxValue)
        {
            isComplete = true;
        }
    }

    void DisplayAnswer (int index)
    {
        Image buttonImage;

        if (index == currentQuestion.GetCorrectAnswerIndex())
        {
            questionText.text = "Correct!";
            buttonImage = answerButtons[index].GetComponent<Image>();
            buttonImage.sprite = correctAnswerSprite;
            scoreKeeper.IncrementCorrectAnswers();

        }
        else
        {
            correctAnswerIndex = currentQuestion.GetCorrectAnswerIndex();
            string correctAnswer = currentQuestion.GetAnswer(correctAnswerIndex);
            questionText.text = "Sorry, correct answer was;\n" + correctAnswer;
            buttonImage = answerButtons[correctAnswerIndex].GetComponent<Image>();
            buttonImage.sprite = correctAnswerSprite;
        }
    }

    void GetNextQuestion()
    {
        if(questions.Count > 0)
        {
            SetButtonState(true);
            SetDefaultButtonSprites();
            GetRandomQuestion();
            DisplayQuestion();
            progressBar.value++;
            scoreKeeper.IncrementQuestionsSeeen();
        }
        
    }

    void GetRandomQuestion()
    {
        int index = Random.Range(0, questions.Count);
        currentQuestion = questions[index];

        if(questions.Contains(currentQuestion))
        {
            questions.Remove(currentQuestion);
        }
        
    }
    void DisplayQuestion()
    {

        questionText.text = currentQuestion.GetQuestion();

        for (int i = 0; i < answerButtons.Length; i++)
        {
            TextMeshProUGUI buttonText = answerButtons[i].GetComponentInChildren<TextMeshProUGUI>();
            buttonText.text = currentQuestion.GetAnswer(i);
        }


    }

    void SetButtonState(bool state)
    {
        for (int i = 0; i < answerButtons.Length; i++)
        {
            Button button = answerButtons[i].GetComponent<Button>();
            button.interactable = state;
        }
    }
    void SetDefaultButtonSprites()
    {
        for(int i = 0; i < answerButtons.Length; i++)
        {
            Image buttonImage = answerButtons[i].GetComponent <Image>();
            buttonImage.sprite = defaultAnswerSprite;
        }
    }
}



[Canvasess|690x388](upload://oKH6DVtHQX9qfVqIQpYc1o2Uo4x.png)
[Capture+5.PNG|690x388](upload://12kMCHjjRrwmKi4TU7Ek8Apaars.jpeg)


Hi,

NullReferenceException means that a reference (“link”) to an instance is missing. Double click on the error message to see to which line in your code it is referring. If you exposed a field in the Inspector, make sure that it’s not empty.

Given your script has got no compiler errors, I assume that the references got lost in the Inspector in the Unity Editor.

If the wrong elements appear in your game window, disable game objects in your Hierarchy to figure out which game objects contain those sprites. Then check your Quiz component and the code to figure out which part controls those game objects.

I hope this helped. :slight_smile:


See also:

Hi Nina,

it seems this is the line but I am not sure why canvas is not visible in the scene menu, :face_with_monocle:

Buttons are not showing in the game menu as well I mean the answers are not working

Thanks

If the erroris in line 81, currentQuestion is null. Where does an object get assigned to this variable? Have you already tried to add Debug.Logs to your code to see what is going on during runtime?

I’ve tried to add Debug.Logs but now I’ve got the compiler error such as this:

Assets\Scripts\Quiz.cs(38,5): error CS1585: Member modifier ‘public’ must precede the member type and name

here is my current quiz.cs code: `using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
using UnityEditor.ShaderKeywordFilter;
using UnityEngine.UIElements;

public class Quiz : MonoBehaviour
{
[Header(“Questions”)]
[SerializeField] TextMeshProUGUI questionText;
[SerializeField] List questions = new List();

QuestionSO currentQuestion;

[Header("Answers")]
[SerializeField] GameObject[] answerButtons;
    int correctAnswerIndex;
bool hasAnsweredEarly;

[Header("Button Colors")]
[SerializeField] Sprite defaultAnswerSprite;
[SerializeField] Sprite correctAnswerSprite;

[Header("Timer")]
[SerializeField] UnityEngine.UI.Image timerImage;
Timer timer;

[Header("Scoring")]
[SerializeField] TextMeshProUGUI scoreText;
ScoreKeeper scoreKeeper;

[Header("ProgressBar")]
[SerializeField] Slider progressBar;
[SerializeField] UnityEngine.UIElements.SliderImage

public bool isComplete;


void Start()
{ 
    timer = FindObjectOfType<Timer>();
    scoreKeeper = FindObjectOfType<ScoreKeeper>();
    progressBar.maxValue = questions.Count;
    progressBar.value = 0;
      
}

 void Update()
{
    timerImage.fillAmount = timer.fillFraction;
    if(timer.loadNextQuestion)
    {
        hasAnsweredEarly = false;
        GetNextQuestion() ;
        timer.loadNextQuestion = false;
    }
    else if(!hasAnsweredEarly && !timer.isAnsweringQuestion)
    {
        DisplayAnswer(-1);
        SetButtonState(false);
    }
}

public void OnAnswerSelected(int index)
{
    hasAnsweredEarly=true;
    DisplayAnswer(index);
    SetButtonState(false);
    timer.CancelTimer();
    scoreText.text = "Score: " + scoreKeeper.CalculateScore() + "%";

    if(progressBar.value == progressBar.maxValue)
    {
        isComplete = true;
    }
}

void DisplayAnswer (int index)
{
    Image buttonImage;

    if (index == currentQuestion.GetCorrectAnswerIndex())
    {
        questionText.text = "Correct!";
        buttonImage = answerButtons[index].GetComponent<Image>();
        buttonImage.sprite = correctAnswerSprite;
        scoreKeeper.IncrementCorrectAnswers();

    }
    else
    {
        correctAnswerIndex = currentQuestion.GetCorrectAnswerIndex();
        string correctAnswer = currentQuestion.GetAnswer(correctAnswerIndex);
        questionText.text = "Sorry, correct answer was;\n" + correctAnswer;
        buttonImage = answerButtons[correctAnswerIndex].GetComponent<Image>();
        buttonImage.sprite = correctAnswerSprite;
    }        
}

void GetNextQuestion()
{
    if(questions.Count > 0)
    {
        SetButtonState(true);
        SetDefaultButtonSprites();
        GetRandomQuestion();
        DisplayQuestion();
        progressBar.value++;
        scoreKeeper.IncrementQuestionsSeeen();
    }
    
}

void GetRandomQuestion()
{
    int index = Random.Range(0, questions.Count);
    currentQuestion = questions[index];

    if(questions.Contains(currentQuestion))
    {
        questions.Remove(currentQuestion);
    }
    
}
void DisplayQuestion()
{

    questionText.text = currentQuestion.GetQuestion();

    for (int i = 0; i < answerButtons.Length; i++)
    {
        TextMeshProUGUI buttonText = answerButtons[i].GetComponentInChildren<TextMeshProUGUI>();
        buttonText.text = currentQuestion.GetAnswer(i);
    }


}

void SetButtonState(bool state)
{
    for (int i = 0; i < answerButtons.Length; i++)
    {
        Button button = answerButtons[i].GetComponent<Button>();
        button.interactable = state;
    }
}
void SetDefaultButtonSprites()
{
    for(int i = 0; i < answerButtons.Length; i++)
    {
        Image buttonImage = answerButtons[i].GetComponent <Image>();
        buttonImage.sprite = defaultAnswerSprite;
    }
}

}
`
I’ve added this line “[SerializeField] UnityEngine.UIElements.SliderImage” for the slider because previous error was this

how can I fix this error ?Assets\Scripts\Quiz.cs(27,22): error CS0104: ‘Image’ is an ambiguous reference between ‘UnityEngine.UI.Image’ and ‘UnityEngine.UIElements.Image’

I am totally lost within these codes and understandaing that this part of the course is too much for me I guess :slight_smile:

There is a semicolon missing in that line.

Generally, if you get compiler errors, double click on the message. Then the concerning line will get highlighted. If you cannot spot any issue in that line, go a bit higher in the code. In many cases, there is just a missing semicolon or a missing or misplaced curly bracket. These mistakes are fairly annoying but they also happen to the best programmers. :slight_smile:

I’ve managed to overcome compiling errors with specifying the UnityEngine.UI namespace for the several classes. My buttons and play function is now working in game menu but I am still not able to see any of the canvas in Scene Menu even though they are set to be visible in the inspector.

Would you have any suggestions about what might be the issue here?

Good job on fixing the compiler errors. :slight_smile:

Please go to the top right corner of Unity. Click on Layers and make sure “Everything” is visible.

1 Like

Thank you! :pray:

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

Privacy & Terms