De/activating Gameobject depending on distance from different Activators

So I have a UI-Button that becomes visible if the player is in a certain distance from a Activator-GameObject to activate something, let’s say a door.

The Activator-GameObject has a script called Activator attached:

public GameObject[] targets;
private Transform player;
private float distance;

private ButtonPressed buttonActivate;

void Awake () {
	player = GameObject.Find("Player").transform;
	buttonActivate = GameObject.Find("HUD").transform.GetChild(0).GetComponent<ButtonPressed>();
}

void Update () {
	distance = Vector3.Distance(transform.position, player.position);
	buttonActivate.gameObject.SetActive(distance <= activationRange);
	if(distance <= activationRange && buttonActivate.pressed)
		ToggleActivate();
}

The UI Button has a seperate script called ButtonPressed to give the Activator-script the bool variable:

public bool pressed;

public void OnPressed () {
	StartCoroutine(x ());
}

private IEnumerator x(){
	pressed = true;
	yield return new WaitForEndOfFrame();
	pressed = false;
}

The function OnPressed gets called by OnPointerDown from the EventTrigger-Component that starts an IEnumarator function which sets the bool pressed to true until the end of the frame to avoid staying to true all the time, because the activator-script will run ToggleActivate() every frame, so the door would be closing/opening instantly.

So, everything works as it should, but when I have 2 or more Activator-GameObjects in the game that should activate 2 different objects (light/door), the UI Button gets only visible when the player is in range of the first founded Activator-GameObject in the scene hierarchy, the other Activator-GameObjects are ignored.

1 Like

Well the theory behind it is no different to let’s say a character interaction system in an RPG, that allows said player to interact with the UI when it’s closest to the player and / or closest NPC.

What you want to do is store the gameobjects in an array, with the closest object being the one the UI will interact with. If you need some code to help: