- Home /
Setting Up Damage Reaction in Battle
I am having trouble with the game I am currently working on involving the way I am having the character interact and battle with enemies in game. So far, everything I have tried out has not worked out as planned and currently the game freezes when trying to do what I have told it to do. Does anybody know of a tutorial series or even video on setting up a battle system that does not require rigidbody interaction? I followed the BergZergArcade C# tutorial series and he did some basic stuff on damage interaction but where I am at now, I can't seem to figure it out.
I am open to new ideas on how to set this system up, but here is a bit of my code that I am currently using:
Here is the class that all AI or characters have that contain the health variables. It inherits for BasePlayerData only because in the future I would like to have it set up so that the health value is effected by stats set up in that code:
public class PlayerCharacter : BasePlayerData {
public int curHealth;
public int maxHealth;
public float damageCoolDown;
private Transform _myTransform;
private bool _isDamaged;
private bool _isPlayerHealth;
void Start() {
_myTransform = transform;
_isDamaged = false;
damageCoolDown = 0;
maxHealth = GetVitalIndex(0).AdjustedBaseValue;
curHealth = maxHealth;
if(_myTransform.gameObject.tag == "Player") {
_isPlayerHealth = true;
}
}
void Update() {
if(curHealth < 0) {
curHealth = 0;
Die();
}
if(_isPlayerHealth) {
Messenger.Broadcast("player health update", curHealth, maxHealth);
Debug.Log("Maximum Health = " + maxHealth + "Current Health = " + curHealth);
}
}
public void ApplyDamage(int damage) {
Debug.Log("We Recieved Damage: " + damage);
curHealth -= damage;
}
public void Die() {
animation.Play("die");
}
}
Here is the code that makes the Player's Vital bar react to damage:
public class VitalBar : MonoBehaviour { private int _maxBarLength; //bar length at 100% private int _curBarLength; //cur length of bar private GUITexture _display; void Awake() { _display = gameObject.GetComponent();
} // Use this for initialization void Start () { _maxBarLength = (int)_display.pixelInset.width; OnEnable(); } //this method called when gameobject is enabled public void OnEnable() { Messenger.AddListener("player health update", OnChangeHealthBarSize); } //this method called when gameobject is disabled public void OnDisable() { Messenger.RemoveListener("player health update", OnChangeHealthBarSize); } //this method calculates the size of healthbar in relation to % of health the target has left public void OnChangeHealthBarSize(int curHealth, int maxHealth) { _curBarLength = (int)((curHealth / (float)maxHealth) * _maxBarLength); //calculates current bar length _display.pixelInset = CalculatePosition(); } private Rect CalculatePosition() { float yPos = _display.pixelInset.y / 2 - 10; float xPos = (_maxBarLength - _curBarLength) - (_maxBarLength / 4 +10); return new Rect(_display.pixelInset.x, yPos, _curBarLength, _display.pixelInset.height); }
}
And finally, this is the actual chunk of code that is supposed to be doing the actual damage calculations and sending it to the respective receivers. The Battle function is called when the player presses j or when the AI knows to call it because the player is in its range
public void Battle() {
if(animationTime < 0.1f) {
_attackButton = false;
animationTime = 1;
}
else {
animation.Play("attack");
animationTime -= Time.deltaTime;
target.animation.Play("gothit");
float dist = Vector3.Distance(target.position, _myTransform.position);
if(dist < 5) {
if(_myTransform.tag == "Player") {
if(target.CompareTag("Enemy")) {
PlayerCharacter enemy = target.GetComponent();
enemy.curHealth -= damage;
Debug.Log("Enemy Health = " + enemy.curHealth);
}
}
if(_myTransform.tag == "Enemy") {
if(target.CompareTag("Player")) {
if(_playerhHealthTimer < 0.1f) {
PlayerCharacter player = target.GetComponent();
player.curHealth -= damage;
Debug.Log("Player Health = " + player.curHealth);
_playerhHealthTimer = 1;
}
else {
_playerhHealthTimer -= Time.deltaTime;
}
}
}
}
}
}
public void OnTriggerEnter(Collider other) {
target = other.transform;
}
public void AddAllEnemies(){
GameObject[] go = GameObject.FindGameObjectsWithTag("Enemy");
foreach(GameObject enemy in go)
AddTarget(enemy.transform);
}
public void AddTarget(Transform enemy) {
playerTargets.Add(enemy);
}
private void SortTargetsByDistance() {
playerTargets.Sort(delegate(Transform t1, Transform t2) {
return Vector3.Distance(t1.position, _myTransform.position).CompareTo(Vector3.Distance(t2.position, _myTransform.position));
});
}
private void TargetEnemy() {
if(playerTargets.Count == 0) {
AddAllEnemies();
}
if(playerTargets.Count > 0) {
if(selectedTarget == null) {
SortTargetsByDistance();
selectedTarget = playerTargets[0];
}
else {
int index = playerTargets.IndexOf(selectedTarget);
if(index < playerTargets.Count - 1) {
index++;
}
else {
index = 0;
}
selectedTarget = playerTargets[index];
}
}
}
I understand that this is a lot of code and honestly any help that could be given, a tutorial I should watch, a different way I should think about this or a pointer to a mistake I have made, would greatly be appreciated. I have been struggling with this problem for the last two weeks and I finally decided to ask for help showing all the pieces I am using. Thanks again, to all who try to help.
As Julia Andrews sings, Let's start at the very beginning ...
So, are you familiar with colliders and triggers ?
I have done very basic things using triggers and colliders. I know that collides are on practically all game objects from terrains to the actual characters. I also know that you can make a collider a trigger, allowing things to pass through it. In this game I am making, I have sphere colliders on the enemies set to trigger and when the game object tagged "Player" enters the collider, the enemy has to go towards that game object and when the player exits the collider, the enemy has to return to the empty game object that is its parent (the enemies spawn to empty game objects).
Other than that, that's all I really know about triggers and colliders.
I've played around with the battle system some more, and it works for the most part, until I attack with the character and I get the error "NullReferenceException: Object reference not set to an instance of an object" both at the line in the Battle function where it says PlayerCharacter enemy = target.GetComponent(); and then again for the one that I wrote for the player. After I get those errors, the character can no longer move. Why is that?
Your answer
![](https://koobas.hobune.stream/wayback/20220613080700im_/https://answers.unity.com/themes/thub/images/avi.jpg)