我决定在我的项目中实现一个简单的消息传递系统.我正在使用这个:CSharpMessenger Extended(它是用静态方法实现的).
很奇怪,当我直接调用一个方法时,一切都正常工作.但是当我用消息传递系统广播消息时,我在某些游戏对象上得到了NullReferenceException.令我惊讶的是添加行if(_gameObject == null)返回;解决了这个问题.但是,如果对象对于我得到此异常的每个位置都为null,则不能选择添加检查.
可能是什么问题?
这是我广播消息的代码:
public class Head : MonoBehavIoUr {
public Snake snake;
void OnControllerColliderHit (ControllerColliderHit hit)
{
if ( hit.gameObject.GetComponent<Terrain>() )
return;
//This way everything was working without any surprises.
//snake.PropCollected( hit.gameObject.GetComponent<Prop>() );
//Using messaging system instead
if ( hit.gameObject.GetComponent<Prop>() )
Messenger<Prop>.broadcast( "prop collected", hit.gameObject.GetComponent<Prop>() );
Destroy(hit.gameObject);
}
}
public class Snake : MonoBehavIoUr {
public GameObject headBlock;
public GameObject snakeBlocks;
int lastSnakeBlockId;
private GameObject FindBlockWithId( int _id )
{
if (!snakeBlocks) return null; //This line somehow solves the problem; However the object is 100% assigned in the editor.
foreach (Transform child in snakeBlocks.transform) {
if (child.gameObject.GetComponent<SnakeBlockScript>().blockId == _id)
{
return child.gameObject;
}
}
return headBlock;
}
void Awake()
{
//Set up message listeners
Messenger<Prop>.AddListener("prop collected", AddBlock);
}
public void AddBlock(Prop _prop)
{
GameObject lastBlock = FindBlockWithId(lastSnakeBlockId - 1);
if (!lastBlock) return;
//Some more code
//...
}
}
谢谢!
解决方法:
听起来你有一个条件,其中“snakeBlocks”在应用程序的其他地方被重新初始化,并且这个线程偶尔会在该引用被设置为其他东西时偶然发现.
就像是:
snakeBlocks = null;
//Do some stuff.
snakeBlocks = someNewInstanceOfGameObject;
只是一个想法.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。