C# - Visual Studio and Rage - c#

Hello I'm having some problems with a callout making I don't know if anyone here can help me but I'll try asking anyway.
Information
I'm making a CalloutPack for a game called Grand Theft Auto 5 while using RagePluginHook an add-on needed for that to make it work.
Basically, It works like this Main.cs go trough -> Handler.cs that register all the callouts (source code for main and handler down below). It uses LSPDFR.API.MOD and Rage, now i seem to get an Rage.ISpatial is invalid. at Rage.Entity.DistanceTo(ISpatial spatialObject) and I don't really know where in my code I have f up.
I'm getting a Take over Radio Tower Los Santos: Operation is not valid because the specified Rage.ISpatial is invalid. at Rage.Entity.DistanceTo(ISpatial spatialObject)
do anyone know what I did wrong?
Source code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Rage;
using LSPD_First_Response.Mod.API;
using LSPD_First_Response.Mod.Callouts;
using System.Drawing;
using Rage.Native;
namespace SpeedyPursuit.Callouts
{
[CalloutInfo("Take over Raido Tower Los Santos", CalloutProbability.Medium)]
public class TakeOverLS : Callout
{
private Ped Suspect;
private Ped Suspect2;
private Ped Suspect3;
private Ped Suspect4;
private Ped Suspect5;
//cops Ped
private Ped Fbisupervisor;
private Ped FbiTeamMember1;
private Ped FbiTeamMember2;
private Ped FbiTeamMember3;
private Ped FbiTeamMember4;
private LHandle Pursuit;
private bool PursuitCreated;
private Vehicle vehicle1;
private Vehicle vehicle2;
private Vehicle vehicle1p;
private Vehicle vehicle2p;
private Vehicle vehicle3p;
private Vehicle vehicle4p;
private Vector3 spawnpV1;
private Vector3 spawnpV2;
private Vector3 spawnV1;
private Vector3 spawnV2;
private Vector3 spawnV1p;
private Vector3 spawnV2p;
private Vector3 spawnV3p;
private Vector3 spawnV4p;
//Cops Spawn
private Vector3 FbisupervisorSpawn;
private Vector3 FbiTeamMember1s;
private Vector3 FbiTeamMember2s;
private Vector3 FbiTeamMember3s;
private Vector3 FbiTeamMember4s;
//locationfollow
private Vector3 followlocation;
private float followheading;
//Cops Blip
private Blip FbisupervisorBlip;
private Blip FbiTeamMember1Blip;
private Blip SuspectBlip;
private Blip SuspectBlip2;
private Blip SuspectBlip3;
private Blip SuspectBlip4;
private Blip SuspectBlip5;
private float heading;
private float headingv1;
private float headingv2;
private float headingv1p;
private float headingv2p;
private float headingv3p;
private float headingv4p;
//cops heading
private float headingfbisup;
private float FbiTeamMember1heading;
private float FbiTeamMember2heading;
private float FbiTeamMember3heading;
private float FbiTeamMember4heading;
private Vector3 Spawnpoint;
private Vector3 Spawnpoint2;
private Vector3 Spawnpoint3;
private Vector3 Spawnpoint4;
private Vector3 Spawnpoint5;
private int counter;
private int counter2;
public override bool OnBeforeCalloutDisplayed()
{
//cops spawn
FbiTeamMember1s = new Vector3(845f, 1285f, 360f);
FbiTeamMember2s = new Vector3(845f, 1283f, 360f);
FbiTeamMember3s = new Vector3(847f, 1284f, 360f);
FbiTeamMember4s = new Vector3(847f, 1286f, 360f);
followlocation = new Vector3(801f, 1276f, 360);
followheading = 86.647f;
Spawnpoint = new Vector3(778f, 1287, 360f);
Spawnpoint2 = new Vector3(779f, 1289, 360f);
Spawnpoint3 = new Vector3(778f, 1270f, 360f);
Spawnpoint4 = new Vector3(787f, 1266f, 360f);
Spawnpoint5 = new Vector3(782f, 1297f, 361f);
FbisupervisorSpawn = new Vector3(855f, 1281f, 359f);
headingv1 = 357.922f;
headingv2 = 51.345f;
// cops heading
headingfbisup = 23.187f;
FbiTeamMember1heading = 174.126f;
FbiTeamMember2heading = 354.127f;
FbiTeamMember3heading = 93.946f;
FbiTeamMember4heading = 255.905f;
headingv1p = 119.149f;
headingv2p = 66.722f;
headingv3p = 320.630f;
headingv4p = 358.971f;
spawnV1 = new Vector3(808f, 1279f, 360f);
spawnV2 = new Vector3(807f, 1272f, 360f);
spawnV1p = new Vector3(855f, 1278f, 359f);
spawnV2p = new Vector3(847f, 1276f, 359f);
spawnV3p = new Vector3(848f, 1290f, 359f);
spawnV4p = new Vector3(843f, 1283f, 359f);
ShowCalloutAreaBlipBeforeAccepting(Spawnpoint, 30f);
AddMinimumDistanceCheck(240f, Spawnpoint);
AddMaximumDistanceCheck(4000f, Spawnpoint);
CalloutMessage = "~r~Multiple suspects~w~ have taken over the Los Santos Radio Tower";
CalloutPosition = Spawnpoint;
Functions.PlayScannerAudioUsingPosition("CRIME_ASSAULT_WITH_A_DEADLY_WEAPON_01 IN_OR_AT", Spawnpoint);
PursuitCreated = false;
return base.OnBeforeCalloutDisplayed();
}
public override bool OnCalloutAccepted()
{
try
{
Game.DisplayNotification("char_call911", "char_call911", "~b~SpeedyPursuit~b~", "~r~TO ALL UNITS~w~", "~r~Dispacth:~w~ All Units responde immediately, Multiple armed suspect have forcefully taken over the radio tower in Los Santos");
Game.DisplayNotification("~r~CODE:~w~ ~Y~3 Response~w~");
Functions.PlayScannerAudio("UNITS_RESPOND_CODE_03_01");
Suspect = new Ped("MP_M_BOGDANGOON", Spawnpoint, heading);
Suspect.IsPersistent = true;
Suspect.BlockPermanentEvents = true;
Suspect2 = new Ped("MP_M_BOGDANGOON", Spawnpoint2, heading);
Suspect2.IsPersistent = true;
Suspect2.BlockPermanentEvents = true;
Suspect3 = new Ped("MP_M_BOGDANGOON", Spawnpoint3, heading);
Suspect3.IsPersistent = true;
Suspect3.BlockPermanentEvents = true;
Suspect4 = new Ped("MP_M_BOGDANGOON", Spawnpoint4, heading);
Suspect4.IsPersistent = true;
Suspect4.BlockPermanentEvents = true;
Suspect5 = new Ped("MP_M_BOGDANGOON", Spawnpoint5, heading);
Suspect5.IsPersistent = true;
Suspect5.BlockPermanentEvents = true;
//Cops ped identifer
Fbisupervisor = new Ped("S_M_Y_SWAT_01", FbisupervisorSpawn, headingfbisup);
Fbisupervisor.IsPersistent = true;
Fbisupervisor.BlockPermanentEvents = true;
FbiTeamMember1 = new Ped("S_M_Y_SWAT_01", FbiTeamMember1s, FbiTeamMember1heading);
FbiTeamMember1.IsPersistent = true;
FbiTeamMember1.BlockPermanentEvents = true;
FbiTeamMember2 = new Ped("S_M_Y_SWAT_01", FbiTeamMember2s, FbiTeamMember2heading);
FbiTeamMember2.IsPersistent = true;
FbiTeamMember2.BlockPermanentEvents = true;
FbiTeamMember3 = new Ped("S_M_Y_SWAT_01", FbiTeamMember3s, FbiTeamMember3heading);
FbiTeamMember3.IsPersistent = true;
FbiTeamMember3.BlockPermanentEvents = true;
FbiTeamMember4 = new Ped("S_M_Y_SWAT_01", FbiTeamMember4s, FbiTeamMember4heading);
FbiTeamMember4.IsPersistent = true;
FbiTeamMember4.BlockPermanentEvents = true;
//swat blip
FbiTeamMember1Blip = FbiTeamMember1.AttachBlip();
FbiTeamMember1Blip.Color = System.Drawing.Color.Green;
FbiTeamMember1Blip.IsRouteEnabled = false;
FbisupervisorBlip = Fbisupervisor.AttachBlip();
FbisupervisorBlip.Color = System.Drawing.Color.Yellow;
FbisupervisorBlip.IsRouteEnabled = true;
SuspectBlip = Suspect.AttachBlip();
SuspectBlip.Color = System.Drawing.Color.Red;
SuspectBlip.IsRouteEnabled = false;
SuspectBlip2 = Suspect.AttachBlip();
SuspectBlip2.Color = System.Drawing.Color.Red;
SuspectBlip2.IsRouteEnabled = false;
SuspectBlip3 = Suspect.AttachBlip();
SuspectBlip3.Color = System.Drawing.Color.Red;
SuspectBlip3.IsRouteEnabled = false;
SuspectBlip4 = Suspect.AttachBlip();
SuspectBlip4.Color = System.Drawing.Color.Red;
SuspectBlip4.IsRouteEnabled = false;
SuspectBlip5 = Suspect.AttachBlip();
SuspectBlip5.Color = System.Drawing.Color.Red;
SuspectBlip5.IsRouteEnabled = false;
Suspect.CanAttackFriendlies = false;
Suspect2.CanAttackFriendlies = false;
Suspect3.CanAttackFriendlies = false;
Suspect4.CanAttackFriendlies = false;
Suspect5.CanAttackFriendlies = false;
vehicle1 = new Vehicle("BURRITO", spawnV1, headingv1);
vehicle2 = new Vehicle("BURRITO", spawnV2, headingv2);
vehicle1p = new Vehicle("RIOT", spawnV1p, headingv1p);
vehicle2p = new Vehicle("RIOT", spawnV2p, headingv2p);
vehicle3p = new Vehicle("POLICE", spawnV3p, headingv3p);
vehicle4p = new Vehicle("RIOT", spawnV4p, headingv4p);
vehicle1p.IsSirenOn = true;
vehicle1p.IsSirenSilent = true;
vehicle2p.IsSirenOn = true;
vehicle2p.IsSirenSilent = true;
vehicle3p.IsSirenOn = true;
vehicle3p.IsSirenSilent = true;
vehicle4p.IsSirenOn = true;
vehicle4p.IsSirenSilent = true;
Suspect.RelationshipGroup = "ATTACKER";
Suspect2.RelationshipGroup = "ATTACKER";
Suspect3.RelationshipGroup = "ATTACKER";
Suspect4.RelationshipGroup = "ATTACKER";
Suspect5.RelationshipGroup = "ATTACKER";
FbiTeamMember1.RelationshipGroup = "COP";
FbiTeamMember2.RelationshipGroup = "COP";
FbiTeamMember3.RelationshipGroup = "COP";
FbiTeamMember4.RelationshipGroup = "COP";
Game.LocalPlayer.Character.RelationshipGroup = "COP";
Game.SetRelationshipBetweenRelationshipGroups("ATTACKER", "COP", Relationship.Hate);
Game.SetRelationshipBetweenRelationshipGroups("COP", "ATTACKER", Relationship.Hate);
Suspect.StaysInGroups = true;
Suspect2.StaysInGroups = true;
Suspect3.StaysInGroups = true;
Suspect4.StaysInGroups = true;
Suspect5.StaysInGroups = true;
FbiTeamMember1.StaysInGroups = true;
FbiTeamMember2.StaysInGroups = true;
FbiTeamMember3.StaysInGroups = true;
FbiTeamMember4.StaysInGroups = true;
FbiTeamMember1.Inventory.GiveNewWeapon("WEAPON_CARBINERIFLE", 400, true);
NativeFunction.Natives.SetPedCombatAttributes(FbiTeamMember1, 1, true);
FbiTeamMember2.Inventory.GiveNewWeapon("WEAPON_CARBINERIFLE", 400, true);
NativeFunction.Natives.SetPedCombatAttributes(FbiTeamMember2, 1, true);
FbiTeamMember3.Inventory.GiveNewWeapon("WEAPON_CARBINERIFLE", 400, true);
NativeFunction.Natives.SetPedCombatAttributes(FbiTeamMember3, 1, true);
FbiTeamMember4.Inventory.GiveNewWeapon("WEAPON_CARBINERIFLE", 400, true);
NativeFunction.Natives.SetPedCombatAttributes(FbiTeamMember4, 1, true);
Suspect.Inventory.GiveNewWeapon("WEAPON_CARBINERIFLE", 400, true);
NativeFunction.Natives.SetPedCombatAttributes(Suspect, 1, true);
Suspect2.Inventory.GiveNewWeapon("WEAPON_CARBINERIFLE", 310, true);
NativeFunction.Natives.SetPedCombatAttributes(Suspect2, 1, true);
Suspect3.Inventory.GiveNewWeapon("WEAPON_CARBINERIFLE", 200, true);
NativeFunction.Natives.SetPedCombatAttributes(Suspect3, 1, true);
Suspect4.Inventory.GiveNewWeapon("WEAPON_CARBINERIFLE", 170, true);
NativeFunction.Natives.SetPedCombatAttributes(Suspect4, 1, true);
Suspect5.Inventory.GiveNewWeapon("WEAPON_CARBINERIFLE", 130, true);
NativeFunction.Natives.SetPedCombatAttributes(Suspect5, 1, true);
}
catch
{
Game.LogTrivial("SpeedyPursuit - Something went wrong during loading section");
End();
}
return base.OnCalloutAccepted();
}
public override void Process()
{
base.Process();
if (Game.LocalPlayer.Character.DistanceTo(Fbisupervisor) <= 5f)
{
Game.DisplayHelp("Speak with the SWAT Operatin Lader, To do so press ~y~Y~w~", false);
if (Game.IsKeyDown(Handler.TalkKey))
{
counter++;
if (counter == 1)
{
Game.DisplaySubtitle("~y~SWAT Opeator:~w~ Alright listen closely I will only say this once");
}
if (counter == 2)
{
Game.DisplaySubtitle("~b~Offier:~w~ Yes sir");
}
if (counter == 3)
{
Game.DisplaySubtitle("~y~SWAT Opeator:~w~ Multiple suspects have forcefully taken over the Radio Station");
}
if (counter == 4)
{
Game.DisplaySubtitle("~y~SWAT Opeator:~w~ They are armed to the teeth with rifles and ammo that can last for days");
}
if (counter == 5)
{
Game.DisplaySubtitle("~y~SWAT Opeator:~w~ Negotiations have ended terriblely and our only last option is to lunch ~o~operation payback~w~");
}
if (counter == 6)
{
Game.DisplaySubtitle("~y~SWAT Opeator:~w~ We will force entry through the front gates with swat team ~o~BRAVO~w~");
}
if (counter == 7)
{
Game.DisplaySubtitle("~y~SWAT Opeator:~w~ Our priority is to either eliminate the targets or force them to surrender, Secondly find any hostages and free them");
}
if (counter == 8)
{
Game.DisplaySubtitle("~y~SWAT Opeator:~w~ You will lead team ~o~BRAVO~w~, when ready talk to your team and start the operation!");
FbiTeamMember1Blip.Flash(counter, 1);
}
if (counter == 9)
{
Game.DisplaySubtitle("~y~SWAT Opeator:~w~ Do you understand my commands!");
}
if (counter == 10)
{
Game.DisplaySubtitle("~b~Offier:~w~ Yes sir!");
}
if (counter == 11)
{
Game.DisplaySubtitle("~b~No further speech here, when ready for breach talk to your team.~w~");
Game.DisplayHelp("Speak with your ~o~swat team~w~", false);
}
}
}
if (Game.LocalPlayer.Character.DistanceTo(FbiTeamMember1) <= 5f)
{
Game.DisplayHelp("Speak with your SWAT Team, To do so press ~y~Y~w~", false);
if (Game.IsKeyDown(Handler.TalkKey))
{
counter2++;
if (counter2 == 1)
{
Game.DisplaySubtitle("~y~SWAT Member:~w~ We are ready to force entry when you are, sir!");
}
if (counter2 == 2)
{
Game.DisplaySubtitle("~b~Offier:~w~ Great, now let's do this");
}
if (counter2 == 3)
{
Game.DisplaySubtitle("~b~Offier:~w~ The gun men are armed and they won't be happy with our entrance");
}
if (counter2 == 4)
{
Game.DisplaySubtitle("~y~SWAT Member:~w~ Understood sir");
FbiTeamMember1.BlockPermanentEvents = false;
FbiTeamMember2.BlockPermanentEvents = false;
FbiTeamMember3.BlockPermanentEvents = false;
FbiTeamMember4.BlockPermanentEvents = false;
}
}
}
if (!PursuitCreated && Game.LocalPlayer.Character.DistanceTo(Suspect) <= 55f)
{
Pursuit = Functions.CreatePursuit();
Functions.AddPedToPursuit(Pursuit, Suspect);
Functions.AddPedToPursuit(Pursuit, Suspect2);
Functions.AddPedToPursuit(Pursuit, Suspect3);
Functions.AddPedToPursuit(Pursuit, Suspect4);
Functions.AddPedToPursuit(Pursuit, Suspect5);
Functions.SetPursuitIsActiveForPlayer(Pursuit, true);
Suspect.Tasks.FightAgainstClosestHatedTarget(200);
Suspect2.Tasks.FightAgainstClosestHatedTarget(200);
Suspect3.Tasks.FightAgainstClosestHatedTarget(200);
Suspect4.Tasks.FightAgainstClosestHatedTarget(200);
Suspect5.Tasks.FightAgainstClosestHatedTarget(200);
PursuitCreated = true;
}
if (PursuitCreated && !Functions.IsPursuitStillRunning(Pursuit))
{
End();
}
if (Game.LocalPlayer.Character.DistanceTo(Suspect) <= 60f)
{
Suspect.BlockPermanentEvents = false;
Suspect2.BlockPermanentEvents = false;
Suspect3.BlockPermanentEvents = false;
Suspect4.BlockPermanentEvents = false;
Suspect5.BlockPermanentEvents = false;
}
if (Game.LocalPlayer.Character.DistanceTo(vehicle1p) > 310f)
{
vehicle1p.Delete();
}
if (Game.LocalPlayer.Character.DistanceTo(vehicle2p) > 310f)
{
vehicle2p.Delete();
}
if (Game.LocalPlayer.Character.DistanceTo(vehicle3p) > 310f)
{
vehicle3p.Delete();
}
if (Game.LocalPlayer.Character.DistanceTo(vehicle4p) > 310f)
{
vehicle4p.Delete();
}
if (Rage.Game.IsKeyDown(Handler.EndCallout))
{
End();
vehicle1.Delete();
vehicle2.Delete();
Suspect.Delete();
Suspect2.Delete();
Suspect3.Delete();
Suspect4.Delete();
Suspect5.Delete();
SuspectBlip.Delete();
SuspectBlip2.Delete();
SuspectBlip3.Delete();
SuspectBlip4.Delete();
SuspectBlip5.Delete();
vehicle1p.Delete();
vehicle2p.Delete();
vehicle3p.Delete();
vehicle4p.Delete();
}
if (!Suspect.Exists() || Game.LocalPlayer.Character.IsDead || !Suspect2.Exists() || !Suspect3.Exists() || !Suspect4.Exists() || !Suspect5.Exists())
{
End();
}
}
public override void End()
{
base.End();
if (SuspectBlip.Exists())
{
SuspectBlip.Delete();
}
if (SuspectBlip2.Exists())
{
SuspectBlip2.Delete();
}
if (SuspectBlip3.Exists())
{
SuspectBlip3.Delete();
}
if (SuspectBlip4.Exists())
{
SuspectBlip4.Delete();
}
if (SuspectBlip5.Exists())
{
SuspectBlip5.Delete();
}
if (FbiTeamMember1Blip.Exists())
{
FbiTeamMember1Blip.Delete();
}
if (FbiTeamMember1Blip.Exists())
{
FbiTeamMember1Blip.Delete();
}
if (FbisupervisorBlip.Exists())
{
FbisupervisorBlip.Delete();
}
if (FbiTeamMember1.Exists())
{
FbiTeamMember1.Dismiss();
}
if (FbiTeamMember2.Exists())
{
FbiTeamMember2.Dismiss();
}
if (FbiTeamMember3.Exists())
{
FbiTeamMember3.Dismiss();
}
if (FbiTeamMember4.Exists())
{
FbiTeamMember4.Dismiss();
}
Game.LogTrivial("SpeedyPursuit - TakeOverLS cleaned up!");
Game.DisplayNotification("~b~SpeedyPursuit~w~ - ~g~Code 4~w~");
Functions.PlayScannerAudio("ATTENTION_ALL_UNITS WE_ARE_CODE 4");
}
}
}
Main.cs
using LSPD_First_Response;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Rage;
using Rage.Native;
using LSPD_First_Response.Mod.API;
using LSPD_First_Response.Mod.Callouts;
using LSPD_First_Response.Engine.Scripting.Entities;
using SpeedyPursuit;
using SpeedyPursuit.Callouts;
using System.Reflection;
namespace SpeedyPursuit
{
public class Main : Plugin
{
public override void Initialize()
{
Functions.OnOnDutyStateChanged += OnOnDutyStateChangedHandler;
Game.LogTrivial("SpeedyPursuit" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() + " has been initialised.");
Game.LogTrivial("Go on duty to fully load SpeedyPursuit.");
}
public override void Finally()
{
Game.LogTrivial("SpeedyPursuit has been cleaned up.");
}
private static void OnOnDutyStateChangedHandler(bool OnDuty)
{
if (OnDuty)
{
Handler.Initialize();
Game.DisplayNotification("web_lossantospolicedept", "web_lossantospolicedept", "~b~SpeedyPursuit~b~", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() + " has loaded ~g~successfully~w~", "~o~SpeedyPursuit~w~ Is now running Update name: ~o~Proud-unit~w~");
}
}
}
}

