When I launch my game in game editor or on the phone - it glitches for the 2-3 seconds and calls the function OnApplicationPause. But when I close application/pause in editor it doesn't calls. That's bad for my project so how to fix it? There's function code :
void OnApplicationPause()
{
DateTime time = DateTime.Now;
SaveVariablesInClass();
PlayerPrefs.SetString("SV", JsonUtility.ToJson(save)); //saves special class
}
void SaveVariablesInClass()
{
save.Bananas = bananas;
save.GoldBananas = goldBananas;
save.TwoBananasSpawnChance = twoBananasSpawnChance;
save.HigherBananaLevelChance = higherBananaLevelChance;
save.SimpleBananaStormChance = simpleBananaStormChance;
save.GoldBananaChance = goldBananaChance;
save.TwoGoldBananaChance = twoGoldBananaChance;
save.offlineEfficiency = offlineEfficiency;
save.offlineProductionTime = offlineProductionTime;
save.goldCoefficient = goldCoefficient;
save.BonusLevels = bonusLevels;
save.GoldBonusLevels = goldBonusLevels;
save.SimpleBonusLevelPrices = simpleBonusLevelPrices;
save.GoldBonusLevelPrices = goldBonusLevelPrices;
save.simpleMaxLevels = simpleMaxLevels;
save.goldMaxLevels = goldMaxLevels;
save.time = time.ToString();
save.CurrentSimpleBonus1 = currentSimpleBonus1;
save.LaunchedGame = launchedGame;
}
You are missing the bool parameter in the method. It should be OnApplicationPause(bool pauseStatus). OnApplicationPause is called on each GameObject after Awake. So your code should be:
void OnApplicationPause(bool pauseStatus)
{
if (pauseStatus)
{
DateTime time = DateTime.Now;
SaveVariablesInClass();
PlayerPrefs.SetString("SV", JsonUtility.ToJson(save)); //saves special class
}
}
The lag you show in comments is caused by rendering not script.
Related
I need to play a audio file which is 3 minutes length. But default notification sound does not play more than 30 seconds. So my idea is Calling a Avplayer
which will play my desired audio. But i do not know how to call this. Can any one please help me. I will be very grateful.
I am attaching my notification method here.
public void AVPlayer()
{
NSUrl songURL;
if (!MusicOn) return;
//Song url from your local Resource
songURL = new NSUrl("azan.wav");
NSError err;
player = new AVAudioPlayer(songURL, "Song", out err);
player.Volume = MusicVolume;
player.FinishedPlaying += delegate {
// backgroundMusic.Dispose();
player = null;
};
//Background Music play
player.Play();
}
public void CreateRequest(JamatTime jamat)
{
// Create action
var actionID = "pause";
var title = "PAUSE";
var action = UNNotificationAction.FromIdentifier(actionID, title, UNNotificationActionOptions.None);
// Create category
var categoryID = "message";
var actions = new UNNotificationAction[] { action };
var intentIDs = new string[] { };
var categoryOptions = new UNNotificationCategoryOptions[] { };
var category = UNNotificationCategory.FromIdentifier(categoryID, actions, intentIDs, UNNotificationCategoryOptions.None);
// Register category
var categories = new UNNotificationCategory[] { category };
UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet<UNNotificationCategory>(categories));
// Rebuild notification
var content = new UNMutableNotificationContent();
content.Title = " Jamat Time alert";
content.Badge = 1;
content.CategoryIdentifier = "message";`enter code here`
content.Sound = UNNotificationSound.GetSound("sample.wav");
var times = new string[] { jamat.Asr, jamat.Dhuhr, jamat.Faijr, jamat.Ishaa, jamat.Jumah, jamat.Maghib };
int id = 0;
foreach (var time in times)
{
var ndate = DateTime.ParseExact(time, "h:mm tt", null);
var date = new NSDateComponents()
{
Calendar = NSCalendar.CurrentCalendar,
Hour = ndate.Hour,
Minute = ndate.Minute,
Second = 0
};
content.UserInfo = new NSDictionary<NSString, NSString>(
new NSString[] {
(NSString)"time1",
(NSString)"time2"
},
new NSString[] {
(NSString)DateTime.Now.ToString("h:mm tt"),
(NSString)time
});
var trigger = UNCalendarNotificationTrigger.CreateTrigger(date, true);
// ID of Notification to be updated
var request = UNNotificationRequest.FromIdentifier(id++.ToString(), content, trigger);
// Add to system to modify existing Notification
UNUserNotificationCenter.Current.AddNotificationRequest(request, (err1) =>
{
if (err1 != null)
{
Console.WriteLine("Error: {0}", err1);
}
Console.WriteLine($"Success: {request}");
});
}
}
You can't play an audio file instead of the UNNotificationSound.
There's no way to trigger the player's play method when the local notification comes. You could only configure the sound property using the code you post above. And the file should be embedded in the bundle resource.
It seems you are aware of UNNotificationSound: https://developer.apple.com/documentation/usernotifications/unnotificationsound?language=objc. But I still want to remind you of the file's format and length limitations.
Finally I have solved my problem.
When a notification fires then WillPresentNotification() method hits and I simply call the AVplayer there and perfectly working. If u want to play sound via UNNotificationSound then not possible because that is limited by 30 second duration..but problem this works only in foreground.
According to this post, you can make Visual Studio find.
I update the code of Asif Iqbal K from the article a bit to eliminate build error.
public const string vsWindowKindFindResults1 = "{0F887920-C2B6-11D2-9375-0080C747D9A0}";
public string FindInFiles(string searchText)
{
EnvDTE80.DTE2 dte;
dte = (EnvDTE80.DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE");
dte.MainWindow.Activate();
EnvDTE.Find find = dte.Find;
find.Action = EnvDTE.vsFindAction.vsFindActionFindAll;
find.FindWhat = searchText;
find.MatchWholeWord = false;
find.ResultsLocation = EnvDTE.vsFindResultsLocation.vsFindResults1;
find.Target = EnvDTE.vsFindTarget.vsFindTargetSolution;
find.PatternSyntax = EnvDTE.vsFindPatternSyntax.vsFindPatternSyntaxRegExpr;
find.SearchSubfolders = true;
var x = dte.Find.FindWhat;
EnvDTE.vsFindResult result = find.Execute();
var findWindow = dte.Windows.Item(vsWindowKindFindResults1);
string data = "";
System.Threading.Thread.Sleep(5000);//Comment out this code to see the problem, this line of code is not the solution though.
if (result == EnvDTE.vsFindResult.vsFindResultFound)
{
var selection = findWindow.Selection as EnvDTE.TextSelection;
selection.SelectAll();
data = selection.Text;
}
return data;
}
I see that the problem is the function return the string (string data) too early, so it can't get all the text from the result window.
So the code comes so close to get the find text. One remaining puzzle is to check if the find process complete, then get the text.
So the question is: replace what code with the code
System.Threading.Thread.Sleep(5000);
So that the function FindInFiles() can get all the text of 'FindResult 1" window.
Thanks for reading.
Here is the solution
EnvDTE80.DTE2 s_dte;
EnvDTE.FindEvents s_findEvents;
public const string vsWindowKindFindResults1 = "{0F887920-C2B6-11D2-9375-0080C747D9A0}";
public frmFindHelper()
{
InitializeComponent();
s_dte = (EnvDTE80.DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE");
s_dte.MainWindow.Activate();
s_findEvents = s_dte.Events.FindEvents;
s_findEvents.FindDone += new EnvDTE._dispFindEvents_FindDoneEventHandler(OnFindDone);
}
private void OnFindDone(EnvDTE.vsFindResult result, bool cancelled)
{
if (result == EnvDTE.vsFindResult.vsFindResultFound)
{
var findWindow = s_dte.Windows.Item(vsWindowKindFindResults1);
string data = "";
var selection = findWindow.Selection as EnvDTE.TextSelection;
selection.SelectAll();
data = selection.Text;
MessageBox.Show("Done!");
}
}
private void btnFind_Click(object sender, EventArgs e)
{
EnvDTE.Find find = s_dte.Find;
find.Action = EnvDTE.vsFindAction.vsFindActionFindAll;
find.FindWhat = txtSearch.Text;
find.MatchWholeWord = false;
find.ResultsLocation = EnvDTE.vsFindResultsLocation.vsFindResults1;
find.Target = EnvDTE.vsFindTarget.vsFindTargetSolution;
find.PatternSyntax = EnvDTE.vsFindPatternSyntax.vsFindPatternSyntaxRegExpr;
find.SearchSubfolders = true;
var x = s_dte.Find.FindWhat;
EnvDTE.vsFindResult result = find.Execute();
}
Thanks to Ed Dore from this post
I have an app that plays a youtube video when a proper link is given. Problem is, the app uses what is probably a native player that overrides the youtube one. Here is my current code:
if (newsVideo != "" && isConnected == true)
{
myWebView = FindViewById<WebView>(Resource.Id.NewsVideo);
int intDisplayHeight;
var screenwidth = metrics.WidthPixels;
intDisplayHeight = screenwidth / 2;
string convertednewsVideo = newsVideo.Replace("=\"\\", "=\\");
List<string> newsVideoLink = VideoParseHTML.ReturnVideoUrl(convertednewsVideo);
foreach (string item in newsVideoLink)
{
string strUrl = item.Substring(1, item.Length - 2);
string html = #"<html><body><iframe src=""strUrl"" width=""100%"" height=""videoHeight"" frameborder=""0"" ></iframe></body></html>";
var settings = myWebView.Settings;
settings.JavaScriptEnabled = true;
settings.UseWideViewPort = true;
settings.LoadWithOverviewMode = true;
settings.JavaScriptCanOpenWindowsAutomatically = true;
settings.DomStorageEnabled = true;
settings.SetRenderPriority(WebSettings.RenderPriority.High);
settings.BuiltInZoomControls = false;
settings.AllowFileAccess = true;
settings.SetPluginState(WebSettings.PluginState.On);
myWebView.SetWebChromeClient(new WebChromeClient());
string strYouTubeURL = html.Replace("videoHeight", intDisplayHeight.ToString()).Replace("strUrl", strUrl);
myWebView.LoadData(strYouTubeURL, "text/html", "UTF-8");
}
}
This is what the player looks like:
What I want is either force the application to use the youtube player or if that isn't possible, to at least remove the fullscreen button from the native player, as I don't want this functionality.
Thank you
I'm making an app where a use enters values for two times (starthour, startminute, endhour, endminute). I wrote a function that saves the values and then checks for value and puts the values inside the text boxes. However, it isn't working and I'm not sure why. I'm assuming its a mistake on my part, but I'm not exactly sure. Here's the code:
public async Task savedata()
{
while (true)
{
var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
localSettings.Values["starthour1"] = starthour1.Text;
localSettings.Values["starthour2"] = starthour2.Text;
localSettings.Values["starthour3"] = starthour3.Text;
localSettings.Values["starthour4"] = starthour4.Text;
localSettings.Values["starthour5"] = starthour5.Text;
localSettings.Values["starthour6"] = starthour6.Text;
localSettings.Values["starthour7"] = starthour7.Text;
localSettings.Values["startminute1"] = startminute1.Text;
localSettings.Values["startminute2"] = startminute2.Text;
localSettings.Values["startminute3"] = startminute3.Text;
localSettings.Values["startminute4"] = startminute4.Text;
localSettings.Values["startminute5"] = startminute5.Text;
localSettings.Values["startminute6"] = startminute6.Text;
localSettings.Values["startminute7"] = startminute7.Text;
localSettings.Values["endhour1"] = endhour1.Text;
localSettings.Values["endhour2"] = endhour2.Text;
localSettings.Values["endhour3"] = endhour3.Text;
localSettings.Values["endhour4"] = endhour4.Text;
localSettings.Values["endhour5"] = endhour5.Text;
localSettings.Values["endhour6"] = endhour6.Text;
localSettings.Values["endhour7"] = endhour7.Text;
localSettings.Values["endminute1"] = endminute1.Text;
localSettings.Values["endminute2"] = endminute2.Text;
localSettings.Values["endminute3"] = endminute3.Text;
localSettings.Values["endminute4"] = endminute4.Text;
localSettings.Values["endminute5"] = endminute5.Text;
localSettings.Values["endminute6"] = endminute6.Text;
localSettings.Values["endminute7"] = endminute7.Text;
//get data
Object starthour1o = localSettings.Values["starthour1"];
if (starthour1o == null)
{
// No data
}
else
{
starthour1.Text = starthour1o.ToString();
}
Object starthour2o = localSettings.Values["starthour2"];
if (starthour2o == null)
{
// No data
}
else
{
starthour2.Text = starthour2o.ToString();
}
Object starthour3o = localSettings.Values["starthour3"];
if (starthour3o == null)
{
// No data
}
else
{
starthour3.Text = starthour3o.ToString();
}
Object starthour4o = localSettings.Values["starthour4"];
if (starthour4o == null)
{
// No data
}
else
{
starthour4.Text = starthour4o.ToString();
}
Object starthour5o = localSettings.Values["starthour5"];
if (starthour5o == null)
{
// No data
}
else
{
starthour5.Text = starthour5o.ToString();
}
Object starthour6o = localSettings.Values["starthour6"];
if (starthour6o == null)
{
// No data
}
else
{
starthour6.Text = starthour6o.ToString();
}
Object starthour7o = localSettings.Values["starthour7"];
if (starthour7o == null)
{
// No data
}
else
{
starthour7.Text = starthour7o.ToString();
}
await Task.Delay(10);
}
}
Two things you need to do, first you need to explicitly save your settings for them to be persisted by calling Save(). Somewhere in your code you need to do localSettings.Save() and it should work.
2nd, if you have saved settings the first thing your code does is overwrite them with the current values of the text boxes, the whole top section where it is localSettings.Values["Foo"] = Foo.Text needs to be moved to the bottom.
As a side comment, do you really need to be updating your code every 10 miliseconds? That is going to eat up a TON of resources in your program. A much more normal approach is load the values at start-up then save them at shutdown.
I'm working on a flash MMO with a c# server. I have a simple messaging protocol for the sockets. When a client joins he sends out this:
"%|clientId|need"
And positions are updated like this:
"$|clientId|xPosition|yPosition"
For some reason this isn't working. I store all the avatars in an array, the avatar class simply extends movieclip. This should add all clients into the room but it isn't working. Any ideas?
Edit: The error is probably in the client-side code above, I think it's with how I store the Avatars in an array.
Here is my code:
id.text = String(Math.random());
import flash.net.Socket;
import flash.events.MouseEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.utils.Dictionary;
var avatars:Array = new Array();
var _socket:Socket = new Socket();
_socket.addEventListener(ProgressEvent.SOCKET_DATA,socketData);
_socket.addEventListener(Event.CONNECT,socketConnected);
_socket.addEventListener(IOErrorEvent.IO_ERROR,socketError);
_socket.connect("192.168.1.4",8000);
function sendText(msg:String):void {
if (_socket.connected) {
_socket.writeUTFBytes(msg);
_socket.flush();
} else {
}
}
function socketConnected(e:Event):void {
chat.appendText("Connected. \n");
sendText("%|" + id.text + "|need");
//chat.scrollV = chat.maxScrollV;
}
function socketError(e:IOErrorEvent):void {
chat.appendText("SYSTEM MSG:"+e.text+"\n");
//chat.scrollV = chat.maxScrollV;
}
function socketData(e:ProgressEvent):void {
var str:String = e.currentTarget.readUTFBytes(e.currentTarget.bytesAvailable);
trace(str);
//var xml:XML = new XML(str);
chat.appendText(str + "\n");
//[pos]|50|334
if(str.search("$")){
var positionArray = str.split("|");
avatars[str[1]].x = str[2];
avatars[str[1]].x = str[3];
}
if(str.search("%")){
var miniArray = str.split("|");
avatars[miniArray[1]] = new Avatar();
addChild(avatars[miniArray[1]]);
dump.text = miniArray[1];
}
}
me.addEventListener(MouseEvent.MOUSE_DOWN, drag);
me.addEventListener(MouseEvent.MOUSE_UP, sDrag);
var timing:Boolean = false;
var t:Timer = new Timer(1);
t.addEventListener(TimerEvent.TIMER, tick);
function tick(e:TimerEvent){
if(timing){
sendText('$|'+id.text+'|'+me.x+'|'+me.y);
}
else{
}
}
t.start();
function drag(e:MouseEvent){
me.startDrag();
timing = true;
}
function sDrag(e:MouseEvent){
me.stopDrag();
timing = false;
}
Edit: Changing answer based on additional information.
You had a few problems after addressing the code. First was your use of if(str.search)... The $ and % can be parsed as a regular expression. Additionally since your chars were at an index of 0 these if's could fail to be true. Lastly your were using str[1] instead of positionArray[1] etc. Below is the working code with some hacking to test without the use of a socket server. Might show you some tricks on how to do some focused testing when you run into issues like this.
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
public class TestSocket extends Sprite
{
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.net.Socket;
import flash.utils.Dictionary;
import flash.utils.Timer;
[Embed(source="assets/avatar.png")]
private var Avatar:Class;
private var avatars:Array = new Array();
function TestSocket():void
{
socketSimulator(10);
}
function socketData(e:ProgressEvent):void {
var str:String = e.currentTarget.readUTFBytes(e.currentTarget.bytesAvailable);
trace(str);
if(str.indexOf("$") >= 0){
var positionArray = str.split("|");
avatars[positionArray[1]].x = positionArray[2];
avatars[positionArray[1]].x = positionArray[3];
}
if(str.indexOf("%") >= 0){
var miniArray = str.split("|");
avatars[miniArray[1]] = new Avatar();
addChild(avatars[miniArray[1]]);
}
}
/** Test Code **/
private var _numClients;
private function socketSimulator(numClients:int):void
{
_numClients = numClients;
var msg:String;
while(--numClients >= 0)
{
msg = "%|" + numClients + "|need";
sendFakeData(msg);
}
var timer:Timer = new Timer(500, 9999);
timer.addEventListener(TimerEvent.TIMER, sendFakeMovement);
timer.start();
}
private function sendFakeMovement(e:TimerEvent):void
{
var id:uint = Math.random() * _numClients;
var x:Number = Math.random() * 1000;
var y:Number = Math.random() * 1000;
var msg:String = "$|"+id+"|"+x+"|"+y;
sendFakeData(msg);
}
//This is just hacked test code, don't do this in production
private function sendFakeData(msg:String):void
{
var e:MyProgressEvent = new MyProgressEvent(ProgressEvent.SOCKET_DATA);
e.currentTarget = {
readUTFBytes: function(bytes:int = 0):String
{
return msg;
}
}
socketData(e);
}
}
}
import flash.events.ProgressEvent;
class MyProgressEvent extends ProgressEvent
{
private var _currentTarget:Object;
public function set currentTarget(val:Object):void
{
_currentTarget = val;
}
override public function get currentTarget():Object
{
return _currentTarget;
}
function MyProgressEvent(type:String):void
{
super(type);
}
}
Before you test log in/log off/position, make sure that your architecture supports sending and receiving data in the first place, I mean, send a string ("some data") on the front-end and check if you're really receiving ("some data") on the back-end. I am afraid the byte endianness that you're sending on the client is different from that on the server and so the server will mis-understand the incoming data. If so you need to convert the incoming messages to the suitable endianness before trying to process them.