2

我想从laserController.class 访问Hero.class 变量“aspect”,但我收到一条错误消息:NullReferenceException: Object reference not set to an instance of an object

英雄类

using UnityEngine;
using System.Collections;

public class Hero : MonoBehaviour {

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

    }
}

激光控制器类

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

    }
}
4

1 回答 1

2

我猜你的Hero组件没有连接到相同的GameObject位置laserController。如果你想强制这个条件,你可以使用RequireComponentAttribute

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

其他一些不相关的考虑:

  • 定义一个空Update方法是没有用的,并且有性能开销
  • 尝试遵循类的一致性命名约定(驼峰式laserController -> LaserController:)
于 2013-07-11T09:20:46.693 回答