• 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 King_Chanka · Apr 28, 2017 at 05:42 AM · collider.oncollisionenter

How do I know who attacked who?

I'm making a 2D local multiplayer fighting game and currently using OnCollisionEnter2D. I want to make it so when player1 gets hit by player2's attack, player1 loses HP. I don't know how can I tell if player1 attacked, or if player1 attacked player2 which resulted in a collision which made the computer treat it as if player1 has been attacked.

Comment
Add comment
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

3 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by Yokimato · May 01, 2017 at 01:01 PM

As @Dave-Hampson points out, the OnCollisionEnter2D function has the Collision2D argument that you will use to figure out if the thing you collided with is applicable for your action.

If you had a script that controlled player's HP, like a HealthController, you could simply see if the colliding object has one and simply subtract HP from them.

Something like:

public class HealthController : MonoBehaviour { [SerializeField] private int maxHp = 10; [SerializeField] private int hp = 10; public void Hit(int damage) { this.hp -= damage; if(this.hp <= 0) { // do death stuff here } } }

Then in your attack script or whatever is looking for this collision, simply check if there's a health controller on it (i.e, it's attackable) and if so, Hit them with the damage of the move/spell/weapon.

public class AttackController : MonoBehaviour { void OnCollisionEnter2D(Collision2D coll) { HealthController healthController = col.gameObject.GetComponent<HealthController>(); if (healthController != null) { healthController.Hit(1); // todo: replace value with actual damage } } }

If you only have 1 possible thing that can be hit, it would be more performant to first check the colliders tag as the documentation example does, however, this allows you to add a health controller to anything that's damage-able (Breakable tables, environment, etc) without needing to modify the AttackController script each time you add a new possible target.

Hope this helps, good luck.

Comment
Add comment · Share
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
0

Answer by Dave-Hampson · Apr 30, 2017 at 09:40 AM

It's passed as a parameter

https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionEnter2D.html

Comment
Add comment · Share
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
0

Answer by FM-Productions · May 05, 2017 at 01:15 PM

Hi, I am currently making a similar game, just in 3D, but here is the basic concept I am using.

With on OnCollisionEnter2D following object is passed as argument:

https://docs.unity3d.com/ScriptReference/Collision2D.html

  1. I have a global GameManager in my Scene. In the Start() function, I store all Players in a Array. Say, for example, my Player GameObjects have the script "PlayerCharacter" attached. In the GameManager Start() function, I would call PlayerCharacter[] allCharacters = FindObjectsOfType<PlayerCharacter>(); to store all of my Players.

  2. In my PlayerCharacter class, I also store a reference of the GameManager, so that a Player Character can access the GameManager.

  3. When a Character registers a collision with on OnCollisionEnter2D following object is passed as argument: https://docs.unity3d.com/ScriptReference/Collision2D.html. What you can do is to access the gameObject of the Collision2D parameter object.

  4. In the OnCollisionEnter2D, first check if the player receiving your event is attacking. Maybe define a variable isAttacking and set it to true when your player should deal damage, if it is true, inform the GameHandler that damage to the other player (the one that caused the OnCollisionEnter2D) should applied.

  5. Now, pass the received gameObject to the GameHandler, and it should find out what player caused the collision. If the player was found, you can deal the hit to him/her. the function in the GameHandler could look like this:

    public void dealDamage(GameObject collidedGameObject) { for (int i = 0; i <= allCharacters.Length; i++) { if (allCharacters[i].gameObject == collidedGameObject) { allCharacters[i].DealDamage(5f); } } }

  6. And of course, for this to work the PlayerCharacter script has to be attached to the gameObject that has caused the collision. Note that you cannot simply call DealDamage on the gameObject itself, it has to be called on the attached PlayerCharacter script since it is defined in there. You could, however, use the function "SendMessage" which I will explain below.

You may be asking why you would need a GameManager for this simple problem. If you do not want to handle things via a separate GameManager, you can call SendMessage on the gameObject you receive in the OnCollisionEnter2D function (https://docs.unity3d.com/ScriptReference/GameObject.SendMessage.html). It could look like this: gameObject.SendMessage("ApplyDamage", 5.0F);When a script on the gameObject exists that implements an "ApplyDamage" method, it is called with a float parameter of 5. The reason I do not use this approach is because I want to work with direct references and avoid reflection functions (such as SendMessage) as much as possible to increase performance in my game.

Another possibility of accessing the "PlayerCharacter" script of the gameObject that triggers the collision event would be gameObject.GetComponent<PlayerCharacter>() in the OnCollisionEnter2D function. But you may want to check if such a script exists on the colliding object. If not, the colliding object is not another player and damage should not be applied.

I hope I could give you a basic idea how to possibly tackle this problem.

Kind regards

Comment
Add comment · Share
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

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

6 People are following this question.

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

Related Questions

Carcassonne style mechanic using box colliders to check edge type for a match,script for checking if two boxCollisions share a variable type? Carcassonne! 0 Answers

Checking collisions between two objects that don't have rigidbodies 1 Answer

IEnumerator workaround.. not working around. 1 Answer

Prevent a game object collide against specific colliders. 1 Answer

How to find the velocity of a point in a collider? 1 Answer


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