Unity GetComponent: Access Another Script

To access the value of another script, first make sure that the variables in the target script are either public or enclosed using properties. Then, you can use one of the following methods to retrieve the value of another script:

  1. Use the GetComponent method to obtain an instance of the target script, and then access its variables through the instance.
// 获取目标脚本的实例
TargetScript targetScript = GetComponent<TargetScript>();

// 访问目标脚本的变量
int value = targetScript.value;
  1. Utilize the FindObjectOfType method to locate the target script instance in the scene, and access its variables through the instance.
// 查找场景中的目标脚本实例
TargetScript targetScript = FindObjectOfType<TargetScript>();

// 访问目标脚本的变量
int value = targetScript.value;
  1. Use the GameObject.Find method to search for objects in the scene with a specific tag, then retrieve the target script instance from that object, finally access its variables through the instance.
// 查找具有特定标签的对象
GameObject targetObject = GameObject.Find("TargetObject");

// 获取目标脚本的实例
TargetScript targetScript = targetObject.GetComponent<TargetScript>();

// 访问目标脚本的变量
int value = targetScript.value;

By using the above method, you can retrieve the value from another script and use it where needed.

bannerAds