Component.GetComponent help

I am a little confused by the documentation on this. I am trying to access a boolean variable of a script on my object “Background” from another script on my object “Target.” I was originally using static var, however this lead to many bugs when reloading the level. Any help on explaining the documentation would be appreciated.

  • Wade

You’ll first need to get a reference from your “Background” to your “Target” object. You can do that by e.g. assigning it to a public variable directly in the Inspector, or for example use GameObject.FindWithTag(“Name”).

Then you can assign your component to another variable via GetComponent().

public GameObject backgroundObject;	// <!-- assign via inspector, or set a tag and have a look at Start()
public YourScriptClass scriptComponent;
public int valueYouNeed;

void Start() {
	backgroundObject = GameObject.FindWithTag("YourBackgroundObjectTag");	// only needed if you didn't assign it in the Inspector
	
	scriptComponent = backgroundObject.GetComponent<YourScriptClass>();
	
	valueYouNeed = scriptComponent.theValue;
}

Note that you can also introduce another check if the backgroundObject is not null in case you are trying to use FindWithTag.

Thank you!! This worked great. How do I give a thumbs up for your answer I am not seeing it in this post??

That would be only on Unity Answers.