Attack

Tobi_e

New member
okay i tried to use the health component in my attack script but i get this error
Assets\EnemyAttack.cs(86,13): error CS0103: The name 'health' does not exist in the current context I think it's a quite simple solution is there can you help me?

don't worry since i'm not that familiar with c# i have a lot of notes in the code to help me understand everything

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Opsive.UltimateCharacterController.Traits;
public class EnemyAttack : MonoBehaviour
{

public float timeBetweenAttacks = 2f;

public int attackDamage = 7;

public AudioSource attackSound;

public GameObject player;

CharacterHealth characterHealth ;

bool isPlayerInRange;

float timer;

private Animator anim;
void Awake()
{

player = GameObject.Find("Player");

var health = player.GetComponent<Health>();

anim = GetComponent<Animator>();
}

void Update()
{

timer += Time.deltaTime;

if (timer >= timeBetweenAttacks && isPlayerInRange)
{

Attack();
}
}

private void OnCollisionEnter(Collision collision)
{
if (collision.transform.tag == "Player")
{
isPlayerInRange = true;
}
}
private void OnCollisionExit(Collision collision)
{
if (collision.transform.tag == "Player")
{
isPlayerInRange = false;
}
}

void Attack()
{

timer = 0;

if (attackSound != null)
attackSound.Play();

anim.Play("Attack");
// Solange der Spieler noch leben hat
if (health != null)
{
health.Damage(attackDamage);
}
}
}Screenshot 2022-06-27 181930.png
 
You have to remove the var in front of the health in the Awake method as it still defines a new local variable and ignores the member variable.
 
You have to remove the var in front of the health in the Awake method as it still defines a new local variable and ignores the member variable.

I have now added the line 48 Debug.Log to see if the inrange works, but I don't see anything there in the console could it have something to do with it?
 
Unfortunately due to our support load we're not able to help with c# syntax questions. I recommend that you ask these questions on the Unity forum or discord. The Unity Learn tutorials are also a great resource. They will take some time to go through but will be extremely beneficial in the long run. If you have any questions on the character controller API we can definitely help though.
 
Top