Unity3D call function from another script (Unityscript) - unity3d

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();
}

Related

Access datasource in eventhandlers

The below code is generating errors:
Initialize:
var firstC = ["AUD","ZAR"];
var secondC= ["AUD","BRL","CAD","USD"];
function colorG(item, col, row){
var currency = firstC[col] + "-"+ secondC[row];
if(verifyCurrency(currency)==true)
item.getStyle().backgroundColor="green";
}
function verifyCurrency(currency)
{
if(this.getRowData().getExpressionValue("row[digital]").indexOf(currency)!=-1)
return true;
else return false;
}
cell:
colorG(this,1,0);
In which phase do I have to place verifyCurrency so that it will work?
Your assumption about "this" in your verifyCurrency function is wrong. I don't know Javascript good enough to tell you more about this, but I think that "this" is always defined inside a function. But it is not pointing to your item instance!
To fix this (no pun intended), pass the item as an argument to your verifyColor function.

get value for specific question/item in a Google Form using Google App Script in an on submit event

I have figured out how to run a Google App Script project/function on a form submit using the information at https://developers.google.com/apps-script/guides/triggers/events#form-submit_4.
Once I have e I can call e.response to get a FormResponse object and then call getItemResponses() to get an array of all of the responses.
Without iterating through the array and checking each one, is there a way to find the ItemResponse for a specific question?
I see getResponseForItem(item) but it looks like I have to somehow create an Item first?
Can I some how use e.source to get the Form object and then find the Item by question, without iterating through all of them, so I could get the Item object I can use with getResponseForItem(item)?
This is the code I use to pull the current set of answers into a object, so the most current response for the question Your Name becomes form.yourName which I found to be the easiest way to find responses by question:
function objectifyForm() {
//Makes the form info into an object
var myform = FormApp.getActiveForm();
var formResponses = myform.getResponses()
var currentResponse = formResponses[formResponses.length-1];
var responseArray = currentResponse.getItemResponses()
var form = {};
form.user = currentResponse.getRespondentEmail(); //requires collect email addresses to be turned on or is undefined.
form.timestamp = currentResponse.getTimestamp();
form.formName = myform.getTitle();
for (var i = 0; i < responseArray.length; i++){
var response = responseArray[i].getResponse();
var item = responseArray[i].getItem().getTitle();
var item = camelize(item);
form[item] = response;
}
return form;
}
function camelize(str) {
str = str.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()#\+\?><\[\]\+]/g, '')
return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(match, index) {
if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces
return index == 0 ? match.toLowerCase() : match.toUpperCase();
});
}
//Use with installable trigger
function onSubmittedForm() {
var form = objectifyForm();
Logger.log(form);
//Put Code here
}
A couple of important things.
If you change the question on the form, you will need to update your
code
Non required questions may or may not have answers, so check if answer exists before you use it
I only use installable triggers, so I know it works with those. Not sure about with simple triggers
You can see the form object by opening the logs, which is useful for finding the object names

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.

Access to the elements of the page in the Page-Worker

I've created a page-worker in the extension
dup = pageWorker.Page({
contentScript: "self.port.on('alert', function(message) {"+
"console.log(message);"+
"document.querySelector('.test-element').title = message;"+
"});",
contentScriptWhen: "ready",
contentURL: "http://example.com/Licznik-beta/addon.html"
});
In "contentScript" I can relate to "document".
But I can not relate to the window, or function, or variable.
console.log(window) in contentScript return "TypeError: cyclic object value timers.js:43".
I do not understand how it works.
Can someone explain to me?
How to change it?
EDIT
I've added a few lines to the test:
self.port.on('addon-licznik', function () {
console.log(document);
console.log(window); // TypeError: cyclic object value timers.js:43
runFromAddon(); // ReferenceError: runFromAddon is not defined timers.js:43
});
Function: runFromAddon(); Of course there is.
Second test:
function funSet (tresc) {
var addonScript = document.querySelector(".addon-script");
if ( addonScript != undefined ) {
document.querySelector('head').removeChild( addonScript );
}
var script = document.createElement("script");
script.className = "addon-script";
script.textContent = tresc;
document.querySelector('head').appendChild(script);
}
function marmo (message) {
console.log(message);
funSet("console.log(window); runFromAddon();");
}
self.port.on('addon-licznik', marmo);
It works well.
Window → http://example.com/Licznik-beta/addon.html
runFromAddon-Log
If you're writing the HTML yourself, then use addon instead of self and attach the script to the page using <script></script> instead of contentScript(File). See Scripting trusted page content.
If you're not writing the HTML, then see Communicating with Page Scripts.

Calling class function within a constructor isn't being recognised

Answer:
It turns out I had neglected to use the new keyword when creating the class instance. The code in the question itself is fine.
Question:
I have a fairly simple class where the constructor calls another method on the class (editor_for_node). The call happens inside a jQuery each() loop, but I've also tried moving it outside.
define ['jquery'], ($) ->
class Editor
constructor: (#node, #data, #template) ->
#node.widgets().each (i, elem) =>
data = if #data then #data[i] else null
node = $(elem)
#editor_for_node node, data
editor_for_node: (node, data) ->
console.log 'hello!'
return {
'Editor': Editor,
}
When the line #editor_for_node node, data gets called, I get an error (in Firebug) saying this.editor_for_node is not a function.
I really can't see why this isn't working properly, the only possible source of weirdness that I can see is my use of require.js's define function at the start.
Edit: Generated output
(function() {
define(['jquery'], function($) {
var Editor;
Editor = (function() {
Editor.name = 'Editor';
function Editor(node, data, template) {
var _this = this;
this.node = node;
this.data = data;
this.template = template;
this.node.widgets().each(function(i, elem) {
data = _this.data ? _this.data[i] : null;
node = $(elem);
return _this.editor_for_node(node, data);
});
}
Editor.prototype.editor_for_node = function(node, data) {
return console.log('hello!');
};
return Editor;
})();
return {
'Editor': Editor
};
});
}).call(this);
First: Which version of CoffeeScript are you using? The fat arrow has been a source of bugs in certain previous releases.
If you're using the latest (1.3.1), then I'm going to go ahead and say that this is an indentation issue. When I copy and paste your code, it works fine. Are you mixing tabs and spaces? Verify that the compiled output contains the line
Editor.prototype.editor_for_node = ...
Update: See the comments on this answer. Turns out the problem was that the new keyword wasn't being used when invoking the constructor.