for some reason i cant figure it out this script that makes it so when the enemy projectile hits the player it damages the player but it dosnt work pls help
using UnityEngine;
public class AIprojectiledamage : MonoBehaviour
{
public float damage = 15f;
void OnCollisionEnter (Collision collisionInfo)
{
if (collisionInfo.collider.tag == "Target")
{
Damage();
Debug.Log ("Hit");
}
}
void Damage()
{
singleplayertarget attack = GetComponent<singleplayertarget>();
if (attack != null)
{
attack.TakeDamage(damage);
}
}
}
???
what do i do?
Your GetComponent call is looking for the player script on the projectile, but I’m guessing that’s not where the player script is. GetComponent will only look for other components on the same component you use it on. GetComponent is a method of a base class of MonoBehaviour (the base Component class). Instead you most likely want to search for the player script on the object you collided with.
Something like this:
public class Projectile : MonoBehaviour
{
public float damage = 15f;
void OnCollisionEnter (Collision collisionInfo)
{
var player = collisionInfo.collider.GetComponentInParent<Player>();
if (player == null)
{
return; // hit a collider that doesn't have a Player in it's parent hierachy, ignore this collision.
}
player.Damage(damage);
}
}
public class Player : MonoBehaviour
{
public void Damage(float amount)
{
// process damage here
}
}