UnityEvents, I think I need help to fully understand

Hi there,

I try to change the text on a UI Text element when an int value in the Player object changes. But I can’t get it to work, I think there’s still a missing piece I don’t get in regards to UnityEvents.

This is the script on my UI Text element:

public class MyText : MonoBehaviour
{
    public void ChangeText(int value)
    {
        GetComponent<Text>().text = value.ToString("##,### $");
    }
}

And this is the code in my Player script that has to do with the UnityEvent:

[System.Serializable]
public class OnNumberChangeEvent : UnityEvent<int>
{
}

public class Player : MonoBehaviour
{
	private int number = 200000;

    public OnNumberChangeEvent numberChange;

	public void ChangeNumber(int newNumber)
	{
		// doing some other stuff...
		
		numberChange.Invoke(newNumber);
	}
}

I dragged the MyText GameObject into the “Number Change (Int32)” area on my Player GameObject and chose the method MyText.ChangeText with one parameter. But the text on the Text UI doesn’t change, can anyone help? (I also chose the MyText.ChangeText with zero parameters, same result.)

you need to call the change text void…
public myText;

public void ChangeNumber(int newNumber)
     {
         // doing some other stuff...
         
         numberChange.Invoke(newNumber);
         myText.ChangeText(newNumber);
     }

plus, it appears that you are doing a lot of unnecessary functions… just simplify those down to one function ‘UpdateNumber’ or something that changes number, updates text, and does anything else necessary.

Partly solved! But there’s another problem now.

The UI Text element is called now, I didn’t have a reference to the Text prefab in my Player prefab in the UnityEvent.

But now I have another strange problem. I debug the active state of the Text element:

Debug.Log("My Text ActiveSelf? " + gameObject.activeSelf);
Debug.Log("My Text ActiveInHierarchy? " + gameObject.activeInHierarchy);

I can debug it when pressing the M key and it is debugged when the element is called by the UnityEvent. Console output when I press M at different occasions:

My Text ActiveSelf? True
UnityEngine.Debug:Log(Object)

My Text ActiveInHierarchy? True
UnityEngine.Debug:Log(Object)

But when the UnityEvent calls the method on the Text Element, the debug output is:

My Text ActiveSelf? True
UnityEngine.Debug:Log(Object)

My Text ActiveInHierarchy? False
UnityEngine.Debug:Log(Object)

Any ideas? It’s really bugging me that I can’t get the reason for that.

SOLVED!

Ok I finally solved that problem! I’ve read a hint in another forum thread somewhere that took me in the right direction. The problem was that I tried to change the text on the prefab Text element and not on the instance in the Scene.

What I’ve tried so far (WRONG!):

GetComponent<Text>().text = value.ToString("##,### $");

What I do now and what works (CORRECT!):

FindObjectOfType<MyText>().GetComponent<Text>().text = value.ToString("##,### $");