Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by guitargodd97 · Sep 06, 2012 at 01:37 AM · damagereaction

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.

Comment
Add comment · Show 3
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Fattie · Sep 06, 2012 at 08:27 AM 0
Share

As Julia Andrews sings, Let's start at the very beginning ...

So, are you familiar with colliders and triggers ?

avatar image guitargodd97 · Sep 07, 2012 at 12:25 AM 0
Share

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.

avatar image guitargodd97 · Sep 08, 2012 at 02:58 AM 0
Share

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?

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

7 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How to change the damage my gun does? 1 Answer

The damage to my player keeps stacking even after I quit the game and restart. 2 Answers

Health below zero but shows negative numbers 1 Answer

Screen flashes red when taking damage 3 Answers

How do I simulate a tsunami wave? 6 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges