Как я и подозревал, вы используете DontDestroyOnLoad
.
Ваш первый скрипт, кажется, прикреплен к тому же объекту, что и GameSession
, или находится в иерархии под ним (дочерний элемент).
Это делает Start
be никогда , вызываемым снова.
Но вы можете зарегистрировать обратный вызов на SceneManager.sceneLoaded
вЧтобы обновить текст:
public class GameSession : MonoBehaviour
{
// ...
private YourFirstScript yourFirstScript;
// rather implement a Singleton pattern this way
private static GameSession Instance;
private void Awake()
{
if(Instance)
{
Destroy(gameObject);
return;
}
Instance = this;
DontDestroyOnLoad(gameObject);
// Add the callback
// it is save to remove even if not added yet
// this makes sure a callback is always added only once
SceneManager.sceneLoaded -= OnSceneLoaded;
SceneManager.sceneLoaded += OnSceneLoaded;
yourFirstScript = GetComponentInChildren<YourFirstScript>(true);
}
private void OnDestroy()
{
// make sure to remove callbacks when not needed anymore
SceneManager.sceneLoaded -= OnSceneLoaded;
}
// called everytime a scene was loaded
private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
scoreText.text = currentScore.ToString();
// Since you made it public anyway simply call the method
// of your first script
// You shouldn't call it Start anymore
// because now it will be called twice
yourFirstScript.Start();
}
// ...
}
Примечание. Также важно, чтобы livesText
также был либо DontDestroyOnLoad
, либо переназначался после загрузки сцены.В противном случае вы получите NullReferenceException
в любом случае.
Как переназначить livesText
?
Вы можете сделать Instance
из GameSession
public static GameSession Instance;
это немного злоупотребляет одноэлементным шаблоном и противоречивым типом ... но я думаю, что это хорошо для быстрого прототипирования.
и также делает levelText
в YourFirstScript
public TextMeshProUGUI levelText;
Тогда вы можете просто добавить новый компонент в соответствующий объект levelText
, например
[RequireComponent(typeof(TextMeshProUGUI))]
public class LevelTextAssigner : MonoBehaviour
{
// you can reference this already in the Inspector
// then you don't need to use GetComponent
[SerializeField] private TextMeshProUGUI _text;
// Is called before sceneLoaded is called
private void Awake()
{
if(!_text) _text = GetComponent<TextMeshProUGUI>();
// It is possible that the first time GameSession.Instance is not set yet
// We can ignore that because in this case the reference still exists anyway
if(GameSession.Instance)
{
GameSession.Instance.YourFirstScript.leveltext = _text;
}
}
}