using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using UnityEngine.SceneManagement;
public class Quiz1 : MonoBehaviour
{
[SerializeField] private TMP_Dropdown dropdown;
var answer1;
public void OnChangedDropdown (int value)
{
int answer1 = dropdown.value + 1;
Debug.Log(answer1);
}
Debug.Log(answer1);
}
I would like to use the “variable: answer1” in the above code in other scripts. But I cannot take it out from within a function. Please tell me how I can easily take it out and use it in other scripts.
public class Quiz1 : MonoBehaviour
{
[SerializeField] private TMP_Dropdown dropdown;
public int answer1; // public means it's accessible from other classes
public void OnChangedDropdown (int value)
{
// Access the class variable, answer1 (which is declared above)
this.answer1 = dropdown.value + 1;
Debug.Log(this.answer1);
// The keyword "this" is not necessary in this case, but it makes it clear
// where you intend to access it from
}
}
SomeOtherScript component which needs access to Quiz1 and answer1:
public class SomeOtherScript : MonoBehaviour
{
public Quiz1 quiz1; // Set this reference via the Inspector if you want or use methods like GetComponent()
private void DoSomethingWithAnswer1 ()
{
// Checks if quiz1 has a reference to an instance of Quiz1
if (quiz1 != null)
{
Debug.Log(quiz1.answer1);
}
}
}