本文介绍了Unity3D:NullReferenceException:对象引用未设置为对象的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

Hero.class

using UnityEngine;
using System.Collections;

public class Hero : MonoBehaviour {

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

    }
}

laserController.class

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

    }
}

推荐答案

我想您的Hero组件未附加到与laserController相同的GameObject上.如果要强制该条件,可以使用RequireComponentAttribute:

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:

  • 定义一个空的Update方法是没有用的,并且会产生性能开销
  • 尝试遵循类的一致性命名约定(驼峰式案例:laserController -> LaserController)
  • Defining a empty Update method is useless and has performances overhead
  • Try to follow consistence naming conventions for classes (camel case: laserController -> LaserController)

这篇关于Unity3D:NullReferenceException:对象引用未设置为对象的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-29 12:03