Raycast if no hit problems
Hi, I'm trying to make a script that locks on to a target if it is hit by the ray for a certain period of time, while the script works for the most part, if the raycast hits something the "locking" variable does not get turned to true. I think the "Locking" variable is being overwritten by the else function that is meant to set it to false.
this GIF shows what happens if I have the locking set to false in the raycast else statement.
this Gif shows what happens if I remove the locking bool from the raycast else statement
void Update() {
{
RaycastHit hit;
if (Physics.Raycast(transform.position, gameObject.transform.forward, out hit, 1000)) {
ArmLeft.transform.LookAt(hit.point);
ArmRight.transform.LookAt(hit.point);
Debug.DrawLine(gameObject.transform.position, hit.point, Color.yellow);
locking = true;
///////////////Lockon Setting//////////////////
// #region LockOn
if (hit.collider.gameObject.tag == "Mech") {
foundTarget = hit.collider.gameObject;
}
else
foundTarget = null;
}
else
///////This is what I want to happen if the ray doesn't hit///////////
ArmLeft.transform.LookAt(nullRayHit);
ArmRight.transform.LookAt(nullRayHit);
locking = false;
}
////////these control the setting and unsetting the locked target///////
if (foundTarget != null) {
lostTime = startLostTime;
lockTime -= Time.deltaTime;
}
else
lockTime = startLockTime;
lostTime -= Time.deltaTime;
if(lockTime <=0 ) {
lockedTarget = foundTarget;
}
if (lostTime <= 0) {
lockedTarget = null;
}
//#endregion
thanks for your help.
Answer by Larry-Dietz · Dec 24, 2017 at 05:03 AM
Your problem is in your else clause.
Right now the only thing in else is ArmLeft.transform.LookAt(nullRayHit);
You are missing { }'s around your else clause, so only the first line is being used in else, and the next two lines which should be in else are executing every time.
Just wrap the lines for your else clause in { }'s and you should be good.
Also, just to point it out, you have another else clause near the bottom of the code with the same issue.
Hope this helps, -Larry
Thanks for your answer, the scipt is working perfectly now.
Your answer
Follow this Question
Related Questions
Raycasting problem, colliders not being recognized? 1 Answer
RayCast appears to bug out for no apparent reason 1 Answer
Raycast help 0 Answers
Switching from object to object with Raycast Problem 1 Answer
Raycast doesn't stay in one place 0 Answers