OneStepAhead
OneStepAhead

Reputation: 17

How to check if i`m touching something in Unity

I've got OnCollisionEnter2D function, but it say's only once, when i`m landing on ground, i want function that will return object name(or smthng like this) if i'm touching it, so if i'll stay on it it will say me about it not only once but every frame.

Upvotes: 0

Views: 856

Answers (1)

derHugo
derHugo

Reputation: 90639

It's as simple as using the correct method OnCollisionStay2D which is called every frame while you are colliding with another object

Sent each frame where a collider on another object is touching this object's collider (2D physics only).

To be fair: Their example in that link is bullshit since it is for OnTriggerStay2D ^^

It could look like

private void OnCollisionStay2D(Collision2D collision) 
{ 
    Debug.Log($"I am touching {collision.gameObject.name}", this); 
} 

If instead you want to keep track of every touching object I would rather use something like

private HashSet<GameObject> _currentlyTouching = new HashSet<GameObject>();

private void OnCollisionEnter2D(Collision2D collision)
{
    if(!_currentlyTouching.Contains(collision.gameObject))
    {
        _currentlyTouching.Add(collision.gameObject);
    }
}

private void OnCollisionExit2D(Collision2D collision)
{
    if(_currentlyTouching.Contains(collision.gameObject))
    {
        _currentlyTouching.Remove(collision.gameObject);
    }
}

private void Update()
{
    var logString = new StringBuilder("I am touching ");
    foreach(var touchingObject in _currentlyTouching)
    {
        logString.Append(touchingObject.name).Append(" ");
    }
    Debug.Log(logString.ToString(), this);
}

Upvotes: 1

Related Questions