Game Development Reference
In-Depth Information
Now, we need a script that can find these locations. It will be based on our earlier
scripts and will contain three methods: one to find a target, one to move to a target,
and another to hang around.
You can find the completed script at
Disk
|
Scripts
|
React AI
|
LookBusy.cs
. To
get the tags to show up as a dropdown, we've also provided a custom editor, which
is also available at
Disk
|
Scripts
|
React AI
|
TagOption.cs
. You will need to put
this under
Assets/Editor
for it to work in Unity.
TagOptions
is a script that does
nothing more than give a drop-down selector for the tag to be used.
LookBusy
uses
the selected tag to find objects that are targets in the game.
Here are a couple of the methods inside the script. These are easy to reproduce or
modify on your own:
GameObject[] targets =
GameObject.FindGameObjectsWithTag(this.SelectedTag);
// If there are not at least two targets to
choose from return an error
if(targets.Length < 2)
{
Debug.LogWarning("LookBusy.cs:FindTarget()
--> There are less than 2 targets with the tag,
'" + this.SelectedTag + "'. This script wants
more positions.");
yield return NodeResult.Failure;
yield break;
}
// From the targets randomly select one and if
it is closer than our minimum distance return
it, otherwise keep trying a constant number of
times before failing
int attempts = 0;
while(Vector3.Distance(this.Destination.transform.position,
this.transform.position) < this.MinimumDistance)
{
this.Destination = targets[Random.Range(0,
targets.Length)];