Innanzitutto è necessario per ottenere il componente script della variabile, e se sono in diversi oggetti di gioco, è necessario passare l'oggetto del gioco come riferimento nella finestra di ispezione.
Ad esempio, ho scriptA.cs
in GameObject A
e scriptB.cs
in GameObject B
:
scriptA.cs
// make sure its type is public so you can access it later on
public bool X = false;
scriptB.cs
public GameObject a; // you will need this if scriptB is in another GameObject
// if not, you can omit this
// you'll realize in the inspector a field GameObject will appear
// assign it just by dragging the game object there
public scriptA script; // this will be the container of the script
void Start(){
// first you need to get the script component from game object A
// getComponent can get any components, rigidbody, collider, etc from a game object
// giving it <scriptA> meaning you want to get a component with type scriptA
// note that if your script is not from another game object, you don't need "a."
// script = a.gameObject.getComponent<scriptA>(); <-- this is a bit wrong, thanks to user2320445 for spotting that
// don't need .gameObject because a itself is already a gameObject
script = a.getComponent<scriptA>();
}
void Update(){
// and you can access the variable like this
// even modifying it works
script.X = true;
}
fonte
2014-09-19 10:55:34
Potresti aggiungere qualche codice di esempio dei tuoi due script? Sarebbe di aiuto nel fornirti una soluzione. –
possibile duplicato di [In Unity, come posso passare i valori da uno script a un altro?] (Http: // StackOverflow.it/questions/13891892/in-unity-how-can-i-pass-values-da-one-script-a-another) – Heisenbug