- Home /
Help with raycast == null
Hey all, so i have a bit of a problem which i just cant seem to find a solution to. Imagine this: An enemy ship moves towards a grid of tiles (0.5 unit grid). If it collides with a tile, it adds it to an array of objects to attack. Then it shoots a raycast at the tile above and at the tile below. If they are != null, they are also added to the array. If one of the tiles are null, the script does not work. It works fine if all tiles are existing, but if only one or two are there, it breaks. Any help appreciated. Thanks.
Here is the function:
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag == "MortarRange")
{
health -= 10;
}
if (!isGoingBack)
{
if (canTag)
{
if (collision.tag != "Enemy")
{
if (collision.tag == "Tile" || collision.tag == "Building")
{
targets.Clear();
canClear = false;
canMove = false;
collision.GetComponent<SpriteRenderer>().color = Color.red;
targets.Add(collision.gameObject);
canTag = false;
RaycastHit2D hit = Physics2D.Raycast(new Vector2(targets[0].transform.position.x, targets[0].transform.position.y + 0.5f), Vector2.zero);
if (hit.collider.gameObject != null)
{
if (hit.collider.name != "tile_water_rocks(Clone)" && hit.collider.tag != "Enemy")
{
targets.Add(hit.collider.gameObject);
hit.collider.GetComponent<SpriteRenderer>().color = Color.red;
}
}
RaycastHit2D hit2 = Physics2D.Raycast(new Vector2(targets[0].transform.position.x, targets[0].transform.position.y - 0.5f), Vector2.zero);
if (hit2.collider.gameObject != null)
{
if (hit2.collider.name != "tile_water_rocks(Clone)" && hit.collider.tag != "Enemy")
{
targets.Add(hit2.collider.gameObject);
hit2.collider.GetComponent<SpriteRenderer>().color = Color.red;
}
}
CancelInvoke("Attack");
InvokeRepeating("Attack", 0.1f, 3);
}
}
}
}
}
I haven't read your code completely, but giving Vector2.zero
as direction in the Physics2D.Raycast
method does not make sense.
You may want to do this ins$$anonymous$$d:
RaycastHit2D hit = Physics2D.Raycast(targets[0].transform.position, Vector2.up);
and
RaycastHit2D hit2 = Physics2D.Raycast(targets[0].transform.position, -Vector2.up);
Its a 2D game and the raycast shoots just where i want it to. Thats not the problem.
Your answer
![](https://koobas.hobune.stream/wayback/20220612224255im_/https://answers.unity.com/themes/thub/images/avi.jpg)