Unity 5 unityscript returns errors when trying to write to a file - unity3d

I have successfully made a level with a Terrain, a Rigidbody FPS Controller from Standard Assets -> Characters and some other GameObjects. I now need to save my system so I have started to google file IO for UnityScript. I have found some examples but they return compiler errors (details below).
OS is Windows 10 64-bit. Unity version is 5.5.1f1 64-bit. Code editor is Visual Studio 2015, line endings corrected to Windows line endings. Language is UnityScript. Code I have used:
#pragma strict
import System;
import System.IO;
var Filename : String = "save.ini";
private var rwfile : StreamWriter;
var x;
var y;
var z;
var Player : GameObject;
private var startTime : int;
private var timer1 : int;
function TimerSet() {startTime = Time.time;}
function TimerUpdate() {
timer1 = Time.time;
if(timer1 > 60) {
Debug.Log("Saving");
Write();
TimerSet();}}
function WriterSetup() {
Debug.Log("File Writer setup...");
if (!File.Exists(Filename)) {
rwfile = File.CreateText(Filename);}
Debug.Log("File Writer configured sucsessfully");}
function Write() {
rwfile = File.CreateText(Filename);
x = Player.transform.position.x;
y = Player.transform.position.y;
z = Player.transform.position.z;
rwfile.WriteLine(x);
rwfile.WriteLine(y);
rwfile.WriteLine(z);
rwfile.Close();}
function Start() {Debug.Log("Saver Script Setup");
WriterSetup();
TimerSet();}
function Update() {TimerUpdate();}
My error:

Your error is telling you that it dosen't know what OpenText is. I don't see in your code anything about a function called OpenText, so i guess you were trying to use the File.OpenText function so you should change this line
rwfile = OpenText(Filename);
To this
rwfile = File.OpenText(Filename);
Also for the other errors you need to assigne your rwfile to a StreamWriter
private var rwfile : StreamWriter;
You should also change your Write function for this:
function Write() {
x = Player.transform.position.x;
y = Player.transform.position.y;
z = Player.transform.position.z;
using (rwfile = File.CreateText(Filename))
{
rwfile.WriteLine(x);
rwfile.WriteLine(y);
rwfile.WriteLine(z);
rwfile.Close();
}
}

Related

Unity NullReferenceException after accessing a variable of another script

after trying to acces a variable in another Script of another GameObject out of a List, I get every time an Exception. The Main code looks like this:
private var BombList = new List.<GameObject>();
private var BombTemp : GameObject;
private var BombTempScript : Bomb;
function Start () {
BombTemp = null;
BombTempScript = null;
BombList.Clear();
}
function Update () {
if(BombList.Count > 0){
for(var i : int = 0; i<BombList.Count;i++){
BombTemp = BombList[i];
BombTempScript = BombTemp.GetComponent.<Bomb>();
if(BombTempScript.bombCountdown <= 0){
BombTempScript.explode();
BombList.Remove(BombTemp);
addHealth(-1);
}
}
}
}
function OnTriggerEnter (other : Collider) {
if(other.gameObject.CompareTag("Bomb")){
BombList.Add(other.gameObject);
other.gameObject.GetComponent.<Bomb>().notListed = false;
}
}
function OnTriggerExit(other : Collider){
if(other.gameObject.CompareTag("Bomb")){
if(BombList.Contains(other.gameObject)){
BombList.Remove(other.gameObject);
other.gameObject.GetComponent.<Bomb>().notListed = true;
}
}
}
If there isn't an object in the List the Code in the Update function does not work as intended. But when there is an object inside it produces a NullReferenceException in the if Line:
if(BombTempScript.bombCountdown <= 0)
The variable which is pointed at named bombCountdown, is continuously changing.
Here is the intended code:
#pragma strict
public var bombCountdown : float;
public var notListed : System.Boolean;
function Start () {
bombCountdown = 10.0;
notListed = true;
}
function Update () {
bombCountdown -= Time.deltaTime;
if(bombCountdown <= 0 && notListed)
explode();
}
function explode(){
Destroy(myText);
Destroy(this.gameObject);
}
I hope you could help us.
Thanks in advance, the Silly Scientists
I think there's a small bug in the code, which is making it happen.
In the Bomb script, in the following portion, you are destroying the bomb object, without removing it from the BombList of the first script.
As a result, BombList[i] may become null, as it may already have been destroyed.
If you make sure that you update the BombList when the Bomb is destroyed, I guess the code will work.
You remove gameobject from list in the for loop, so all indexes in the list shift to left from removed object. And the count is not the same as for loop started. At first you must complete your for loop, then remove objects after that.

