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 () {

    }
}

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

    }
}
4

1 に答える 1

2

Heroあなたのコンポーネントは、接続先と同じGameObject場所に接続されていないと思いますlaserController。その条件を強制したい場合は、次を使用できますRequireComponentAttribute

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

その他の無関係な考慮事項:

  • 空のUpdateメソッドの定義は役に立たず、パフォーマンスのオーバーヘッドがあります
  • クラスの一貫した命名規則に従うようにしてください (キャメルケース: laserController -> LaserController)
于 2013-07-11T09:20:46.693 に答える