I need a little advice about playing sounds once

Hello! I am not posting the whole code because it would not be useful!

I am writing (badly!!!) a “patrolling” routine for my enemy, so I am always checking the distance between player and enemy. If this distance is less than “a float” … enemy starts a “surprise” sound and chase player.

The problem is that … when checking distance … if distance is less than the one i gave, it will always starts sound and it messes up! So I thought to use an INT number that i put to 0 when not patrolling and n++ when patrolling. Sound will be played only if n == 0. Well It works, but I don’t think this is the “right way” do achieve this. What do you think?

Here I check distances (canWalk is false because to stop enemy when player is caught)

if (distancePlayerEnemy < engageDistance)
        {

            if (distancePlayerEnemy > minDistance && justTurned) { patrol = 0; canWalk = true; }
            if (distancePlayerEnemy < minDistance && !justTurned) { patrol = 0; canWalk = false; }
        }

        else { Patrol(); }

Here I check if n = 0. If true then play sound, if > 0 not. CanWalk is FALSE at now, but later I will implement the patrolling …

public void Patrol ()
    {
        canWalk = false; // Solo per test, se si ferma la routine funziona
        justTurned = true;
        if (n == 0) { Sfx(2); }
        n++;
    }

Thanks for helping!

This sort of thing is often done with an overall “this is what I’m currently doing” variable. For example, very crude: int currentAction; where 0=patrolling, 1=chasing the player, 2=caught player. The main code uses IF’s. Only if your action is patrolling do you check distance and make the sound, then set yourself to chasing. It’s pretty close to what you have.

That system is often called a State Machine. The action is often done as an enumerated type (which are ints, but easier to read). Mechanim, for animation, is a state machine, done visually. There are various fancy ways to do it for monster AI, but normal code with IF’s is fine for smaller stuff.