- Home /
Why i can't use method in gameObject.getComponent
Hi everyone, sorry for my English level.
My problems it's: I can use method in my enemy in there include scripts TakeDamage().
My Player attack class: public class PlayerAttack : MonoBehaviour {
private Animator anim;
private PlayerCharacteristics PlayerCharacteristics;
// Attack
public Transform attackPoint;
public float attackRange = 0.5f;
public LayerMask enemyLayers;
private void Start()
{
anim = GetComponent<Animator>();
PlayerCharacteristics = GetComponent<PlayerCharacteristics>();
}
// Attack method
public void Attack()
{
if (PlayerCharacteristics.startAtkCoolDown == 0)
{
PlayerCharacteristics.startAtkCoolDown = PlayerCharacteristics.attackCoolDown;
// Play an attack animation
anim.SetTrigger("Attack");
// Detect enemies in range of attack
Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(attackPoint.position, attackRange, enemyLayers);
// Damage enemies
foreach (Collider2D enemy in hitEnemies)
{
enemy.GetComponent<Enemy>().TakeDamage();
// Enemy mark wrong and It say "Could not find namespace type or name"
}
}
}
void OnDrawGizmosSelected()
{
if (attackPoint != null)
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(attackPoint.position, attackRange);
}
}
}
and it's my enemy class
public class Enemy : MonoBehaviour {
// Player health
public float maxHealth;
public float currentHealth;
// Player mana
public float maxMana;
public float currentMana;
// Player data
public int level;
public int strength;
// Attack power
public float attack;
void Start()
{
// Health
currentHealth = maxHealth;
// Mana
currentMana = maxMana;
// Attack
attack = (level + (strength * 3) + 10);
}
public void **TakeDamage**(float damage)
{
currentHealth -= damage;
Debug.Log("Damage...");
if (currentHealth <= 0)
{
Die();
}
}
void Die()
{
Debug.Log(name + " - enemy died!");
Destroy(gameObject);
}
}
And I forgot to add and am writing now, as maybe it wags. Player and Enemy script files are located in different folders.
I am not sure, but try this enemy.gameObject.GetComponent<Enemy>().TakeDamage();
Answer by Marioooo · Feb 04, 2020 at 04:37 PM
Hello! It seems that you're trying to get a component... from a component... you have to get the componen, from the gameobject.
enemy.gameobject.GetComponent<Enemy>().TakeDamage();
this is caused because the variable you're pointing at, is a collider and not a gameobject. Hope this helps
Your answer
![](https://koobas.hobune.stream/wayback/20220612222659im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Player vibrating when falling 1 Answer
When I Enter Play Mode My Player Goes Off The Ground 0 Answers
Random Grid Genaration with walls C# 0 Answers
Unity 5.5 - How to Properly Fix 2D Box Collider Trigger? 4 Answers
Largest Rectangle of Tiles 1 Answer