How can I use raycast to activate a button?

I need to use raycast to see if I am facing an object and if I am within a few feet and and press E, //something happens.

its just rough code… havent tested it… tag the object u want to face - “Obj1”

`update()
    {

      RaycastHit hit;
           if (Physics.Raycast(transform.position, -Vector3.up, out hit, 100.0F))
             {
               if(hit.transform.tag == "Obj1)
               {   // ur in 100 meters of the object
                     if (Input.GetKeyDown(KeyCode.E))
                       {  //u hit  E do something
                       }
              }
            }
    } `

  

To further clarify and help with the above answer, I assume you are using an FPS and the raycast is from the players POV yes?

If so you can add a tag, and you can add a distance variable to the ray cast (in the above answer the 100.0F is a float specifying the distance range, so sub that for what you want the range to be).

You will need to tag the object with a layer (e.g. “Button1”) so make sure its on the object.

The logic of the above code is: Cast a ray out 100F, from the forward direction (he uses up, but you could also use the Vector3.fwd instead). If the ray cast hits something, check its tag. If that tag is the button poll (i.e. keep checking) if the user presses the button (in this case he used E).

Make sense?

I’m usin the following class to handle hold Action.

using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using System.Collections;
using System;



public class ButtonHoldBehaviour : MonoBehaviour{

	public Action onHold;
	public bool hold = false;
	void Start () {
		onHold = () => {
			print ("No Button Behaviour for: " + gameObject.name);
		};
	}
	
	void Update () {
		hold = false;
		if(Input.touches.Length==1){
			if (Input.touches[0].deltaTime>0 ) {
				hold = hover (Input.touches [0].deltaPosition, transform.gameObject);
			}

		}

		if (Input.GetMouseButton (0)) {
			hold = hover (Input.mousePosition, transform.gameObject);
		} 

		if (hold)
			onHold ();
	}

	private bool hover(Vector3 pos, GameObject desired ){
		RectTransform r = desired.GetComponent<RectTransform> ();
		return RectTransformUtility.RectangleContainsScreenPoint (r, pos);
	}
}

It might be usefull @Doneyes.
It worked for me.