- Home /
finding a tag with a variable
hello. i downloaded this Ai from a video (see code here). on line 2 and 3, i tried doing this code:
var Target : GameObject[];
Target = GameObject.FindGameObjectsWithTag("BlueTeam");
so it could target any game object with the BlueTeam tag but it didnt work. please could somebody help me fix this?
PS. by "didnt work" i mean that nothing happens and the enemy does not target me
Put your line:
Target = GameObject.FindGameObjectsWithTag("BlueTeam");
inside the Start() function;
Answer by DRRosen3 · Feb 19, 2015 at 08:06 PM
Target = GameObject.FindGameObjectsWithTag("BlueTeam");
...should be...
Target = FindGameObjectsWithTag("BlueTeam");
now it finds the object but doesnt follow or attack it
Not entirely sure and javascript isn't my strong suit, but it looks to me like even though Target is an array of multiple objects, the code you posted treats it as a single gameobject.
In function lookAt ():
var rotation = Quaternion.LookRotation(Target.position - transform.position);
What if there are 1000 Targets? How is your object supposed to rotate?
When I operate with GameObject[] arrays in c#, I usually handle them with "foreach".
You need an additional variable for a specific target. Here's some code that I use.
public GameObject target;
public List<GameObject> targets;
private void AddAllTargets()
{
GameObject[] go = GameObject.FindGameObjectsWithTag("BlueTeam");
foreach(GameObject g in go)
{
AddTarget(g);
}
}
private void AddTarget(GameObject target)
{
if(target.gameObject != this.gameObject)
targets.Add(target);
}
private void SortTargetsByDistance()
{
targets.Sort(delegate(GameObject c1, GameObject c2){
return Vector3.Distance(this.transform.position, c1.transform.position).CompareTo
((Vector3.Distance(this.transform.position, c2.transform.position)));
});
}
private void TargetEnemy()
{
if(target == null)
{
SortTargetsByDistance();
target = targets[0];
hud.SetTarget(target.GetComponent<Enemy>());
}
else
{
int index = targets.IndexOf(target);
if(index < targets.Count - 1)
{
index++;
}
else
{
index = 0;
}
target = targets[index];
}
}
So... do I add this to the ai code or is it a separate code
Well this code (for me) is strictly for player input. I have it set up so that at the start AddAllTargets is called. void Start() { AddAllTargets(); }
Then when player presses a certain key (for example TAB) the list of targets is sorted by their distance from the player, and the closest target is selected. I'm not 100% sure how you'll need to implement this. I just wanted to point/guide you in the right direction.