- Home /
Press button once to enter vehicle and once again to exit
So, I made a script where a First Person Character can enter the Unity Skycar. But I have run into a situation where I want the enter and exit input to be controlled by the same button. It seems whenever I press the "Interact" button (controlled by the "E" key and "Y" button on an Xbox Controller) it enters and exits the vehicle simultaneously. I just can't seem to figure out how to write the piece of code where I press the button once to enter and once again to exit. Any help would be greatly appreciated.
Thanks
(The script is as follows)
using UnityEngine;
using System.Collections;
using UnityStandardAssets.Vehicles.Car;
public class EnterCar : MonoBehaviour
{
private bool inVehicle = false;
CarUserControl vehicleScript;
CarAudio soundScript;
public GameObject guiObj;
GameObject player;
GameObject carcamera;
void Start()
{
vehicleScript = GetComponent<CarUserControl>();
soundScript = GetComponent<CarAudio>();
player = GameObject.FindWithTag("Player");
carcamera = GameObject.FindWithTag("CarCamera");
guiObj.SetActive(false);
carcamera.SetActive(false);
}
// Update is called once per frame
void OnTriggerStay(Collider other)
{
if (other.gameObject.tag == "Player" && inVehicle == false)
{
guiObj.SetActive(true);
if (Input.GetButton("Interact"))
{
guiObj.SetActive(false);
player.transform.parent = gameObject.transform;
vehicleScript.enabled = true;
soundScript.enabled = true;
player.SetActive(false);
carcamera.SetActive(true);
inVehicle = true;
}
}
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "Player")
{
guiObj.SetActive(false);
}
}
void Update()
{
if (inVehicle == true && Input.GetButton("Interact"))
{
vehicleScript.enabled = false;
soundScript.enabled = false;
player.SetActive(true);
carcamera.SetActive(false);
player.transform.parent = null;
inVehicle = false;
}
}
}
Answer by Xpartano · Mar 19, 2020 at 01:23 AM
When you use Input.GetButton...
your program will register an input on every frame while you keep pressing it. To avoid this, use Input.GetButtonDown
. This will only register the Input one time per button press, no matter if you keep pressing it. It seems your player exits the car and enters because you are calling Input.GetButton...
twice, one if inVehicle == true
and one if inVehicle == false
Check this link for more info about GetButtonDown: https://docs.unity3d.com/ScriptReference/Input.GetButtonDown.html
Your answer
Follow this Question
Related Questions
Help In Making a SphereCast for 3D Tire! Working RayCast Script included! 0 Answers
GetButton will only play animation when held down 2 Answers
Baffling Input.Mouseposition problem. If statement not correctly working. 1 Answer
HoloLens: detect Airtap regardless of Raycast hit 0 Answers
Wanting timer to run after single click 2 Answers