Can't use the collision and update void together

In my program (2D), I want the player to be able to do some kind of ability in a certain area. I already know that I can’t put two voids together (in this case [OnTriggerEnter2D(Collider2D other)] and [Update()] ). I know that the update void is used to update the game every tick and look for any input while the collider void is used to see if an object is touching another object with a certain tag (I know this isn’t everything about the voids but it is what I mostly know).

private void OnTriggerEnter2D(Collider2D other))
 {
    if (other.tag == "Ability"){
        if (UnityEngine.Input.GetKeyDown(KeyCode.A)){
           //ability
        }
    }
}

or

void Update(){
    if (UnityEngine.Input.GetKeyDown(KeyCode.A)){
       if (other.tag == "Ability"){
          //ability
        }
    }
}

I don’t think I have any problem in the design itself (the colliders and the tags are right) but I have been stuck at this for about two months and don’t know what to do.

Just use OnTriggerEnter/Exit to disable/enable the component:

public class ExampleComponent : MonoBehaviour
{
	public const string PlayerTag = "Player";
	
	private void Awake()
	{
		// don't need it updating when player isn't inside
		this.enabled = false; 
	}
	
	private void OnTriggerEnter2D(Collider2D other)
	{
		if (other.CompareTag(PlayerTag) == true)
		{
			this.enabled = true;
		}
	}
	
	private void OnTriggerExit2D(Collider2D other)
	{
		if (other.CompareTag(PlayerTag) == true)
		{
			this.enabled = false;
		}
	}
	
	private void Update()
	{
		if (Input.GetKeyDown(KeyCode.A) == true)
		{
			// do stuff
		}
	}
}

Components that are disabled don’t get their Update and other methods called.

It worked! Thanks!

1 Like