I am making a simple health script that is based off of the enemy health in the Survival Shooter tutorial, and so far I have everything working, but the enemy is not sinking as expected.
usingUnityEngine;
usingSystem.Collections;
public class MonsterHealth : MonoBehaviour
{
public int health = 100;
NavMeshAgent nav;
Rigidbody rig;
float speed;
void Start()
{
nav = GetComponent<NavMeshAgent> ();
rig = GetComponent<Rigidbody> ();
}
public void TakeDamage(int amount)
{
health -= amount;
if (health <= 0)
{
Dead();
}
}
public void Dead()
{
nav.enabled = false;
rig.isKinematic = true;
/*everything is working to this point. the enemy just immediately drops, and the distance the enemy drops
varies accoding to the speed, rather than changing the speed at which the enemy sinks
*/
transform.Translate (-Vector3.up * speed * Time.deltaTime);
//the enemy is destroyed on delay as expected.
Destroy (gameObject, 5f);
}
}
Dead is only called once. Your code is doing the translate in one frame. You need to have it do it over time once death happens. If you destroy the object after 5 seconds then you need to translate the enemy over that 5 seconds. You could do it in a coroutine, that gets run on death.
LOL I just saw your reply. You posted it exactly one minute after I posted my solution. Just wanted to say thank you for the feedback, that totally would have worked as well.
I was looking to avoid a coroutine, because I’ve only been learning coding for a month now and was worried that I have been relying on coroutines too often. I’ve seen a few people say online that excess use of coroutines can affect performance, but I honestly don’t know enough yet to know if that is true or not.
Yeah, your post showed up after I hit the post reply button.
I would say that excess use of anything can affect performance. I don’t really use coroutines myself, so I couldn’t tell you about the performance of them. I’ve been doing things without coroutines for a long time and haven’t felt the need to use them.