Hello everyone can someone give me a way how my enemy able to chase more than 1 target with a tag("Human") ? It seems that

target = GameObject.FindGameObjectsWithTag("Human").GetComponent<Transform>(); 

Transform is not applicable to use this.

3

2 Answers

The GameObject.FindGameObjectsWithTag function returns an array of GameObject. You would use it like this:

GameObject[] target = GameObject.FindGameObjectsWithTag("Human"); 

If you need array of Transform, create new array with the size of the GameObject returned by GameObject.FindGameObjectsWithTag then copy it in a loop. You don't need the GetComponent function. The transform property should be used here.

GameObject[] target = GameObject.FindGameObjectsWithTag("Human"); Transform[] targetTransform = new Transform[target.Length]; //Copy the GameObject transform to the new3 transform array for (int i = 0; i < target.Length; i++) { targetTransform[i] = target[i].transform; } 
1

@Programmer a decent solution but as I have been learning more about the efficiency of ECS and structs a clean solution could be the following. It will also be more adaptable in the future.

[System.Serializeable] public struct Human { Transform transform; } GameObject[] targets = GameObject.FindGameObjectsWithTag("Human"); List<Human> humans = new List<Human>(); foreach (GameObject target in targets) { Human human = new Human(); human.transform = target.transform; humans.add(human); } 

It looks slower and it's initial setup may be, but access down the road won't. You shouldn't deal with straight arrays if you don't need to and now you have an extensible Human object.

3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy