[英]Error MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it
I have been making a 2D game in Unity.我一直在 Unity 中制作 2D 游戏。 I'm trying to make a game over screen appear every time a ball touches the player.每次球接触玩家时,我都试图让游戏结束屏幕出现。 I also added advertisements to release it.我还添加了广告来发布它。 I added Restart and Continue buttons.我添加了重新启动和继续按钮。 When you press continue, an ad shows and the game continues.当您按继续时,会显示广告并且游戏会继续。 When Restart is pressed, it resets the game and your score.当按下重新启动时,它会重置游戏和您的分数。 Whenever I restart the game and then press continue, the ad is played, but the game does not continue.每当我重新启动游戏然后按继续时,就会播放广告,但游戏不会继续。
Here is the collision script:这是碰撞脚本:
using UnityEngine;
public class hitDetect : MonoBehaviour
{
public GameObject menuContainer;
private void OnTriggerEnter2D(Collider2D other)
{
Debug.Log("HIT");
menuContainer.SetActive(true);
Time.timeScale = 0;
}
}
This is the script that restarts the game:这是重新启动游戏的脚本:
using UnityEngine;
using UnityEngine.SceneManagement;
public class RestartGame : MonoBehaviour
{
public void Restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
Time.timeScale = 1;
}
}
Here is the advertisement and continue script:这是广告和继续脚本:
using UnityEngine;
using UnityEngine.Advertisements;
public class continueGame : MonoBehaviour, IUnityAdsListener
{
string placement = "rewardedVideo";
public GameObject menuContain;
private void Start()
{
Advertisement.AddListener(this);
Advertisement.Initialize("4006857", true);
}
public void Continue(string p)
{
Advertisement.Show(p);
}
public void OnUnityAdsReady(string placementId)
{
}
public void OnUnityAdsDidError(string message)
{
}
public void OnUnityAdsDidStart(string placementId)
{
}
public void OnUnityAdsDidFinish(string placementId, ShowResult showResult)
{
if(showResult == ShowResult.Finished)
{
menuContain.SetActive(false);
Time.timeScale = 1;
}
}
}
Once you call一旦你打电话
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex)
a "new" scene is loaded and therefore anything currently existing is destroyed.加载了“新”场景,因此当前存在的任何内容都将被破坏。
In continueGame
you do在continueGame
你做
private void Start()
{
Advertisement.AddListener(this);
Advertisement.Initialize("4006857", true);
}
But you never remove that listener!但是您永远不会删除该侦听器!
Thus the next time the Advertisement
fires its event it is still trying to execute them of the now already destroyed continueGame
instance.因此,下次Advertisement
触发其事件时,它仍在尝试执行已销毁的continueGame
实例。
Therefore you always should remove any listeners as soon as you don't need them anymore:因此,一旦不再需要任何侦听器,您就应该立即删除它们:
private void OnDestroy ()
{
Advertisement.RemoveListener(this);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.