c# - assigning 'this' as reference in another script

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
}

}

Worked fine for me.
This was the code I used, which is just your code except I made updateScore have a capital U and I put instantiateMe inside the Instantiate and added a debug.log to make sure things were being called.
Click for code

using UnityEngine;

public class ScriptA : MonoBehaviour
{
    public GameObject instantiateMe;
    int score = 0;

    void Start()
    {
        GameObject go = Instantiate(instantiateMe) as GameObject;
        ScriptB scriptB = go.GetComponent<ScriptB>();
        scriptB.scriptA = this;
    }

    public void UpdateScore()
    {
        score++;
    }
}
using UnityEngine;

public class ScriptB : MonoBehaviour
{
    public ScriptA scriptA;

    void Start()
    {
        scriptA.UpdateScore();
        Debug.Log("Updated Score");
    }
}

I even changed the script execution order of ScriptA and ScriptB and it still worked fine.

Hey thanks for looking into it. Yeah it is working for me now too, must have just been a mistake in my development scripts somewhere!

1 Like