In UnityScript, why does GUI not get called within hit on collider? - user-interface

I'm trying to print out text when a user touches a sprite, however, even though I get no errors when building and running the code, the code refuses to printout the text and I cannot understand what I am doing wrong. Please help me understand why it does not print.
It prints the debug text when I touch the sprite, but not the GUI text with total.
This is the code:
#pragma strict
function Start () {
OnGUI();
}
function OnGUI(){
//var total = 0;
//GUI.Label( myRect, total.ToString() ); // Displays "10".
//GUI.Label( myRect, "" + bullets ); // Displays "10".
// GUI.Label(Rect(0,0,Screen.width,Screen.height),"Total:"+total);
}
//function Update () {
//}
var platform : RuntimePlatform = Application.platform;
function Update(){
if(platform == RuntimePlatform.Android || platform == RuntimePlatform.IPhonePlayer){
if(Input.touchCount > 0) {
if(Input.GetTouch(0).phase == TouchPhase.Began){
checkTouch(Input.GetTouch(0).position);
}
}
}else if(platform == RuntimePlatform.WindowsEditor){
if(Input.GetMouseButtonDown(0)) {
checkTouch(Input.mousePosition);
}
}
}
function checkTouch(pos){
var total = 0;
var wp : Vector3 = Camera.main.ScreenToWorldPoint(pos);
var touchPos : Vector2 = new Vector2(wp.x, wp.y);
var hit = Physics2D.OverlapPoint(touchPos);
if(hit){
GUI.Label(Rect(0,0,Screen.width,Screen.height),"Total:");
Debug.Log(hit.transform.gameObject.name);
hit.transform.gameObject.SendMessage('Clicked',0,SendMessageOptions.DontRequireReceiver);
//total = total +1;
}
}

You cannot put a gui item outside the OnGUI Method. You need to set a boolean to turn on the label.
Something along these lines.
OnGUI(){
if(labelbool)
GUI.Label ....
}
check(){
labelbool = true;
}

Related

Getting 'Error: AppleEvent handler failed' every time I run this script in Script Editor

