- Home /
store contact with last before destruction
Hey guys, I will get straight to the topic. I have a tower shooting an arrow at an enemy - the enemy gets hit the arrow destructed. I want the tower to receive exp when the enemy gets destroyed. So far so easy ;) my problem - i have several towers shooting arrows at the enemy. I am storing the Towers ID in a variable attached to the arrow (GetInstanceID()) . How does the game realize which arrow hit the enemy the last(before destruction)? so that i can reference back to the according tower? my code is in c# . Any ideas? THanks! :) cheers Kergal
Answer by Meltdown · Aug 07, 2012 at 01:26 PM
Add a variable to each enemy called LastHitById, which stores your TowerID that last hit.
When your enemy health is <= 0, stop accepting hits from arrows or the towers. This will make sure LastHitById has the correct value.
You can then create a public method on your Tower called AddXP, which you call from the enemy just before it dies.
Answer by Kergal · Aug 07, 2012 at 05:46 PM
hey Greg Quinn, that was fast :) . Thank you - that was exactly what I was looking for.
No problem. Please upvote and mark as answer so we know your question has been resolved. Also please don't post comments as 'answers'.
Answer by Owen-Reynolds · Aug 07, 2012 at 03:18 PM
GQ's idea of remembering who hit you last is more versitile (esp if you can be poisoned, and die from it 2 seconds after being hit.)
But, the simplest way to "reference back to the according tower" is to store the tower's transform in the arrow (instead of the ID.) Then when you get a kill, use that to find and tell your owner. Ex (assuming your arrow does the work, not the player):
Transform myTower; // set when arrow(me) is spawned
OnCollisionEnter(Collision C)
if(C is an enemy)
enemyScript ES = C.transform.GetComponenent<enemyScript>();
if(ES.dead==true) quit // rats -- overkilled a dying mob
ES.takeDamage(); // even if it dies, will be around to end-of-frame
// the new part:
if(ES.dead == true)
if(myTower!=null) // did my owner die since it fired me?
myTower.GetComponent<towerScript>.youKilled(C.transform);
Or, have the enemy "give" the credit: ES.takeDamage(myTower); and have the enemy's takeDamage check if the tower is still living and call getEXP for the tower.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Destroying Prefab Also Destroys Prefab Reference 1 Answer
Component passing self to method 1 Answer
How to reference another script and call a function in C# ? 2 Answers