why does my object reference go out of scope?

Hi.

I’ve got a scene with two cubes. cube1 and cube2.
cube1 has a script attached called script1. cube2 has a script attached called script2.

I’m trying to reference a variable in script1 from script2.

My code looks like this.

using UnityEngine;
using System.Collections;

public class script2 : MonoBehaviour {

	// Use this for initialization
	void Start () {
	
		GameObject cube1 = GameObject.Find ("Cube1");
		script1 myScript = cube1.GetComponent<script1>();

		Debug.Log (myScript.testFloat); //this works fine.

	}



	// Update is called once per frame
	void Update () {
		Debug.Log (myScript.testFloat); //this doesn't work.
	}
}

The 1st debug.log statement gives me the value of testFloat.
the second one (the one in update) returns the following error.

The name `myScript’ does not exist in the current context

Why does the reference to script1 seemingly go out of scope in update?

Because you declared the variable inside Start. So it does only exist in Start. You have to declare it as a member variable of your class and assign / initialize it in Start:

public class script2 : MonoBehaviour
{
    script1 myScript; // private member variable of the "script2" class
    
    // Use this for initialization
    void Start ()
    {
        GameObject cube1 = GameObject.Find ("Cube1");
        myScript = cube1.GetComponent<script1>();
    }