c# - 在 Inspector 中分配的 Unity 值在代码中抛出 Null
问题描述
我是 Unity 的初学者,遇到了一个我无法在任何板上找到答案的问题。创建一个非常基本的 Unity C# 脚本,我的Awake()
函数中有以下代码行:
Assert.IsNotNull(sfxJump);
Assert.IsNotNull(sfxDeath);
Assert.IsNotNull(sfxCoin);
第三个断言 "
Assert.IsNotNull(sfxCoin)
throws as null
,即使硬币AudioClip
设置在 Inspector 中:
检查器脚本值:
但是——这是让我感到困惑的部分——由于某种原因sfxCoin
,不是 null
在OnCollisionEnter()
例程的同一个脚本中调用时
因此,Unity 似乎确实使用代码注册了对象 - 最终 - 但断言在初始Awake()
,Start()
和Update()
方法中失败。
而这只发生在sfxCoin
. sfxJump
并且sfxDeath
没有这个问题。
任何帮助,将不胜感激
整个脚本如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
public class Player : MonoBehaviour
{
[SerializeField] private float jumpForce = 100f;
[SerializeField] private float forwardMomentum = 5f;
[SerializeField] private AudioClip sfxJump;
[SerializeField] private AudioClip sfxDeath;
[SerializeField] private AudioClip sfxCoin;
private Animator anim;
private Rigidbody Rigidbody;
private bool jump = false;
private AudioSource audioSource;
private void Awake()
{
Assert.IsNotNull(sfxJump);
Assert.IsNotNull(sfxDeath);
Assert.IsNotNull(sfxCoin);
}
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
Rigidbody = GetComponent<Rigidbody>();
audioSource = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
if (!GameManager.instance.GameOver() && GameManager.instance.GameStarted())
{
if (Input.GetMouseButton(0))
{
GameManager.instance.PlayerStartedGame();
anim.Play("Jump");
audioSource.PlayOneShot(sfxJump);
Rigidbody.useGravity = true;
jump = true;
}
}
}
private void FixedUpdate()
{
if (jump)
{
jump = false;
Rigidbody.velocity = new Vector2(0, 0);
Rigidbody.AddForce(new Vector2(forwardMomentum, jumpForce), ForceMode.Impulse);
}
}
private void OnCollisionEnter(Collision collision)
{
switch (collision.gameObject.tag)
{
case "obstacle":
Rigidbody.AddForce(new Vector2(-50, 20), ForceMode.Impulse);
Rigidbody.detectCollisions = false;
audioSource.PlayOneShot(sfxDeath);
GameManager.instance.PlayerCollided();
break;
case "coin":
audioSource.PlayOneShot(sfxCoin);
GameManager.instance.Score(1);
print("GOT COIN");
break;
}
}
}
解决方案
抱歉,我发现了问题所在。
还有一个游戏对象的第二个实例也使用相同的脚本,但没有设置 sfxCoin。它隐藏在层次结构中的一个节点下,所以我没有看到它。
就像我说的,我是这方面的初学者。
推荐阅读
- python - 如何在 pandas 列中处理不同的日期格式?
- youtube - Youtube m3u8 url 无法播放视频 js 和 hls
- r - devtools::check - 系统命令“Rcmd.exe”失败,退出 status:1,stdout + stderr:
- javascript - 笑话:SyntaxError:意外的令牌导出
- node.js - Nodejs Expressjs Mongodb Javascript 单元测试使用 Mocha Chai Sinon 进行随机 Nodejs 项目
- javascript - CORS 策略已阻止从源“http://localhost:3000”访问 XMLHttpRequest
- sql - 显示两列,但其中一列与 SQL Server 中另一个表中的另一列联合
- decidable - 具有有限状态的给定 TM 是否可判定?
- python - 在 Python 中打印倒金字塔
- java - 当对象足够大时,如何告诉杰克逊序列化程序停止继续序列化和写入