Script to script variable access

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).

How would I access that boolean?

The pattern for accessing other scripts is simple.

  • Get a reference to the GameObject
  • Call GetComponent to get the component you want
  • Access the variable

In your case the GameObject reference can be gotten from the collider that is passed into OnTriggerEnter

1 Like

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.
        }
    }
}
1 Like

Thanks, in the end I ended up creating the public variable class access with the Unity interface:

public playerDetection trigger;

Dragging the gameobject to the slot and accessing the bool with:

pDetStatus = trigger.playerDetected;

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.

1 Like