Unity3D call function from another script (Unityscript)

I've looked up similar questions and responses and still have not been able to get this to work.
LessonRightButton.js
//#pragma strict
public var audio1 : AudioPlayback;
function OnClick(){
var findAudioSource = GameObject.Find("AudioPlaybackButton");
var audio1:AudioPlayback = findAudioSource.GetComponent(AudioPlayback);
audio1.woo(); // THIS IS LINE 50 IN THE ERROR
}
AudioPlayback.js
//#pragma strict
function woo(){
Debug.Log("wooooooooooooooo");
}
I get this error:
NullReferenceException: Object reference not set to an instance of an
object LessonRightButton.OnClick () (at
Assets/Scripts/LessonRightButton.js:50)
I'm trying to call the woo function from a different script.
These scripts are shortened for the purpose of ease of reading. Please advise.
you have no AudioPlayback attached on that AudioPlaybackButton object.
Either add one manually or by code:
function OnClick(){
var findAudioSource = GameObject.Find("AudioPlaybackButton");
var audio1:AudioPlayback = findAudioSource.GetComponent(AudioPlayback);
if(audio1 == null){
audio1 = findAudioSource.AddComponent(AudioPlayback);
}
audio1.woo();
}

How to Listen Keys in JScript.Net

What I wish is to catch the keypress using JScript .NET, and compile the code using that jsc.exe.
So, is there any equivalent of "addEventListener("keyDown", keyCheck)" from FLASH actionscript. Or GetAsyncKeyState() from C++.
And what library do I have to use?
Please be kind enough to share a small, simple example.
Here's a simple solution if you're writing a console app.
import System;
Console.Write("Press the M key... ");
var key:ConsoleKeyInfo;
while (1) {
while (!Console.KeyAvailable) {
System.Threading.Thread.Sleep(1);
}
key = Console.ReadKey(1);
if (key.Key == ConsoleKey.M) break;
}
Console.Write("Accepted.");
Read more about ConsoleKeyInfo.
If you need GetAsyncKeyState(), it is possible to access the method in JScript.NET. A couple days ago I came across a JScript.NET function that exposes Win32 API methods via P/Invoke. Here it is, slightly modified for simpler syntax (allowing pass-through of arguments from API function definitions).
import System;
import System.Reflection;
import System.Reflection.Emit;
// Invoke a Win32 P/Invoke call.
// credit: http://cx20.main.jp/blog/hello/2013/03/07/hello-win32-api-jscript-net-world/
function InvokeWin32(dllName:String, returnType:Type, methodName:String, params:Object[]) {
var paramTypes:Type[] = new Type[params.length];
for (var i:int in params) {
paramTypes[i] = params[i].GetType();
}
// Begin to build the dynamic assembly
var domain = AppDomain.CurrentDomain;
var name = new System.Reflection.AssemblyName('PInvokeAssembly');
var assembly = domain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
var module = assembly.DefineDynamicModule('PInvokeModule');
var type = module.DefineType('PInvokeType',TypeAttributes.Public
+ TypeAttributes.BeforeFieldInit);
// Define the actual P/Invoke method
var method = type.DefineMethod(methodName, MethodAttributes.Public
+ MethodAttributes.HideBySig + MethodAttributes.Static +
MethodAttributes.PinvokeImpl, returnType, paramTypes);
// Apply the P/Invoke constructor
var ctor = System.Runtime.InteropServices.DllImportAttribute.GetConstructor(
[System.String]
);
var attr = new System.Reflection.Emit.CustomAttributeBuilder(ctor, [dllName]);
method.SetCustomAttribute(attr);
// Create the temporary type, and invoke the method.
var realType = type.CreateType();
return realType.InvokeMember(methodName, BindingFlags.Public + BindingFlags.Static
+ BindingFlags.InvokeMethod, null, null, params);
}
With this function, you can expose Win32 DLL methods with the following syntax. (See? Told you it was simpler.)
// ShowWindowAsync(hWnd:IntPtr, nCmdShow:int);
function ShowWindowAsync(... args:Object[]):boolean {
return InvokeWin32("user32.dll", System.Boolean, "ShowWindowAsync", args);
}
// GetWindowLong(hWnd:IntPtr, nIndex:int);
function GetWindowLong(... args:Object[]):int {
return InvokeWin32("user32.dll", System.Int32, "GetWindowLong", args);
}
// FindWindowEx(parentHandle:IntPtr, childAfter:IntPtr,
// lclassName:IntPtr, windowTitle:String);
function FindWindowEx(... args:Object[]):IntPtr {
return InvokeWin32("user32.dll", System.IntPtr, "FindWindowEx", args);
}
And I've never used GetAsyncKeyState(); but since it's a user32.dll method, I'm guessing it'll work the same way. (Edit: It does.)
// GetAsyncKeyState(vKey:int);
function GetAsyncKeyState(... args:Object[]):short {
return InvokeWin32("user32.dll", System.Int16, "GetAsyncKeyState", args);
}
Then for a trivial example:
import System; // for Console methods
import System.Windows.Forms; // for Keys object constants
Console.Write("Press the M key... ");
// while the M key is not being pressed, sleep
while (!GetAsyncKeyState(Keys.M)) {
System.Threading.Thread.Sleep(1);
}
// flush input buffer
while (Console.KeyAvailable) Console.ReadKey(1);
Console.WriteLine("Accepted.");

