Cause player to take damage in Unity 2D










0















I made two scripts. One that'll keep track of the player's health, health bar and cause the screen to flash when the player is damaged. The other script is meant to be placed on any object I wish to do damage to the player, on contact. My problem is, Nothing seems to be doing any damage to the player.



PlayerHealth.cs:





using UnityEngine;
using UnityEngine.UI;

public class PlayerHealth : MonoBehaviour

public int currentHealth;
public float flashSpeed = 5;
public Slider healthSlider;
public Color flashColour = new Color(1, 0, 0, 0.1f);
bool isDead;
bool damaged;

private void Awake()

currentHealth = 100;


private void Update()

damaged = false;


public void TakeDamage(int amount)

damaged = true;
currentHealth -= amount;
healthSlider.value = currentHealth;




AttackPlayer.cs:



using UnityEngine;

public class AttackPlayer : MonoBehaviour

public float timeBetweenAttacks = 0.5f;
public int attackDamage = 10;

GameObject player;
PlayerHealth playerHealth;

float timer;

private void Awake()

player = GameObject.FindGameObjectWithTag("Player");
playerHealth = player.GetComponent<PlayerHealth>();


private void OnTriggerEnter2D(Collider2D col)

if (col.gameObject == player)

Attack();



private void Update()

timer += Time.deltaTime;

if(playerHealth.currentHealth <=0)

// TODO: add death script here.



void Attack()

timer = 0f;
if(playerHealth.currentHealth > 0)

playerHealth.TakeDamage(attackDamage);





The player has a rigidbody2D. The player and damaging objects have Box Collider 2D's on them.










