[C#]Battery Pick Up - need help

How do i make on object pickable on button and from certian distance?

now it works onTrigger

using UnityEngine;
using System.Collections;

public class BatteryPickUp : MonoBehaviour {
	
	public bool removeOnUse = true;
	
	//for late ruse
	public AudioClip pickupSound;
	public AudioClip fullSound;	
	
	
	void OnTriggerEnter(Collider other) {
		
	    if (other.gameObject.tag == "Player") {		
			
			Flashlight flashlightscript = Camera.main.gameObject.GetComponent<Flashlight>();			
			flashlightscript.AddBattery();
					
				if(removeOnUse){				
					Object.Destroy(gameObject);
				}
		}
	}
		
}

Not sure I correct understand you, but if you want to make the same action on button press as the on trigger enter, then write something like this:

    using UnityEngine;
    using System.Collections;
     
    public class BatteryPickUp : MonoBehaviour {
       
        public bool removeOnUse = true;
       
        //for late ruse
        public AudioClip pickupSound;
        public AudioClip fullSound; 
       
       
        void OnTriggerEnter(Collider other) {
           
            if (other.gameObject.tag == "Player") {    
                PickUp();
                }
            }
        }

        public void PickUp() {

                Flashlight flashlightscript = Camera.main.gameObject.GetComponent<Flashlight>();           
                flashlightscript.AddBattery();
                       
                    if(removeOnUse){               
                        Object.Destroy(gameObject);
                    }
        }

     void OnGUI()
     {
          if(Event.Current.keyCode == KeyCode.E)
               PickUp();
     }
        
    }

I thought of this method but what i wanted to achieve was:

1.check if crosshair is on object (or the center of screen - easier)
2.check distance by vector.distance < maxdistance
3.then PickUp(); and Destroy();

first one probably with raycasy but dunno how it works right now , but i give a thought about the second

void Start(){
  		player=GameObject.FindWithTag("Player");
	}

//in update

distance = Vector3.Distance (transform.position, player.position);

something like that?

Yes.

About first - use camera.ScreenPointToRay(crosshairPosition) method to detect if crosssfire hit the baterry

Example of ScreenPointToRay:

...
            Ray ray = camera.ScreenPointToRay(Input.mousePosition);
            ray.direction = camera.transform.forward;
            RaycastHit hit;
            if(Physics.Raycast(ray,out hit,maxDistance)){
                if(hit.collider.name == "BatteryPickUp"){
                    hit.collider.gameObject.GetComponent<BatteryPickUp>().PickUp();
                }
            }
...

thank you so mouch ! :slight_smile: it works perfectly ! now when i look on object it gives battery and get destroyed! now i can adjust on how i want it to work exactly!

again thank you so mouch :smile: