Unity: Player take damage from enemy projectile

Here is a snippet of the code I have and this code is for making the player take damage when a projectile hits him but when I enter the code I get an error saying: error CS0246: The type or namespace name ‘Player’ could not be found (are you missing a using directive or an assembly reference?)

I have given the player object the Player tag and I have also named the object Player but nothing seems to be working.

Does anyone know how to fix this? I believe it should be an easy fix but I guess I am too big of a noob haha.

      void OnTriggerEnter2D(Collider2D hitInfo) {
                  Player player = GameObject.FindGameObjectWithTag("Player");

Hi @ericsjo119

Nice try with the GameObject change, I think you spotted where the problem was but your solution was just a little off. (To see a list of methods available to GameObject, you can click anywhere on it and hit F12. This will take you to GameObject.cs - and since there is no TakeDamage method in it’s class, you cannot make a GameObject take damage while the object is of type GameObject)

Can you share a code snippet of the class ‘Player’ being defined in your project? If you don’t know what that means, or you don’t have that anywhere, can you instead tell me what class the code you shared is contained in? You should see it at the top of the document.

Also, where is ‘TakeDamage’ method? Is it in the same class as this ‘voidOnTriggerEnter2D’ method?


  • Andrew

I also tried to replace Player player (line 4) with GameObject player but then I got this error: GameObject’ does not contain a definition for ‘TakeDamage’ and no accessible extension method ‘TakeDamage’ accepting a first argument of type ‘GameObject’ could be found (are you missing a using directive or an assembly reference?)