I am making a 2D game. When the objects and AI are off the camera, is there a way to make them disappear and reappear again if my camera comes back to them?
If I go from the beginning to the end and don’t kill any AI, they will flood the game and FPS goes down horribly. But I still need them to be there if I go back. I don’t want them to disappear completely if I’ve already passed them
Is there a way to do it to other objects or 2D sprite/UI if off screen, too?
Please help
void OnBecameInvisible()
{
if (thisGameObject != null)
{
thisGameObject.SetActive(false);
}
}
I used this but there is a problem. When I kill an AI, and go away, and then come back, the AI is playing default animation. he still have the walking and shooting animation running but only stands in one place. I also can no longer interact with that AI.
If you kill an AI, why does it re-appear if you go back? If AI is the main problem you could check all AI coordinates and compare them to player to see if they are behind you at a certain distance and just destroy them?
Assuming your script above works, this could solve the animation problem, unless you WANT them to respawn when you go away from them?
In that case you could respawn them?
Kinda solved the problem for now 
I used two cameras for this to work
1st camera is the main camera (it fits the screen)
2nd camera is the one that do that “draw distance.” (bigger than the 1st camera and off screen)
This means if AI or objects enter the second camera, they will pop up outside the screen. This works so far because AI and objects don’t pop up inside the screen.
But sometimes when I enter a scene, Unity will use the second camera as the main one, and it is zoomed out too much.
What I did was I put the 1st camera under the 2nd one in the hierarchy and disable the 1st one. When I enter a scene, Unity will recognized the disabled 1st camera as the main one which is weird.
The method above is my way to deal with the problem. I don’t know what is a better way. Please help if you have better suggestions