Using LinecastAll

Could I get a sample code for how I’m supposed to use “Physics2D.LinecastAll”?

The documentation gives me all the parameters, but I don’t know how to actually use it in a real line of code.

it creates an array filled with Collider2D’s, right? Well, where is that array? How do I gain access to it?

The documentation starts like static RaycastHit2D[ ] LinecastA… which means it is going to give you an array of RaycastHit2Ds.

RaycastHit2D[] hits = Physics2D.LinecastAll(Vector2.zero, Vector2.one);
foreach (RaycastHit2D hit in hits) {
  if (hit.collider.tag == "Player") {
    Debug.Log("Found the player!");
    break;
  }
}
1 Like

Okay, that’s how it works; I need to create my own variable anyway. Doesn’t seem like there’s much point to using this over LinecalNonAlloc.

Aw crap, I didn’t realize it returns results as “RaycastHit2D” and not Collision2D!
How can I turn that into a gameobject so I can run code on it’s attached script?

Or is there another method for finding objects between two points that I missed?

The RaycastHit2D class has a property “collider” that gives you the Collider2D that was hit.

The Collider2D class has a property “gameObject” that gives you the gameObject attached to the Collider2D.

So a minor modification of my previous code:

RaycastHit2D[] hits = Physics2D.LinecastAll(Vector2.zero, Vector2.one);
foreach (RaycastHit2D hit in hits) {
  if (hit.collider.tag == "Player") {
    GameObject playerGameObject = hit.collider.gameObject;
    Debug.Log("Found the player! It's gameObject has name " + playerGameObject.name);
    break;
  }
}