- Home /
Question by
unity_8v5OkcOBfZnEIg · Jun 17, 2021 at 04:00 PM ·
scripting problem
Help with OnTriggerEnter
So, I want the variable "inShadow" to change based on if you are standing in a shadow or not, and it seems to be working if you step in to a shadow, but not the otherway around.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShadowDetection : MonoBehaviour
{
public bool inShadow = false;
void Update()
{
if (inShadow == true)
{
Debug.Log("Shadow");
}
else
{
Debug.Log("Light");
}
}
void OnTriggerEnter2D(Collider2D colinfo)
{
if (colinfo.gameObject.tag == "Shadow")
{
inShadow = true;
}
if (colinfo.gameObject.tag == "Background")
{
inShadow = false;
}
}
}
Comment
Answer by kristiandgrey · Jun 17, 2021 at 04:07 PM
you can use the void OnTriggerExit2D to detect when you leave a shadow , try this:
void OnTriggerExit2D(Collider2D c)
{
if (c.CompareTag("Shadow"))
{
inShadow = false;
}
}
i also recommend using CompareTag instead of .tag :)