Where am i going wrong with changing my Input-field placeholder color if if a user has entered a text.
Default placeholder color is grey
User inputs text
Placeholder white
using UnityEngine.UI;
public class InputField : MonoBehaviour
{
public InputField inputField;
// Update is called once per frame
void Update()
{
if (inputField != null)
{
inputField.GetComponent<Image>().material.color = Color.blue;
}
}
}
InputFields include an OnEndEdit event or an OnValueChanged event that would work much better for this. Either check the text property of the InputField when edit is done and see if it has any characters (recommended) or when the value changes in case you want to change it as they type or delete characters.
By default, InputFields don’t have a material. So if you just plan to change the color of the Image, you should remove the .material part.
And of course, make sure your inputField variable actually has something dragged and dropped into it.
However, you mention Placeholder in your description, but you are targeting the Image. If you want to target the Placeholder text, you need to target it instead.
inputField.placeholder.color = Color.blue; This should change the color of the placeholder text instead if that is what you want to do.
Thanks for the reply! Probably did not make it clear. Im not changing the text color, i am trying to change the actually inputfield background colour to go from one colour to another. I will update the forum with a screenshot
Create an Image variable in your script and drag the appropriate image component from the hierarchy into that field. Then change the color of that component in the script.
Thanks I had to make more edits related to naming conventions but thanks your response it helped! Just a question…How would i go about retreving the original colour after changing the inputfield.
using UnityEngine.UI;
public class InputField1 : MonoBehaviour
{
public InputField mainInputField;
void Start()
{
defaultColour = GetComponent<Image>().color = Color.white;
}
// Update is called once per frame
void Update()
{
if (mainInputField.textComponent.text.Length > 0)
{
mainInputField.GetComponent<Image>().color = Color.white;
}
else
{
}
}
}
What you have is close. Capture it in a variable in Start(). Then just set it back when the field is empty:
using UnityEngine.UI;
public class InputField1 : MonoBehaviour
{
public InputField mainInputField;
Color defaultColour;
void Start()
{
defaultColour = GetComponent<Image>().color;
}
// Update is called once per frame
void Update()
{
var imageComponent = mainInputField.GetComponent<Image>();
if (mainInputField.textComponent.text.Length > 0)
{
imageComponent.color = Color.white;
}
else
{
imageComponent.color = defaultColour;
}
}
}
What @Brathnann said about using events instead of Update() is valid, but I also wouldn’t worry about it for now if this works for you, especially if you’re a beginner. It’s an optimization for later. Good luck!