Virtual Methods For Dummies

<p>In a previous tutorial, we take a look at&nbsp;<a href="https://medium.com/@alexandrmayor/custom-classes-5e23f7bc0c04" rel="noopener">Custom Classes</a>&nbsp;and&nbsp;<a href="https://medium.com/@alexandrmayor/class-inheritance-what-is-it-c1ba4d75ee55" rel="noopener">Inheritance</a>.</p> <p>Now we will take a look at&nbsp;<strong>Virtual Methods</strong>&nbsp;within Unity. For the purposes of this example, we have a script named Pet that will inherit from Monobehavior.</p> <p><img alt="" src="https://miro.medium.com/v2/resize:fit:316/1*RWQHnqb8knqor4dYPbEGDA.png" style="height:311px; width:287px" /></p> <p>Say we have a game object named Duck with a Duck script on it that inherits from Pet (which inherits from Monobehavior).</p> <p><img alt="" src="https://miro.medium.com/v2/resize:fit:231/1*kO2ZTfGUu3KNv3ckmXOPJQ.png" style="height:138px; width:210px" /></p> <p>The Duck script would have access to the Speak method declared in the Pet script. HOWEVER, ducks don&rsquo;t say, &ldquo;Speak!&rdquo;. They say, &ldquo;Quack!&rdquo;. So, how do we override the original method?</p> <p>We can make the Speak method a&nbsp;<strong>protected virtual</strong>&nbsp;method.&nbsp;<strong><em>Protected</em></strong>&nbsp;means that the variable or method is private and inaccessible to other scripts but accessible to the initial script and all that inherit from it.</p> <p><a href="https://medium.com/@alexandrmayor/virtual-methods-for-dummies-ae2f6e1e0431"><strong>Learn More</strong></a></p>