Unity !IsDestroying() Error - c#

In Unity I'm currently getting an error where none existed before, or if they did it didn't appear to matter.
Whenever I destroy something and go to restart the level in my game, the game freezes partway into loading and comes up with this error:
!IsDestroying()
UnityEngine.GameObject:AddComponent()
EggScript:OnDestroy() (at Assets/Scripts/GameScripts/EggScript.cs:85)
The function it's talking about:
void OnDestroy()
{
PlayerPrefs.SetInt("Game Paused", 1);
transform.parent.gameObject.transform.parent.gameObject.AddComponent<GameOverScript>();
}
I've removed the PlayerPrefs call to no apparent avail but I need the other call to actually restart the level.
The other error that hasn't appeared to matter is:
batchDelete.reservedObjectCount >= batchDelete.objectCount
I'm not quite sure where I'm creating that because what I'm working on is a bit of a conglomeration of tutorials but I don't think it's relevant to this particular error.
The GameOverScript code is below (though it doesn't sound like it would be the error either):
void Start()
{
GameManagerScript.Instance.pauseGame();
//gameObject.BroadcastMessage("saveScore", null, SendMessageOptions.DontRequireReceiver);
if (PlayerPrefs.GetString("curLevel") == "Tutorial" || PlayerPrefs.GetString("curLevel") == "Tutorial1" || PlayerPrefs.GetString("curLevel") == "Tutorial2")
{
//Do nothing
}
else
{
//We're in an infinite level, so we save the score
gameObject.BroadcastMessage("saveScore");
}
PauseScript.displayMenu();
//gameObject.AddComponent<FrontmostClickCheckerScript>();
//HighScoreManager._instance.SaveHighScore("You", (System.Int32)PlayerPrefs.GetFloat("LatestScore"));
HighScoreManager._instance.SaveHighScore("You", GameManagerScript.Instance.getScore());
}

I actually believe you might be making a few mistakes here:
transform.parent.gameObject.transform.parent.gameObject.AddComponent() should be replaced with a public variable to hold that GameObject, the calling AddComponent on it, also replacing your AddComponent with enabled as was mentioned in the comments would also work.
You're destroying an object on pause. You should post more code to give context here, but you don't want to be using OnDestroy to manage game state the way it appears that you are. You can use messaging, or references, the latter is faster, but the former is fine when you're not using it too often (read: repeatedly in OnUpdate)
I think the likeliest possibility here is the object you're calling AddComponent on might be getting Destroyed while you're trying to add the component. It'd be a very hard thing to debug here because you're climbing the hierarchy manually. Also, try removing the AddComponent altogether, it sounds like you need SetActive instead.

Related

Neither null nor type check detecting destroyed object/component?

I have an issue for which I've found a workaround, but can't understand why Unity isn't working the way I expect, or what I'm doing wrong. Basically, I am referencing a renderer component of a destroyed object in a script (long after it's been destroyed), and neither null checks nor type checks let me know it's destroyed.
I have a script that's modifying the shaders on some objects temporarily so I can apply effects on to them; when the effects are done it puts the materials/shaders back the way they were.
It happened that I was swapping out a character's weapon in the same frame I began one of these effects, so the script wound up with a reference to the renderer of a destroyed object (the old weapon). Many frames later when the effect was to finish, it naturally err'd out.
I tried a type check first to see if the reference was still to a renderer -- no luck. Unity's doc says a null check should work, but it still doesn't.
if (pair.Key != null && pair.Key is Renderer renderer) { renderer.materials = pair.Value; }
I get:
MissingReferenceException: The object of type 'SkinnedMeshRenderer' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
activeInHierarchy likewise does not work.
Adding a DestroyImmediate to the code where I destroy the object works fine; the object isn't there by the time the effect starts, so the reference is never made. However, that only solves this one problem, and not other such cases.
Can anyone tell me how to check properly for references to destroyed objects or components, or if I'm doing something wrong in my checking? Should I be referencing the gameObject instead of the renderer component or something like that?
EDIT:
Since a commenter asked for it, here's a gist of the full code for the effect. The destruction is happening outside this, as it's totally unrelated.
https://gist.github.com/jackphelps/f507d949a84c53457f570c5009bcb6d4
SOLVED -- SORT OF?
I changed the dictionary to store the renderer's game object instead of the renderer, and as expected a simple null check worked for detecting a destroyed object. I'd love to know why it doesn't work on the renderer, and if there's a proper way to check!
The best way I could find to solve this was to store a reference to the renderer's gameObject rather than to the renderer component itself. In this case, a simple null check at the end of the script works fine, as expected.
I'm not accepting this answer because it still doesn't tell me how to check for a component's presence when the game object was removed ¯(°_o)/¯

How can I destroy multiple game objects at once?

I am trying to figure out how I can basically stand on a pressure plate and have something that's in the way disappear. I have it working to destroy the object you interact with but not finding any solution to make another object be destroyed.
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("PressurePlate"))
{
Destroy(collision.gameObject.CompareTag("tree"));
}
}
Destroy(Object) takes in an Object, more specifically, a component or a game-object;(Though nothing would happen if you attempt to destroy a boolean, like what you did in this case; Someone can correct me on that though.)
If you want to destroy the game-object that it has collided with, Destroy(collision.gameObject) would do it.
If you want to destroy all GameObjects with a specific tag, you can do GameObject.FindGameObjectsWithTag(tag), like so:
foreach (var gameObj in GameObject.FindGameObjectsWithTag("Your target tag")){
Destroy(gameObj);
}
There are a few other methods like Object.FindObjectsOfType(Type) which you can use to fetch all game-objects with a certain type.
But since they are generally slow, I do not highly recommend using those unless you need to;You can consider caching the respective game-objects somewhere first, and destroying them later.

