How could this code be optimized?

I am building a black hole gun in my game. Everything works perfectly, but it takes a pretty big hit on performance due to all the physics calculations.

Here is the script that calculates all the physics: Black Hole Script -

For reference, here is a gif of what it looks like: Black Hole Gun GIF | Gfycat

I know it’s really bad to use FindObjectsOfType() every frame, but I can’t think of any other way to make sure I’m always affecting every particle system.

If you would like more clarification on how any of the code works, please ask.

That’s a huge amount of code to process every frame.

For better performance you want to use your heavy Find functions as rarely as possible. Maintain a list of Components of the type you are interested. Have the Component itself check in in OnEnable and out in OnDestroy. This will eliminate your FindObjectsOfType call.

Run this through the profiler to find which of your various sub methods costs the most. Optimise the worst performing method.

I’m afraid I don’t feel like reading that code (too spread out!). If you can paraphrase it that’d be nice :wink:

I reckon there’s too much code there. This seems like a pretty simple problem.

But to address your problems without reading it:

  1. If you’re instantiating from one place, just store a reference to all the instantiated objects (or rigidbodies, see below) in the blackhole.

  2. I don’t know if this still creates a performance hit… but avoid referencing rigidbodies and transforms with .notation lookups. These used to be crazy slow. I’d try and store references in the blackhole directly to the rigidbody. You can use “rigidbody.worldCenterOfMass” to avoid transform lookups completely.

    currentPowerup.rigidbody2D.velocity = Vector3.Lerp(currentPowerup.rigidbody2D.velocity, currentPowerup.transform.position.CalculateBlackHoleForce(outerForce, transform.position, outerRadius.radius, outerRotation), 0.5f);

I’d go for implementing something like this:


  • Find reference to every physics component on creation.
  • Some physical constants.
  • Simple loop, applying force to every referenced RigidBody every tick.


  • When spawning a physics object check for black holes and add the
    RigidBody (not the object) to the
    black holes lists.

Ideally you’d have one custom
instantiate() command which would
automatically check for black-holes.

This reduces lookups considerably, and keeps the code concise, simple, and re-usable.