Zak The Hat Zak The Hat - 1 year ago 112
C# Question

Change Background Of Button In Unityscript

In Unity I can't seem to convert this C# code to javascript (unityscript) here it is:

public Color buttonColor;
GetComponent<Image>().color = buttonColor;

This is what I've Tried:

var buttonColor : Color;
GetComponent(Image).color = buttonColor;

Like other questions I'm not trying to get an object of colors. I want one Color variable and change the color of a button using that variable.

My Error Is: NullReferenceException: Object reference not set to an instance of an object
iPhone Investment.Update () (at Assets/__Scripts/iPhone Investment.js:29)

Another error I'm getting is: Unkown identifier: Image

Answer Source

In your C# code, buttonColor variable is public, so you should as well make it public in your Javascript code.

public var buttonColor : Color;
function Start () {
    GetComponent(Image).color = buttonColor;

As for the NullReferenceException error, that's because using GetComponent will only get Component on the GameObject the script is attached to. That line of code is failing because the script is not attached to a GameObject with an Image component.

Either attach the script to a GameObject with an Image Component or Find that GameObject with the Image component first then perform GetComponent on it.

GameObject.Find("MyImageName").GetComponent(Image).color = buttonColor;

Finally, make sure to initilize/assign color to the public variable(buttonColor) from the Editor or else the image will disappear when you click Play.

If you don't want buttonColor to be a public variable, you can make it private but then initialize it from code instead of Editor like below:

var buttonColor : Color;
buttonColor =; //initialize
GameObject.Find("MyImageName").GetComponent(Image).color = buttonColor;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download