Clamp value problem [solved]

Hi, I’d like to ask you guys (or girls) for a little help.
I’m currently trying to implement a zoom-in/zoom-out control for an orthographic camera. So I’m modifying its size but I want to set some limits. I used the “Mathf.Clamp” function but for some reason the value get set to 0 instead of the min/max value. Here’s the code:

public Camera previewCamera;
public float zoomSpeed = 10.0F;
public float maxZoom = 0.01F;
public float minZoom = 0.5F;

private float cameraZoom;

void Start () {
	cameraZoom = previewCamera.orthographicSize;
	Debug.Log(cameraZoom);
}

void OnMouseOver() {
	CameraZoom(Input.GetAxis("Mouse ScrollWheel"));
}
	
private void CameraZoom (float mouseWheelAxis) {
	cameraZoom -= mouseWheelAxis / zoomSpeed;
	Debug.Log(cameraZoom);
	cameraZoom = Mathf.Clamp(cameraZoom, maxZoom, minZoom);
	Debug.Log(cameraZoom);
	previewCamera.orthographicSize = cameraZoom;
}

The very first Debug.Log displays “0.3”, which is the default size value in the inspector. The second one too but the third one just after the clamp displays “0”. It’s also weird that the value is modified in the first place since its default value is set between the min & max values.
“maxZoom” being set to the Clamp min parameter is not a mistake (and vice-versa), it might be confusing here but since zooming-in makes the size smaller I preferred to name it that way.
If someone had a solution to this it would be really helpful.
Thank you.

If you try logging the maxZoom and minZoom values do you get the expected values?

I've just tried that: they were both at 0. Thanks for the advice, now I know the problem has to do with those values and not the clamp.

3 Answers

3

Yeah like emalb said,
I would start by debugging your maxZoom and minZoom to check if they are as expected.
I’ve done the mistake tons of times where I don’t set the public float value to anything, test it, change the value in code and still receive 0 from the public variable, since the variable is serialized with the value 0.

So double check the public floats, the rest looks fine to me (but I havent had my morning coffee yet).

The problem will be that when you initialize the variable with a value rather then doing it in start you only have the option to do it the first time when you first create it. So, if you created public float maxZoom; public float minZoom; Then after realizing you needed a value in there (after allowing the editor to view the update) then changed the value to .01f and .5f they will not actually update. To fix this either remove the script and re-add it or better yet just initialize those 2 variables in the start.

Ok I feel really stupid now, it was a typical mistake I would make in Unity: I declared the two min and max variables and saved the script but without assigning them a default value. Then I did that but the values in the inspector were still at 0.

Thanks for the help.