raycast troubles

can some one tell me why this isnt working

var rangevar=100;


function Update () {

	var hit : RaycastHit;

    var fwd = transform.TransformDirection (Vector3.forward);     
    
    if (Physics.Raycast (transform.position, fwd, rangevar)) {
    	  
    	   	
    	
        print ("hitsomething");
        
        if(hit.rigidbody)
        
        
        hit.rigidbody.AddForceAtPosition(10.0 * fwd, hit.point);
        
        
        
        
        
        
        
        
    }
}

i have that on a rigidbody FPS, and when the lvl starts theres a rigidbody with a bx collier in front of him, im trying to get it to move away from my char, im not getting an error, but the things not moving

i was doing this just to try to figure out how raycasting works so while im here ill just ask you guys, am i correct to assume

a.when it says “hit” in the code after the raycast, its refering to the object that was hit

b.once an object has been hit, my char stops raycasting

c.if hit does refer to the object that was hit, can i get its instance ID and change var’s with in it

thanks

You forgot to assign a value to the hit variable. You have to pass it as the third parameter to Physics.Raycast as in the code below:

var rangevar=100.0; 
function Update () { 

    var hit : RaycastHit; 
    var fwd = transform.TransformDirection (Vector3.forward);      
    
    if (Physics.Raycast (transform.position, fwd, hit, rangevar)) { 
        
        print ("hitsomething"); 
        
        if(hit.rigidbody) 
           hit.rigidbody.AddForceAtPosition(10.0 * fwd, hit.point); 
    } 
}

Good catch, I didn’t even see that. Isn’t there an error on Unity’s status bar when you save that script saying that you have an unused variable? There should be.

The variable IS being used. :slight_smile:

I believe in C# you’d get a warning that the variable may not be set before it’s used. Perhaps Javascript is different?

Oops, you’re right! Well, at the very least I would expect a complaint about it not being initialized then.

RaycastHit is a struct, so it is automatically initialised to a default value when declaring the variable.

sigh

I’ll get my coat.

ahhh i see, thanks alot