#how do i reference a script thats inside
1 messages · Page 1 of 1 (latest)
im trying to access a variable thats inside a script of a prefab from another game object
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class ScoreUI : MonoBehaviour
{
public Score score;
TextMeshProUGUI textMesh;
// Start is called before the first frame update
void Start()
{
textMesh = GetComponent<TextMeshProUGUI>();
textMesh.text = ($"Score: {score.currentScore}");
}
// Update is called once per frame
void Update()
{
}
}```
Score is the script thats inside a prefab but everytime i try to start the game theres an error
What's your error ?
null reference exception
I suppose it's a nullRef since you're trying to access Score
Well, you'll need a ref to the instantiated gameObject that holds Score, then you can call GetComponent<Score>() on it
The simplest (but not the best) way would be to use (Score)Object.FindObjectOfType(typeOf(Score)) in your Start()
that doesnt work
When is your prefab holding the Score script instantiated in your Scene ?
Is it already there when you press play ?
OK, so that's because Start() is called before your prefab even exist in the scene
Are you familiar with the singleton pattern ?
uh no
Give me a minute, I'll try to give you an example
uh okay now im not getting the error
but now it doesnt show on the text
it does print tho
public class ScoreUI : MonoBehaviour
{
// Singleton : Here we have a static ref that will be globally accessible
public static ScoreUI Instance { get; private set; }
private TextMeshProUGUI textMesh;
// When you're initializing your ref, better do it in Awake
private void Awake()
{
/* Singleton : For a singleton, we have to ensure we have a single existing instance
/* so we cache the ref as Instance if there isn't already one existing,
/* and destroy it otherwise
*/
if(Instance == null)
{
Instance = this;
}
else if(Instance != this)
{
Destroy(this);
}
textMesh = GetComponent<TextMeshProUGUI>();
}
// I assume the score is an int, but you can change the type accordingly
public void UpdateScore(int newScore)
{
// Make sure your textMesh actually exist
if(textMesh == null)
{
return;
}
textMesh.text = $"Score: {newScore}";
}
}
so let me explain a little bit
you'll reverse the responsability
instead of having your ui know your Score holder
you'll have your score holder tell the UI to update
so when your score change, use ScoreUI.Instance.UpdateScore(currentScore) and it should update properly
Here's a hastebin if it makes it more readable https://hastebin.com/share/payerigava.csharp
And you can learn more about the singleton pattern here : https://gameprogrammingpatterns.com/singleton.html
Just be aware that this is something you'll have to use sparingly