Tasharen Entertainment Forum
Support => NGUI 3 Support => Topic started by: unitymoo on December 24, 2016, 08:09:00 AM
-
Hi,
I want to change the color of a sprite on click -- to a random color from array.
When I click the sprite, the console message shows I'm getting a color from the array.
But I can't get the sprite to actually change color on-screen.
Does anyone know how to make this work properly?
Also I'm new to NGUI / coding in general so if there is an elegant solution to this problem please let me know.
Here is my code:
using UnityEngine;
using System.Collections;
public class btnUpdate2 : MonoBehaviour {
public Color[] squareColor;
public void onClickTweenColor () {
print ("example color from array: " + squareColor [Random.Range (0, squareColor.Length)]);
GameObject.Find ("WhiteSquare").GetComponent<UIWidget> ().color = squareColor [Random.Range (0, squareColor.Length)];
}
}
-
hmm... if I could figure out how to change the title of my original post
I would change it to something like:
How to properly change color of a Sprite with NGUI
-
try this:
transform.FindChild("WhiteSquare").GetComponent<UISprite>().color = Color.red;
PS stay away from GameObject.Find
-
Thanks, this worked for me.
Here's how I used your code in an on click function to change the color of a sprite
I put the sprite at the same position as my button
and changed sprite depth to 1 (above the button, which has depth 0)
since adding the button script to an object seems to disable ability to change color
public void OnBlueBtnClicked () {
print ("blue was clicked");
transform.FindChild("WhiteSquare").GetComponent<UISprite>().color = Color.green; // change sprite to color red
}
-
Hmm.... still trying to figure out how to color sprite randomly from an array of colors
using UnityEngine;
using System.Collections;
public class BtnActionColor : MonoBehaviour {
public Color[] myRandomSpriteColor;
public void OnBtnClick () {
transform.FindChild ("WhiteSquare").GetComponent<UISprite> ().color = myRandomSpriteColor [Random.Range (0, myRandomSpriteColor.Length)];
}
}
In the Inspector I must create an array of colors
but when I test the project and click the button
the white square sprite which I have placed on top of my button just disappears
Instead I want the white square to change to a random color from the array of colors I have created...
Any other helpful ideas on how to change a white sprite to a random color from array?
-
Buttons use color tweens to change colors. If you want to change a color of a specific sprite, first you should reference it, not try to find it by name -- and second, make sure you are not already coloring it via other means (like a button). Also what's OnBtnClick? NGUI's click event is OnClick, not OnBtnClick.