Hey GameDev Community!
In lecture #73 “Instantiate GameObject” of Unity2D course I see Rick do two things that I have questions about:
-
Rick put
gamestatus = FindObjectOfType<GameSession>();
into a method which is called when the Block is destroyed and also called the method AddScore() within. But I chose to put this line at the Start function. I just figured the Block objects should identify GameSession and then call the AddScore() only when needed, which is when it is destroyed and GameSession has already been found in Start.
I want to understand what is the most correct way of executing this and why. -
In the DestroyBlock method (for me it is DestroyBrick) Rick called several other methods but he places them after
Destroy(gameObject);
. I chose to place the Destroy function last, since in my logic everything else has to be executed before the object is deleted.
My question is, does it matter? and if it is how much?
I try to optimise my scripting along as well to keep it clean and clear, for a good habbit.
public class Brick : MonoBehaviour
{
[SerializeField] AudioClip destroyedClip;
[SerializeField] GameObject brickSparklesVFX;
// Cached reference
Level level;
GameSession gamestatus;
private void Start()
{
// Assigning a level instance to find an object of type Level
level = FindObjectOfType<Level>();
level.BreakableBricksCount();
gamestatus = FindObjectOfType<GameSession>();
}
private void OnCollisionEnter2D(Collision2D collision)
{
DestroyBrick();
}
private void DestroyBrick()
{
level.BrickDestroyed();
gamestatus.AddToScore();
AudioSource.PlayClipAtPoint(destroyedClip, Camera.main.transform.position);
TriggerSparklesVFX();
Destroy(gameObject);
}
private void TriggerSparklesVFX()
{
GameObject sparkles = Instantiate(brickSparklesVFX, transform.position, transform.rotation);
Destroy(sparkles, 1f);
}
}