Avoid using Object.Instantiate without “Transform Parent” parameter and using SetParent later
All Unity game objects have a transform component that specifies the object's position, rotation and scale, relative to its parent in a transform hierarchy. Calling
Object.Instantiate to create a new instance of an object without setting a parent transform will create a new root transform hierarchy. The parent can be set later by calling
Transform.SetParent or assigning a value to
Instantiate and setting the parent separately is an unnecessarily expensive operation, as the new root transform hierarchy is allocated, initialised and immediately thrown away. It is recommended to set the parent transform as part of the call to
Instantiate, avoiding the unnecessary allocations.
This inspection will highlight calls to
Object.Instantiate when the
parent parameter is not specified but set later in the method. It also adds an Alt+Enter Quick Fix that will add the parent to the call to
Instantiate and remove the assignment to
parent or call to
This inspection was first added in Rider/ReSharper 2018.3.