Unity3D:NullReferenceException:未将对象引用设置为对象的实例

时间:2013-07-11 08:38:42

标签: unity3d nullreferenceexception

我想从laserController.class访问Hero.class变量“aspect”,但收到错误消息: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 个答案:

答案 0 :(得分:2)

我猜您的Hero组件未附加到GameObject附加laserController的{​​{1}}。 如果您想强制使用该条件,可以使用RequireComponentAttribute

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

其他一些无关的考虑因素:

  • 定义空Update方法是无用的,并且具有性能开销
  • 尝试遵循类的一致命名约定(camel case:laserController -> LaserController