So I Made A Working Level Selector Using A Brackeys Video
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LevelSelector : MonoBehaviour
{
public LevelFaderScript fader;
public Button[] levelsButtons;
void Start()
{
int levelReached = PlayerPrefs.GetInt("levelReached", 1);
for (int i = 0; i < levelsButtons.Length; i++)
{
if (i + 1 > levelReached)
{
levelsButtons[i].interactable = false;
}
}
}
public void SelectLevel(int levelIndex)
{
fader.FadeToLevel(levelIndex);
}
}
And I Want In The Game Manager, In The PlayerPrefs, Use This Function: PlayerPrefs.SetInt(“levelReached”, levelReached + 1);
But I Cannot Use The LevelReached variable since it is in another script.
Will it work if I Use static variable, or no?
I just want to increase the levelReached when I Win A Level and pass the other
Somebody help me!
Make the variable/field public or use properties (get and set accessors). Then you need to just reference the object somehow in your code, like making a public field where you drag your
another script. Now you can access that data in your current code.
For example,
Public field:
public int levelReached;
Get/Set accessors:
// Your private variable
private int _levelReached;
// public access to it
public int LevelReached
{
get { return _levelReached; }
set { _levelReached = value; }
}
How to reference another location:
you need to fill this field either in code or in Inspector by dragging and object in that contains the script GameManager:
GameManager gameManager;
When you need to access that level value, you can:
// Print it out to Debug log
Debug.Log("LevelReached: " + gameManager.LevelReached);
// Increment the level counter by one
gameManager.LevelReached++;
The problem is that The LevelSelector Script And The GameManager Are In DifferentScene
The Level Selector Is In The LevelSelector Scene And The Game manager is in the level01
so i couldn’t use a public variable, maybe a static? but i want to save the progress
what should i do then
you already answered your own question.
make it static.
I mean get rip of MonoBehaviour
public static class GameDB
{
public static int levelReached
{
get => PlayerPrefs.GetInt("levelReached", 0);
set => PlayerPrefs.SetInt("levelReached", value);
}
}
however put things in static as global, was not a good practice.
use it wisely.
OR~
if you have any requirement depend on MonoBehaviour.
try to implement the singleton design pattern. https://wiki.unity3d.com/index.php/Singleton
and make it [DontDestroyOnLoad](https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html)