I’m trying to get a specific script that’s on all game objects marked with a certain tag but I’m having a bit of difficulty understanding how FindGameObjectsWithTag works. Here is what I tried:
public HitReaction hitReaction;
void Awake(){
hitReaction = GameObject.FindGameObjectsWithTag("HitReactor").GetComponents<HitReaction>();
}
(I need to use hitReaction later on in the script with a Raycast hit)
But I get the error: Type UnityEngine.GameObject[]' does not contain a definition for GetComponents’ and no extension method GetComponents' of type UnityEngine.GameObject[]’ could be found (are you missing a using directive or an assembly reference?)
Clearly that’s not the way to do this. I looked through the manual for FindGameObjectsWithTag but I couldn’t find any examples using it with GetComponent. Any advice?
FindGameObjectsWithTag returns an array of GameObjects. You can only call GetComponents on a single GameObject, not an array.
Since it looks likes you’re only looking to store a single HitReaction, I’m assuming you only have one HitReactor? If that’s the case, then is this what you were trying to do?
public HitReaction hitReaction;
void Awake(){
hitReaction = GameObject.FindWithTag("HitReactor").GetComponent<HitReaction>();
}
If you have multiple HitReactors, and you want to store the HitReaction for each one, then I think this is what you want:
public HitReaction[] hitReaction;
void Awake(){
GameObject[] reactors = GameObject.FindGameObjectsWithTag("HitReactor");
hitReaction = new HitReaction[reactors.Length];
for ( int i = 0; i < reactors.Length; ++i )
hitReaction _= reactors*.GetComponent<HitReaction>();*_