Unity: Camera.main is failing after I switch scenes

I am having a weird issue with some of my code, and I could really use some help.
I have a script attached to a gameobject that is unique to a particular scene, so anything within Start() will only run when that scene is loaded. In this script, I am accessing Camera.main, since I use settings attached to the camera gameobject (it may sound inefficient, but it is necessary for the style of game we are creating). Anyway, if I start from that scene directly in Unity, it works just fine, but if I start from my intro scene and then load into the aforementioned scene, I get this error:
MissingReferenceException: The object of type 'Camera' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
The weird thing is, I can Debug.Log(Camera.main) and it gives me the name of the camera. So Camera.main is not null, and it is not destroyed like it says in the error message. Here is my full script:
private void Start()
{
Debug.LogError(Camera.main);
gameManager = FindObjectOfType<GameManagerScript>();
if (Camera.main == null)
{
Debug.LogError("Camera.main is null");
}
else
{
gameManager.LoadMusic(Camera.main);
gameManager.LoadAmbient(Camera.main);
gameManager.FadeStereoPan(Camera.main.gameObject.GetComponent<SwipeActivator>().stereoPanInNode);
}
}
The three functions above are custom functions I wrote, but I don't know why they would be causing the issue, since they work if I start up the scene directly.
I wasn't having this issue for months, and then all of a sudden, I am getting this error, even though I didn't change any of the code. Any help would be greatly appreciated.
I believe your MainCamera is being destroyed between scenes. Set it up as "DontDestroyOnLoad()"
See this Unity question:
https://answers.unity.com/questions/430141/need-the-same-main-camera-for-multiple-scenes.html
Ah, I fixed it. I dove into my custom functions and found that I was accessing a camera variable that is set at the beginning of the game, and then on each camera transition, but it was failing since I was loading a scene and no transitions that scene had yet to be completed. I just had to reassign that variable in the script above so it was not pointing to the destroyed object in the previous scene. Thank you JiveTurkey for pointing me in the right direction!

Unity3D - GameObject.Find() vs Inspector Assignment performance

