How to make an Integer not go below 0

Hello Guys!

I was wondering if there was an easy way to make an integer not go below zero and into negative numbers! I searched the docs and found Mathf.CeilToInt, but it is not making an sense to me. And I’m guessing I would not do something like this:

function Update () {
	guiText.text = TheScore.ToString();
	
	if (TheScore <= 0){
		TheScore = 0;
	}
}

Or do I use Mathf.Clamp? I tried this:

function Update () {
	TheScore = (Mathf.clamp(0, 100));  // 0 = min 100 = max
}

and this

function Update () {
TheScore.int = Mathf.clamp(TheScore.int, 0, 100);
}

But it gives me this error:

Thank you so much for your help!

–Rush Rage

TheScore = Mathf.clamp(TheScore, 0, 100);

1 Like
Mathf.Clamp
not
Mathf.clamp

Also, if you don’t have a maximum limit it would be:

Mathf.Clamp (0, Mathf.Infinity);
1 Like

There is no Mathf.clamp; you mean Mathf.Clamp.

Aside from putting the guiText.text line at the end (in case the score is below 0), yes that is in fact what you’d do. (Although “< 0” would be slightly more efficient, since you wouldn’t continuously set the score to 0 if it’s already 0.)

However, it would be significantly more efficient not to have this in Update, since it’s highly unlikely the score changes every frame. Instead, just make a function that’s only called when the score changes, and put the above code in that function.

–Eric

Hmm, still gives me this error when I click play:

You’re still trying to use Mathf.clamp, when there is no such thing. Anyway it’s better just to use the “if score < 0, score = 0” technique.

–Eric

Wow! 3 responses with in 5 minutes! This community is awesome.

Thanks for your guys posts, I figured it out!

–Rush Rage

Edit:

When I checked this post I only saw his post not yours. But when I refreshed it I saw yours and Daniels.

1 Like