Hi,
I am having some problems understanding the c# below. I know all the learning resources say I should use a findobjectby method to get a reference to a script already in the scene but I am just wondering why you cannot pass a reference with this as below instead?
Warning the below will crash your program do not try
SCRIPT A - live in the scene attached to an existing gameobject i.e. game manager script / spawner script
public class ScriptA : MonoBehaviour {
public GameObject instantiateMe; // prefab with scriptB attached
int score = 0;
void Start(){
GameObject go = Instantiate(/…/) as GameObject;
ScriptB scriptB = go.GetComponent();
scriptB.scriptA = this;
}
public void updateScore(){
score++;
}
}
SCRIPT B - attached to the prefab being instantiated in Script A
public class ScriptB : MonoBehaviour {
public ScriptA scriptA;
void Start(){
scriptA.updateScore(); // fails with no error messages
}
}