Related

How to bind an object to an event so that when touch the event is called in SkiaSharp?

I draw a pie chart using SkiaSharp, I want some information to be displayed when I clicked on the pieces of these charts
There is such a thing, for example, when you click on the black color, some information was displayed
You could use the CanvasView to draw the circle. And use SKCanvas.DrawPath to draw four parts of the circle with four colors.
Xaml: TouchCanvasView is the custom control according to the CanvasView.
<Grid>
<local:TouchCanvasView x:Name="canvasView" PaintSurface="OnPainting" Touched="OnTouched" />
</Grid>
Define the variables:
private SKPoint sKPoint;
public float _temp;
public float _total;
public float _percentage;
public float _arcAnglePoint;
private bool isDraw = false;
SKPath black;
private bool isblack = false;
SKPath orange;
private bool isOrange = false;
SKPath red;
private bool isred = false;
SKPath green;
private bool isgreen = false;
private ObservableCollection<Profile> _profileDetails;
public ObservableCollection<Profile> ProfileDetails
{
get { return _profileDetails; }
set
{
_profileDetails = value;
OnPropertyChanged(nameof(ProfileDetails));
}
}
private float _sweepAngle = 0;
public float SweepAngle
{
get { return _sweepAngle; }
set
{
_sweepAngle = value;
OnPropertyChanged(nameof(SweepAngle));
}
}
private float _startAngle = 0;
public float StartAngle
{
get { return _startAngle; }
set
{
_startAngle = value;
OnPropertyChanged(nameof(SweepAngle));
}
}
Use the two method below to get the percentage of the circle of four colors.
private void ArcPercentCalculator(float _percentage)
{
var _sweepAngle = _percentage / 100 * 360;
_arcAnglePoint = _sweepAngle;
_arcAnglePoint = _arcAnglePoint * -1;
}
private void PercentageCalculator(float values)
{
var percent = values / _total * 100;
_percentage = percent;
}
OnPainting: Use the PaintSurface to draw the circle and text. The //black, //orange, //read, //green mean the different execution for different colors.
private void OnPainting(object sender, SkiaSharp.Views.Forms.SKPaintSurfaceEventArgs e)
{
SKImageInfo info = e.Info;
SKSurface surface = e.Surface;
SKCanvas canvas = surface.Canvas;
canvas.Clear();
SKPoint center = new SKPoint(info.Width / 2, info.Height / 2);
SKRect _rect = new SKRect(center.X - 150, center.Y - 150, center.X + 150, center.Y + 150);
ProfileDetails = new ObservableCollection<Profile>()
{
new Profile{Id = 0,Name = "Blank", sKColors = SKColors.Black , Values = 541 },
new Profile{Id = 1,Name = "Orange",sKColors = SKColors.Orange ,Values = 1587 },
new Profile{Id = 2,Name = "Red",sKColors = SKColors.Red, Values = 965 },
new Profile{Id = 3,Name = "Green",sKColors = SKColors.Green, Values = 857 }
};
foreach (var item in ProfileDetails)
{
_total += item.Values;
}
//black
#region
PercentageCalculator(ProfileDetails[0].Values);
ArcPercentCalculator(_percentage);
SweepAngle = _arcAnglePoint;
SweepAngle = (float)Math.Round(SweepAngle, 2);
if (ProfileDetails[0].Id == 0)
{
StartAngle = (float)0;
_temp = SweepAngle;
}
else
{
StartAngle = (float)_temp - 1;
var x = SweepAngle;
_temp = _temp + x;
}
using (SKPath path = new SKPath())
using (SKPaint fillPaint = new SKPaint())
{
fillPaint.Style = SKPaintStyle.Stroke;
fillPaint.StrokeWidth = 50;
fillPaint.Color = ProfileDetails[0].sKColors;
path.AddArc(_rect, StartAngle, SweepAngle);
black = fillPaint.GetFillPath(path);
canvas.DrawPath(path, fillPaint);
}
#endregion
//Orange
#region
PercentageCalculator(ProfileDetails[1].Values);
ArcPercentCalculator(_percentage);
SweepAngle = _arcAnglePoint;
SweepAngle = (float)Math.Round(SweepAngle, 2);
if (ProfileDetails[1].Id == 0)
{
StartAngle = (float)0;
_temp = SweepAngle;
}
else
{
StartAngle = (float)_temp - 1;
var x = SweepAngle;
_temp = _temp + x;
}
using (SKPath path = new SKPath())
using (SKPaint fillPaint = new SKPaint())
{
fillPaint.Style = SKPaintStyle.Stroke;
fillPaint.StrokeWidth = 50;
fillPaint.Color = ProfileDetails[1].sKColors;
path.AddArc(_rect, StartAngle, SweepAngle);
orange = fillPaint.GetFillPath(path);
canvas.DrawPath(path, fillPaint);
}
#endregion
//red
#region
PercentageCalculator(ProfileDetails[2].Values);
ArcPercentCalculator(_percentage);
SweepAngle = _arcAnglePoint;
SweepAngle = (float)Math.Round(SweepAngle, 2);
if (ProfileDetails[2].Id == 0)
{
StartAngle = (float)0;
_temp = SweepAngle;
}
else
{
StartAngle = (float)_temp - 1;
var x = SweepAngle;
_temp = _temp + x;
}
using (SKPath path = new SKPath())
using (SKPaint fillPaint = new SKPaint())
using (SKPaint outlinePaint = new SKPaint())
{
fillPaint.Style = SKPaintStyle.Stroke;
fillPaint.StrokeWidth = 50;
fillPaint.Color = ProfileDetails[2].sKColors; //_Color
path.AddArc(_rect, StartAngle, SweepAngle);
red = fillPaint.GetFillPath(path);
canvas.DrawPath(path, fillPaint);
}
#endregion
//green
#region
PercentageCalculator(ProfileDetails[3].Values);
ArcPercentCalculator(_percentage);
SweepAngle = _arcAnglePoint;
SweepAngle = (float)Math.Round(SweepAngle, 2);
if (ProfileDetails[3].Id == 0)
{
StartAngle = (float)0;
_temp = SweepAngle;
}
else
{
StartAngle = (float)_temp - 1;
var x = SweepAngle;
_temp = _temp + x;
}
using (SKPath path = new SKPath())
using (SKPaint fillPaint = new SKPaint())
using (SKPaint outlinePaint = new SKPaint())
{
fillPaint.Style = SKPaintStyle.Stroke;
fillPaint.StrokeWidth = 50;
fillPaint.Color = ProfileDetails[3].sKColors; //_Color
path.AddArc(_rect, StartAngle, SweepAngle);
green = fillPaint.GetFillPath(path);
canvas.DrawPath(path, fillPaint);
}
#endregion
//draw text
if (isDraw)
{
SKPaint paint = new SKPaint();
paint.TextSize = 28;
paint.Color = SKColors.Purple;
paint.Typeface = SKTypeface.FromFamilyName("Arial", SKFontStyleWeight.Bold, SKFontStyleWidth.Normal, SKFontStyleSlant.Italic);
if (isblack)
{
canvas.DrawText(ProfileDetails[0].Name, sKPoint, paint);
}
else if (isOrange)
{
canvas.DrawText(ProfileDetails[1].Name, sKPoint, paint);
}
else if (isred)
{
canvas.DrawText(ProfileDetails[2].Name, sKPoint, paint);
}
else if (isgreen)
{
canvas.DrawText(ProfileDetails[3].Name, sKPoint, paint);
}
}
_total = 0;
}
Use the custom renderer to get the point (x,y) which you clicked from Touched event. And then use the SKPath.Contains(float x, float y)` to determine whether the point is in the specified area.
TouchCanvasView:
public class TouchCanvasView : SKCanvasView, ITouchCanvasViewController
{
public event Action<SKPoint> Touched;
public virtual void OnTouch(SKPoint point)
{
var x = point.X;
var y = point.Y;
Console.WriteLine("x1 = {0}----------------y1={1}", x, y);
Touched?.Invoke(point);
}
}
public interface ITouchCanvasViewController : IViewController
{
void OnTouch(SKPoint point);
}
TouchCanvasViewRenderer:
[assembly: ExportRenderer(typeof(TouchCanvasView), typeof(TouchCanvasViewRenderer))]
namespace App10.Droid
{
public class TouchCanvasViewRenderer : SKCanvasViewRenderer
{
public TouchCanvasViewRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<SKCanvasView> e)
{
// clean up old native control
if (Control != null)
{
Control.Touch -= OnTouch;
}
// do clean up old element
if (Element != null)
{
var oldTouchCanvas = (TouchCanvasView)Element;
var oldTouchController = (ITouchCanvasViewController)Element;
// ...
}
base.OnElementChanged(e);
// set up new native control
if (Control != null)
{
Control.Touch += OnTouch;
}
// set up new element
if (e.NewElement != null)
{
var newTouchCanvas = (TouchCanvasView)Element;
var newTouchController = (ITouchCanvasViewController)Element;
// ...
}
}
private void OnTouch(object sender, TouchEventArgs e)
{
var touchController = Element as ITouchCanvasViewController;
if (touchController != null)
{
var wasTap = e.Event.ActionMasked == MotionEventActions.Up || e.Event.ActionMasked == MotionEventActions.Cancel;
if (wasTap)
{
//var scale = Control.Resources.DisplayMetrics.Density;
//touchController.OnTouch(new SKPoint(e.Event.GetX() / scale, e.Event.GetY() / scale));
touchController.OnTouch(new SKPoint(e.Event.GetX(), e.Event.GetY()));
}
}
}
}
}
OnTouched event of this TouchCanvasView to get the point (x,y) and do the judement.
private void OnTouched(SKPoint obj)
{
float x = obj.X;
float y = obj.Y;
if (black.Contains(x, y))
{
sKPoint = obj;
isDraw = true;
isblack = true;
isOrange = false;
isred = false;
isgreen = false;
canvasView.InvalidateSurface();
}
else if (orange.Contains(x, y))
{
sKPoint = obj;
isDraw = true;
isblack = false;
isOrange = true;
isred = false;
isgreen = false;
canvasView.InvalidateSurface();
}
else if (red.Contains(x, y))
{
sKPoint = obj;
isDraw = true;
isblack = false;
isOrange = false;
isred = true;
isgreen = false;
canvasView.InvalidateSurface();
}
else if (green.Contains(x, y))
{
sKPoint = obj;
isDraw = true;
isblack = false;
isOrange = false;
isred = false;
isgreen = true;
canvasView.InvalidateSurface();
}
else
{
isDraw = false;
canvasView.InvalidateSurface();
}
}
Model:
public class Profile
{
public int Id { get; set; }
public string Name { get; set; }
public float Values { get; set; }
public SKColor sKColors { get; set; }
}

Admob ads are not showing in Unity, C#

My Admob ads are not showing in my app on Android, I tried everything, different versions of unity, types of ads, re-installation of admob plugin, different combinations of player settings for android compilation.
Log on Unity (I tested it on Android) is:
Dummy IsLoaded
Dummy ShowIntertitial
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using GoogleMobileAds.Api;
public class ControllerMain : MonoBehaviour
{
public Button LV1, LV2, LV3, LV4, LV5, LV6, LV7, LV8, LV9, LV10;
public int ReturnedVal;
private string MyIdA = "ca-app-pub-3940256099942544/1033173318";
//private InterstitialAd fullscreenad;
//private string FullScreenID = "ca-app-pub-3940256099942544/1033173651";
//private BannerView bannerView;
private InterstitialAd InterFULLSC;
void LOV1() {
SceneManager.LoadScene(1);
}
void LOV2()
{
SceneManager.LoadScene(2);
}
void LOV3()
{
SceneManager.LoadScene(3);
}
void LOV4()
{
SceneManager.LoadScene(4);
}
void LOV5()
{
SceneManager.LoadScene(5);
}
void LOV6()
{
SceneManager.LoadScene(6);
}
void LOV7()
{
SceneManager.LoadScene(7);
}
void LOV8()
{
SceneManager.LoadScene(8);
}
void LOV9()
{
SceneManager.LoadScene(9);
}
void LOV10()
{
SceneManager.LoadScene(10);
}
// Start is called before the first frame update
void Start()
{
MobileAds.Initialize(initStatus => { });
this.InterFULLSC = new InterstitialAd(MyIdA);
//LV1.GetComponent<Image>().color = Color.black;
ReturnedVal = GameMonitor.IsPassed;
if (ReturnedVal > 0)
{
AdRequest requ = new AdRequest.Builder().Build();
this.InterFULLSC.LoadAd(requ);
if (this.InterFULLSC.IsLoaded()) {
this.InterFULLSC.Show();
}
//MobileAds.Initialize(appID);
//go
//bannerView = new BannerView("ca-app-pub-3940256099942544/6300978111", AdSize.Banner, AdPosition.Bottom);
//AdRequest requ = new AdRequest.Builder().Build();
//bannerView.LoadAd(requ);
//bannerView.Show();
//end
//fullscreenad = new InterstitialAd(FullScreenID);
//AdRequest request = new AdRequest.Builder().Build();
//fullscreenad.LoadAd(request);
//if (fullscreenad.IsLoaded())
//{
// fullscreenad.Show();
//}
//else { Debug.Log("Didn't load"); }
}
Debug.Log(ReturnedVal);
LV1.GetComponent<Image>().color = Color.green;
LV2.GetComponent<Image>().color = Color.black;
LV3.GetComponent<Image>().color = Color.black;
LV4.GetComponent<Image>().color = Color.black;
LV5.GetComponent<Image>().color = Color.black;
LV6.GetComponent<Image>().color = Color.black;
LV7.GetComponent<Image>().color = Color.black;
LV8.GetComponent<Image>().color = Color.black;
LV9.GetComponent<Image>().color = Color.black;
LV10.GetComponent<Image>().color = Color.black;
LV2.interactable = false;
LV3.interactable = false;
LV4.interactable = false;
LV5.interactable = false;
LV6.interactable = false;
LV7.interactable = false;
LV8.interactable = false;
LV9.interactable = false;
LV10.interactable = false;
LV1.interactable = true;
LV1.onClick.AddListener(LOV1);
if (ReturnedVal == 2 || ReturnedVal>2) {
LV2.interactable = true;
LV2.GetComponent<Image>().color = Color.green;
LV2.onClick.AddListener(LOV2);
}
if (ReturnedVal == 3 || ReturnedVal > 3)
{
LV3.interactable = true;
LV3.GetComponent<Image>().color = Color.green;
LV3.onClick.AddListener(LOV3);
}
if (ReturnedVal == 4 || ReturnedVal > 4)
{
LV4.interactable = true;
LV4.GetComponent<Image>().color = Color.green;
LV4.onClick.AddListener(LOV4);
}
if (ReturnedVal == 5 || ReturnedVal > 5)
{
LV5.interactable = true;
LV5.GetComponent<Image>().color = Color.green;
LV5.onClick.AddListener(LOV5);
}
if (ReturnedVal == 6 || ReturnedVal > 6)
{
LV6.interactable = true;
LV6.GetComponent<Image>().color = Color.green;
LV6.onClick.AddListener(LOV6);
}
if (ReturnedVal == 7 || ReturnedVal > 7)
{
LV7.interactable = true;
LV7.GetComponent<Image>().color = Color.green;
LV7.onClick.AddListener(LOV7);
}
if (ReturnedVal == 8 || ReturnedVal > 8)
{
LV8.interactable = true;
LV8.GetComponent<Image>().color = Color.green;
LV8.onClick.AddListener(LOV8);
}
if (ReturnedVal == 9 || ReturnedVal > 9)
{
LV9.interactable = true;
LV9.GetComponent<Image>().color = Color.green;
LV9.onClick.AddListener(LOV9);
}
if (ReturnedVal == 10)
{
LV10.interactable = true;
LV10.GetComponent<Image>().color = Color.green;
LV10.onClick.AddListener(LOV10);
}
}
// Update is called once per frame
void Update()
{
}
}
Initialize the ads using the following format:
MobileAds.Initialize(appID);
Also you are trying to load and show the ad together in start function which might be one of the reason for the issue you are facing.
Load the ad in start function but show the ad on any button click by calling the below function
void ShowAd(){
if (this.InterFULLSC.IsLoaded()) {
this.InterFULLSC.Show();
}
}

It stops for a while when button is clicked

public class green : MonoBehaviour
{
private AudioSource source;
public AudioClip sound;
static int result = 0;
// Use this for initialization
void Start()
{
StartCoroutine("RoutineCheckInputAfter3Minutes");
Debug.Log("a");
}
IEnumerator RoutineCheckInputAfter3Minutes()
{
System.Random ran = new System.Random();
int timeToWait = ran.Next(1, 50) * 1000;
Thread.Sleep(timeToWait);
source = this.gameObject.AddComponent<AudioSource>();
source.clip = sound;
source.loop = true;
source.Play();
System.Random r = new System.Random();
result = r.Next(1, 4);
Debug.Log("d");
yield return new WaitForSeconds(3f * 60f);
gm.life -= 1;
Debug.Log(gm.life + "값");
source.Stop();
Debug.Log("z");
if (gm.life >= 0)
{
StartCoroutine("RoutineCheckInputAfter3Minutes");
}
}
// Update is called once per frame
public void Update()
{
if (result == 1 && gm.checkeat == true)
{
Debug.Log("e");
gm.life += 1;
Debug.Log("j");
Debug.Log(gm.life + "값");
source.Stop();
gm.checkeat = false;
StopCoroutine("RoutineCheckInputAfter3Minutes");
StartCoroutine("RoutineCheckInputAfter3Minutes");
}
if (result == 2 && gm.checkshit == true)
{
Debug.Log("f");
gm.life += 1;
Debug.Log("o");
Debug.Log(gm.life + "값");
source.Stop();
gm.checkshit = false;
StopCoroutine("RoutineCheckInputAfter3Minutes");
StartCoroutine("RoutineCheckInputAfter3Minutes");
}
else if (result == 3 && gm.checksleep == true)
{
Debug.Log("g");
gm.life += 1;
Debug.Log(gm.life);
Debug.Log(gm.life + "값");
source.Stop();
gm.checksleep = false;
StopCoroutine("RoutineCheckInputAfter3Minutes");
StartCoroutine("RoutineCheckInputAfter3Minutes");
}
}
}
public class gm : MonoBehaviour
{
static public int life = 0;
static public bool checkeat = false;
static public bool checkshit = false;
static public bool checksleep = false;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void eating(string eat)
{
Debug.Log(life + "값");
checkeat = true;
}
public void shitting(string shit)
{
Debug.Log(life + "값");
checkshit = true;
}
public void sleeping(string sleep)
{
Debug.Log(life + "값");
checksleep = true;
}
}
when i click a button , program stops for a while and then works... i think it is because of thread or something...
please share your opinion..
.when i click a button , program stops for a while and then works... i think it is because of thread or something...
please share your opinion..
Stop using :
Thread.Sleep(timeToWait);
This stalls the entire thread, in this case Unity completely from running.
Since your using routines anyway, use this instead :
yield return new WaitForSeconds(timeToWait);
And change this line :
int timeToWait = ran.Next(1, 50) * 1000;
To this :
int timeToWait = ran.Next(1, 50);

Turn Based Game in unity C# in android

Good Day! I have this code but I have an error, for example (I set two players me, and 1 computer). I take the first turn, and the dice respawn with a value of 4 (just an example), the game piece then move from 1st to 4th tile when I touch the screen, when computer turns, it also move from 1st to 4th tile (because I set the result to 4 just an example). Now its my turn again, the dice never respawn and it doesn't wait to touch the screen if (Input.GetMouseButtonDown(0)) and move again by 4...
public class singlePlay : MonoBehaviour {
//Player
public GameObject[] playerprefab;
//Player Clone
public GameObject[] playerprefabC;
//Game Cards and Dice
public GameObject[] situationCard;
public GameObject dice;
int diceresult;
//Game Cards and Dice clone
public GameObject diceclone;
public int currentPlayer;
public int compPlayer;
public int playerTurn;
public string compPlayerstring;
public string playerTurnstring;
//GUI Boolean
bool play = false;
//Game Boolean
bool pieces = false;
bool giveturn = false;
bool myturn = false;
bool diceSpawn = false;
bool moving = false;
bool routine = false;
bool checking = false;
bool compturn = false;
//icon1
public GameObject[] icon;
//population
int[] population = new int[3];
//Tile
public GameObject[] Tile;
int[] playerTile = new int[3]; //current location
int[] playerTileUp = new int [3]; // updated location after dice roll
bool endTurn = false;
void Update ()
{
if (giveturn == true) {
int h = 0;
Giveturn(h);
giveturn = false;
}
if (play == true) {
if (pieces == true){
SpawnPlayer();
pieces = false;
}
if (myturn == true){
compturn = false;
if(diceSpawn == true) {
dice.transform.position = new Vector3(0,0,-1);
diceclone = Instantiate(dice, dice.transform.position, Quaternion.identity) as GameObject;
diceSpawn = false;
}
if (Input.GetMouseButtonDown(0))
{
Debug.Log("click");
diceresult = 4;
Destroy(diceclone);
moving = true;
Updateposition(diceresult);
}
}
else
{
Debug.Log("comp");
myturn = false;
diceresult = 4;
moving = true;
Updateposition(diceresult);
}
}
}
void Giveturn(int k)
{
Debug.Log("" + k);
currentPlayer = k;
if (k == playerTurn) {
Debug.Log("Yes");
compturn = false;
myturn = true;
diceSpawn = true;
moving = false;
}
else
{
Debug.Log("No");
compturn = true;
myturn = false;
moving = false;
}
}
void Updateposition(int diceresult)
{
if (moving == true) {
playerTileUp[currentPlayer] = playerTile[currentPlayer] + diceresult;
Debug.Log("" + playerTileUp[currentPlayer]+ " " +currentPlayer);
routine = true;
StartCoroutine(MyMethod());
}
moving = false;
}
IEnumerator MyMethod()
{
if (routine == true) {
if (myturn == true) {
compturn = false;
}
else
{
myturn = false;
}
int f = playerTile[currentPlayer] + 1;
Debug.Log(" " + currentPlayer );
while (f <= playerTileUp[currentPlayer]) {
Debug.Log("waiting");
yield return new WaitForSeconds(1);
Debug.Log(" " + Tile[f]);
playerprefabC[currentPlayer].transform.position = Tile[f].transform.position;
Debug.Log(" " + currentPlayer);
f++;
}
checking = true;
TrapCheck();
}
routine = false;
}
void TrapCheck()
{
if (checking == true) {
if (playerTileUp[currentPlayer] == 8) {
Debug.Log("Trap spawning");
Instantiate(situationCard[0], situationCard[0].transform.position, Quaternion.identity);
population[currentPlayer] = population[currentPlayer] -1;
}
playerTile[currentPlayer] = playerTileUp[currentPlayer];
Endturn();
myturn = false;
compturn = false;
checking = false;
}
}
void Endturn()
{
currentPlayer++;
Debug.Log(" " + currentPlayer);
if (currentPlayer > compPlayer) {
currentPlayer = 0;
}
Giveturn(currentPlayer);
}
}
There are few things that I could see wrong there already. First while the coroutine is running, it seems you are not preventing the update from running since play remains true. In TrapCheck, you call EndTurn which call GiveTurn and sets myTurn (true) and compTurn (false) booleans. But those two are reset in TrapCheck, myTurn is set back to false. You need to rethink the logic of your class.
A solution would be to use delegate. This would remove many of your boolean that you set and reset. Here is a basic idea:
Action currentUpdate;
bool playerTurn = true;
void Start(){
SetTurn();
}
void Update(){
if(currentUpdate != null)currentUpdate();
}
void SetTurn(){
// Prepare initial setting for moving
if(playerTurn == true){ currentUpdate = PlayerTurn; }
else{ currentUpdate = CompTurn; }
playerTurn = !playerTurn;
}
void PlayerTurn(){
// Check input
// Get dice value
currentUpdate = Move;
}
void CompTurn(){
// Get dice value
currentUpdate = Move;
}
void Move(){
if(position != target){
}else{
SetTurn();
}
}
This is fairly simplified but once you get the thing about delegate (maybe you already know), this will make it all so much more flexible.

Play three sounds simultaneously c#

I want to play three sounds simultaneously, but second sound must play after one seconds, third sound after two seconds. I have this code:
private void Play()
{
AxWindowsMediaPlayer player1 = new AxWindowsMediaPlayer();
player1.CreateControl();
AxWindowsMediaPlayer player2 = new AxWindowsMediaPlayer();
player2.CreateControl();
AxWindowsMediaPlayer player3 = new AxWindowsMediaPlayer();
player3.CreateControl();
player1.URL = "sounds\\1.wav";
player1.Ctlcontrols.play();
System.Threading.Thread.Sleep(1000);
player2.URL = "sounds\\2.wav";
player2.Ctlcontrols.play();
System.Threading.Thread.Sleep(1000);
player3.URL = "sounds\\3.wav";
player3.Ctlcontrols.play();
Why all this sounds are playing in one time after two seconds?
I ended up using SharpDX (available via NuGet packages SharpDX
and SharpDX.XAudio2.
An example of its usage can be found in one of my GitHub projects: 2DAI
You can hear the various sounds overlapping in this screen recording as well.
Playing a sound:
var backgroundMusicSound = new AudioClip(#".\Assets\Sounds\Music\Background.wav" /*Sound path*/, 1.0 /* Volumne*/, true /*Loop Forever?*/)
backgroundMusicSound.Play();
The class that I pieced together:
public class AudioClip
{
private XAudio2 _xaudio = new XAudio2();
private WaveFormat _waveFormat;
private AudioBuffer _buffer;
private SoundStream _soundstream;
private SourceVoice _singleSourceVoice;
private bool _loopForever;
private bool _isPlaying = false; //Only applicable when _loopForever == false;
private bool _isFading;
private string _wavFilePath; //For debugging.
private float _initialVolumne;
public AudioClip(string wavFilePath, float initialVolumne = 1, bool loopForever = false)
{
_loopForever = loopForever;
_wavFilePath = wavFilePath;
_initialVolumne = initialVolumne;
var masteringsound = new MasteringVoice(_xaudio); //Yes, this is required.
var nativefilestream = new NativeFileStream(wavFilePath,
NativeFileMode.Open, NativeFileAccess.Read, NativeFileShare.Read);
_soundstream = new SoundStream(nativefilestream);
_waveFormat = _soundstream.Format;
_buffer = new AudioBuffer
{
Stream = _soundstream.ToDataStream(),
AudioBytes = (int)_soundstream.Length,
Flags = BufferFlags.EndOfStream
};
if (loopForever)
{
_buffer.LoopCount = 100;
}
}
public void Play()
{
lock (this)
{
if (_loopForever == true)
{
if (_isPlaying)
{
if (_isFading)
{
_isFading = false;
_singleSourceVoice.SetVolume(_initialVolumne);
}
return;
}
_singleSourceVoice = new SourceVoice(_xaudio, _waveFormat, true);
_singleSourceVoice.SubmitSourceBuffer(_buffer, _soundstream.DecodedPacketsInfo);
_singleSourceVoice.SetVolume(_initialVolumne);
_singleSourceVoice.Start();
_isPlaying = true;
return;
}
}
var sourceVoice = new SourceVoice(_xaudio, _waveFormat, true);
sourceVoice.SubmitSourceBuffer(_buffer, _soundstream.DecodedPacketsInfo);
sourceVoice.SetVolume(_initialVolumne);
sourceVoice.Start();
}
public void Fade()
{
if (_isPlaying && _isFading == false)
{
_isFading = true;
(new Thread(FadeThread)).Start();
}
}
private void FadeThread()
{
float volumne;
_singleSourceVoice.GetVolume(out volumne);
while (_isFading && volumne > 0)
{
volumne -= 0.25f;
volumne = volumne < 0 ? 0 : volumne;
_singleSourceVoice.SetVolume(volumne);
Thread.Sleep(100);
}
Stop();
}
public void Stop()
{
if (_loopForever == true)
{
if (_singleSourceVoice != null && _isPlaying)
{
_singleSourceVoice.Stop();
}
_isPlaying = false;
_isFading = false;
}
else
{
throw new Exception("Cannot stop overlapped audio.");
}
}
}
It should also be notes that loading the sounds can be a heavy process, so if you are doing it a lot then you might want to cache them as I did:
private Dictionary<string, AudioClip> _audioClips { get; set; } = new Dictionary<string, AudioClip>();
public AudioClip GetSoundCached(string wavFilePath, float initialVolumne, bool loopForever = false)
{
lock (_audioClips)
{
AudioClip result = null;
wavFilePath = wavFilePath.ToLower();
if (_audioClips.ContainsKey(wavFilePath))
{
result = _audioClips[wavFilePath];
}
else
{
result = new AudioClip(wavFilePath, initialVolumne, loopForever);
_audioClips.Add(wavFilePath, result);
}
return result;
}
}

Categories

Resources