GetComponent keeps returning null

Hi all, this is my first post here, I’m currently learning Unity next to my CG work. All is going well so far, with the exception of the following problem, which really has me stumped.

Im trying to access a script called “Car1health” on the same object, called Car1. This script contains a variable, public float “carCurrenthealth”, with a starting value of 10. I do this with the following code:

	Car1health other = gameObject.GetComponent< Car1health >();
		if(other == null)
		Debug.Log ("other is null");
		else if(other.carCurrenthealth < 0){


Yet the function keeps returning null. What am I doing wrong?

Any insights would be much appriciated:)

Update: After some more testing, the script actually does execute, (it loads the next scene when the variable reaches 0) but gives a nullreferenceexception at start, unless I add an exception for when the GetComponent retrieves null. Any insights about why this is happening?

if your script is called Car1 then your GetComponent should be getting Car1 rather than Car1health

The variable carCurrenthealth(in the "Car1health"script) is declared at monobehaviour, where the actual code which calculates damage taken is in Update. Declaring the variable in Awake doesnt change anything, and I assume I can’t put the damage calculation in Awake, since I have to check for damage every frame.

However, after some more testing I found it actually does work, although it still gives me a nullreferenceexception at start. Afterwards it retrieves the value just fine. I think you are right about declaring the variable earlier, but I am unsure how.

I added the relevant part of the Car1health script below, if it gives any insights.

using UnityEngine;
using System.Collections;

public class Car1health : MonoBehaviour

	public float carCurrenthealth = 10;
	public float collisionDamage = 1;

	void DamageTaken(){
		carCurrenthealth -= collisionDamage;

	void OnCollisionEnter(Collision collision){

		Debug.Log("Car 1 Health: " + carCurrenthealth);


I really appreciate the help and quick answers by the way:)

Check in inspector if you forgot to add a component to your object