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);

    }
}
1

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.