- Home /
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?
Answer by Bunny83 · Jan 18, 2014 at 01:04 PM
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>();
}
@Bunny83 looks like i was a little early accepting your answer. now the debug.Log in Update gives me...
Object reference not set to an instance of an object script2.Update ()
In Start()
it should be:
myScript = cube1.GetComponent<script1>();
Otherwise you declare and initialise a new variable.
Your answer
Follow this Question
Related Questions
Does Garbage Collector Collect variables Made Inside Scope? 1 Answer
Multiple Cars not working 1 Answer
Class Scope Variable 1 Answer
Distribute terrain in zones 3 Answers
Members not reset with SceneManager.LoadScene(scene); 0 Answers