I know this is a generic problem, but I can’t wrap my head around how to fix it.
the problem is on line 36. “gameObject.GetComponent().health -= gunDamage;”
public class PlayerShoot : MonoBehaviour
{
public Camera fpsCam;
public GameObject crosshair;
public PlayerLook playerLook;
public EnemyBehavior enemyInfo;
public float gunDamage;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//RaycastHit hit;
//Ray shootingRay = new Ray(fpsCam.transform.position, Vector3.forward);
Please use code tags. We can’t easily see which line is 36 otherwise.
But in cases like this, the issue can be easily narrowed down. You are stringing together multiple references, and most likely, theGetComponent() invocation returned null.
Try using more verbose code that is more likely to reveal errors in your code:
EnemyBehaviour eb = this.gameObject.GetComponent<EnemyBehaviour>();
if (eb !=null){
eb.health -= gunDamage;
}else{
debug.Log("I have no enemy behaviour attched"):
}
… which leads to the second question: Why do you search the own game object (this.gameObject) for the enemyBehaviour script, and not the object that is attached to the collider? That is very likely the reason why the GetComponent() call returns Null and fails on the access to .health. You are accessing the wrong object.
I’m guessing here, but I’m quite convinced that you wanted to write
Using ‘this’ as on line 1 in the first example, even though not required, makes the code much, much more obvious, and reveals mistakes you’d overlook otherwise. This may sound silly, but if you get into the habit of always prepending a statement that starts with ‘gameObject’ or ‘transform’ with ‘this’, you’ll cut down your frustration-derived intake of alcohol and chocolate by a good 50%