Increase score on Raycast hit.

Hello :slight_smile: I’m kinda new to unity and I couldn’t figure out a way to solve this. I also searched a bit in this forum and didn’t find a fix to my problem.

My problem is, I use a Raycast to detect when the Player hits the top of my other GameObject(Cube). This Raycast decision is inside my Update void which means this will run every frame. I only want my score to increment by 1 for every hit on the Cube, not for every frame it is sitting on the Cube.

My code: (C#)

void Update () {
    
    		RaycastHit hit;
    		//detect if player has hit the top of the platform
    		if(Physics.Raycast(transform.position, Vector3.down, out hit, 0.6f))
    		{
    			if(hit.collider.tag == "Platform") //i check if i hit the specific Cube
    			{
    
    				print ("HIT!!!!!!!!!");
    				isAir = false;
    				//PlatformMovement.platformMovement.shouldMove = false;
    				GameController.controller.score += 1; // i increase my score here
    			}
    		}
    }

Any help would be appreciated :smiley: Thank you

These type of situations can be solved by using bool. I tried to explain it in comments

	public RaycastHit hit; //Assign hit here so it doesn't get assigned every frame.

	public bool hitOnce = false;	//Bool to update score once.

	void Update () {
    
		Debug.DrawRay(transform.position, Vector3.down * 0.6f, Color.red);

		//detect if player has hit the top of the platform
		if(Physics.Raycast(transform.position, Vector3.down, out hit, 0.6f))
		{
            //i check if i hit the specific Cube and it has not been hit yet.
			if(hit.collider.name == "Platform" && !hitOnce ) 
			{
			    print ("HIT!!!!!!!!!");
				//Change 'hitOnce' to 'true' so that 'if' statement is not executed every frame while player is sitting on the Cube.'
				hitOnce = true;
				isAir = false;
				//PlatformMovement.platformMovement.shouldMove = false;
				GameController.controller.score += 1; // i increase my score here
			}
		}
		//Change 'hitOnce' back to false when player moves away from Cube. That is 'RayCast' return false.
		else hitOnce = false;
	}