I have an object and I\'m trying to get the player to enter the trigger and press a key, swap the camera.
My code:
public class Canhao : MonoBehaviour
{
Don't check input in a physics callback function. Set a flag to true
in the OnTriggerEnter
function then to false
in the OnTriggerExit
function. You can then check the flag in the Update
function. The Update
function is also where you should check if the 'C' key is pressed since that's checked every frame.
Finally, to check if there is a trigger while 'C' key is pressed, use &&
not ||
. When you use ||
, it means that the if
statement will validate to true
when any of the condition is true
but you want both to be true
so &&
should be used.
public Camera cameraPlayer;
public Camera CameraCanhao;
bool triggered = false;
private void Start()
{
cameraPlayer.gameObject.SetActive(true);
CameraCanhao.gameObject.SetActive(false);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.C) && triggered)
{
if (cameraPlayer.gameObject.activeSelf)
{
cameraPlayer.gameObject.SetActive(false);
CameraCanhao.gameObject.SetActive(true);
}
}
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
triggered = true;
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
triggered = false;
}
}
Note that if this is not working for you, make sure to put Debug.Log
inside OnTriggerEnter
and OnTriggerExit
verify that they are being called. If they are not being called then make sure that "Is Trigger" is enabled on the colliders and that a Rigidbody
is attached to the colliders too.
You are puting TRIGGER || KEYPRESS you must replace the || with &&.
if(other.gameObject.CompareTag("Player") && Input.GetKeyDown(KeyCode.C))