antfarmar / Unity-3D-Asteroids

A simple Asteroids clone. In 3D.
The Unlicense
65 stars 15 forks source link

FindObjectOfType<> Usage #20

Closed antfarmar closed 8 years ago

antfarmar commented 8 years ago
Problem:

BulletBehaviour.cs uses the slow FindObjectOfType<> method (parses the entire Scene hierarchy) on Awake() to locate ShipShooter.cs to get the reference to its pool currently located there. Called by each bullet instance (~10). Though there's no noticeable slowdown, it's bad practice.

Link to the code.

Possible fixes:

_Side Note:_ How to permanently link to lines of code in an actual SHA hash for a particular commit, rather than the current version of the file on master.

ghost commented 8 years ago

I removed the dependency to ShipShooter in my experimental cleanup. I mean, the only reason it even exists there is because the bullet want to get removed from the game after x seconds. I made it so that Poolable knows which pool it belongs to, so it can be recycled (put back into the pool for later use).

Perhaps it could be food for thought. (Implicitly, you get rid of FindObjectOfType since you have no reason to know about ShipShooter and ShipShooter.m_BulletPool any longer)

BulletBehaviour.cs GameBehaviour.cs Poolable.cs ObjectPool.cs

(It's refactoring-in-progress so please don't get hung up on the separation of Poolable and Recyclable. For all intents and purposes, they are the same. I wish I had waited with publication until I got it right, but I felt trigger happy and wanted to get something out to discuss before you moved ahead too far)

antfarmar commented 8 years ago

Good idea.

I mostly "borrowed" the initial pool implementation (was a new concept to me), then rewrote parts of it (to make it serializable, mostly as an experiment on live recompilation).

It could definitely be improved to handle more of the administrative tasks it creates, as you point out.

I certainly could've done more research though. But again, I wanted something simple to start with, so avoided implementations such as this robust ObjectPool.