Box Collider 2D as a trigger

I’m making a basic platformer/endless runner and I have an obstacle which is a hole through which the player can fall. Currently the player is able to jump out of the hole if the run straight into it, so I am trying to create a trigger the stops the player from jumping once inside the whole.


Currently I have a 2D box collider in the hole area. The collider has the ‘trigger’ box checked but it doesn’t work at all. I’ve attached my script below, which aims to change the players jumpforce when they enter the collider and I know it a fault with the jumpforce as when watched in real-time in the inspector panel, the jumpforce number doesn’t change. There are no compiler errors, but perhaps it is the way in which I phrased the script.

using UnityEngine;
using System.Collections;

public class NoJump : MonoBehaviour {
	public float jumpForce = 400f;
	
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	

		void OnTriggerEnter2D(Collider2D other) {
			jumpForce = 0f;
		}
		
		void OnTriggerExit2D(Collider2D other) {
		jumpForce = 400f;
		}
	

}

First of all, you should check in the OnTrigger methods that the ‘other’ collider that has passed in the trigger is indeed the player object that you don’t want to jump anymore. In the first line of the OnTrigger methods, do a check of the 'other’s tag (e.g. if(other.gameObject.tag == “Player”)) and then do to that object what you will.

Secondly, which I think is your problem here, is that you are changing a variable ‘jumpForce’ in this class which is in no way affecting the player object. You have made a jumpForce variable and changed it in this particular script, but I bet that the jumpForce that the player is using is in a separate script attached to the player object. You would need to get the script in the player object and change the jumpForce variable in that script (e.g. other.gameObject.GetComponent<PlayerScriptWithJumpForceValue().jumpForceVariableInTHATScript = 'new value'). Make sure that the jumpForce variable in the player’s script is public so that it can be reached this way.

Finally, and this is just a personal tip: If you don’t want the player to be controlled anymore and they’re using a rigidbody, set the rigidbody to ‘isKinematic’ to stop them from moving at all and you could have an animation play to simulate falling in the hole. Or better yet, if the infinite runner stays as a long horizontal road where the holes are at the same y-value throughout, then you can write in the player’s script that if they are below a certain y-value to just do whatever you want to be done when the player falls into the hole. It would be much more efficient this way as the infinite runner wouldn’t have to generate colliders.

All the best!