How to change text color on click

I just wanted to make the text go from white to gold and I found a tutorial that showed how to change a button image doing so, so I figured if I change image to text in the getcomponent section it would get the text component. And it did let me add it to the canvas, thus I added it to the text to which I had added a button component to previously. However! When I did a test run I got this error:

NullReferenceException: Object reference not set to an instance of an object
AthleticsColor.changeColor () (at Assets/AthleticsColor.cs:12)
UnityEngine.Events.InvokableCall.Invoke () (at <ba783288ca164d3099898a8819fcec1c>:0)
UnityEngine.Events.UnityEvent.Invoke () (at <ba783288ca164d3099898a8819fcec1c>:0)
UnityEngine.UI.Button.Press () (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:70)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:114)
UnityEngine.EventSystems.ExecuteEvents.Execute (UnityEngine.EventSystems.IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:57)
UnityEngine.EventSystems.ExecuteEvents.Execute[T] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.ExecuteEvents+EventFunction`1[T1] functor) (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:272)
UnityEngine.EventSystems.EventSystem:Update() (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/EventSystem.cs:514)

And the code in question:

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

public class AthleticsColor : MonoBehaviour
{
    public GameObject athleticsText;
   
    public void changeColor()
    {
        athleticsText.GetComponent<Text>().color = new Color(231,179,20);
    }
}

I feel like I’m so close to getting it but I’m hitting a wall here. I’m not getting any compiler errors outside of running it and I tried changing the class and the file name to match the gameobject and it told me not to do that so I undid that. Anybody have advice?

The answer is literally in the first line of the error message.

What object in code can be null?

Solution? Drag and drop GameObject in Inspector so you can use it.

The answer for this error is ALWAYS the same, ALWAYS:

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Three steps to success:

  • Identify what is null ← any other action taken before this step is WASTED TIME
  • Identify why it is null
  • Fix that

Here’s the thing they are linked, I even changed the name of the gameobject, named said gameobject in the code and re-connected it to the canvas and the component itself. Am I just blind?

The game object’s inspector

The Canvas’ inspector

And the updated code:

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

public class AthleticsColor : MonoBehaviour
{
    public GameObject Athletics_SkillText;
   
    public void changeColor()
    {
        Athletics_SkillText.GetComponent<Text>().color = new Color(231,179,20);
    }
}

Small update, tried putting the script in the main parent canvas and linking the game object to that, same issue.

The video tutorial I followed if that helps any:

No, pretty much the only thing that will help is when you complete Step #1:

Identify what is null.

This means: find the instance of the class that is having the problem in the scene, and find the variable within that class that is null.

If you have no idea, time to start debugging! Here is how you can begin your exciting new debugging adventures:

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the names of the GameObjects or Components involved?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

When in doubt, print it out!™

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

You are attempting to get a component of type Text, but the component on your GameObject is of type TextMeshProUGUI.

The tutorial you were following created a Text object, but Unity nowadays installs the TextMeshPro package by default, so it’s possible to create TextMeshProUGUI objects instead, which is what you did.

Per Kurt’s advice, you could have broken down the line further to help pinpoint the cause of this particular issue. The assumption that athleticsText was the null object is a natural one, but can be misleading. Example:

var text = athleticsText.GetComponent<Text>();
text.color = new Color(231,179,20); // The error would point to this line

Went to reddit and the folks over at r/gamedev helped me out step by step.

  1. I was using TextMeshProUGUI, which requires adding using TMpro; at the top.
  2. I wasn’t using f colors, so even if the click was working the color wasn’t being recognized and therefore wasn’t going to change.
  3. Lastly my getComponent couldn’t just be Text, it had to be TMPro.TextMeshProUGUI

So it wasn’t just “what’s null” it was a little bit more than that, because, as I stated, I’m brand new so I don’t know all the terminology unlike you. I didn’t know “using TMpro;” was a thing I need to add to get functionality out of a basic UI object, I didn’t know getComponent need specific terminology in order to even access TMPro. I didn’t know RBG color hexes wouldn’t work and thus would require me to divide by 255 in order to get the color I wanted. A lot of those things I don’t think I would have gotten out of a basic debug and a lot of the reading I came across assumes you know these things.

Sorry if that is annoying.

I totally missed this when looking at your code, oops!

You can use Color32 to provide int values 0-255 instead of float values 0-1, eg. new Color32(231,179,20), if that’s more your speed.

It’s not annoying at all, and being able to get into the headspace of a new user is an important aspect of the ability to effectively help in a forum like this. Trying things and having them not work is an important part of learning, and facilitating the learning process is what this forum is about (at least for me). I’m sorry you felt that the help you received in this thread did not facilitate your learning process.