if statements and or operators

I am trying to get an object to scale down, stop, then scale up again to a certain point and start the cycle again, but I can’t seem to get it to work. Here is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Pulsing : MonoBehaviour {
public float Scaletop = 10f;
public float Scalebottom = 6f;

Vector3 temp;

void Start () {
	
}


void Update () {
	temp = transform.localScale;

	if (temp.x == Scaletop || temp.x != Scalebottom){
		temp.x -= .01f;
		temp.y -= .01f;
	} 
	else if (temp.x == Scalebottom || temp.x != Scaletop) {
		temp.x += .01f;
		temp.y += .01f;
	}
	transform.localScale = temp;
}

}

You have to imagine what happens here. Let’s say temp.x equals Scaletop at the start, so the object shrinks. Then it shrinks a few times until it reaches Scalebottom (which it probably won’t, I’ll get to that in a second), so the first if condition is not true anymore.

Then, the program checks the second if statement. temp.x equals Scalebottom, so the size increases once. The next frame, temp.x will not equal Scalebottom anymore, so the first condition immediately is true again. The result: The first condition will not be false twice in a row.

In general: The computer can’t know whether you are currently shrinking or growing the object just by looking at the current size. Makes sense if you think about it. When I show you a screenshot of your object, you couldn’t tell either just by looking at the current size, right?

So you need an extra variable that stores whether we are shrinking or growing at the moment.

Another problem is that float calculations are not exact. For example, you can test this:

if(0.1f + 0.1f + 0.1f + 0.1f + 0.1f != 0.5f)
{
  print("Say what??");
}

And the weirdest thing: It’s not even persistent. So… (almost) never compare exact floats. Instead, use > and <.

In the end, you should have something like this:

private bool growing = false;
private float size = 1f;

void Update()
{
  if(growing)
  {
    size += 0.1f * Time.deltaTime;
    if(size > maxSize)
    {
      growing = false;
    }
  }
  else
  {
    size -= 0.1f * Time.deltaTime;
    if(size < minSize)
    {
      growing = true;
    }
  }

  transform.localScale = new Vector3(scale, scale, 1);
}

Note the usage of Time.deltaTime so your animation doesn’t run twice as fast with double the framerate.