Detecting a collision and doing something to the colliding object
Hi, I'm pretty new to Unity and I'm trying to write a script that detects a collision with an enemy and applies damage specified in other scripts. The problem is, I think that the script executes the "DealDamage" function before even detecting the collision, so the script ends up not working at all. Please, Im stuck on this for a couple of days already lol.
public class DamageDealerScript : MonoBehaviour {
public GameObject Unit, Target;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
private void FixedUpdate()
{
Target = Unit;
}
void OnCollisionStay(Collision collision)
{
Unit = collision.gameObject;
Debug.Log("Collision detected with: " + collision.gameObject.name.ToString());
}
public void DealDamage(int amount, string type)
{
Debug.Log("Received Damage info with these properties: " + amount.ToString() + " , " + type);
if (type == "Meele")
{
Debug.Log("Preparing to deal Damage to:" + Target.name);
Target.gameObject.GetComponent<Bot_Movement>().TakeDamage(amount);
Debug.Log("Damaging Unit: " + Target.name + " for " + amount.ToString() + " damage");
Destroy(gameObject);
}
}
}
Nitpicking, it might be simpler to just reference that Bot_$$anonymous$$ovement component ins$$anonymous$$d of referencing the GameObject it's sitting in.
Can you expand on I think that the script executes the "DealDamage" function before even detecting the collision? $$anonymous$$aybe link the other script that you think is calling this prematurely? Clearly it's not being called here, so we can't help with that yet.
There's not much to show with the other script. It just instantiates the damage dealer at a location and immidiately sends info about the damage amount and type to the instantiated damage dealer.
`{
Instantiate(DamageDealer, new Vector3(BotPosRot.position.x, BotPosRot.position.y, BotPosRot.position.z - 1), BotPosRot.rotation);
}
}
GameObject[] CreatedDamageDealers = GameObject.FindGameObjectsWithTag("Dam_deal");
foreach (GameObject dealers in CreatedDamageDealers)
{
dealers.GetComponent<DamageDealerScript>().DealDamage($$anonymous$$eleeDamage, "$$anonymous$$eele");
Debug.Log("Sending Damage info to: " + dealers.gameObject.ToString());
}`
I just Changed the script a bit, and apparently it doesn't detect the collision at all. I have no idea what's wrong, the colliders are there, they are just not working
Your answer
Follow this Question
Related Questions
Collision Detection Not Working (Unity 5.2.3) 5 Answers
Preventing A Teleporting GameObject From Passing Through Walls 2 Answers
Collision script doesnt work,OnCollisonEnter2D does not work if it collides with the enemy 2 Answers
Cannot detect trigger 2 Answers
Detect overlapping objects 2D game 0 Answers