- Home /
How to have GetComponentWithTag return more than one object?
var enemyUnit : GameObject;
var enemyAIScript : EnemyAI;
var enemyHuntScript : EnemyHunt;
function Start(){
enemyUnit = GameObject.FindGameObjectWithTag("Enemy");
enemyAIScript = enemyUnit.GetComponent.<EnemyAI>();
enemyHuntScript = enemyUnit.GetComponent.<EnemyHunt>();
}
Hi all.
I've got a script that accesses an objects(The one tagged with enemy). I've only posted a small section of the script but basically the other functions change if the AIScript and HuntScript are active or not.
I have 5 enemies in this scene but script only accesses one when I need it to get all the enemies. If I try GetComponentsWithTag rather than GetComponentWithTag I get a "BCE0022: Cannot convert 'UnityEngine.GameObject[]' to 'UnityEngine.GameObject'" error. How can I get the script to retrieve more than one instance of an object.
Thanks SeventhStealth
Answer by AngryBurritoCoder · Feb 07, 2015 at 11:24 PM
What you tried was to make many enemies into 1 gameobject variable, thats why you get an error
basically if you want to retreive many enemies then you need to declare a var enemyUnity : GameObject as an array like this var enemyUnity : GameObject[]
now what you did before will work
Answer by jenci1990 · Feb 08, 2015 at 07:42 AM
var enemyUnits : GameObject[]; //Array of GameObject;
var enemyAIScript : EnemyAI;
var enemyHuntScript : EnemyHunt;
function Start() {
enemyUnits = GameObject.FindGameObjectsWithTag("Enemy");
for (var enemy : GameObject in enemyUnits) {
enemyAIScript = enemyUnit.GetComponent(EnemyAI);
enemyHuntScript = enemyUnit.GetComponent.(EnemyHunt);
//example
enemyAIScript.enable = false; //example
}
}
//or you can find all script:
var enemyAIScripts : EnemyAI[]; //Array of EnemyAI
var enemyHuntScripts : EnemyHunt[]; //Array of EnemyHunt
function Start() {
enemyAIScripts = FindObjectsOfType(EnemyAI);
enemyHuntScripts = FindObjectsOfType(EnemyHunt);
for (var enemyAI : EnemyAI in enemyAIScripts) {
//...
}
}
Your answer
Follow this Question
Related Questions
Having some trouble with GetComponent(ScriptName"); Missing Method Exception. 0 Answers
GetComponent getting the whole Object instead of a script. 1 Answer
Can someone help me fix my Javascript for Flickering Light? 6 Answers
iTween Help Please MoveTo not working 1 Answer
Cannot get script component while the game object has a refered script 1 Answer