Can Someone tell me what this error is?

I got this error and I don’t what it is, I tried googling it and still don’t understand it.

Assets\Scripts\Gun.cs(49,32): error CS1061: ‘IDamageable’ does not contain a definition for ‘TakeDamage’ and no accessible extension method ‘TakeDamage’ accepting a first argument of type ‘IDamageable’ could be found (are you missing a using directive or an assembly reference?)

This is my script too:

using UnityEngine;
using System;
using System.Collections;

public class Gun : MonoBehaviour
{
    [Header("References")]
    [SerializeField] private GunData gunData;
    [SerializeField] private Transform muzzle;

    float timeSinceLastShot;

    private void Start()
    {
        PlayerShoot.shootInput += Shoot;
        PlayerShoot.reloadInput += StartReload;
    }

    public void StartReload()
    {
        if (!gunData.reloading)
        {
            StartCoroutine(Reload());
        }
    }

    private IEnumerator Reload()
    {
        gunData.reloading = true;

        yield return new WaitForSeconds(gunData.reloadTime);

        gunData.currentAmmo = gunData.magSize;

        gunData.reloading = false;
    }

    private bool CanShoot() => !gunData.reloading && timeSinceLastShot > 1f / (gunData.fireRate / 60f);

    public void Shoot()
    {
        if (gunData.currentAmmo > 0)
        {
            if (CanShoot())
            {
                if (Physics.Raycast(muzzle.position, transform.forward, out RaycastHit hitInfo, gunData.maxDistance))
                {
                    IDamageable damageable = hitInfo.transform.GetComponent<IDamageable>();
                    damageable?.TakeDamage(gunData.damage);
                }

                gunData.currentAmmo--;
                timeSinceLastShot = 0;
                OnGunShot();
            }
        }
    }

    private void Update()
    {
        timeSinceLastShot += Time.deltaTime;

        Debug.DrawRay(muzzle.position, muzzle.forward);
    }

    private void OnGunShot() {
        throw new NotImplementedException();
    }

}

in IDamageable damageable = hitInfo.transform.GetComponent<IDamageable>(); you have selected a type of IDamageable, it does not grant you access to TakeDamage even if there is one, its not part of that interface

so how would I fix it?

Is that exact method, with that exact argument, defined in IDamageable? If not, then you should add it to the interface contract. If you define it in some other class that inherets IDamageable, then you cannot cast to the interface and still have access to the method. Make sure to define that method in the interface.

So would this work?

public interface IDamageable
{
       int CurrentHealth { get; }

       void ApplyDamage(int damage);
}

ApplyDamage or TakeDamage? Pick one, and use it consistently. You can’t call a method that doesn’t exist.

2 Likes

Closed. Low effort. Please use the learn section and some tutorials rather than posting “how do I fix?”

1 Like