- Home /
Trouble setting a parameter with a collision
Hi, I'm working on health script that does script that damages different health meter depending on what gameobject is hit, unfortunately I am unable to set the gameobject in the "takeDamage" function from the "projectileBullet" script's OnCollisionEnter function.
When the bullet hits the collider the prints the "colBase" as the object it hits but the console gives me a NullReferenceException for the set colBase line(Line 18).
I don't know if it matters but the gameobjects and colliders are children to an empty gameobject.
The Bullet Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ProjectileBullet : MonoBehaviour {
public GameObject colBase;
[SerializeField] int damage;
[SerializeField] GameObject hitEffect;
private void OnCollisionEnter(Collision col) {
ContactPoint conActual = col.contacts[0];
Vector3 pos = conActual.point;
Instantiate(hitEffect, pos, transform.rotation);
colBase = col.gameObject;
print(colBase);
col.gameObject.GetComponent<ArmorScriptHumanoid>().takeDamage(damage,colBase);
Destroy(this.gameObject);
}
}
The Health Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ArmorScriptHumanoid : MonoBehaviour {
////////////Torso parts///////////
public GameObject midTorso;
[SerializeField] float CoreArmor;
public GameObject leftTorso;
[SerializeField] float leftCoreArmor;
public GameObject rightTorso;
[SerializeField] float rightCoreArmor;
void Start () {
}
void Update () {
}
public void takeDamage(int amount,GameObject colActual) {
print(colActual +"armor");
if ((colActual==midTorso) || (leftCoreArmor <=0) || (rightCoreArmor <=0)) {
CoreArmor -= amount;
return;
}
if (colActual == leftTorso) {
leftCoreArmor -= amount;
print("Left");
}
if (colActual == rightTorso) {
rightCoreArmor -= amount;
print("Right");
}
}
}
Have you double checked if your target has the ArmorScriptHumanoid component? The null reference can come from the GetComponent() and not from the colBase.
Answer by niocy · Dec 28, 2017 at 12:46 PM
ArmorScriptHumanoid aScript;
If((aScript = col.gameObject.GetComponent(ArmorHumanoidScript)) != null){ Do stuff }
It might hit something that doesnt have that script so check it
Thanks for your help I changed ` col.gameObject.GetComponent().takeDamage(damage,colBase); To
col.gameObject.transform.parent.GetComponent().takeDamage(damage,colBase);
And now it works.
Your answer
Follow this Question
Related Questions
health not subtracting 1 Answer
Health Regeneration 2 Answers
Health bar losing health 1 Answer
Damage/Health problem 2 Answers
Weapon Mesh Damage 1 Answer