- Home /
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?
Answer by Elier · Dec 31, 2015 at 02:54 PM
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:
http://docs.unity3d.com/ScriptReference/Random.Range.html http://docs.unity3d.com/ScriptReference/GameObject.FindGameObjectsWithTag.html
Thanks @Elier but I think that's in Javascript, I should've specified it was in C#
there's a button on the topright of the page that says C# / Javascript
click on c#