Been struggling to get this script to work. It's meant to batch export notes out of Apple Notes. Script is below.
// set things up
var app = Application.currentApplication();
app.includeStandardAdditions = true;
var notesApp = Application('Notes');
notesApp.includeStandardAdditions = true;
// choose which notes
var notes = notesApp.notes;
var whichNotes = app.chooseFromList(notes.name(), { withPrompt: "Which Notes?", multipleSelectionsAllowed: true });
if (whichNotes) {
// choose save location
var saveWhere = app.chooseFolder().toString();
if (saveWhere) {
// loop through all notes
for(var i=0; i<notes.length; i++) {
// is this note one to be exported?
if (whichNotes.indexOf(notes[i].name()) > -1) {
// save file as html
var filename = saveWhere+"/"+notes[i].name()+".html";
var file = app.openForAccess(Path(filename), { writePermission: true });
app.setEof(file, { to: 0 });
app.write(notes[i].body(), {to: file});
app.closeAccess(file);
}
}
}
}
A bunch of other people have used it with no problems.
I have the same problem with the same script on 10.15.7. The issue is raised on notes.name().
I assume this is related to either too many notes (it used to work, but I created a lot of notes since), or some special char in the note title. But I did not managed to fix it with my notes.
I copied my version below.
(notice the replace to build a valid file name if your note title contain "/".)
// set things up
var app = Application.currentApplication();
app.includeStandardAdditions = true;
var notesApp = Application('Notes');
notesApp.includeStandardAdditions = true;
// choose which notes
var notes = notesApp.notes;
this.console.log("before notes.name()")
var whichNotes = app.chooseFromList(notes.name(), { withPrompt: "Which Notes?", multipleSelectionsAllowed: true });
this.console.log("After notes.name()")
this.console.log("Let's do it") // view / show log / message tab
if (whichNotes) {
// choose save location
var saveWhere = app.chooseFolder().toString();
if (saveWhere) {
this.console.log("note count:"+notes.length)
// loop through all notes
for(var i=0; i<notes.length; i++) {
// is this note one to be exported?
if (whichNotes.indexOf(notes[i].name()) > -1) {
// save file as html
var notename = notes[i].name().replace(/\//gi,'-')
this.console.log("next:"+notename) // view / show log / message tab
var filename = saveWhere+"/"+ notename +".html";
var file = app.openForAccess(Path(filename), { writePermission: true });
app.setEof(file, { to: 0 });
app.write(notes[i].body(), {to: file});
app.closeAccess(file);
}
}
}
}

Photoshop CC2019 auto-update all linked smart objects including nested ones

I have Photoshop CC2019 PSD document containing several smart objects that contains other smart objects that contains other smart objects. Some of these have linked layers. Normally, such images are not updated automatically (which is extremely annoying, Adobe!) but you have to manually update each of them once the linked image content has changed.
There is a .jsx script file named "Update All Modified Content.jsx" which auto-updates linked layers (PNG image in my case) but only if the smart object is in the top most document - that is no nested smart objects with linked layers are updated automatically.
My question is: does anyone know how to update the content of the above mentioned .jsx file so that it would auto-update all linked images across all the smart objects in PSD document including nested ones?
For those who care or would be willing to help updating the code here it is:
// Update all modified content
var idplacedLayerUpdateAllModified = stringIDToTypeID( "placedLayerUpdateAllModified" );
executeAction( idplacedLayerUpdateAllModified, undefined, DialogModes.NO );
So, after spending half a day with it I finally solved it myself. Here is the code:
#target photoshop
// SET INITIAL ACTIVE DOCUMENT
var mainDocument = app.activeDocument;
// SAVE THE DOCUMENT NAME FOR FUTURE USE
var mainDocName = mainDocument.name;
// RUN THE MAIN UPDATE FUNCTION
mainDocument.suspendHistory("processAllSmartObjects", "autoupdateAllSmartObjects(mainDocument, 0)");
// FINALLY SAVE THE MAIN DOCUMENT
mainDocument.save();
function autoupdateAllSmartObjects(theParent, prevVal) {
// FUNCTION TO TEST IF SMARTOBJECT IS LINKED
function isLinkedSO(obj) {
var localFilePath = "";
var ref = new ActionReference();
ref.putIdentifier(charIDToTypeID('Lyr '), obj.id);
var desc = executeActionGet(ref);
var smObj = desc.getObjectValue(stringIDToTypeID('smartObject'));
var isLinked = false;
// TEST IF IT HAS LINKED FILE
try {
var localFilePath = smObj.getPath(stringIDToTypeID('link'));
isLinked = true;
} catch(e) {
//
}
return isLinked;
}
// FUNCTION TO UPDATE LINKED SMART OBJECT
function doTheUpdate(LYR, stackNr) {
// SET ACTIVE LAYER TO ACTUALY ITERATED ONE
app.activeDocument.activeLayer = LYR;
// RUN IN "SILENT" MODE
app.displayDialogs = DialogModes.NO;
var layer = app.activeDocument.activeLayer;
// IF ACTIVE LAYER IS SMARTOBJECT
if (layer.kind == "LayerKind.SMARTOBJECT") {
//alert(layer);
// OPEN THE SMARTOBJECT
app.runMenuItem(stringIDToTypeID('placedLayerEditContents'));
// DO THE ACTUAL FILE UPDATE
var idplacedLayerUpdateAllModified = stringIDToTypeID( "placedLayerUpdateAllModified" );
executeAction( idplacedLayerUpdateAllModified, undefined, DialogModes.NO);
// IF IT IS NOT THE "CORE/MAIN" DOCUMENT
if(stackNr > 0) {
// SAVE CHANGES (UPDATE) AND CLOSE IT
app.activeDocument.close(SaveOptions.SAVECHANGES);
}
// CONTINUE INSIDE THIS ACTIVE SMARTOBJECT
autoupdateAllSmartObjects(app.activeDocument, stackNr);
}
return;
}
// FUNCTION TO PARSE GROUPS
function parseGroup(LYR) {
var groupLayers = LYR.layers;
// IF GROUP IS NOT EMPTY
if(groupLayers.length > 0) {
// PARSE ALL LAYERS IN THE GROUP
for (var i = groupLayers.length - 1; i >= 0; i--) {
var lyr = groupLayers[i];
// IF NOT LOCKED = NOT EDITABL:E
if(!lyr.allLocked) {
// YET ANOTHER GROUP?
if (lyr.typename == "LayerSet") {
// IF IT IS NOT EMPTY
if (lyr.layers.length > 0) {
// RE-RUN THE SCRIPT ANEW WITH THE SELECTED GROUP AS LAYERS SOURCE
autoupdateAllSmartObjects(lyr, 0);
}
// LAYERS
} else if (lyr.typename == "ArtLayer") {
// IF THE LAYER IS SMARTOBJECT
if (lyr.kind == LayerKind.SMARTOBJECT) {
// IF THE LAYER IS SET TO "visible" (THAT IS: NOT DISABLED)
if(lyr.visible){
// TEST IF THE SMARTOBJECT IS ACTUALLY LINKED
if(!isLinkedSO(lyr)) {
// RUN THE UPDATE SUB-FUNCTION
doTheUpdate(lyr, i);
}
}
}
}
}
}
}
}
// PARSE ALL THE LAYERS
for (var i = theParent.layers.length - 1 - prevVal; i >= 0; i--) {
var theLayer = theParent.layers[i];
// ONLY ArtLayers
if (theLayer.typename == "ArtLayer") {
// IF THE LAYER IS SMARTOBJECT
if (theLayer.kind == LayerKind.SMARTOBJECT) {
// IF THE LAYER IS SET TO "visible" (THAT IS: NOT DISABLED)
if(theLayer.visible){
// TEST IF THE SMARTOBJECT IS ACTUALLY LINKED
if(!isLinkedSO(theLayer)){
// RUN THE UPDATE SUB-FUNCTION
doTheUpdate(theLayer, i);
// IF WE ARE AT THE LAST LAYER IN THE STACK AND IT IS NOT OUR MAIN DOCUMENT
if(i == 0 && app.activeDocument.name !== mainDocName) {
// SAVE CHANGES (UPDATE) AND CLOSE IT
app.activeDocument.close(SaveOptions.SAVECHANGES);
}
}
}
}
// ONLY Groups
} else if (theLayer.typename == "LayerSet") {
// RUN SUB-FUNCTION FOR GROUP PARSING
parseGroup(theLayer);
// ANYTHING ELSE
} else {
autoupdateAllSmartObjects(theLayer, m);
}
}
return;
};
OP's script works!! It was going in loops for me too but after some trial and error, I realised that my smart objects (SO) that are linked across artboards ( - e.g. if you change one SO, it changes on various artboards) - were the issue. I hid all such SO and it works.
so basically, it only works for Smart Objects + copies made via 'New smart object via copy' NOT 'duplicate layer' / copypaste smart objects. If your work contains a 'duplicate layer' SO - it will break the script. You need to hide these objects ( or not work like that all together) before running the script

Pictures keep going to the top left.(Actionscript 3)

So my project was to make two gallery pages. I called them "gallery1" and "gallery2".The gallery pages each have 5 thumbnails that act like buttons so when you click on em, it opens an swf of the picture. Now the problem is, it always opens on the top left, i want them to be in the middle of the page. This is the code for gallery1. Gallery 2 is the samething but with different pics. b1-b5 are the thumbnails.Please help.
var swfRequest1:URLRequest = new URLRequest("image1.swf");
var swfRequest2:URLRequest = new URLRequest("image2.swf");
var swfRequest3:URLRequest = new URLRequest("image3.swf");
var swfRequest4:URLRequest = new URLRequest("image4.swf");
var swfRequest5:URLRequest = new URLRequest("image5.swf");
var swfLoader:Loader = new Loader();
function opengal(evt:MouseEvent):void
{
var pTarget:String = evt.currentTarget.name;
if(pTarget == "b1")
{
swfLoader.load(swfRequest1);
addChild(swfLoader);
}
else if(pTarget == "b2")
{
swfLoader.load(swfRequest2);
addChild(swfLoader);
}
else if(pTarget == "b3")
{
swfLoader.load(swfRequest3);
addChild(swfLoader);
}
else if (pTarget == "b4")
{
swfLoader.load(swfRequest4);
addChild(swfLoader);
}
else if(pTarget == "b5")
{
swfLoader.load(swfRequest5);
addChild(swfLoader);
}
};
b1.addEventListener(MouseEvent.CLICK, opengal);
b2.addEventListener(MouseEvent.CLICK, opengal);
b3.addEventListener(MouseEvent.CLICK, opengal);
b4.addEventListener(MouseEvent.CLICK, opengal);
b5.addEventListener(MouseEvent.CLICK, opengal);
To set your loaded content in the middle of your stage, you can do like this :
// store files path into an array
var files:Array = ['image01.swf', 'image02.swf', 'image03.swf', 'image04.swf', 'image05.swf'];
var loader:Loader = new Loader();
// use loader.contentLoaderInfo to listen to Event.INIT
loader.contentLoaderInfo.addEventListener(
Event.INIT, function(e:Event):void {
// center our loader
loader.x = (stage.stageWidth - loader.width)/2;
loader.y = (stage.stageHeight - loader.height)/2;
})
addChild(loader);
function opengal(evt:MouseEvent):void {
// here the pTarget should be between 0 and 4 as an array index
var pTarget:int = Number((evt.currentTarget.name).substr(-1, 1)) - 1;
loader.load(new URLRequest(files[pTarget]));
};
...
I hope this can help you.
You have to position your swfLoader in the middle of the screen.
You can do this with this code:
swfLoader.x = (swfLoader.width - stage.stageWidth)/2; // and the y axis in a similar way
The required width and height properties can be retrieved when the contentLoaderInfo dispatches an Event.INIT.

Unity3D - GUIText Does Not Show On Collision With Object

Ive been following this article online and have swapped a few names and tags about but I dont seem to see any text appearing on the screen...
Here is my PlayerCollision script:
#pragma strict
function Update () {
}
function OnControllerColliderHit(hit : ControllerColliderHit){
if(hit.gameObject.tag == "Collider"){
ShowMessage.message = "HELLO WORLD";
ShowMessage.turnTextOn = true;
}
}
This is my ShowMessage script:
#pragma strict
static var turnTextOn : boolean = false;
static var message : String;
private var timer : float = 0.0;
function Start(){
timer = 0.0;
turnTextOn = false;
guiText.text = "";
}
function Update () {
if(turnTextOn){
guiText.enabled = true;
guiText.text = message;
timer += Time.deltaTime;
}
if(timer >= 5){
turnTextOn = false;
guiText.enabled = false;
timer = 0.0;
}
}
I have linked the ShowMessage script to my GUIText object and have linked the PlayerCollision script with the CharacterController. There is also a box collider object with the Collision tag I also Have the GUIText in view just to rule that out.
Anyone any idea what is wrong? Thanks
The tag should be "Collider" not "Collision" because if(hit.gameObject.tag == "Collider")
Problem solved. Turns out I ticked isTrigger which stopped the collision from being detected. This gives the problem of the character not being able to move through the object. What i did was tick the isTrigger option and change OnControllerColliderHit(hit : ControllerColliderHit) to OnTriggerEnter (obj : Collider)

XNA Hold screen to move object

im working with windows phone game using xna... and looking a way to make my object to move with holding some rectangle that i made as a button on screen....
i already tried this but it just read tap gesture only
foreach (GestureSample gestureSample in input.Gestures)
{
switch (gestureSample.GestureType)
{
case GestureType.Hold:
case GestureType.Tap:
Point tapLocation = new Point((int)gestureSample.Position.X, (int)gestureSample.Position.Y);
if (rightRectangle.Contains(tapLocation))
{
rightTouched = true;
player.Catapult.CurrentState = CatapultState.MoveRight;
playerPositionUpdate.X += 20;
player.catapultPosition.X += 20;
player.Catapult.catapultPosition.X += 20;
player.Catapult.projectilePositionUpdate.X += 20;
if (player.Catapult.catapultPosition.X == player.Catapult.catapultPosition.X + 20)
rightTouched = false;
CenterOnPosition(player.Catapult.Position - catapultCenterOffset);
}
break;
}
}
Gestures are discrete events. You want to poll the state of the touch panel every frame. Use TouchPanel.GetState() for that.
See Working with Touch Input (Windows Phone) for information.
As mentioned above you shouldn't use GestureSample for that purpose, because using dragcomplete and freedrag a bit tricky. Instead you should code your own gestures using TouchPanel.GetState()
TouchCollection touchCollection = TouchPanel.GetState();
if (touchCollection.Count == 1)
{
var touch = touchCollection[0];
switch (touch.State)
{
case TouchLocationState.Pressed:
if (rectangle.Contains((int) touch.Position.X, (int) touch.Position.Y))
{
isMoving = true;
}
break;
case TouchLocationState.Moved:
if (isMoving)
{
TouchLocation prevLocation;
touch.TryGetPreviousLocation(out prevLocation);
if (prevLocation.Position != touch.Position)
{
Vector2 delta = touch.Position - prevLocation.Position;
//offset your rectangle on delta
}
}
break;
case TouchLocationState.Released:
isMoving = false;
break;
}
}
else if (touchCollection.Count == 2)
{
var touchOne = touchCollection[0];
var touchTwo = touchCollection[1];
//pinch logic here
}
I guess you understand the idea.

Resources