首页 > 解决方案 > 使用附加到触发器的此脚本时出现 NullReferenceException

问题描述

我正在使用附加到设置为触发器的 GameObject 的此脚本,但我无法解决此 NullReferenceException 错误:

对象引用未设置为对象的实例。IntExt_Trigger.awake() (在 Assets/scripts/IntExt_Trigger.cs)

我不知道是什么原因造成的……因为据我所知,唤醒功能正在正确应用,有什么我完全遗漏的吗?

这是脚本。

using System.Collections.Generic;
using UnityEngine;

public class IntExt_Trigger : MonoBehaviour
{
    private AudioSource ACinside, Blizzard_from_INT, Blizzard_from_INT_2, rain;
    private AudioSource AirlockSealOpen_HV, AirlockSealClose_HV;
    private AudioReverbZone Int_Reverb_Zone, Ext_Reverb_Zone;
    private AudioSource ext_wind;
    
    private void Awake()
    {

        ACinside = GameObject.Find("ACinside").GetComponent<AudioSource>();
        Blizzard_from_INT = GameObject.Find("Blizzard_from_INT").GetComponent<AudioSource>();
        Blizzard_from_INT_2 = GameObject.Find("Blizzard_from_INT_2").GetComponent<AudioSource>();

        AirlockSealOpen_HV = GameObject.Find("AirlockSealOpen_HV").GetComponent<AudioSource>();
        AirlockSealClose_HV = GameObject.Find("AirlockSealClose_HV").GetComponent<AudioSource>();

        Int_Reverb_Zone = GameObject.Find("Int_Reverb_Zone").GetComponent<AudioReverbZone>();
        Ext_Reverb_Zone = GameObject.Find("Ext_reverb_Zone").GetComponent<AudioReverbZone>();
        ext_wind = GameObject.Find("ext_wind").GetComponent<AudioSource>();
            
    }
    //this section above defines the variables and functions//

    private void OnTriggerEnter(Collider other)
    {
        // for OnTriggerEnter to run the trigger and the player model objects must have colliders//
        // the folowing actions are executed when an entrance or collision to the trigger is detected//

        Int_Reverb_Zone.enabled = false;

        if (ext_wind.isPlaying == true)
        {
            ACinside.Stop();
            Blizzard_from_INT.Stop();
            rain.Stop();
            

            Int_Reverb_Zone.enabled = false;
            Ext_Reverb_Zone.enabled = true;

            ext_wind.Play();
        }
        else
        {
            ACinside.Play();
            Blizzard_from_INT.Play();
            Blizzard_from_INT_2.Play();
            rain.Play();
           

            Int_Reverb_Zone.enabled = true;
            Ext_Reverb_Zone.enabled = false;

            ext_wind.Stop();
        }
    }

   
}





标签: c#unity3daudionullreferenceexception

解决方案


你应该验证你得到的所有组件,像这样:

GameObject?.Find("ACinside")?.GetComponent<AudioSource>();

要么GameObjectACinside对象为空。


推荐阅读