How to Make a Transform Variable Target a Random GameObject?

I have a script where an object needs to target a random GameObject, it then immediately faces it and starts moving towards it (last bits not important). Does anybody have any ideas of how I can target a random gameObject. So far I have tried making a transform variable and setting it to an object with the tag ‘Target’ (I tagged my targets ‘target’).

public Transform tr_player;

tr_Player = GameObject.FindGameObjectWithTag (“Target”).transform;

This always sets tr_player to my fifth target though, any other ideas?

Use the plural version to get all targets, then pick one at random from the array:

GameObject[] targets = GameObject.FindGameObjectsWithTag("Target");
GameObject randomTarget = targets [Random.Range(0, targets.length];

Scripting Reference: