- Home /
Am I doing this correctly?
So will this script;
Detect when the bullet enters the enemy's collider
Subtract the bullet damage from the total enemy health
Destroy the enemy when the enemy health is less than or equal to 0:
using UnityEngine;
using System.Collections;
public class M9Damage : Monobehaviour {
public GameObject M9_Round;
public float Enemy_Health = 100.0f;
public float M9_Damage = 24.0f;
void EnemyDeath ()
{
Destroy.gameObject;
}
void OnCollisionEnter (Collision col)
{
if (co.gameobject.name == "M9 Round")
{
Enemy_Health -= M9_Round;
}
}
void Update ()
{
if (Enemy_Health <= 0) {
EnemyDeath ();
}
}
}
change
if (co.gameobject.name == "$$anonymous$$9 Round")
to
if (col.gameobject.name == "$$anonymous$$9 Round")
Answer by LiterallyJeff · Sep 15, 2017 at 04:31 PM
The main issue I see is that:
Destroy.gameObject;
Is not valid syntax.
It should be:
Destroy(gameObject);
Secondly, you don't need to check health every frame, because health is not changing every frame. You can call a function like this to change the health value:
private void TakeDamage(float damage)
{
Enemy_Health -= damage;
if(Enemy_Health <= 0)
{
Enemy_Health = 0;
EnemyDeath();
}
}
Answer by unit_nick · Sep 15, 2017 at 04:39 PM
using UnityEngine;
using System.Collections;
public class M9Damage : Monobehaviour {
// not required
// public GameObject M9_Round;
public float Enemy_Health = 100.0f;
public float M9_Damage = 24.0f;
void EnemyDeath ()
{
Destroy.gameObject;
}
void OnCollisionEnter (Collision col)
{
// typo
// if (co.gameobject.name == "M9 Round")
if (col.gameObject.name == "M9 Round")
{
// wrong item
// Enemy_Health -= M9_Round;
Enemy_Health -= M9_Damage;
}
}
void Update ()
{
if (Enemy_Health <= 0) {
EnemyDeath ();
}
}
}
Answer by kaplica · Sep 15, 2017 at 05:03 PM
using UnityEngine;
using System.Collections;
public class M9Damage : Monobehaviour {
public GameObject M9_Round;
public float Enemy_Health = 100.0f;
public float M9_Damage = 24.0f;
void EnemyDeath ()
{
Destroy(gameObject);
}
void OnCollisionEnter (Collision col)
{
if (col.gameObject.name == "M9 Round")
{
Enemy_Health -= M9_Damage;
}
}
void Update ()
{
if (Enemy_Health <= 0) {
EnemyDeath ();
}
}
}
Very simple code, but the way you are doing this will simply cause a lot of trouble once the game gets bigger, You have a damage script for a round, what happens if you get different types of rounds, or even different types of objects ? You will create a script for each type of object? That's a no-no in development world. You need to learn about polymorphism. I would suggest you to learn at least basics in C# before you jump in into creating more advanced games like FPS.
https://www.tutorialspoint.com/csharp/csharp_polymorphism.htm https://en.wikipedia.org/wiki/Composition_over_inheritance
Your answer
Follow this Question
Related Questions
ScriptableObject Inheritance Serialization failure 0 Answers
Understanding compiled code 0 Answers
How does "build" work? 1 Answer