- Home /
SendMessage to objects in an array
Hey,
So I'm trying to make a fighter squadron-like system for my game, where there is a general squadron manager object and several non-parented child fighter gameobjects. As I understand it this is how a lot of games do it.
Anyways, I'm stuck on creating a system to send orders to the units in the squadron from the manager object. Right now, when the manager is created, it instantiates the fighters at certain points on the mothership, and then adds them to an array. So far so good.
function LaunchAllFighters(interval:float) {
var tempMember:GameObject;
for (var n=0; n < (numCraft ); n++) {
var launchPt = hangarBones[hangarIndex];
if (hangarIndex < maxIndex) {
hangarIndex = hangarIndex+1;
} else {
hangarIndex = 0;
}
tempMember =Instantiate (fighter, launchPt.position,launchPt.rotation);
tempMember.rigidbody.velocity = tempMember.transform.forward*launchVel;
tempMember.SendMessage("OnJustLaunched",launchTime);
tempMember.SendMessage("AssignSquadController",transform.GetComponent(SquadronController));
squadMembers.Add(fighter);
yield WaitForSeconds(interval);
}
launchComplete = true;
}
The problem comes when I try to use SendMessage to send orders to the objects in the array. Here I'm just passing a single element of a Vector3 array (the unit's position in formation) to the objects.
function FormUpSquadron() {
var n = 0;
for (var ship: GameObject in squadMembers) {
ship.SendMessage("Teleport",squadPosns[n]);
n = n+1;
}
}
The objects in the squadron have this function in their attached script:
function Teleport(pos:Vector3) {
transform.position = pos;
}
I get a "SendMessage has no reciever" error. Usually that happens when the object you're sending to has no corresponding function, but this one does. So I think it must be something to do with how the object is referenced in the array. I feel like it's something really simple and embarrasing too.
Thanks.
Answer by aldonaletto · Aug 26, 2011 at 03:32 AM
You're adding the prefab fighter to squadMembers, but you should add tempMember:
squadMembers.Add(tempMember);
It happens to everyone! But the rest of your code shows that you know what you're doing, so it was clearly a fool mistake.
Your answer
![](https://koobas.hobune.stream/wayback/20220612192012im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
SendMessage - how to send 2 details? - 2 Vector3's actually 1 Answer
Error referencing custom class elements 0 Answers
Send a message to multiple scripts within an Array - Javascript 1 Answer
SOLVED: Problem with SendMessage -- silently failing 2 Answers
Communicating between objects without any physical connection? 3 Answers