Home > Software engineering >  I only can use my list named "Questions" in void start
I only can use my list named "Questions" in void start

Time:11-08

I can't use List in void update it says "Questions does not exists in the current context"

I tried it making in void start, it worked but I have to do it in void update.

Is there a way to do it?

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

public class QController : MonoBehaviour
{
    [SerializeField] string Qstring;
    [SerializeField] Text Qtext;
    [SerializeField] PlayerController PlayerController;
    // Start is called before the first frame update
    void Start()
    {
        string q1 = "Selimiye caminin mimarı bu camiyi ne olarak adlandırmıştır?";
        string q2 ="Selimiye Camiyi kim yapmıştır?";
        // ...
       
        List<string> Questions = new List<string>();
        Questions.Add(q2);
        // ...
    }


    // Update is called once per frame
    void Update()
    {
        // here it says Questions doesn't exist in the current context        
        Qstring=Questions[PlayerController.randomQnumber];
        Qtext.text=Qstring;
    }
}

CodePudding user response:

This should do the trick. As you can see PlayerController is accessible but Questions is not. That only means you should be placing the list at the same location the PlayerController is. Before trying anything more I would be doing some Programming Tutorials to know the why and how it works. This is basic programming.

Check madmonk46 comment for a good tutorial.

public class QController : MonoBehaviour
{
    [SerializeField] string Qstring;
    [SerializeField] Text Qtext;
    [SerializeField] PlayerController PlayerController;
    private List<string> Questions;
    // Start is called before the first frame update
    void Start()
    {
        string q1 = "Selimiye caminin mimarı bu camiyi ne olarak adlandırmıştır?";
        string q2 ="Selimiye Camiyi kim yapmıştır?";
        // ...
       
        Questions = new List<string>();
        Questions.Add(q2);
        // ...
    }


    // Update is called once per frame
    void Update()
    {
        // here it says Questions doesn't exist in the current context        
        Qstring=Questions[PlayerController.randomQnumber];
        Qtext.text=Qstring;
    }
}
  • Related