Alternative way to add score: which is more beneficial?

Hi! Great course so far! Thank you for that.

I have a question about the solution of the AddToScore challenge. I’m still new to coding and as English is not my native language I might have some trouble with the terminology. I hope that you understand what I mean here.

So, my solution was a bit different from the one used in the video. I put the FindObjectOfType into the Start method and only called for gameStatus.AddToScore in the DestroyBlock method. After the challenge my Block.cs script was like this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Block : MonoBehaviour
    [SerializeField] AudioClip destroyBlockSound;

    // Cached reference

    Level level;
    GameStatus gameStatus;

    private void Start()
        level = FindObjectOfType<Level>(); 

        gameStatus = FindObjectOfType<GameStatus>();

    private void OnCollisionEnter2D(Collision2D collision)

    private void DestroyBlock()
        AudioSource.PlayClipAtPoint(destroyBlockSound, Camera.main.transform.position); 



I tested and it works like a charm. However I’d like to know if there are any significant benefits for using the solution shown on the lecture video.



Good job on developing your own solution. I’ve read it, and I wasn’t able to spot an issue. If it works, it’s valid. In many cases, there are multiple ways of making something work in Unity.

Whether you look for an object in the Start method or in your DestroyBlock method is more or less a matter of taste. Since the DestroyBlock method is the only place where you call AddToScore and BlockDestroyed and since it is supposed to happen only once during the lifetime of the Block, it could make sense to use local variables. This would be a fairly common approach because programmers usually try to keep the scope as small as possible. If you don’t need the references anywhere else, don’t assign them to an instance variable because every method in the instance could change the reference.

Nevertheless, it’s definitely not wrong to do it your way. Well done! :slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms