- Home /
2D Platformer - Action When Key Is Pressed During Collision C#
Hello, I would appreciate any help provided by anyone. My issue is that I have a Player script which is attached to the Player, and I have a separate GameObject which is an Apple. The Apple has a Box Collider 2D on it, but what i'm wondering is how can I make a Debug.Log statement when the player is during the Collision and when the Player Presses 'E', the Debug.Log Statement works, because at the moment, it is not working. Here is the Void which is attached to the Player. (Hopefully this will give you a better Idea of what I need help with).
void OnCollisionStay2D(Collision2D coll) {
if (Input.GetKeyDown (KeyCode.E)) {
if (coll.collider.tag == "Item") {
Debug.LogError ("Player Picked Up: " + "Apple" + "!");
}
}
}
So this statement does not work for some reason. I've gone through and I thought it was correct. I've made sure of things such as the Apple having the tag 'Item', but for some reason it only prints the Debug.Log statement when the 2D Player is moving and then when you rapidly press 'E', then it sometimes prints the LogError. (By the way the LogError isn't actually an error, it just helps seeing the contrast between Debug.Log statements).
All help is very much appreciated. Thank You, Kind Regards, Trent!
try this :
void OnCollisionStay2D(Collision2D coll) {
if (coll.gameObject.tag == "Item") {
if (Input.Get$$anonymous$$eyDown ($$anonymous$$eyCode.E))
print ("it work");
}
}
@Fredex8 edited & it work now . @TBART82 use print()
or Debug.Log()
.for simplicity the Debug.LogError is something else se the doc doc
That gives an error by the way as a collision 'does not contain a definition for tag'.
Use either if (coll.gameObject.tag == "Item") {
or if (coll.collider.tag == "Item") {
Both work.
The 3D equivalent of this code works fine. However the issue is that Get$$anonymous$$eyDown is only called on the frame when the key is pressed down so the player would have to release E and press it again for the debug to work. Using Get$$anonymous$$ey ins$$anonymous$$d would fix that and cause it to trigger anytime they are inside the collider and so create the effect of them walking in and picking up the apple without having to do anything else.
A boolean could then be used to cause the pickup to only happen once, or limit the number of apples picked up... whatever the desired behaviour is. However I prefer to use OnCollisionEnter and OnCollisionExit to trigger a boolean that is listened for on Update or to call a separate function. That gets around the fact that OnCollisionStay is going to be constantly called.
This should print the error every time you press E whilst inside the collider. If it is only 'sometimes' doing it then you may have an issue regarding the collision itself.