Access non static function from static function - unity3d

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.

Related

How to fix : The object of type 'GameObject' has been destroyed but you are still trying to access it ? -Unity

I made a 5 second time bar to replace the wave. when wave1 has been 5 seconds it will move to wave2. then the first wave will be destroyed. when I got to wave3, an error came out. here's my code:
IEnumerator ChangeWave()
{
for (int i = 0; i < wave.Length - 1; i++)
{
yield return new WaitForSeconds(5f);
Destroy(wave[i]);
wave[i+1].SetActive(true);
}
}
the error said The object of type 'GameObject' has been destroyed but you are still trying to access it. - unity
sorry for my bad english.
There's a few things going on here.
Remove the -1 in the for loop, so it iterates to end
wave[i+1] will cause an error, so check if (i < wave.Length -1)
Destroy( array[index] ) will try and access Game Object but it's destroyed, so you should create a temporary var to hold gameobject, and set null to the array element.
Some fixes below - there might be a better way, but this is what I use:
Version 1 - Using the above fixes
IEnumerator ChangeWaveV2()
{
for (int i = 0; i < wave.Length; i++)
{
yield return new WaitForSeconds(.2f);
var t = wave[i];
wave[i] = null;
Destroy(t);
if(i < wave.Length - 1)
wave[i + 1].SetActive(true);
}
}
Version 2 - A variation without needing to null out the element and create a temporary var. If you iterate from end to front of the array, you can freely Destroy() GameObjects in an array. May not be useful as it changes the wave array.
IEnumerator ChangeWaveV3()
{
System.Array.Reverse(wave);
for (int i = wave.Length - 1; i >= 0; i--)
{
yield return new WaitForSeconds(.2f);
Destroy(wave[i]);
if(i > 0)
wave[i - 1].SetActive(true);
}
}

Linked List Parameterized constructor

I tried to do a Parameterized constructor for a linked list my program is about to implement a queue by using a liked list so i want to do a parameterized constructor like Queue(int value , int size) and it dose not run or doing a list
this is my code for this problem
Queue(int value,int _size)
{
for(int i = 0; i < _size; ++i)
{
Node* temp = new Node;
temp->data = value;
temp->next = nullptr;
if(head == nullptr)
{
head = tail = temp;
}
else
{
tail->next = temp;
tail = temp;
}
}
}
i expected that the result is to fill the lest by value times size like if i run this function Queue x(20,3) the linked list should be
20 20 20
Since that this is a constructor, The head and tail are not properly initialized to use them. I would suggest adding head = tail = nullptr just before the loop and see what happens.
Follow this code after your node creation. I hope this will work. And do use i++ instead of ++i, as the later will make the loop for size-1 times.
if(head == NULL)
head = temp;
else{
Node *x;
x= head;
while(x->next != NULL)
x = x->next;
x->next = temp;
}

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.

How to do simple javascript looping in protractor

for ( i = 0; i < 100; i++) {
browser.manage().logs().get('browser').then(function(browserLog) {
console.log(i);
});
}
I am trying to run this using protractor, but i get hundred times 100 printed in console. I have some functionality which am trying to implement using looping.How can i do looping in protractor?
This is because the functions you're passing to then all close over the variable i, not the value that variable has when you create the functions. So later, when the functions are called, they all see the value of i as it is then, after the loop is complete (100).
If you want to capture the value of i as it is when you create the function, you can use ES5's Function#bind:
for ( i = 0; i < 100; i++) {
browser.manage().logs().get('browser').then(function(index, browserLog) {
console.log(index);
}.bind(null, i));
}
bind returns a new function that, when called, will call the original function with a given this value (in this case I'm using null) and any arguments you follow that with, followed by arguments given to the function bind returned.
Another approach is a builder function:
for ( i = 0; i < 100; i++) {
browser.manage().logs().get('browser').then(buildHandler(i));
}
function buildHandler(index) {
return function(browserLog) {
console.log(index);
};
}
That has the advantage of allowing the caller to control this.

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