Unity Increasing Value Only Once

Viewed 81

I am trying to increase speed value for my enemy only once whenever I reach defined points value in another script.

private void Start()
{
    target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
}

private void Update()
{
    timeInGame += Time.deltaTime;

    if (timeInGame <= lifeLength)
    {
        ChasePlayer();
    }
    else
    {
        StopChase();
        Destroy(gameObject, 3f);
    }

    switch (GameController.instance.points)
    {
        case 10:
            readyToSpeedUpEnemy = true;
            break;
        case 25:
            readyToSpeedUpEnemy = true;
            break;
        default:
            break;
    }

    if (readyToSpeedUpEnemy)
    {
        speed++;
        readyToSpeedUpEnemy = false;
    }

}

That being sad - what I am trying to acomplish here is - whenever the "points" value in my GameController script reach 15, 25, 35, etc. points I would like to increase my enemy's speed value by 1.

Can you advise me how to acomplish this, as the above script doesn't work the way I wish?

All your feedback and comments will be appreciated as I am still new in this.

Cheers!

2 Answers

I am not sure if I understood you well. But I can advise you to aggregate some cases in one and that way you also don't need a boolean variable:

static bool[] speedAdded = new bool[2]; // It should be a global variable

...

switch (GameController.instance.points)
{
    case int n when (n >= 15 and n < 25):
        if (!speedAdded[0])
        {
            speed++;
            speedAdded[0] = true;
        }

        break;
    case int n when (n >= 25):
        if (!speedAdded[1])
        {
            speed++;
            speedAdded[1] = true;
        }

        break;

    default:
        break;
}

There are many possibilities to solve this. I use a boolean array in order to store if the speed was added for every case category.

I am not sure your exact case but I hope this might solve your case or maybe at least give you an idea.

There is also a slightly more clear way to write the switch-case without repeating the code as in the example above (note, you need to write at least in C# 8.0 to have this feature):

int index = GameController.instance.points switch
{
    >= 15 and < 25 => 0,
    >= 25 => 1
};

if (!speedAdded[index])
{
    speed++;
    speedAdded[index] = true;
}

if points are always multiple of 5, you can increase speed if points mod by 5 is 0 and points are odd number

Related