- Home /
C# SendMessage to objects in array
So I've been pulling out my hairs one by one trying figure this one out. It's probably quite an obvious mistake, but I can't seem to find it. I'm trying to send a message to all enemies in the scene from the player when the player dies.
Here are the parts of the player script:
public GameObject[] enemies;
void Awake()
{
enemies = GameObject.FindGameObjectsWithTag("Enemy");
}
void Respawn()
{
for (int i=0; i<enemies.Length; i++)
{
enemies[i].SendMessage("PlayerDied");
}
}
And the enemy script just has a function called "PlayerDied", which sets the enemy in a passive state. The problem is, I keep getting the error that says: 'SendMessage has no receiver!'
Any help would be appreciated!
Answer by TheAlmightyPixel · Jan 01, 2015 at 02:36 PM
Okay, I got it to work. Basically my enemies have multiple child objects on them. They were all tagged with the tag 'Enemy'. So, instead of calling the PlayerDied() method on a 'Brain' child object of the enemy, the method was trying to be called on the enemy parent object, which is just a NavMesh Agent. All I had to do was to use a different tag on the brain object and search for objects with that tag...
I feel dumb for not realising that.
Answer by Landern · Jan 01, 2015 at 12:57 PM
try:
enemies[i].SendMessage("PlayerDied", SendMessageOptions.DontRequireReceiver);
That way if there is other components/scripts that dont' have that method on them, it won't throw an error RequireReceiver is the default when not specificied.
I tried doing so, but now the function isn't ran at all. I tried using a Debug.Log just to see if it actually ran, but it's not doing anything.
Is the scope of the script directly attached to the array of GameObjects called enemies? Does enemies have a Length? What is the structure of one of the enemy gameobjects in the inspector? What does the other script look like that has PlayerDied method on it? Is it also c# or unityscript?
The length of the array is the same as the amount of enemies in the scene. The enemies do actually have multiple child objects, with one of them being their 'brain' with the script. The enemy script is C#, and the PlayerDied method is a regular void method. I think it might be possible that the script isn't calling the function from the brain object, but on the enemy parent object itself, as I have them all tagged as 'Enemy'. I'll mess with the tags a bit and see how it goes.