Check if tag is the same as the previous one

Hello,

I’m actually making a system where when my ball touch the ground, a hit sound is playing. I’m using this piece of code:

 void OnCollisionEnter(Collision hit)
    	{
    		if(hit.gameObject.tag == "Floor")
    		{
    				hitball.volume = speed/(maxSpeed);
    				hitball.pitch =  speed/(maxSpeed);
    				hitball.PlayOneShot(ballhit);
    		}
    	}

It works perfectly, but my problem is that my maps are built with blocks, so everytime I reach a new block, the sound is playing.
I so had the idea to check what’s the previous tag so the sound doesn’t play when the next tag is the same. But that’s what I’m searching for, and I don’t really know how to do it.
So, can someone explain me how can I get it to work?

Thanks.

Hello there,

This should be pretty easy, what you need to do is make a string variable to hold the tag and have it only change inside your if statement when ever a new object is touched, then that var will always have the most recent tag but lagged slightly allowing you to do this:

private string tempTag;
     void OnCollisionEnter(Collision hit)
     {
         if(hit.gameObject.tag == "Floor" &&  hit.gameObject.tag != tempTag)
         {
                 hitball.volume = speed/(maxSpeed);
                 hitball.pitch =  speed/(maxSpeed);
                 hitball.PlayOneShot(ballhit);
                 tempTag = hit.gameObject.tag
         }
     }

This addition to the code will make it only fire when the tag differes from the previous tag(also if tag == Floor, I don’t know if you want to remove that part or not).

I hope this helps!