(New UI) How to edit two text objects in same script

Im trying to edit two separate text objects from the same script. My script looks like this so far:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;


public class HUD : MonoBehaviour {

	Text text;
	Text text2;


	// Use this for initialization
	void Awake () {
	
		text = GetComponent <Text> ();
		text2 = GetComponent <Text> ();
	}
	
	// Update is called once per frame
	void Update () {
	

		text.text = "EXP   " + EXP.exp.curExp;
		text2.text = "Level    " + EXP.exp.curLevel;
	}
}

But text2 overwrites text. I need help. I dont want to use two separate scripts to do the same thing.

Thank you, I was indeed overriding it with GetComponent

1 Answer

1

Calling GetComponent will get the text field assigned to the same game object as the script.

You need to get a reference to the object holding the text field.

Either make a variable that can be assigned in the editor

[SerializeField]
Text text2;

Or find the object at runtime.

i tried making it public and assigning it in the editor. It just ignores it. That doesnt seem to do anything at all.

If you assign it in editor then you shouldn't call GetComponent any more or you will overwrite it.

Well that was simple. That was the problem, I was overriding it with GetComponent. Thanks for your help