Zak The Hat
Zak The Hat

Reputation: 327

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

Upvotes: 0

Views: 534

Answers (1)

Programmer
Programmer

Reputation: 125275

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, Unity automatically assign 0 to the alpha value of Color variable declared in script. Make sure to change alpha variable of the buttonColor from the Editor to 1 or else the image will disappear when you click Play

EDIT:

For your new error, you must add import UnityEngine.UI; to the top of your script. Since you mentioned that this is done in the Update function, you must do the GameObject.Find outside the Update function to cache the Image component for later use.

import UnityEngine.UI;

private var myImage:Image;
public var buttonColor : Color;

function Start () {
    myImage = GameObject.Find("MyImageName").GetComponent(Image);
}

function Update () {
    myImage.color = buttonColor;
}

If you want to change other button color properties such as pressedColor,highlightedColor and disabledColor, you do it like below:

import UnityEngine.UI;

private var myButton:Button;
public var buttonColor : Color;

function Start () {
    //myButton = GameObject.Find("MyButtonName").GetComponent(Button);
    myButton = GameObject.Find("Button").GetComponent(Button);
}

function Update () {

    var colorBlock = myButton.colors;
    colorBlock.normalColor = new Color(0.0, 0.0, 0.0, 1.0);
    colorBlock.highlightedColor = new Color(0, 1, 0.0, 1.0);
    colorBlock.disabledColor = new Color(0, 0, 1, 1.0);

    myButton.colors = colorBlock;
}

Upvotes: 2

Related Questions