C# Enabling and Disabling Components in Unity! – Beginner Scripting Tutorial

– [Instructor] To enable or
disable a component in Unity, simply use the Enabled flag. In this example, we have
a references to a light called myLight. And in Start, we’re setting this variable using the getComponent function to the light component
attached to our object. In Update, I’m waiting
for the key press space. And then I’m setting the enabled
flag on my light to false. Let’s see it in action. I could also set this to True, but it would be even more efficient to make it a toggle. So I’ll set it to the
inverse of myLight.enabled. So by using the exclamation
mark, not keyword, I’m effectively saying, set this to whatever
it’s not at the moment. So I’ll save my script. And now you can see
that when I press Play, the space bar acts as a toggle, switching the light component on and off, signified by the checking and unchecking of the checkbox next to
the name of the component in the Inspector. Keep in mind that because
scripts are also components, you can use the .enabled
flag to disable those too.

Leave a Reply

Your email address will not be published. Required fields are marked *