All scripts need to be on the same object?

I learned yesterday that in order to access values from a different script, that script needs to be on the same game object. Does this mean that ALL scripts I want to access from my main script need to be on the same object? If so, this means that if I wanted to do a bigger scale game, like an RPG, that EVERY quest and every dialog need to be attached to the same object?

Is there any other way to access scripts from different objects?



You can access scripts in any other objects as well. GetComponent(ScriptName) searches for the script only in the same object, but prefixing it with a reference to another object makes GetComponent search in that object. Let’s suppose that you want to access the script EnemyHealth in the enemy hit by your projectile - just add this code to the projectile (which must be a rigidbody in this case):

function OnCollisionEnter(col: Collision){
  // try to get the script EnemyHealth in the object hit:
  var healthScript: EnemyHealth = col.gameObject.GetComponent(EnemyHealth);
  // if the object hit has an EnemyHealth script...
  if (healthScript){ // apply the damage to it -= 10;

You can access values from another script which is attached to a different script but in order to do this you have to have access to the gameobject or the variable is static (which you should avoid if possible).

Here are some question about the same topic.