Little Change in the code

Hey, I just tried to change a code a little bit. Instead of creating an object of SceneLoader in Level, can I create an object of SceneLoader in Blocks?

Code for Blocks

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

public class OnCollisionWithBlock : MonoBehaviour
{
    // Start is called before the first frame update
    //SpriteRenderer spriteRendererValue;
    //Color color;
    //GameObject blockPre= Instantiate(GameObject.Find("redBlock")) as GameObject;
    // GameObject blockPre= GameObject.Find("Name");
   
    //int blockCount;
   [SerializeField] AudioClip clip;
    Level level;
    LoadNextScene loadNextScene;
    int blockCount;
    private void Start()
    {
        level = FindObjectOfType<Level>();
        level.countBreakableBlock();
        loadNextScene = FindObjectOfType<LoadNextScene>();
    }
    private void OnCollisionEnter2D(Collision2D collision)
    {
        // GetComponent<SpriteRenderer>().color= Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f); 
        level.breakableBlock--;
         AudioSource.PlayClipAtPoint(clip,Camera.main.transform.position);
     
        if(level.breakableBlock>0)
            Destroy(gameObject);
        else
        {
            loadNextScene.LoadNextScene1();
        }

        

    }
}

Code for Level

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

public class Level : MonoBehaviour
{
    // Start is called before the first frame update
    [SerializeField] public int breakableBlock;

    //cached reference

    
    public void countBreakableBlock()
    {
        breakableBlock += 1;
    }
    /*
    public voif blockDestroy()
    {
        breakableBlock--;

    }
    */
    
}

Hi Bhishman,

If what you did works, you can do it. The question is: Should you do it?

In this course, we follow one of the most important principles of object-oriented programming: the single responsibility principle. It means that each class is supposed to have one single task. Ideally, this applies to methods.

Should a block be responsible for loading any scenes? What if you had a count down? You would have to scatter your code for loading scenes all over the place which makes debugging fairly exhausting. If you have one class for this task, you could simply change the code there.

That’s the idea behind the single responsibility principle.

In the end, you are the developer, though, so you have to decide how your code is supposed to look like. :slight_smile:

1 Like

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