- Home /
Trying to call a variable from another script in C#
I have been able to do this successfully with Unityscript by declaring
var instanceName : ScriptName;and then by using instanceName.variable
but I haven't had any luck in trying to accomplish the same thing in C#.
Any one able to help me with this? Thanks
Answer by DaveA · Mar 22, 2012 at 09:46 PM
make sure you put 'public' before the declaration, eg
public ScriptName instanceName;
Thanks :) always forget about that.
Now I have this error:
An object reference is required to access non-static memberin my update call I'm trying to set a variable
string result = SearchField.stringToEdit;where SearchField.stringToEdit calls a string from the SearchField class.
Have you declared and assigned the SearchField variable?
never $$anonymous$$d, the problem was I was calling the function of SearchField using SearchField.property rather than using the instance name of search.property
Thanks guys :)
oh wait... the error has come back. its saying
Object reference not set to an instance of an object
I have a SearchField class with the following:
using UnityEngine; using System.Collections;
public class SearchField : $$anonymous$$onoBehaviour { /properties/
public string stringToEdit = "Hello World";
/*methods*/
public string SetResult()
{
return stringToEdit;
}
void OnGUI(){
stringToEdit = GUI.TextField(new Rect(10, 10, 200, 20), stringToEdit, 25);
//static function TextField (position : Rect, text : String, maxLength : int) : String
}}
and then I'm trying to pass the edited string from the search box known as stringToEdit to the CameraPositions class:
using UnityEngine; using System.Collections;
public class CameraPositions : $$anonymous$$onoBehaviour { SearchField search; public Vector3 entry; public string result;
void Update()
{
result = search.stringToEdit;
if(result == "Earth")
{
entry.x = -87.37f;
entry.y = 49.43f;
entry.z = 20.22f;
}
}
}
the error is pointing to the
result = search.stringToEdit;
Your "search" variable is a private variable, do you assign any reference to this variable? i guess not(if that's the whole script). You should either make it public and drag & drop the correct script instance onto the variable, or use GameObject.Find and GetComponent to get the desired script-instance via code.