I'm making a mobile clone of pacman for android. Everything is working fine, but I am trying to optimize my game as much as possible.
Currently in some scripts I am finding GameObject's by doing GameObject.Find() in the Start() function of my scripts, like this:
void Start()
{
ghosts = GameObject.FindGameObjectsWithTag("Ghost");
pacman = GameObject.Find("Pacman");
gameManager = GameObject.Find("Game Manager").GetComponent<GameManager>();
}
My question is, would performance increase if I made some of these GameObject's inspector assigned variables instead of doing .Find()?
Would that increase the performance speed or would it make no difference seen as though I do a .Find() in the Start() function?
Obviously performance would decrease if it was called in the Update() as the script would try and find a GameObject every frame, but a Start() function would only search for it once?
Performance at startup for this kind of things is totally negligible, Inspector assignment requires deserialization, while Find requires message dispatch, both are slow operations, if you think that matters, profile that.
I would anyway use
FindObjectOfType<GameManager>() as GameManager
wich is at least more typesafe, I would not use editor inspection if possible, because manual wiring is source of many little errors. So I give a human-time performance reason:
Do not use editor inspection because if you miss to wire something you will have to debug a nullpointer wich on the long run will eat hours of your time.
You have anyway to use Editor Insection in cases where you do not have just to find 1 component, no workaround for that (unless you use Svelto or Svelto-ECS wich are rather advanced topics.)

DontDestroyOnLoad is not Working on Scene?

I Need to apply DontDestroyOnLoad on Scene.is it possible?
I Need to Do not disturb the scene when going in to another scenes also.here i'm sending mail,when ever clicking send button its going to authentication in mail server in this time my scene idle means not responding anything until come back to the response from mail server,so on that time i show one loading bar in my scene.this is not do process.the entire scene is hang until came response from mail server,so how to solve this?
void Awake()
{
DontDestroyOnLoad(this.gameObject);
}
After reading so many non-answers I finally found the answer in a Unity forum. DontDestroyOnLoad ONLY works if the game object in question is at a "root level" meaning right under the scene, not nested under any other object. This is not mentioned anywhere in the documentation.
When loading a new level, scene, all Game Objects of the previous scene are destroyed by Unity.
If you want to protect a Game Object you can use the function.
DontDestroyOnLoad(gameObject);
It is important to note that when you say: this.gameObject you are pointing to pretty much the same thing, it just happens that this points directly to the script attached to that gameObject. So you don't need the this part, just gameObject will do.
Ideally you could protect that gameObject inside void Awake()
void Awake()
{
DontDestroyOnLoad(gameObject);
}
The above code will prevent Unity from destroying that gameObject unless your game closes completely or at a later point you call Destroy() on it. That means you can change from scene to scene and the gameObject will survive. However, if you make it back to the scene that creates that gameObject you are protecting you may run into problems if you do not have the logic implemented that prevents you from protecting a second, third, or many of that gameObject.
Your second question, if I understand it correctly:
You want to send mail when you change scenes, but your progress bar wont progress while changing scenes, it just stays there, static.
If that is the case then your problem is in Application.LoadLevel(sceneName); If you have the free version of Unity, then you need to come up with your own creative way of showing that progress bar, because Application.LoadLevel() will halt everything until it takes you to the new scene.
I don't completely understand what you are saying.
But because in your context, this in represents most probably a Monobehaviour, try the following:
void Awake() {
DontDestroyOnLoad(this.gameObject);
}
or
void Awake() {
DontDestroyOnLoad(gameObject);
}
See http://docs.unity3d.com/Documentation/ScriptReference/Object.DontDestroyOnLoad.html
I recommend you use a coroutine, with the 'yield' statement
check out this documentation of the WWW class, which likewise involves writing code to cope with waiting for a response from the web, without hanging your Unity3d program
coroutines are pretty powerful if you're working with tasks that take more than a frame or two. Richard Fine (AltDevBlog) has posted a really detailed description of what they are and how to use them, which I thoroughly recommend.

Categories