So i am working on a project using a webcam.If i go out-of-screen(view of the camera) a timer starts which track the time i am out of view and if it goes above a certain max value my game gets paused. Similarly for the In-screen view(inside camera view), timer starts and after max value it resumes the game.
void Update()
{
if (InFrontOfScreen()) //This is a condition
{
isInFront = true;
}
else
{
isInFront = false;
}
InView();
Pausing();
}
private void Pausing()
{
if (isPaused)
Time.timeScale = 0f;
else
Time.timeScale = 1f;
}
private void InView()
{
if (isInFront)
{
inViewTime = Time.unscaledDeltaTime;
if (inViewTime >= maxInViewTime)
{
isPaused = false;
}
outOfViewTime = 0f;
}
else
{
outOfViewTime = Time.unscaledDeltaTime;
if (outOfViewTime >= maxOutOfViewTime)
{
isPaused = true;
}
inViewTime = 0f;
}
}
Now in another script I have to call functions that depend on whether the game is paused or not.
void Update()
{
SwitchCameras();
}
private void SwitchCameras()
{
if(PauseController.isPaused)
{
gameCam.enabled = false;
mainCam.cullingMask = pausedLayerMask;
}
else
{
gameCam.enabled = true;
mainCam.cullingMask = originalLayerMask;
}
}
The problem is that this gameCam.enabled and mainCam should be called only once when the bool isPaused changes.It is being called every frame. I get the answer right but I want it to be called only once and not every frame.Is there a way to acheive this? Though isPaused can change back and forth the functions should be called once and then again when isPaused changes . Thank you
CodePudding user response:
From what I can see you only need to cache the value and when a new update is called just check if the value changed
// Somewhere have a field that saves previous state
private bool _wasPaused;
void Update()
{
SwitchCameras();
}
private void SwitchCameras()
{
if (_wasPaused != PauseController.isPaused)
{
if (PauseController.isPaused)
{
gameCam.enabled = false;
mainCam.cullingMask = pausedLayerMask;
}
else
{
gameCam.enabled = true;
mainCam.cullingMask = originalLayerMask;
}
}
_wasPaused = PauseController.isPaused;
}
CodePudding user response:
We can use a private variable and a property. This way we can check to see when a property changes value, and just process an action when the value changes.
Very quickly, this should be a way to achieve what you’re trying to do:
private bool _isInFront;
public bool isInFront
{
get => _isInFront;
set
{
if ( _isInFront == value )
return;
_isInFront = value;
InView();
}
}
private void Update ()
{
isInFront = InFrontOfScreen(); //This is a condition
Pausing();
}