share|improve this question
























  • Are your damaging object has "Is trigger" checked on box collider 2D? There is good table when collision activating docs.unity3d.com/Manual/CollidersOverview.html, check that your setup meet requirements.

    – maximelian1986
    Nov 14 '18 at 6:10












  • Also have you debug it? Does OnTriggerEnter2D fires at all and something wrong with rest part of the scripts, or collision does not even activate it?

    – maximelian1986
    Nov 14 '18 at 6:17











  • Looks like it should work. Inside the OnTriggerEnter2D, try doing if (col.tag == "Player" Attack(); instead

    – JTizzle
    Nov 14 '18 at 6:29















0















I made two scripts. One that'll keep track of the player's health, health bar and cause the screen to flash when the player is damaged. The other script is meant to be placed on any object I wish to do damage to the player, on contact. My problem is, Nothing seems to be doing any damage to the player.



PlayerHealth.cs:





using UnityEngine;
using UnityEngine.UI;

public class PlayerHealth : MonoBehaviour

public int currentHealth;
public float flashSpeed = 5;
public Slider healthSlider;
public Color flashColour = new Color(1, 0, 0, 0.1f);
bool isDead;
bool damaged;

private void Awake()

currentHealth = 100;


private void Update()

damaged = false;


public void TakeDamage(int amount)

damaged = true;
currentHealth -= amount;
healthSlider.value = currentHealth;




AttackPlayer.cs:



using UnityEngine;

public class AttackPlayer : MonoBehaviour

public float timeBetweenAttacks = 0.5f;
public int attackDamage = 10;

GameObject player;
PlayerHealth playerHealth;

float timer;

private void Awake()

player = GameObject.FindGameObjectWithTag("Player");
playerHealth = player.GetComponent<PlayerHealth>();


private void OnTriggerEnter2D(Collider2D col)

if (col.gameObject == player)

Attack();



private void Update()

timer += Time.deltaTime;

if(playerHealth.currentHealth <=0)

// TODO: add death script here.



void Attack()

timer = 0f;
if(playerHealth.currentHealth > 0)

playerHealth.TakeDamage(attackDamage);





The player has a rigidbody2D. The player and damaging objects have Box Collider 2D's on them.










share|improve this question
























  • Are your damaging object has "Is trigger" checked on box collider 2D? There is good table when collision activating docs.unity3d.com/Manual/CollidersOverview.html, check that your setup meet requirements.

    – maximelian1986
    Nov 14 '18 at 6:10












  • Also have you debug it? Does OnTriggerEnter2D fires at all and something wrong with rest part of the scripts, or collision does not even activate it?

    – maximelian1986
    Nov 14 '18 at 6:17











  • Looks like it should work. Inside the OnTriggerEnter2D, try doing if (col.tag == "Player" Attack(); instead

    – JTizzle
    Nov 14 '18 at 6:29













0












0








0








I made two scripts. One that'll keep track of the player's health, health bar and cause the screen to flash when the player is damaged. The other script is meant to be placed on any object I wish to do damage to the player, on contact. My problem is, Nothing seems to be doing any damage to the player.



PlayerHealth.cs:





using UnityEngine;
using UnityEngine.UI;

public class PlayerHealth : MonoBehaviour

public int currentHealth;
public float flashSpeed = 5;
public Slider healthSlider;
public Color flashColour = new Color(1, 0, 0, 0.1f);
bool isDead;
bool damaged;

private void Awake()

currentHealth = 100;


private void Update()

damaged = false;


public void TakeDamage(int amount)

damaged = true;
currentHealth -= amount;
healthSlider.value = currentHealth;




AttackPlayer.cs:



using UnityEngine;

public class AttackPlayer : MonoBehaviour

public float timeBetweenAttacks = 0.5f;
public int attackDamage = 10;

GameObject player;
PlayerHealth playerHealth;

float timer;

private void Awake()

player = GameObject.FindGameObjectWithTag("Player");
playerHealth = player.GetComponent<PlayerHealth>();


private void OnTriggerEnter2D(Collider2D col)

if (col.gameObject == player)

Attack();



private void Update()

timer += Time.deltaTime;

if(playerHealth.currentHealth <=0)

// TODO: add death script here.



void Attack()

timer = 0f;
if(playerHealth.currentHealth > 0)

playerHealth.TakeDamage(attackDamage);





The player has a rigidbody2D. The player and damaging objects have Box Collider 2D's on them.










share|improve this question
















I made two scripts. One that'll keep track of the player's health, health bar and cause the screen to flash when the player is damaged. The other script is meant to be placed on any object I wish to do damage to the player, on contact. My problem is, Nothing seems to be doing any damage to the player.



PlayerHealth.cs:





using UnityEngine;
using UnityEngine.UI;

public class PlayerHealth : MonoBehaviour

public int currentHealth;
public float flashSpeed = 5;
public Slider healthSlider;
public Color flashColour = new Color(1, 0, 0, 0.1f);
bool isDead;
bool damaged;

private void Awake()

currentHealth = 100;


private void Update()

damaged = false;


public void TakeDamage(int amount)

damaged = true;
currentHealth -= amount;
healthSlider.value = currentHealth;




AttackPlayer.cs:



using UnityEngine;

public class AttackPlayer : MonoBehaviour

public float timeBetweenAttacks = 0.5f;
public int attackDamage = 10;

GameObject player;
PlayerHealth playerHealth;

float timer;

private void Awake()

player = GameObject.FindGameObjectWithTag("Player");
playerHealth = player.GetComponent<PlayerHealth>();


private void OnTriggerEnter2D(Collider2D col)

if (col.gameObject == player)

Attack();



private void Update()

timer += Time.deltaTime;

if(playerHealth.currentHealth <=0)

// TODO: add death script here.



void Attack()

timer = 0f;
if(playerHealth.currentHealth > 0)

playerHealth.TakeDamage(attackDamage);





The player has a rigidbody2D. The player and damaging objects have Box Collider 2D's on them.







c# unity3d






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 7:26









derHugo

5,50421229




5,50421229










asked Nov 14 '18 at 6:00









icestorm0806icestorm0806

1901313




1901313












  • Are your damaging object has "Is trigger" checked on box collider 2D? There is good table when collision activating docs.unity3d.com/Manual/CollidersOverview.html, check that your setup meet requirements.

    – maximelian1986
    Nov 14 '18 at 6:10












  • Also have you debug it? Does OnTriggerEnter2D fires at all and something wrong with rest part of the scripts, or collision does not even activate it?

    – maximelian1986
    Nov 14 '18 at 6:17











  • Looks like it should work. Inside the OnTriggerEnter2D, try doing if (col.tag == "Player" Attack(); instead

    – JTizzle
    Nov 14 '18 at 6:29

















  • Are your damaging object has "Is trigger" checked on box collider 2D? There is good table when collision activating docs.unity3d.com/Manual/CollidersOverview.html, check that your setup meet requirements.

    – maximelian1986
    Nov 14 '18 at 6:10












  • Also have you debug it? Does OnTriggerEnter2D fires at all and something wrong with rest part of the scripts, or collision does not even activate it?

    – maximelian1986
    Nov 14 '18 at 6:17











  • Looks like it should work. Inside the OnTriggerEnter2D, try doing if (col.tag == "Player" Attack(); instead

    – JTizzle
    Nov 14 '18 at 6:29
















Are your damaging object has "Is trigger" checked on box collider 2D? There is good table when collision activating docs.unity3d.com/Manual/CollidersOverview.html, check that your setup meet requirements.

– maximelian1986
Nov 14 '18 at 6:10






Are your damaging object has "Is trigger" checked on box collider 2D? There is good table when collision activating docs.unity3d.com/Manual/CollidersOverview.html, check that your setup meet requirements.

– maximelian1986
Nov 14 '18 at 6:10














Also have you debug it? Does OnTriggerEnter2D fires at all and something wrong with rest part of the scripts, or collision does not even activate it?

– maximelian1986
Nov 14 '18 at 6:17





Also have you debug it? Does OnTriggerEnter2D fires at all and something wrong with rest part of the scripts, or collision does not even activate it?

– maximelian1986
Nov 14 '18 at 6:17













Looks like it should work. Inside the OnTriggerEnter2D, try doing if (col.tag == "Player" Attack(); instead

– JTizzle
Nov 14 '18 at 6:29





Looks like it should work. Inside the OnTriggerEnter2D, try doing if (col.tag == "Player" Attack(); instead

– JTizzle
Nov 14 '18 at 6:29












1 Answer
1






active

oldest

votes


















1














  1. Make sure that the players Collider has isTrigger enabled.



  2. attackDamage is public -> set in the inspector. Make sure it is not 0.



    You could use



    [Range(1,100)] public int attackDamage = 10;


    to automatically clamp the value in the inspector.




  3. A guess but I'ld say your Collider might not be on the GameObject player but probably on one of its children => the condition col.gameObject == player is not true.



    Instead of GameObject references rather compare the PlayerHealth (since there is only one) reference like



    private void OnTriggerEnter2D(Collider2D col)

    // gets PlayerHealth component on this or any parent object
    var health = col.GetComponentInParent<PlayerHealth>();
    if (health == playerHealth)

    Attack();





  4. You have



    private void Update()

    damaged = false;


    public void TakeDamage(int amount)

    damaged = true;
    currentHealth -= amount;
    healthSlider.value = currentHealth;



    I don't know what else should happen on TakeDamage but the value of damaged is resetted in Update so right after it was set by the Trigger because Physics events like OnTriggerEnter are executed before Update (see execution Order).




Hint: Instead of



player = GameObject.FindGameObjectWithTag("Player");
playerHealth = player.GetComponent<PlayerHealth>();


you could also use



playerHealth = FindObjectOfType<PlayerHealth>();


if that component exists only once in your scene.




Or to be more flexible (having multiple Players) all you have to do is change your OnTriggerEnter2D and Attack method to



private void OnTriggerEnter2D(Collider2D col)

// gets PlayerHealth component on this or any parent object
var health = col.GetComponentInParent<PlayerHealth>();
if (health != null)

Attack(health);



void Attack(PlayerHealth health)

timer = 0f;
if(health.currentHealth > 0)

health.TakeDamage(attackDamage);




So you wouldn't need to get the reference before.






share|improve this answer

























  • Sadly, right after setting "isTrigger", it started to work. I had separate issues I was able to work through after that. i also used some tips, including the range for health. Thank you.

    – icestorm0806
    Nov 14 '18 at 18:12











  • @icestorm0806 I wouldn't call it Sadly than ;) Glad O could help. Most of the times the reason we know about those things is because everyone made this mistake once ;)

    – derHugo
    Nov 14 '18 at 18:15










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53294004%2fcause-player-to-take-damage-in-unity-2d%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














  1. Make sure that the players Collider has isTrigger enabled.



  2. attackDamage is public -> set in the inspector. Make sure it is not 0.



    You could use



    [Range(1,100)] public int attackDamage = 10;


    to automatically clamp the value in the inspector.




  3. A guess but I'ld say your Collider might not be on the GameObject player but probably on one of its children => the condition col.gameObject == player is not true.



    Instead of GameObject references rather compare the PlayerHealth (since there is only one) reference like



    private void OnTriggerEnter2D(Collider2D col)

    // gets PlayerHealth component on this or any parent object
    var health = col.GetComponentInParent<PlayerHealth>();
    if (health == playerHealth)

    Attack();





  4. You have



    private void Update()

    damaged = false;


    public void TakeDamage(int amount)

    damaged = true;
    currentHealth -= amount;
    healthSlider.value = currentHealth;



    I don't know what else should happen on TakeDamage but the value of damaged is resetted in Update so right after it was set by the Trigger because Physics events like OnTriggerEnter are executed before Update (see execution Order).




Hint: Instead of



player = GameObject.FindGameObjectWithTag("Player");
playerHealth = player.GetComponent<PlayerHealth>();


you could also use



playerHealth = FindObjectOfType<PlayerHealth>();


if that component exists only once in your scene.




Or to be more flexible (having multiple Players) all you have to do is change your OnTriggerEnter2D and Attack method to



private void OnTriggerEnter2D(Collider2D col)

// gets PlayerHealth component on this or any parent object
var health = col.GetComponentInParent<PlayerHealth>();
if (health != null)

Attack(health);



void Attack(PlayerHealth health)

timer = 0f;
if(health.currentHealth > 0)

health.TakeDamage(attackDamage);




So you wouldn't need to get the reference before.






share|improve this answer

























  • Sadly, right after setting "isTrigger", it started to work. I had separate issues I was able to work through after that. i also used some tips, including the range for health. Thank you.

    – icestorm0806
    Nov 14 '18 at 18:12











  • @icestorm0806 I wouldn't call it Sadly than ;) Glad O could help. Most of the times the reason we know about those things is because everyone made this mistake once ;)

    – derHugo
    Nov 14 '18 at 18:15















1














  1. Make sure that the players Collider has isTrigger enabled.



  2. attackDamage is public -> set in the inspector. Make sure it is not 0.



    You could use



    [Range(1,100)] public int attackDamage = 10;


    to automatically clamp the value in the inspector.




  3. A guess but I'ld say your Collider might not be on the GameObject player but probably on one of its children => the condition col.gameObject == player is not true.



    Instead of GameObject references rather compare the PlayerHealth (since there is only one) reference like



    private void OnTriggerEnter2D(Collider2D col)

    // gets PlayerHealth component on this or any parent object
    var health = col.GetComponentInParent<PlayerHealth>();
    if (health == playerHealth)

    Attack();





  4. You have



    private void Update()

    damaged = false;


    public void TakeDamage(int amount)

    damaged = true;
    currentHealth -= amount;
    healthSlider.value = currentHealth;



    I don't know what else should happen on TakeDamage but the value of damaged is resetted in Update so right after it was set by the Trigger because Physics events like OnTriggerEnter are executed before Update (see execution Order).




Hint: Instead of



player = GameObject.FindGameObjectWithTag("Player");
playerHealth = player.GetComponent<PlayerHealth>();


you could also use



playerHealth = FindObjectOfType<PlayerHealth>();


if that component exists only once in your scene.




Or to be more flexible (having multiple Players) all you have to do is change your OnTriggerEnter2D and Attack method to



private void OnTriggerEnter2D(Collider2D col)

// gets PlayerHealth component on this or any parent object
var health = col.GetComponentInParent<PlayerHealth>();
if (health != null)

Attack(health);



void Attack(PlayerHealth health)

timer = 0f;
if(health.currentHealth > 0)

health.TakeDamage(attackDamage);




So you wouldn't need to get the reference before.






share|improve this answer

























  • Sadly, right after setting "isTrigger", it started to work. I had separate issues I was able to work through after that. i also used some tips, including the range for health. Thank you.

    – icestorm0806
    Nov 14 '18 at 18:12











  • @icestorm0806 I wouldn't call it Sadly than ;) Glad O could help. Most of the times the reason we know about those things is because everyone made this mistake once ;)

    – derHugo
    Nov 14 '18 at 18:15













1












1








1







  1. Make sure that the players Collider has isTrigger enabled.



  2. attackDamage is public -> set in the inspector. Make sure it is not 0.



    You could use



    [Range(1,100)] public int attackDamage = 10;


    to automatically clamp the value in the inspector.




  3. A guess but I'ld say your Collider might not be on the GameObject player but probably on one of its children => the condition col.gameObject == player is not true.



    Instead of GameObject references rather compare the PlayerHealth (since there is only one) reference like



    private void OnTriggerEnter2D(Collider2D col)

    // gets PlayerHealth component on this or any parent object
    var health = col.GetComponentInParent<PlayerHealth>();
    if (health == playerHealth)

    Attack();





  4. You have



    private void Update()

    damaged = false;


    public void TakeDamage(int amount)

    damaged = true;
    currentHealth -= amount;
    healthSlider.value = currentHealth;



    I don't know what else should happen on TakeDamage but the value of damaged is resetted in Update so right after it was set by the Trigger because Physics events like OnTriggerEnter are executed before Update (see execution Order).




Hint: Instead of



player = GameObject.FindGameObjectWithTag("Player");
playerHealth = player.GetComponent<PlayerHealth>();


you could also use



playerHealth = FindObjectOfType<PlayerHealth>();


if that component exists only once in your scene.




Or to be more flexible (having multiple Players) all you have to do is change your OnTriggerEnter2D and Attack method to



private void OnTriggerEnter2D(Collider2D col)

// gets PlayerHealth component on this or any parent object
var health = col.GetComponentInParent<PlayerHealth>();
if (health != null)

Attack(health);



void Attack(PlayerHealth health)

timer = 0f;
if(health.currentHealth > 0)

health.TakeDamage(attackDamage);




So you wouldn't need to get the reference before.






share|improve this answer















  1. Make sure that the players Collider has isTrigger enabled.



  2. attackDamage is public -> set in the inspector. Make sure it is not 0.



    You could use



    [Range(1,100)] public int attackDamage = 10;


    to automatically clamp the value in the inspector.




  3. A guess but I'ld say your Collider might not be on the GameObject player but probably on one of its children => the condition col.gameObject == player is not true.



    Instead of GameObject references rather compare the PlayerHealth (since there is only one) reference like



    private void OnTriggerEnter2D(Collider2D col)

    // gets PlayerHealth component on this or any parent object
    var health = col.GetComponentInParent<PlayerHealth>();
    if (health == playerHealth)

    Attack();





  4. You have



    private void Update()

    damaged = false;


    public void TakeDamage(int amount)

    damaged = true;
    currentHealth -= amount;
    healthSlider.value = currentHealth;



    I don't know what else should happen on TakeDamage but the value of damaged is resetted in Update so right after it was set by the Trigger because Physics events like OnTriggerEnter are executed before Update (see execution Order).




Hint: Instead of



player = GameObject.FindGameObjectWithTag("Player");
playerHealth = player.GetComponent<PlayerHealth>();


you could also use



playerHealth = FindObjectOfType<PlayerHealth>();


if that component exists only once in your scene.




Or to be more flexible (having multiple Players) all you have to do is change your OnTriggerEnter2D and Attack method to



private void OnTriggerEnter2D(Collider2D col)

// gets PlayerHealth component on this or any parent object
var health = col.GetComponentInParent<PlayerHealth>();
if (health != null)

Attack(health);



void Attack(PlayerHealth health)

timer = 0f;
if(health.currentHealth > 0)

health.TakeDamage(attackDamage);




So you wouldn't need to get the reference before.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 14 '18 at 7:35

























answered Nov 14 '18 at 7:13









derHugoderHugo

5,50421229




5,50421229












  • Sadly, right after setting "isTrigger", it started to work. I had separate issues I was able to work through after that. i also used some tips, including the range for health. Thank you.

    – icestorm0806
    Nov 14 '18 at 18:12











  • @icestorm0806 I wouldn't call it Sadly than ;) Glad O could help. Most of the times the reason we know about those things is because everyone made this mistake once ;)

    – derHugo
    Nov 14 '18 at 18:15

















  • Sadly, right after setting "isTrigger", it started to work. I had separate issues I was able to work through after that. i also used some tips, including the range for health. Thank you.

    – icestorm0806
    Nov 14 '18 at 18:12











  • @icestorm0806 I wouldn't call it Sadly than ;) Glad O could help. Most of the times the reason we know about those things is because everyone made this mistake once ;)

    – derHugo
    Nov 14 '18 at 18:15
















Sadly, right after setting "isTrigger", it started to work. I had separate issues I was able to work through after that. i also used some tips, including the range for health. Thank you.

– icestorm0806
Nov 14 '18 at 18:12





Sadly, right after setting "isTrigger", it started to work. I had separate issues I was able to work through after that. i also used some tips, including the range for health. Thank you.

– icestorm0806
Nov 14 '18 at 18:12













@icestorm0806 I wouldn't call it Sadly than ;) Glad O could help. Most of the times the reason we know about those things is because everyone made this mistake once ;)

– derHugo
Nov 14 '18 at 18:15





@icestorm0806 I wouldn't call it Sadly than ;) Glad O could help. Most of the times the reason we know about those things is because everyone made this mistake once ;)

– derHugo
Nov 14 '18 at 18:15

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53294004%2fcause-player-to-take-damage-in-unity-2d%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Top Tejano songwriter Luis Silva dead of heart attack at 64

ReactJS Fetched API data displays live - need Data displayed static

政党