Hello, i know this error gets asked a lot, but im posting this because the other posts havent helped me. I got the following code on the player gun:
if(Physics.Raycast (shootRay, out shootHit, range, shootableMask))
{
EnemyHealth enemyHealth = shootHit.collider.GetComponent <EnemyHealth> ();
if(enemyHealth != null)
{
enemyHealth.TakeDamage (damagePerShot, shootHit.point);
}
}
And it WORKS. If the raycast hits an enemy, it accesses its EnemyHealth script and it takes damage. My problem comes when i try to use the SAME CODE in an automated turret. The turret does shoot at the enemy, and the raycast correctly hits it (ive used debug.log to make sure its hitting the enemy) but the getcomponent always returns null on the turret. I have even tried to make the enemyHealth in “TurretShooting” public and dragging and dropping the enemy object on it in the inspector, but even tho it lets me drop it (the forbidden sign doesnt appear), it instantly disappears when i let go of the mouse click. (on the player i can drop it and works flawlessly)
Here are some screenshots of how i have it set up. Its based on the Unity Survival Shooter Tutorial:
ENEMY with the EnemyHealth script attached.
TURRET
PARTS OF THE TURRET THAT ROTATE AND SHOOT (The code pasted above is in TurretShooting script.
Object that the player uses to shoot