- Home /
sending a message to child objects
I have a pirate ship with a few plates on it. the plates have individual health's. When i shoot a cannon i want it to hit a single plate and use send message to let it know its been hit. Problem is, that whenever i shoot at the ship, it goes to the parent object. How do i register a hit on a child object?
Answer by Odinwastaken · Oct 15, 2020 at 09:34 AM
you can use FindObjectOfType, example further down, just make sure that both the function trying to call it and the function that is getting called are public, if you need anymore help just @ me with your question. I deleted the tab while writing this answer twice now...
if(hit)
{
FindObjectOfType<Script>().Function();
}
all of the plates have the same script. will it still work?
@$$anonymous$$adkrumper9 I don't think it would work if they all have the same script. What is the parent? If it's just a empty gameobject make sure it isn't tagged.
So I'm making a 2d game and I have it so if the player enters the ammo box it would give the ammo to the player and destroy the ammo box it touches. I don't know if this is going to help you but it is another example of something that you are trying to do.
void OnTriggerEnter2D(Collider2D collison) { if (collison.tag == "Ammo10") { currentAmmo += 10; Destroy(collison.gameObject); }
if (collison.tag == "Ammo5") {
currentAmmo += 5;
Destroy(collison.gameObject);
}
if (collison.tag == "Ammo3") {
currentAmmo += 3;
Destroy(collison.gameObject);
}
}
@Odinwastaken i've made progress. when i fire a cannon at the ship telling the cannonball to destroy the ship it does that. Though i want to send a message to a child object (plate) on the ship. how would i do that.
Answer by Madkrumper9 · Oct 15, 2020 at 02:42 PM
forgot to mention cannonball script:
void OnCollisionEnter(Collision hit)
{ // col is a reference to the collider hit
if (hit.gameObject.tag == "ShipPlate")
{ // if the collider belongs to the Player...
hit.gameObject.SendMessage("ApplyDamage", 5); // send the message to its owner
Debug.Log("Collision Detected");
Destroy(hit.gameObject);
}
plateScript:
public void ApplyDamage(int damageTotal)
{
health -= damageTotal;
Debug.Log("Damage " + damageTotal + " was applied");
Destroy(gameObject);
}
Your answer
Follow this Question
Related Questions
onTriggerEnter is unclear to me... 3 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Children must not flip with parent. 3 Answers
Script to add script to all children 1 Answer