

If, however, other scripts do not need to access it, but you do need to see it in the inspector then you can use Serialize Field instead. Generally speaking, it’s good practice to only make a variable public if other scripts need to access it and, if they don’t, to keep it private. Like this: // This will not show in the inspector It’s also possible to make a variable available to other scripts without also showing it in the Inspector. Like this: // This will show in the inspector It is possible to show a private variable in the Inspector, using Serialize Field, However… there’s a little more to it than that. You may have already used both public and private variables in tutorials and other examples and, generally, it’s the simplest way to show a variable in the Inspector or allow another script to access it. Here’s what it looks like in code: public float publicFloat The access modifier is added before the data type and, if neither is used, the variable will be private by default…

If the public and private Access Modifiers are new to you then, put simply, public variables can be accessed by other scripts and are visible in the Inspector while private variables are not accessible by other scripts and won’t show up in the Inspector. I’ve made the audio source variable public, which means so that it’s visible in the Inspector and available to other scripts. In this example I’ve added an audio source component to the player object and have created a public audio source reference variable in my player health script.

SELECT MULTIPLE COMPONENTS LOGICWORKS HOW TO
How to manually access a variable using the Inspector There are several ways I can do this but let’s start with the simplest method. Next, I need to connect that reference to the audio source component on the character, so that the script knows which audio source I’m referring to. Like this: public class PlayerHealth : MonoBehaviour In my player health script, I’ve created a public audio source reference variable. In this example, I want to get a reference to an audio source component on my Knight character.īefore I can trigger the audio source component to play from the script, first, I need to get a reference to it.

You might have already accessed components on a game object from code, or created connections between objects through an interaction between them, such as when two objects collide.īut what if you want to create a connection between different scripts or components, on different objects, that don’t otherwise interact? In fact, even if you’re only just getting started with the basics of Unity, chances are you’ve already created a public reference between a script variable and another object, by dragging and dropping it in the Inspector. Getting a variable from another script in Unity can be pretty straightforward.
