2

I want to access Hero.class variable "aspect" from laserController.class, but I receive an error message : NullReferenceException: Object reference not set to an instance of an object.

Hero.class

using UnityEngine;
using System.Collections;

public class Hero : MonoBehaviour {

public float aspect = 0.1f;
void Update () {

    }
}

laserController.class

using UnityEngine;
using System.Collections;

public class laserController : MonoBehaviour {

public float health = 0f;
//public float aspect = 0.1f;

void OnCollisionEnter(Collision collision) {
    if(collision.gameObject.tag == "enemy"){
        Destroy(gameObject);
        Destroy(collision.gameObject);
    }
 }      

void Update () {

    Hero direction = gameObject.GetComponent<Hero>();

    //LaserHealth
    health += Time.deltaTime;

    if(health > 7f){
        Destroy(gameObject);
    } 
    //problem in here
    transform.Translate(Vector3.up * -direction.aspect);

    }
}
John Saunders
  • 157,405
  • 24
  • 229
  • 388
Halil Cosgun
  • 427
  • 3
  • 11
  • 23
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – LearnCocos2D Feb 16 '15 at 10:45

1 Answers1

2

I guess your Hero component isn't attached to the same GameObject where laserController is attached to. If you want to force that condition you can use a RequireComponentAttribute:

[RequireComponent(typeof(Hero))]
public class laserController : MonoBehaviour 

Some other unrelated consideration:

  • Defining a empty Update method is useless and has performances overhead
  • Try to follow consistence naming conventions for classes (camel case: laserController -> LaserController)
Heisenbug
  • 37,414
  • 27
  • 126
  • 181