- Home /
Problem with translating C# variable to JS.
Hello.
I am putting this code in Standard Assets folder:
using UnityEngine;
using System;
using System.Collections;
using System.IO;
public class ResolutionChanger : MonoBehaviour
{
public string fileName = "Settings.ini";
public float timer;
private int screenWidth;
private int screenHeight;
private int fullscreen;
void Start()
{
using (StreamReader fileStream = File.OpenText(Path.GetFullPath(fileName)))
{
string fileLine = "";
while ((fileLine = fileStream.ReadLine()) != null)
{
string option = fileLine.Substring(0, fileLine.IndexOf("="));
switch (option)
{
case "gametime":
timer = Convert.ToInt32(fileLine.Substring(fileLine.IndexOf("=") + 1));
break;
case "screenwidth":
screenWidth = Convert.ToInt32(fileLine.Substring(fileLine.IndexOf("=") + 1));
break;
case "screenheight":
screenHeight = Convert.ToInt32(fileLine.Substring(fileLine.IndexOf("=") + 1));
break;
case "radius":
fullscreen = Convert.ToInt32(fileLine.Substring(fileLine.IndexOf("=") + 1));
break;
}
}
fileStream.Close();
}
Screen.SetResolution(screenWidth, screenHeight, false);
}
}
And its working. I have access from text file. But when i try to use the variable "timer" in other JS file, like this:
private var csScript : ResolutionChanger;
function Awake()
{
csScript = this.GetComponent("ResolutionChanger");
}
var guiScore : GUIText;
var myTimer = csScript.timer;
function Update (){
myTimer -= Time.deltaTime;
if(myTimer < 0){
Application.LoadLevel("GameOver");
}
var count : int = myTimer;
guiScore.text = " " + count;
}
I have an error: NullReferenceException: Object reference not set to an instance of an object Timer..ctor () (at Assets/scripts/Timer.js:10)
Whats the problem?
Answer by sparkzbarca · Jan 24, 2013 at 04:45 PM
you cant mix and match java and C# like that. Google accessing a javascript from a C# unity for more information.
But http://www.41post.com/1935/program$$anonymous$$g/unity3d-js-cs-or-cs-js-access says that i can do this
Answer by Loius · Jan 24, 2013 at 06:13 PM
csScript isn't set to any thing.
Order of operations: First executed is code outside any function, then Awake, then Start, then Update.
You're setting something = csScript.something outside a function, then you're setting csScript = something in Awake.