I have my attacking system set up so that the player attacks the enemy by clicking on them. Currently the raycast has no limits on it so i added a check to see if the target was 1 square above, below, left or right of the player. When the player attacks the enemy however it returns this error: NullReferenceException: Object reference not set to an instance of an object.
private void attackEnemy()
{
bool adjacent = false;
Vector3 mousePos = Input.mousePosition;
mousePos.z = 0;
Vector3 screenPos = Camera.main.ScreenToWorldPoint(mousePos);
//send out a raycast to check to see if the tile clicked has an enemy
RaycastHit2D hit = Physics2D.Raycast(screenPos, Vector2.zero);
//check to see if the raycast hit an enemy
if ((hit) && hit.transform.tag == "Enemy")
{
float targetX = GameObject.Find(hit.collider.gameObject.name).transform.position.x; //error starts on this line
float targetY = GameObject.Find(hit.collider.gameObject.name).transform.position.y;
float currentX = GameObject.Find("player").transform.position.x;
float currentY = GameObject.Find("player").transform.position.y;
if (Math.Round(targetX, 0) == Math.Round(currentX, 0))
{
if (Math.Round(targetY, 0) == Math.Round(currentY +- 1, 0))
{
//checks to see if the traget is 1 tile above or below
adjacent = true;
}
else
{ adjacent = false; print("miss"); }
}
else
{
if (Math.Round(targetY, 0) == Math.Round(currentY, 0))
{
if (Math.Round(targetX, 0) == Math.Round(currentX +- 1, 0))
{
//check to see if the target is 1 tile to the left or right
adjacent = true;
}
else
{ adjacent = false; print("miss"); }
}
}
}
}
Is there a substitute for hit.collider.gameObject.name that I can use for GameObject.Find that will return x and y coordinates seperetly or another method that will return the same results?