问题
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