Access variables of other scripts in C#
In Unity development, it is often necessary to access variables in different scripts. Here's a guide to achieving this:
Get the script component:
To access a variable in another script, you first need to get the script component itself. If the script is in a different game object, you must pass the game object as a reference in the inspector.
Sample code:
Consider two scripts: scriptA contains a public variable X, and scriptB needs to access X.
scriptA.cs
<code class="language-c#">public bool X = false;</code>
scriptB.cs
<code class="language-c#">public GameObject a; // 游戏对象A的引用 public scriptA script; // scriptA的容器 void Start() { // 从游戏对象A获取脚本组件 script = a.GetComponent<scriptA>(); } void Update() { // 访问并修改变量 script.X = true; }</code>
Update variable value:
To update the value of a variable from another script, just assign it a value in the Update function. In the above example, script.X is set to true in scriptB's Update function.
Other instructions:
The above is the detailed content of How Can I Access Variables from One C# Script in Unity to Another?. For more information, please follow other related articles on the PHP Chinese website!