I want to construct a 7 segment
display (as shown below). When you input a number, the script will read the input number and light up the respective segment
(change the spriterenderer color to red) to display the number.
But I think the code has become too long, since there is 0-9 digit to display, I need 10 if statements
, 8 scripts
and the function of each statement is to light up the respective segment so it displays the number correctly.
Is there any better way to make the code shorter?
using UnityEngine;
public class ClockController : MonoBehaviour
{
Rect1 rect1;
Rect2 rect2;
Rect3 rect3;
public GameObject othergameobjectrect2;
public GameObject othergameobjectrect3;
void Start()
{
int x = 1;
if (x == 1)
{
rect1 = GetComponent<Rect1>();
rect1.Rectangle1();
rect2 = othergameobjectrect2.GetComponent<Rect2>();
rect2.Rectangle2();
rect3 = othergameobjectrect3.GetComponent<Rect3>();
rect3.Rectangle3();
}
}
}
using UnityEngine;
public class Rect3 : MonoBehaviour
{
public void Rectangle3()
{
GetComponent<SpriteRenderer>().color = Color.red;
}
}
using UnityEngine;
public class Rect2 : MonoBehaviour
{
public void Rectangle2()
{
GetComponent<SpriteRenderer>().color = Color.red;
}
}
using UnityEngine;
public class Rect1 : MonoBehaviour
{
public void Rectangle1()
{
GetComponent<SpriteRenderer>().color = Color.red;
}
}
prefabs
. You don't want 1 script per rectangle, you want 1Rectangle
class (without any number in the name) and make 8 different instances of that prefab in your scene, at different positions and with different indexes. To contol them, you could make an array of those rectangle prefabs, which is keyed by 0-7, so instead of doingif(x == 1) { rectangle1... }
you don't have to check anything, you just say give me array[1] or array[2] and that returns you the correct one. \$\endgroup\$ – D.Kallan Jan 13 at 4:30