Question by
ptlam61004 · Jul 21, 2021 at 01:05 AM ·
scripting problemvariablesdontdestroyonload
Calling variable within DontDestroyOnLoad() script yields different result from calling from another script without
I have two scripts, GameMaster and ItemCollector.
GameMaster script:
public class GameMaster : MonoBehaviour
{
private static GameMaster instance;
[SerializeField] public int maxCherries;
[SerializeField] public bool[] cherriesCollected = new bool[100];
public int numberOfCherriesCollected;
public GameObject[] cherries = new GameObject[100];
private void Start() {
cherries = GameObject.FindGameObjectsWithTag("Cherry");
}
private void Awake() {
Debug.Log(instance);
if(instance == null){
instance = this;
DontDestroyOnLoad(instance);
}
else{
Destroy(gameObject);
}
Debug.Log(numberOfCherriesCollected);
}
}
ItemCollector script:
public class ItemCollector : MonoBehaviour
{
private GameMaster gameMaster;
private void Start() {
gameMaster = GameObject.FindGameObjectWithTag("Game Master").GetComponent<GameMaster>();
Debug.Log(gameMaster.numberOfCherriesCollected);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.CompareTag("Cherry"))
{
int cherryId = collision.GetComponent<CherriesId>().id;
gameMaster.cherriesCollected[cherryId] = true;
gameMaster.numberOfCherriesCollected++;
Debug.Log("collected cherry at: " + cherryId);
for(int i = 0;i<gameMaster.maxCherries;i++){
Debug.Log("Object: " + i + ": " + gameMaster.cherriesCollected[i]);
}
Destroy(collision.gameObject);
}
}
}
After collecting a cherry and then die, the screen reloads. However, in the GameMaster script, the debug showed 0, and the ItemCollector showed 1. Can anyone help me with this case? Thank you!
Comment
Your answer
Follow this Question
Related Questions
Countdown Timer 2 Answers
Add a script to a GameObject via script at runtime? 1 Answer
Game Objects not using same script independently. 1 Answer
Adding a cost reduction to my purchasable items 1 Answer
scripting problems please help 0 Answers