Fall Damage script not working
I'm new to unity and c#. I wrote a fall damage script and everything seems to work fine. It captures the starting y position and ending y position but then it doesn't take away health. As soon as I hit the ground I get the error
"NullReferenceException: Object reference not set to an instance of an object FallDamage.Update () (at Assets/Scripts/FallDamage.cs:60)"
Also in that line I want to do TakeDamage(startYPos - endYPos - damageThreshold);
but it says "can't convert from float to int."
Here is my fall damage script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class FallDamage : MonoBehaviour {
public Transform healthBar;
public float startYPos;
public float endYPos;
public float damageThreshold;
public bool damageMe = false;
public bool firstCall = true;
public bool isGrounded = true;
// Use this for initialization
void OnCollisionEnter(Collision collision)
{
isGrounded = true;
}
void OnCollisionStay(Collision collision)
{
isGrounded = true ;
}
void OnCollisionExit(Collision collision)
{
isGrounded = false;
}
// Update is called once per frame
void Update () {
damageThreshold = 1;
if(GetComponent<Rigidbody>() && isGrounded == false)
{
if(gameObject.transform.position.y > startYPos)
{
firstCall = true;
}
if(firstCall == true)
{
startYPos = gameObject.transform.position.y;
firstCall = false;
damageMe = true;
}
}
if(GameObject.FindObjectOfType<Rigidbody>() && isGrounded == true)
{
endYPos = gameObject.transform.position.y;
if(startYPos - endYPos > damageThreshold)
{
if (damageMe == true)
{
healthBar.GetComponent<Health>().TakeDamage(startYPos - endYPos - damageThreshold);
damageMe = false;
firstCall = true;
}
}
}
}
}
And here is my Health script:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Health : MonoBehaviour
{
public const int maxHealth = 100;
public int currentHealth = maxHealth;
public Image healthBar;
float CalculateHealth()
{
return (float)currentHealth / maxHealth;
}
public void TakeDamage(int amount)
{
currentHealth -= amount;
healthBar.fillAmount = CalculateHealth();
if (currentHealth <= 0)
{
Destroy(gameObject);
currentHealth = 0;
Debug.Log("Dead!");
}
}
}
Answer by exzizt · Mar 21, 2018 at 09:10 PM
Cast from float to int: TakeDamage((int)(startYPos - endYPos - damageThreshold))
.
This GameObject.FindObjectOfType<Rigidbody>()
should be GetComponent<Rigidbody>()
.
Better yet, cache your Rigidbody to improve performance and not call GetComponent in Update:
private Rigidbody _rigidbody;
void Awake() { _rigidbody = GetComponent<Rigidbody>(); }
// Now use _rigidbody in your code instead of GetComponent.
Ensure that "healthBar" really does have a Health component attached to it.
Your answer
Follow this Question
Related Questions
can't damage spawned prefab 1 Answer
Enemy wont deal damage 0 Answers
How to do multiple inheritance (or workaround) with Unity? 1 Answer
Health Script 2 Answers