For example, this is my current script (I’m still working on it, so the variables are not accurate at this point):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerNearbyObjectDetection : MonoBehaviour
{
public bool pushableObjectAtLeft;
public bool pushableObjectAtRight;
public bool pushableObjectAtTop;
public bool pushableObjectAtBottom;
void FixedUpdate()
{
RaycastHit2D leftRayCast = Physics2D.Raycast(transform.position, Vector2.left, 1f);
RaycastHit2D rightRayCast = Physics2D.Raycast(transform.position, Vector2.right, 1f);
RaycastHit2D topRayCast = Physics2D.Raycast(transform.position, Vector2.up, 1f);
RaycastHit2D bottomRayCast = Physics2D.Raycast(transform.position, Vector2.down, 1f);
if (leftRayCast.collider != null)
{
pushableObjectAtLeft = true;
}
else
{
pushableObjectAtLeft = false;
}
if (rightRayCast.collider != null)
{
pushableObjectAtRight = true;
Debug.Log(rightRayCast.collider.transform.gameObject.tag);
}
else
{
pushableObjectAtRight = false;
}
if (topRayCast.collider != null)
{
pushableObjectAtTop = true;
}
else
{
pushableObjectAtTop = false;
}
if (bottomRayCast.collider != null)
{
pushableObjectAtBottom = true;
}
else
{
pushableObjectAtBottom = false;
}
}
}
The “if (rightRayCast.collider != null)” part successfully prints out the tag “Pushable Object” as I had put on the object I was trying to detect: an object that can be pushed. But when I change the if statement to something like this:
if (rightRayCast.collider != null && rightRayCast.collider.transform.gameObject.tag == "Pushable Object")
{
pushableObjectAtRight = true;
Debug.Log(rightRayCast.collider.transform.gameObject.tag);
}
It stops working entirely. The variable stops changing and the log is not printed. Even if I try to put the if statement inside it still doesn’t work. Any reason why? And how can I fix it?