Does it count the blocks because we put blocks after breakable?, i don’t understand how can it know what to count
I’m still new to Unity and C#, but I’ll try to outline what I think the scripts are doing.
As far as I understand, it doesn’t directly count the blocks in the scene, but rather how many times the method CountBreakableBlocks in Level.cs is called.
Since all our prefab blocks have the Block.cs script attached, all the blocks in our scene will run the script, calling our method CountBreakableBlocks in Level.cs. This adds 1 to our int breakableBlocks everytime.
public class Level : MonoBehaviour
{
int breakableBlocks;
//Here we declare int (a whole number) and breakableBlocks (where the whole number is stored)
public void CountBreakableBlocks()
// CountBreakableBlocks is the method we want to call from our Block.cs script
{
breakableBlocks++;
// breakableBlocks++; adds 1 everytime its called
}
}
public class Block : MonoBehaviour
{
[SerializeField] AudioClip breakSound;
// cached reference
Level level;
private void Start()
{
level = FindObjectOfType<Level>();
//level now = Level.cs script
level.CountBreakableBlocks();
//Here we call the method in Level.cs script, and it adds 1 to breakableBlocks everytime.
}
}
Hope this helps. I’m sure more experienced people can chime in If I got something wrong or missed something important.
3 Likes