Virtual Methods For Dummies
<p>In a previous tutorial, we take a look at <a href="https://medium.com/@alexandrmayor/custom-classes-5e23f7bc0c04" rel="noopener">Custom Classes</a> and <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 <strong>Virtual Methods</strong> 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’t say, “Speak!”. They say, “Quack!”. So, how do we override the original method?</p>
<p>We can make the Speak method a <strong>protected virtual</strong> method. <strong><em>Protected</em></strong> 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>