Doubt with timesHit

In the previous lectures we used a variable breakingblocks(or something like that) in a function called CountBlock() and called it in the Start(). When our script executed every breakable block called this function and thus we got our no. of breakable block.

In this lecture we used a variable timesHit and we increased its value when ball collides with block and it dosen’t destroy. However every block consist this same variable in the same script and just like breakingblocks, if the ball collides with any block in my scene then timesHit should increase by one. But this is not the case and timesHit is working like an individual variable for all types of block…WHY???.. :exploding_head:

Also one more thing…
What’s the difference in using if( tag == "Something") and if(CompareTag("Something"))

Hi Abhinav,

Your question regarding timesHit is very good. timesHit is a so-called instance member. While it looks as if all instances of Block have got the same variable, that’s actually not the case. Each one has got its own timesHit variable, its own methods. Everything inside the class block gets copied. The instances are not sharing the same variable unless the static keyword is involved.

Regarding tag vs. CompareTag, from what I read the latter is more performant. See this answer in the official Unity forum.

See also:

Okay, i got that each gameobject consist of its own timesHit and its own maxHits variable, but for the breakingblock variable in the CountBlocks() functions, we didn’t used any static keyword n still it is shared by all…why?

Who/what is “all”? To which instance is breakingblock and CountBlocks() belong? And how many instances of that type do we use in our scene?

Do u want say that in our game their is only one GameStatus gameobject in which the CountBlocks()
function is their and all our blocks are referring to that single GameStatus only, becaz of which they all refer to a single breakingblocks variable inside that GameStatus object? Am i correct?

You are correct. :slight_smile:

We implemented the “singleton” in the GameStatus class to ensure that we have only one GameStatus object in our scene. And that GameStatus object is supposed to keep track of the number of breaking blocks.

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