我想从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);
}
}
答案 0 :(得分:2)
我猜您的Hero
组件未附加到GameObject
附加laserController
的{{1}}。
如果您想强制使用该条件,可以使用RequireComponentAttribute
:
[RequireComponent(typeof(Hero))]
public class laserController : MonoBehaviour
其他一些无关的考虑因素:
Update
方法是无用的,并且具有性能开销laserController -> LaserController
)