I have created a trigger zone to detect the main player with an attached script that generates a boolean. I want to access that boolean variable in my enemy script (to do a comparison with my raycast boolean to check when the player is in sight).
I want to add that the proper method to do such things is as following:
class TriggerDetector
{
private bool _isEnteredByPlayer = false;
// This allows other scripts to get the value of
// _isEnteredByPlayer but not change it.
public bool IsEnteredByPlayer
{
get{ return _isEnteredByPlayer; }
}
void OnTriggerEnter(collider other)
{
if(other.tag == "player")
{
_isEnteredByPlayer = true;
}
}
}
class Enemy
{
[SerializeField] // Allows the field to be edited in the inspector.
private TriggerDetector _TriggerDetector;
void Update()
{
if(_TriggerDetector != null && _TriggerDetector.IsEnteredByPlayer)
{
// Do whatever the enemy should do.
}
}
}
You really should use “[SerializeField] private” instead of “public” and a property if the field needs to be accessed by different scripts. As long as you do small projects you might not see the benefit of encapsulating, but is soon as you begin with large projects or with a project team it can really bite your butt if you don’t do it.