Incrementing a value every time a bool becomes true

So i have a script for whenever the player looks at the enemy it does something. I want to increment a variable once every time the onScreen boolean has is true, the problem is that since the teleport function has to be in update it increments it every frame.

 void Teleport()
    {
        Vector3 screenPoint = testCamera.WorldToViewportPoint(transform.position);
        bool onScreen = screenPoint.z > 0 && screenPoint.x > 0 && screenPoint.x < 1 && screenPoint.y > 0 && screenPoint.y < 1;

        if (timesLookedAt >= 3 && !onScreen)
        {
           
            Debug.Log("Teleport");
            // Teleport away
        }       
    }

Try using the following definitions for onscreen and timeslookedat (outside of the Teleport function)

    private int timesLookedAt;
    private bool _onScreen;
    bool onScreen {
        get {
            return _onScreen;
        }
        set {
            if (_onScreen == false && value == true) timesLookedAt++;
            _onScreen = value;
        }

    }

Now any time you modify the onScreen bool (never directly access _onScreen), it checks if it is being changed from false to true, and only increments one time

1 Like