GetComponent используется для gameObject, чтобы получить один из сценариев, назначенных ему в инспекторе. Так что если у вас есть скрипт Example1, прикрепленный к одному gameOBject:
public class Example1 : MonoBehaviour
{
public string customMessage = "Hi there.";
// Start is called before the first frame update
void Start()
{
}
}
И еще один игровой объект с присоединенным Example2:
public class Example2 : MonoBehaviour
{
public GameObject otherGameObject;
Example1 example1Component;
// Start is called before the first frame update
void Start()
{
//gets script instance from gameObject;
example1Component = otherGameObject.GetComponent<Example1>();
//reads message from variable on script instance
Debug.Log(example1Component.customMessage);
}
}
, который будет обращаться к переменным из другого скрипта. Кроме того, вы можете сделать свою пользовательскую переменную типом другого скрипта, и когда вы перетаскиваете ее в инспектор единства, она напрямую ссылается на этот скрипт. и любая переменная publi c также может быть легко доступна. вот так:
public class Example2 : MonoBehaviour
{
//already referencing other script
public Example1 otherComponent;
// Start is called before the first frame update
void Start()
{
//reads message from variable on script instance
Debug.Log(otherComponent.customMessage);
}
}