Press 3D-button Script

Hi there!

I had nothing to do so I made this press 3D-button script!

All you need is a gameobject with a collider that is tagged as “button” to make this script work.

If you want something special to happend when you press the button just put that code within the GetKeyDown-statement.

if you got any improvements to the script feel free to add! :smile:

using UnityEngine;
using System.Collections;

public class ButtonPress : MonoBehaviour {
	
	public Camera activeCamera;
	bool showGUI = false;

	public float PressDistance = 50;

	GameObject buttonGameObject;
	// Use this for initialization
	void Start () {
		if(activeCamera == null)
			activeCamera = Camera.current;
	}
	
	// Update is called once per frame
	void Update () {
		
		showGUI = false;
		buttonGameObject = null;
		
		RaycastHit[] hits;
		
	hits = Physics.RaycastAll(activeCamera.transform.position,activeCamera.transform.forward,PressDistance);
		if(hits.Length > 0)
		{
			foreach (RaycastHit hit in hits) {
				if(hit.collider.gameObject.tag == "button")
				{
					showGUI = true;
					buttonGameObject = hit.collider.gameObject;
				}
			}
		}
		if(showGUI)
		{
			if(Input.GetKeyDown(KeyCode.E))
			{
				Debug.Log("button pressed");
				/*Do button animation*/
				/*Play sound*/
				/*Do stuff*/
				/*Change buttons tag if you do not want to be able to press it again*/
			}
		}
	}
	void OnGUI()
	{
		if(showGUI)
			GUI.Label(new Rect(Screen.width/2,Screen.height/2 + 100,300,300),"Press E to press button");
	}
}
using UnityEngine;
using System.Collections;

public class ButtonPress : MonoBehaviour {

	public GameObject ButtonOn;
	public GameObject ButtonOff;

	private bool CurrentState = true;

	public Camera activeCamera;
	bool showGUI = false;
	
	public float PressDistance = 50;
	
	GameObject buttonGameObject;
	// Use this for initialization
	void Start () {
		if(activeCamera == null)
			activeCamera = Camera.current;
	}
	
	// Update is called once per frame
	void Update () {
		
		showGUI = false;
		buttonGameObject = null;
		
		RaycastHit[] hits;
		
		hits = Physics.RaycastAll(activeCamera.transform.position,activeCamera.transform.forward,PressDistance);
		if(hits.Length > 0)
		{
			foreach (RaycastHit hit in hits) {
				if(hit.collider.gameObject.tag == "button")
				{
					showGUI = true;
					buttonGameObject = hit.collider.gameObject;
				}
			}
		}
		if(showGUI)
		{
			if(Input.GetKeyDown(KeyCode.E))
			{
				Debug.Log("button pressed");
				/*Do button animation*/
				/*Play sound*/
				/*Do stuff*/
				/*Change buttons tag if you do not want to be able to press it again*/
				if (CurrentState)
				{
					ButtonOff.SetActive (true);
					ButtonOn.SetActive (false);
					CurrentState = false;
				}
				else
				{
					ButtonOff.SetActive (false);
					ButtonOn.SetActive (true);
					CurrentState = true;
				}
			}
		}
	}
	void OnGUI()
	{
		if(showGUI)
			GUI.Label(new Rect(Screen.width/2,Screen.height/2 + 100,300,300),"Press E to press button");
	}
}