-1

I have public variable score in script scr_a that attach to object obj_a in scene sce_a.

now I need to access the variable (score) in script scr_b that attach to object obj_b in scene sce_b.

I have try something but they did not work and I think that's because my scripts are in two different scene...

mmoj
  • 11
  • 1
  • 6

2 Answers2

0

Use a Score managing object that doesn't destroy in scene load or destroy. Unity have have a method DontDestroyOnLoad() for doing that. Get this object from other script with tag like "ScoreManager" then access the public methods as you need.

Use some code like below:

private int score;

void Awake()
{
 DontDestroyOnLoad(this.gameObject);
}

public int GetCurrentScore()//call this method to get the current score
{
 return score;
}

public void UpdateScore()//call this method to update the score increment
{
 score++;
}
Sourav Paul Roman
  • 2,043
  • 2
  • 15
  • 20
  • This would need more to act as a score manager. I generally use a static self reference, given that management scripts shouldn't have multiple instances running at the same time. – Gnemlock Aug 13 '16 at 02:51
-1

You have to maintain/retain/dontDestory scr_a script when you switching from sce_a to sce_b and this can be acheiveable through this

public scr_a{
public int score;
 void Awake() {
        Debug.Log("DontDestory Script's Awake");
        DontDestroyOnLoad(this);
    }
///your logic update or blah blah functions

}

Adding DontDestoryOnLoad in your scr_a script will maintain you scr_a script object in sce_b then you can get it in scr_b using this

scr_a scr_aObj = GameObject.FindObjectOfType<scr_a>();
Debug.Log(scr_aObj.score);
Muhammad Faizan Khan
  • 2,020
  • 3
  • 29
  • 66