I am randomly spawning some Rabbit Prefabs in a set area.
I am also spawning some Carrot Prefabs in a set area.
The Rabbit Prefabs are set to find the closest Carrot Prefab move to it and slowly lower it’s life which I have working perfectly.
Once the Carrots Prefabs life runs out I want to tell the Rabbit Prefab to again find the closet Carrot Prefab.
Once the Carrot Prefabs life has run out I call the function written below:
function changeTarget() {
var rabbits : GameObject = GameObject.FindWithTag("rabbit");
if (rabbits == null) {
print("No rabbits found!");
}
var rabbitScript : mediumRabbitAI = rabbits.GetComponent(typeof(mediumRabbitAI)) as mediumRabbitAI;
rabbitScript.moveOn();
}
The only problem is that instead of telling all the Rabbit Prefabs to run their “moveOn” function it only tells the first Rabbit Prefab it finds.
I’m only just getting into coding and I’ve been scouring the forums trying to put the Rabbit Prefabs into an array because I think this might be the way to do it but I can’t get it right.
If someone could point me in the right direction that would be a great help.
you are trying to use GetComponent on an array, you have to use it on single components (for example rabbits[0]) or just loop through all of them using a for-loop
Thanks alot for your replies guys I think I know where I’m going wrong now.
let me just comment your bit of code just to make sure that I’m getting it?
function changeTarget()
{
//this finds all my game objects with the tag rabbits. Does it automatically put them into an array?
var rabbits = GameObject.FindGameObjectsWithTag("rabbit");
if (rabbits == null)
{
print("No rabbits found!");
}
// this loops through the rabbits in the array until it's gone through all objects in the array
for (var rabbit : GameObject in rabbits)
{
var rabbitScript = rabbit.GetComponent(mediumRabbitAI);
rabbitScript.moveOn();
}
}
so GetComponent will only accept the information for one game object at a time and this is why we loop through them?