Anyway to get the scripts associated with particular game object?

Hi, Is there anyway I could get every script associated with a game object? I want to access it from script of another object. The idea is to optimize the performance by deactivating scripts. Or is there a better solution for optimizing the objects that are in distance from player? It’s a 2d platformer. Thanks!

1 Answer

1

The best solution is to have each script disable itself as appropriate. Managing a bunch of scripts like this is not good, maintainable coding practice. That said, here:

[SerializeField] new GameObject gameObject;

foreach ( var script in gameObject.GetComponents<MonoBehaviour>() )
   script.enabled = false;

Every script that you can attach to a Game Object is a MonoBehaviour.

What you should do, is, track the circumstance that will lead to the mass disabling in one script. Fire an event upon that circumstance. Register for the event in all of the scripts that you care to disable.

What about the terrains in 2d platformers? Like they effect the performance? If I deactivate the entire object, the objects on the terrain would fall off. How do they do in traditional 2d platformers?

–

I don't know what you're asking, but it sounds like a different question, suitable for the forum.

–