I know in Java all I need to do is add the static keyword in front of my var definition. How do I access my variable in C#?
using UnityEngine;
using System.Collections;
public class CameraSwitch : MonoBehaviour
{
public Camera FirstPersonCamera;
public Camera ThirdPersonCamera;
private bool Activated = false;
private float elapsedTime = 0F;
public enum DefaultCamera { First = 1, Third = 3 }
public DefaultCamera View = DefaultCamera.Third;
I want FirstPersonCamera and ThirdPersonCamera available in my javascript, but I get this error:
When I try to access my variable:
var MainCamera = CameraSwitch.ThirdPersonCamera.camera;
Accessing a component from a C# script should work exactly the same way as accessing a component from Javascript unless the javascript is compiled BEFORE the C# script (like if itâs in the Prefabs or Editor folder).
Manny pretty much has it rightâŚ
the code you posted isnât quite right for accessing the component though. it should be something like this:
var camaraObject : GameObject; // declaring the camera object...you can drag the camera object on to the script in the inspector this way
var cameraScript : CameraSwitch; // this is your C# script that's attached to the cameraObject game component
public Start(){ // for performance reasons, it's always good to get your components in the Awake or Start function
cameraScript = cameraObject.GetComponent(CameraSwitch);
// then you can access the vars in the camera script class similarly to what you had:
var MainCamera = cameraScript.ThirdPersonCamera.camera;
}
you can also declare your ThirdPersonCamera variable as static, but then it wonât be accessible through the inspector. One way around this that I use sometimes is to have two vars, a public var thatâs accessible through the inspector and then a static var thatâs accessible everywhere. then in my Start() function I assign the public var to the static var.
One caveat about using static vars is that you always have to access them by referencing the script (even inside the same script).
UnityScript has been deprecated for a long while now, so thereâs probably not a lot of people around that remembers the intricacies of interop anymore.