c# – Inspector中分配的Unity值在代码中抛出Null
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – Inspector中分配的Unity值在代码中抛出Null,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2373字,纯文字阅读大概需要4分钟。
内容图文
我是Unity的初学者,有一个问题,我无法在任何一个主板上找到答案.创建一个非常基本的Unity C#脚本,我的Awake()函数中有以下几行代码:
Assert.IsNotNull(sfxJump);
Assert.IsNotNull(sfxDeath);
Assert.IsNotNull(sfxCoin);
第三个断言“
Assert.IsNotNull(sfxCoin)抛出为null,即使在Inspector中设置了硬币AudioClip:
检查器脚本值:
然而 – 这是令我困惑的部分 – 由于某种原因,当从OnCollisionEnter()例程在同一脚本中调用时,sfxCoin不为null
所以看来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的相同脚本.它隐藏在层次结构中的一个节点下,所以我没有看到它.
就像我说的那样,我是初学者.
内容总结
以上是互联网集市为您收集整理的c# – Inspector中分配的Unity值在代码中抛出Null全部内容,希望文章能够帮你解决c# – Inspector中分配的Unity值在代码中抛出Null所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。