Access non static function from static function

Here is some insight: I am working with UnityScript in Unity 4.6.3. I have one script called Pause.js and it contains this function:
function fadeMusicOut () {
while (audio.volume >= 0.005) {
yield WaitForSeconds(0.1);
Debug.Log("Loop Entered: " + audio.volume);
audio.volume = (audio.volume - 0.015);
}
Another script GameManager.js has this function:
static function Score (wallName : String) {
if (wallName == "rightWall") {
playerScore01 += 1;
}
else {
playerScore02 += 1;
}
if (playerScore01 == SettingsBack.scoreLimit || playerScore02 == SettingsBack.scoreLimit)
{
startParticles = 1;
SettingsBack.gameOver = 1;
BallControl.fadeSound = 1;
yield WaitForSeconds(4);
Camera.main.SendMessage("fadeOut");
Pause.fadeMusic = 1;
SettingsBack.soundVolume = 0;
yield WaitForSeconds(2);
playerScore01 = 0;
playerScore02 = 0;
SettingsBack.soundVolume = oldSoundVol;
Application.LoadLevel("_Menu");
}
}
So pretty much I want to call the fadeMusicOut() function from static function Score, but it will not let me because it says it needs an instance of that object.
The Pause.js script is not attached to any game objects, but it is attached to 2 buttons that call their specific functions. The GameManager.js script is attached to an object called GM. So how can I go about calling fadeMusicOut() from the Score function?
I have tried setting new vars that import the game object but still no luck. I tried making fadeMusicOut() a static function, but it creates many errors.
Any help at all is appreciated.

How can i force website to stay in frame?

I'm using Firefox + searchbastard addon to do a multi-search on shopping search engines.The pages are part of a frame. This works just fine for all sites I tried so far except for shopmania.com.
If I use noscript to forbid scripts from the shopmania domain name then everything stays in place but the part of the website elements become nonresponsive. I know there is an option in Firefox to force links that open in a new window to open in a new tab. Is there something similar to prevent websites from popping out of frame? Maybe a Firefox addon that blocks these requests?
Or at least can someone please tell me what is causing only this website to act like this?
EDIT: What tool can i use to pause firefox OR javascript and stepthrough code like in c++ ? I tried a javascript debugger and firebug. They don't help but i'm probably not using them right..
EDIT2: I tried this greasemonkey script : https://userscripts.org/scripts/show/92424. It does not work so i guess it isn't because of 'target' attribute
This is wrong. I'm guessing you're using a plugin to capture and override the output some site gives you. I'm pretty sure this violates their ToS and it's not a very nice thing to do in general.
JavaScript is not designed to allow this kind of meddling. It's patchy at best.
If you want to use the data from a website, to aggregate or display in some manner, use their public API. If they don't have a public API they probably don't want you to use their service in such a manner.
The solution : I took the script from Stop execution of Javascript function (client side) or tweak it and modified it to search for the tag that has in it top.location = location and then appended a new script with the if (top != self) {top.location = location;} line commented . Being a js total newbie i don't know if it's the most elegant choice but it soves the prob. Special thanks to Tim Fountain.
I will leave this open just in case someone else will suggest a better solution, for my and others's education. Again thanks for the help.
Below is the code:
// ==UserScript==
// #name _Replace evil Javascript
// #run-at document-start
// ==/UserScript==
/****** New "init" function that we will use
instead of the old, bad "init" function.
*/
function init () {
/* //changing stuff around here
var newParagraph = document.createElement ('p');
newParagraph.textContent = "I was added by the new, good init() function!";
document.body.appendChild (newParagraph); */
<!--//--><![CDATA[//><!--
document.getElementsByTagName("html")[0].className+=" js "+(navigator.userAgent.toLowerCase().indexOf("webkit")>=0?"webkit":navigator.userAgent.toLowerCase().indexOf("opera")>=0?"opera":"");
for(i in css3_tags="abbr|header|footer".split("|")){document.createElement(css3_tags[i]);}
var PATH = "http://www.shopmania.com";
var PATH_STATIC = "http://im4.shopmania.org";
var PATH_SELF = "http://www.shopmania.com/";
var RETURN = "http%3A%2F%2Fwww.shopmania.com%2F";
var DOMAIN_BASE = "shopmania.com";
var SUBDOMAINS_FORCE_FILES_JS = "aff.remote,biz.remote,my.remote,cp.remote,cp.register_quick,cp.account_details,partner.remote,site.recommend,site.remote,site.feedback,site.report_problem,site.report,site.cropper";
var URL_REWRITE_MAPPING_JS = "cmd,section,do,option|feed,mode,option|forgot,section|info,page|login,section|logout,section|new_password,section,code|settings,section|shopping,param_main,param_sec|site,store_str_key|register,section|unsubscribe,section|agentie,store_str_key,id|brand,manuf_str_key|brands,letter|build,type,param_main,param_sec|compare,online|confirm,section|edit,section|deal,deal|dictionary,online|home,section|link_accounts,section|profile,user|reactivate,section|searches,letter|signup,section|rs_agent,store_str_key|rs_list,param_main,param_sec|rs_view,ad|agents,state|complex_list,param_main|complex_view,complex|list,cat|ad,a|map,option|my_ads,section|my_alerts,section";
var SVR_SITE_ID = "us";
var CONTEXT = "c5b27de70340c97a94092a43bd34b2b8";
var link_close = "Close";
var txt_loading = "Loading...";
var form_is_submitted = 0;
var search_is_focused = 0;
// Overlay object
var OL;
var DB;
var iframe_cnt = "";
// Facebook post to user's Wall action
var FACEBOOK_WALL_FEED_SIGNUP = "";
var SITENAME = "ShopMania";
//if (top != self) {top.location = location;} // SIT!
var comps = new Array(); comps['all'] = 0;var comps_cat_titles = new Array(); var views = new Array(); views['auto'] = 0; views['prod'] = 0; views['realestate'] = 0; views['classifieds'] = 0; views['all'] = 0; var search = new Array(); search['all'] = 0; search['prod'] = 0;
var favs = new Array(); favs['all'] = 0; favs['prod'] = 0; favs['store'] = 0; favs['manuf'] = 0; favs['other'] = 0; favs['realestate'] = 0; favs['auto'] = 0;
function addCss(c){var b=document.getElementsByTagName("head")[0];var a=document.createElement("style");a.setAttribute("type","text/css");if(a.styleSheet){a.styleSheet.cssText=c}else{a.appendChild(document.createTextNode(c))}b.appendChild(a)};
addCss(".lzl {visibility: hidden;}");
var RecaptchaOptions = { theme : 'clean' };
//--><!]]>
}
/*--- Check for bad scripts to intercept and specify any actions to take.
*/
checkForBadJavascripts ( [
[false, /top.location = location/, function () {addJS_Node (init);} ]
] );
function checkForBadJavascripts (controlArray) {
/*--- Note that this is a self-initializing function. The controlArray
parameter is only active for the FIRST call. After that, it is an
event listener.
The control array row is defines like so:
[bSearchSrcAttr, identifyingRegex, callbackFunction]
Where:
bSearchSrcAttr True to search the SRC attribute of a script tag
false to search the TEXT content of a script tag.
identifyingRegex A valid regular expression that should be unique
to that particular script tag.
callbackFunction An optional function to execute when the script is
found. Use null if not needed.
*/
if ( ! controlArray.length) return null;
checkForBadJavascripts = function (zEvent) {
for (var J = controlArray.length - 1; J >= 0; --J) {
var bSearchSrcAttr = controlArray[J][0];
var identifyingRegex = controlArray[J][1];
if (bSearchSrcAttr) {
if (identifyingRegex.test (zEvent.target.src) ) {
stopBadJavascript (J);
return false;
}
}
else {
if (identifyingRegex.test (zEvent.target.textContent) ) {
stopBadJavascript (J);
return false;
}
}
}
function stopBadJavascript (controlIndex) {
zEvent.stopPropagation ();
zEvent.preventDefault ();
var callbackFunction = controlArray[J][2];
if (typeof callbackFunction == "function")
callbackFunction ();
//--- Remove the node just to clear clutter from Firebug inspection.
zEvent.target.parentNode.removeChild (zEvent.target);
//--- Script is intercepted, remove it from the list.
controlArray.splice (J, 1);
if ( ! controlArray.length) {
//--- All done, remove the listener.
window.removeEventListener (
'beforescriptexecute', checkForBadJavascripts, true
);
}
}
}
/*--- Use the "beforescriptexecute" event to monitor scipts as they are loaded.
See https://developer.mozilla.org/en/DOM/element.onbeforescriptexecute
Note that it does not work on acripts that are dynamically created.
*/
window.addEventListener ('beforescriptexecute', checkForBadJavascripts, true);
return checkForBadJavascripts;
}
function addJS_Node (text, s_URL, funcToRun) {
var D = document;
var scriptNode = D.createElement ('script');
scriptNode.type = "text/javascript";
if (text) scriptNode.textContent = text;
if (s_URL) scriptNode.src = s_URL;
if (funcToRun) scriptNode.textContent = '(' + funcToRun.toString() + ')()';
var targ = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
//--- Don't error check here. if DOM not available, should throw error.
targ.appendChild (scriptNode);
}
there are some escaping issues with the cdata part in the code.So SO does not allow me to post the code.
EDIT: fixed