I am trying to create a script that registers if a collision occurs AND a key is pressed. As the GameObject that it is colliding with moves randomly up or down, I want the player to hit the “a” key if it moves upward (and hits a collider that is positioned above the GameObject), and the “z” key if it moves downward. However, nothing shows up in the console when this happens. I’ve had a look through the forums & the docs and can’t work out why it isn’t working. Here’s my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LeftCollision : MonoBehaviour
{
public GameObject UpperLeftTarget;
public GameObject LowerLeftTarget;
bool LeftCollide = false;
void OnTriggerStay (Collider collision)
{
if (((collision.gameObject.CompareTag("UpperLeftTarget")) && Input.GetKeyDown("a")) || (collision.gameObject.CompareTag("UpperLeftTarget")) && Input.GetKeyDown("z"))
{
Debug.Log("Correct Left Hit!");
LeftCollide = true;
}
}
}
Any suggestions/docs you think would be useful would be much appreciated! Thank you!
If you read up on OnTriggerStay, it doesn’t run every frame. Which means it may not even run the frame your input is triggered.
Instead, you should always check for Input in Update. What I would suggest is you use OnTriggerEnter and OnTriggerExit. When you enter, set a bool or some value that you can compare against. Then in Update, check for your input and the other value so you can determine what to do at that point.
This could be figured out also by adding more Debug.Log statements! Feel free to overuse them when developing! Then you can clean them out later.
Well… A few issues. First, your OnTriggerEnter is within the Update method. And while you can place methods within methods, I’m not sure if that allows it to run as a Unity magic method.
Also, you seem to have an issue with your comparison operators. Remember = is assignment. == is comparison.