I have a prefab of UI.Text with an attached script to Fade-in the text when created.
my Fade-In script looks like this:
void Update()
{
GetComponent<Text>().color = Color.Lerp(
new Color(1.0f, 1.0f, 1.0f, 0.0f),
new Color(1.0f, 1.0f, 1.0f, 1.0f),
Time.time / 6);
}
In my game controller i instantiate the text prefab using:
public void Start()
{
m_startText = Instantiate(FadeInText, Vector3.zero, Quaternion.identity) as Text;
m_startText.transform.SetParent(transform, false);
m_startText.fontSize = 25;
m_startText.text = "Press 'S' to Start";
}
And destroy it when the user press ‘S’:
void Update()
{
if (Input.GetKeyDown(KeyCode.S))
{
Destroy(m_startText)
}
}
This creates a null reference exception
NullReferenceException: Object
reference not set to an instance of an
object FadeIn.Update () (at
Assets/Scripts/FadeIn.cs:26)
Coming from the Fade-In script update function, right where i try to access the color property of the now destroyed Text object,
This is a weird behavior since i would expect all attached scripts to stop running once their GameObject is destroyed.
What is the correct way to destroy such an object ?
It seems that when it comes to standatd GameObjects the script will stop once the object is destroyed but does UI.Text behaves differently or did i make a mistake somewhere ?