Home > Enterprise >  Visual studio can't find definition for TakeDamage from another method
Visual studio can't find definition for TakeDamage from another method

Time:01-23

I am making health and damage script in Unity. I have error CS0117 'PlayerHealth' does not contain a definition for 'TakeDamage'

I want player to have 20 healths and when touched an object it will damage him. I tried searching on google but I didn't find answer.

PlayerHealth script:


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    public int health = 20;

    public void TakeDamage(int damage)
    {
        health -= damage;

        if (health <= 0)
        {
            Destroy(gameObject, 0.3f);
        }
    }
}

And for EnemyDamage script I use this code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerHealth : MonoBehaviour
{
    public int DMG;
    float cooldown = 0f;

    private void Update()
    {
        Debug.Log(cooldown);
        cooldown -= Time.deltaTime;
    }

    private void OnCollisionEnter(Collision collision)
    {
        PlayerHealth health = collision.gameObject.GetComponent<PlayerHealth>();
        if (cooldown <= 0)
        {
            if (health != null)
            {
                PlayerHealth.TakeDamage(DMG);//here is the error
            }
            cooldown = 1f;
        }
    }
}

CodePudding user response:

PlayerHealth.TakeDamage(DMG); tries to call a static method TakeDamage on the class PlayerHealth but there is no such method, hence the error. Your code is a little mess anyway, lets clean it up. Attach this script to your game objects which can lose health (e.g. a player):

public class Health : MonoBehaviour // you called it NewBehaviourScript
{
    public int health = 20;

    public void TakeDamage(int damage) {
        health -= damage;
        if (health <= 0) {
            Destroy(gameObject, 0.3f);
        }
    }
}

Attach this script to your game objects which can inflict damage:

public class Damage : MonoBehaviour  // you called it PlayerHealth (?!)
{
    public int DMG;
    float cooldown = 0f;

    void Update()
    {
        Debug.Log(cooldown);
        cooldown -= Time.deltaTime;
    }

    void OnCollisionEnter(Collision collision)
    {
        if (cooldown <= 0f) {
            Health health = collision.gameObject.GetComponent<Health>();
            if (health != null) {
                // call TakeDamage on the collided >instance<
                health.TakeDamage(DMG); 
            }
            cooldown = 1f;
        }
    }
}

This should give you a starting point with an appropriate colliders setup.

  • Related