I have it set where if the enemy script, named NPC, enters the players collider, which I have set to a trigger,
then they stop, but only if the bool function “hiding” is set to true. Though they seem to just ignore the if statement requiring the bool to be true. I do not receive any errors, it just simply ignores that aspect of the script
here’s the Player script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
private Rigidbody2D rb;
public float speed;
public bool hiding;
public Collider2D collidHide;
public SpriteRenderer sprite;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
hiding = false;
if (Input.GetKey(KeyCode.D))
{
rb.velocity = new Vector2(speed, rb.velocity.y);
}
if (Input.GetKey(KeyCode.A))
{
rb.velocity = new Vector2(-speed, rb.velocity.y);
}
}
private void OnTriggerStay2D(Collider2D collision)
{
if (collision.gameObject.tag == "DoorOpened")
{
if (Input.GetKey(KeyCode.W))
{
hiding = true;
collidHide.GetComponent<Collider2D>().enabled = false;
sprite.GetComponent<SpriteRenderer>().enabled = false;
speed = 0;
rb.velocity = new Vector2(0, rb.velocity.y);
}
if (Input.GetKey(KeyCode.S))
{
hiding = false;
collidHide.GetComponent<Collider2D>().enabled = true;
sprite.GetComponent<SpriteRenderer>().enabled = true;
speed = 4;
}
}
if (collision.gameObject.tag == "DoorClosed")
{
if (Input.GetKey(KeyCode.W))
{
Debug.Log("Closed!!");
}
}
if (collision.gameObject.tag == "NPC")
{
if (!hiding)
{
speed = 0;
rb.velocity = new Vector2(0, rb.velocity.y);
}
}
if (hiding)
{
if (Input.GetKey(KeyCode.S))
{
hiding = false;
collidHide.GetComponent<Collider2D>().enabled = true;
sprite.GetComponent<SpriteRenderer>().enabled = true;
speed = 4;
}
}
}
}
and the NPC script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NPC : MonoBehaviour
{
public int damage = 1;
public float speed;
public GameObject effect;
public GameObject player;
private void Update()
{
transform.Translate(Vector2.left * speed * Time.deltaTime);
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{ if (player.GetComponent<Player>().hiding)
{
Debug.Log("Nothing here!");
}
else
{
StartCoroutine(Caught());
}
}
}
IEnumerator Caught()
{
Debug.Log("surprised!");
speed = 0f;
yield return new WaitForSeconds(5);
}
}