Array indexing problem
I am trying to get my code to cycle through an array when I press a button and it works for the most part, but some of the colors don't change. For instance, the order is supposed to be: white, red, orange, yellow, green, blue, purple, pink, and then back to white. The order it actually goes in is: white, red, yellow, yellow, green, blue, pink, pink, and then back to white.
using UnityEngine;
using System.Collections;
public class InputScript : MonoBehaviour {
public KeyCode UpKey = KeyCode.UpArrow;
public KeyCode DownKey = KeyCode.DownArrow;
public KeyCode ChangeColorKey = KeyCode.Backslash;
SpriteRenderer Sprite;
int CurrentColor = 0;
Color[] Colors;
PongPaddleScript PaddleScript;
// Use this for initialization
void Start () {
PaddleScript = GetComponent<PongPaddleScript>();
Sprite = GetComponent<SpriteRenderer>();
Colors = new Color[8];
// White
Colors[0] = new Color(255, 255, 255, 255);
// Red
Colors[1] = new Color(255, 0, 0, 255);
// Orange
Colors[2] = new Color(255, 102, 0, 255);
// Yellow
Colors[3] = new Color(255, 255, 0, 255);
// Green
Colors[4] = new Color(0, 255, 0, 255);
// Blue
Colors[5] = new Color(0, 0, 255, 255);
// Purple
Colors[6] = new Color(128, 0, 255, 255);
// Pink
Colors[7] = new Color(255, 0, 238, 255);
}
// Update is called once per frame
void Update ()
{
if(Input.GetKey(UpKey))
{
PaddleScript.setDirection(1);
}
else if(Input.GetKey(DownKey))
{
PaddleScript.setDirection(-1);
}
else
{
PaddleScript.setDirection(0);
}
if(Input.GetKeyDown(ChangeColorKey))
{
if(CurrentColor + 1 > Colors.Length - 1)
{
CurrentColor = 0;
}
else
{
CurrentColor += 1;
}
Sprite.color = Colors[CurrentColor];
}
}
}
Answer by Jessespike · Jul 14, 2016 at 08:02 PM
Each color component is a floating point value with a range from 0 to 1.
https://docs.unity3d.com/ScriptReference/Color.html
You can convert the values to a floating point between 0 and 1, or divide the current values with 255.
// Orange
//Colors[2] = new Color(255, 102, 0, 255);
Colors[2] = new Color(255f/255f, 102f/255f, 0f/255f, 255f/255f);
Colors[2] = new Color(1f, 0.4f, 0f, 1f);
Your answer
Follow this Question
Related Questions
getting unexpected symbol ';' error 1 Answer
How to Move an Image to an other Panel 1 Answer
Best way to create a currency converter in Unity with C# 0 Answers
A way to make the player get punished when standing still? 0 Answers
Is there a way to run Destroy(gameObject) after the game has run the previous code? 1 Answer