Unity3D: NullReferenceException: Object reference not set to an instance of an object

不想你离开。 提交于 2020-01-15 07:13:35

问题


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:


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)


来源:https://stackoverflow.com/questions/17588799/unity3d-nullreferenceexception-object-reference-not-set-to-an-instance-of-an-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!