- Home /
changing js public variable from cs script
Hi, Im stuck on changing a variable in a JS script from a CS Script. Can I change the variable directly or do I call a function in the JS script from the CS script?
MouseOrbit.js
var target : Transform;
...code
Original Switch.js
function Update () {
//if (Input.GetButtonDown("Jump"))GetComponent(Follow).target = switchToTarget;
if (Input.GetButtonDown("Jump")){
var newTarget = GameObject.Find("Cube1").transform;
GetComponent(Follow).target = newTarget;
}
}
The cs script I am trying:
using UnityEngine; using System.Collections; using System.Collections.Generic;
public class SceneControl : MonoBehaviour { public void Start (){ GameObject test = GameObject.Find("Main Camera"); Debug.Log("Got:" + test.name); //MouseOrbit myMS = test.GetComponent<MouseOrbit>(); //Debug.Log("Got:" + myMS.name); Component myMS = GetComponent(typeof(MouseOrbit)); Debug.Log(myMS.ToString()); //myMS.target = sceneObj.transform; }
I keep getting a NullReferenceException : Object reference not set to an instance of an object. This is for the getComponent call. the GameObject.Find works ok and I get Main Camera back. Is this even possible?
K this works:
GameObject test = GameObject.Find("Main Camera");
Debug.Log("Got:" + test.name);
MouseOrbit myMS = test.GetComponent<MouseOrbit>();
Debug.Log(myMS.ToString());
myMS.target = sceneObj.transform;
Answer by Tetrad · Jun 21, 2010 at 07:19 AM
It doesn't matter what language the scripts are written in, a public member variable is a public member variable.
The trick is that you have to be using the right type. So your commented out GetComponent is the correct one.
The non-commented-out GetComponent is getting the component on your SceneControl object and not your Camera object. That's probably why you're geting a null reference exception. Also if you wanted to use the non-generic GetComponent you'll have to cast your return type to the type you want to access. Component doesn't have a "target" variable.
Edit: this may not be entirely accurate. http://unity3d.com/support/documentation/ScriptReference/index.Script_compilation_28Advanced29.html