- Home /
Increase score on Raycast hit.
Hello :) 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 :D Thank you
Answer by Priyanshu · Mar 27, 2015 at 07:05 PM
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;
}
Your answer
Follow this Question
Related Questions
Questions about Is Triggers and player collision. HELP! 2 Answers
3D Jump Colission Detection 1 Answer
How to increase score on hit 0 Answers
Make an Enemy Shoot through Raycast 1 Answer
change object material on mouse click. 2 Answers