I found this error:
Cannot implicitly convert type ‘void’ to ‘EnemyHealth’
This is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerAttack : MonoBehaviour
{
public Camera cam;
public GameObject Hand;
public Weapon myWeapon;
Animator handAnim;
void Start()
{
handAnim = Hand.GetComponent<Animator>();
myWeapon = Hand.GetComponentInChildren<Weapon>();
}
void Update()
{
if (Input.GetMouseButtonUp(0))
{
DoAttack();
}
}
private void DoAttack()
{
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, myWeapon.attackRange))
{
if (hit.collider.tag == "Enemy")
{
EnemyHealth eHealth = hit.collider.GetComponent<EnemyHealth>().TakeDamage(10);
eHealth.TakeDamage(myWeapon.attackDamage);
}
}
}
}
What should I do?
I’d say your error arrises from line 35. In the future, you should include that in your question.
Here, you want to assign the EnemyHealth component from the object you hit to the eHealth variable to work with it in the future. But while doing so, you run TakeDamage() on it at the same time. Now, the computer tries to save the result that the TakeDamage() method would return to eHealth. But since TakeDamage() doesn’t return anything, which is noted by giving it the “void” type, that doesn’t work. The program always tries to convert when the types don’t match, sometimes it can do that, sometimes it can’t. In this case, it’s not possible.
Since you run the “TakeDamage()” method again in the line below, I’d say you just need to take that part away in line 35 and it should work.
1 Like
When asking for debugging help, you should always clearly indicate which line the error occurs on.
2 Likes
Thanks for the hints.
I change all the code actually. This is the code now, and works:
using UnityEngine;
using System.Collections;
public class Gun : MonoBehaviour {
public float damage = 10f;
public float range = 100f;
public Camera fpsCam;
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
void Shoot()
{
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit))
{
Debug.Log(hit.transform.name);
Target target = hit.transform.GetComponent<Target>();
if (target != null)
{
target.TakeDamage(damage);
}
}
}
}
}