Reactivating prefab instances upon becoming visible

So I’m working on a 2D game in which I’m instantiating a bunch of prefabs at runtime. These objects are tiles that can be broken, and as such, they all have a script, an animator, a platform effector 2D, and a box collider.

Upon adding the animator to all the tile instances, I noticed a significant drop in FPS, and I have since been trying to fix this problem.

One of the ideas I had was to deactivate an instance’s corresponding gameObject when it isn’t seen by the camera using OnBecameInvisible and reactivate it when it comes back into view using OnBecameVisible. So I have this:

void OnBecameVisible() {
		transform.gameObject.SetActive (true);
	}

	void OnBecameInvisible() {
		transform.gameObject.SetActive (false);
	}

The GameObjects are being set to inactive when they are no longer visible, but they aren’t being reactivated when they come into view. I’m assuming this is because the script associated with the object is no longer seen after becoming inactive, and so the OnBecameVisible function is never called for it.

So how can I disable GameObjects outside the camera view and reactivate them when they come back in?

Thanks in advance.

Your assumption is correct. The script will no longer run when the object is deactivated.

Probably your best bet here would be to enable/disable one or more of the components rather than the game object. Start with the animator and renderer perhaps.

e.g.

GetComponent<Renderer>().enabled = false;

Check this out, and see if it fixes your problems. After looking at that, look at this.

Occlusion culling is what I believe you’re looking for.

On the other hand, you may have problems when trying to animate while using collision. If you’re using an animation, you should probably disable the Animator component, unless you’re not changing the transform.