- Home /
Raycast Hit not toggling variable if stops hitting
I have a script that needs to set a variable to true if Raycast is hitting a gameObject with tag and false if it is not , The issue is if I move the Generator object or the thing it is hitting and the Raycast is not hitting it anymore the variable is not changing to false
private var Generator : GameObject;
public var Power : float = 100;
public var Current : float = 20;
public var CanGivePower : boolean = false;
public var GivingPower : boolean = false;
public var HitObject;
function Start () {
}
function FixedUpdate () {
var fwd = transform.TransformDirection(Vector3.forward);
var hit : RaycastHit;
Debug.DrawRay(transform.position, fwd * 2, Color.red);
if (Physics.Raycast (transform.position, fwd, hit, 2.00))
{
if(hit.collider.gameObject.tag == ("Electric"))
{
Debug.DrawRay(transform.position, fwd * 2, Color.green);
CanGivePower = true;
}
else if(!hit.collider.gameObject.tag == ("Electric"))
{
CanGivePower = false;
}
}
if(CanGivePower == true)
{
Debug.Log("Yes it is true");
}
else {
Debug.Log("No it is false");
}
}
I've had similar problems. It's possible that the ray is ai$$anonymous$$g at an absolute position, rather than a position relative to its origin. I can't say for sure that's what is happening to you, but maybe try having an empty game object as a child of the generator, where you want the ray to aim, then use its position as your target for your raycast. Hope that helps!
Probably that's because in your if-statement you check if something was hit. If nothing was hit your only line assigning false to the variable is not executed.
Your current code will toggle CanGivePower to false only if the raycast hits something, but not your desired object. If you want to toggle it to false when the raycast doesn't hit anything, you will have to add an else statement after the raycast if. Code:
if(Physics.Raycast()){
//Your current code
}
else
CanGivePower = false;
But that code will only be run when the raycast is successful, isn't it? Look at the braces.
Answer by The_Uber_Rasta · Nov 05, 2014 at 11:42 AM
Wow thanks If I just realized that sooner but it makes sense if Raycast then it must be hitting something so I changed it now and added the else to the end of the raycast statement now it seems to be toggling just fine. Thanks
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Why is this giving me a null refrence exeption? -1 Answers
RayCast Boolean Help 1 Answer
Click to move script help 1 Answer
Raycast Coding Issues 1 Answer