How to pick up a "battery" using Raycast javascript?

I want to be able to pick up batteries for my torch. The batteries must add energy to the torch. The torch works fine just this is not working, any help will be appreciated.

This is my first post, and very new to unity.


var rayCastLength = 5;
var batteryPower : int = 10;


function Update (){

var hit : RaycastHit;
if(Input.GetButtonDown(KeyCode.E)&& Physics.Raycast (transform.position, transform.forward, hit, 100)!=false ){
	if(hit.collider.gameObject.tag == "Battery"){
	hit.collider.gameObject.transform.parent = transform;
		Debug.Log("Hit: " + hit.collider.gameObject.name);
		}
	}
}

Below, I have an example, but I haven’t tested your code to see if it is working without simply changing Input.GetButtonDown(KeyCode.E) to Input.GetKeyDown(KeyCode.E) because GetButton is virtual and GetKey the key on your keyboard. Also, I think you might want more than just the frame that your button is pressed, in which case, you want GetKey, not GetKeyDown. GetKey will be processed every frame that the key is held, but when you add down to it, only the frame that the key is pressed will be processed.

If you do this and you still have trouble, maybe it’s your raycast, which, like I mentioned, I didn’t test, but give this ago if that is the case.

var fwd = transform.TransformDirection (Vector3.forward);
    var hit : RaycastHit;
    var layerMask = 1 << 8;
       
     if (Physics.Raycast (transform.position, fwd, 100, layerMask)) {

This should work. You don’t have to use the layerMask, but I wanted to show you that you could cast a ray out to only hit batteries. To do this, you will have to assign the batteries to layer 8 in this example.