Play three sounds simultaneously c# - 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;
}
}

Related

C# - Visual Studio and Rage

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~");
}
}
}
}

Continue Counting

How can I stop the NoAnsweredQuestion.Count when I click on a button...
Problem:
When I click on the reset button, the NoAnsweredQuestion.Count is still counting go to the maximum limit
Random:
private void SetcurrentQuestion()
{
int randomQuestionIndex = Random.Range(0, NoAnsweredQuestion.Count);
currentQuestion = NoAnsweredQuestion[randomQuestionIndex];
factText.text = currentQuestion.fact;
correctAnswerText.text = currentQuestion.answered;
}
This is my limit:
public void ContinueTransition()
{
if (NoAnsweredQuestion.Count == 10)
{
FinalScore.SetActive(true);
}
else
{
StartCoroutine(TransitiontoNextQuestion());
updatequestion();
}
}
Reset button:
public void Restart()
{
var form = new WWWForm();
var www = new WWW(restartBegGrammarIAQ, form);
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
Time.timeScale = 1f;
GameIsPaused = false;
}
Add NoAnsweredQuestion.Clear() in your restart method and it should work

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

How do I remedy this type does not exist in type error?

I need to get value from another script but I keep getting this error that says
The type name 'head' does not exist in the type 'SteamVR_Camera'.
My code:
using UnityEngine;
using System.Collections;
using UnityEngine.VR;
public class HMDHelper : MonoBehaviour
{
private SteamVR_Camera.head.localPosition HMDLocalPos; //Error is thrown here.
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("g"))
{
AutoRotate();
}
}
void AutoRotate()
{
HMDLocalPos = InputTracking.GetLocalPosition(Head);
Debug.Log(HMDLocalPos);
}
}
What exactly do I have to do to fix error?
This is the script that I retrieved the other value (HMDLocalPos) from...
//========= Copyright 2014, Valve Corporation, All rights reserved. ===========
//
// Purpose: Adds SteamVR render support to existing camera objects
//
//=============================================================================
using UnityEngine;
using System.Collections;
using System.Reflection;
using Valve.VR;
[RequireComponent(typeof(Camera))]
public class SteamVR_Camera : MonoBehaviour
{
[SerializeField]
private Transform _head;
public Transform head { get { return _head; } }
public Transform offset { get { return _head; } } // legacy
public Transform origin { get { return _head.parent; } }
[SerializeField]
private Transform _ears;
public Transform ears { get { return _ears; } }
public Ray GetRay()
{
return new Ray(_head.position, _head.forward);
}
public bool wireframe = false;
[SerializeField]
private SteamVR_CameraFlip flip;
#region Materials
static public Material blitMaterial;
// Using a single shared offscreen buffer to render the scene. This needs to be larger
// than the backbuffer to account for distortion correction. The default resolution
// gives us 1:1 sized pixels in the center of view, but quality can be adjusted up or
// down using the following scale value to balance performance.
static public float sceneResolutionScale = 1.0f;
static private RenderTexture _sceneTexture;
static public RenderTexture GetSceneTexture(bool hdr)
{
var vr = SteamVR.instance;
if (vr == null)
return null;
int w = (int)(vr.sceneWidth * sceneResolutionScale);
int h = (int)(vr.sceneHeight * sceneResolutionScale);
int aa = QualitySettings.antiAliasing == 0 ? 1 : QualitySettings.antiAliasing;
var format = hdr ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32;
if (_sceneTexture != null)
{
if (_sceneTexture.width != w || _sceneTexture.height != h || _sceneTexture.antiAliasing != aa || _sceneTexture.format != format)
{
Debug.Log(string.Format("Recreating scene texture.. Old: {0}x{1} MSAA={2} [{3}] New: {4}x{5} MSAA={6} [{7}]",
_sceneTexture.width, _sceneTexture.height, _sceneTexture.antiAliasing, _sceneTexture.format, w, h, aa, format));
Object.Destroy(_sceneTexture);
_sceneTexture = null;
}
}
if (_sceneTexture == null)
{
_sceneTexture = new RenderTexture(w, h, 0, format);
_sceneTexture.antiAliasing = aa;
#if (UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
// OpenVR assumes floating point render targets are linear unless otherwise specified.
var colorSpace = (hdr && QualitySettings.activeColorSpace == ColorSpace.Gamma) ? EColorSpace.Gamma : EColorSpace.Auto;
SteamVR.Unity.SetColorSpace(colorSpace);
#endif
}
return _sceneTexture;
}
#endregion
#region Enable / Disable
void OnDisable()
{
SteamVR_Render.Remove(this);
}
void OnEnable()
{
#if !(UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
// Convert camera rig for native OpenVR integration.
var t = transform;
if (head != t)
{
Expand();
t.parent = origin;
while (head.childCount > 0)
head.GetChild(0).parent = t;
DestroyImmediate(head.gameObject);
_head = t;
}
if (flip != null)
{
DestroyImmediate(flip);
flip = null;
}
if (!SteamVR.usingNativeSupport)
{
enabled = false;
return;
}
#else
// Bail if no hmd is connected
var vr = SteamVR.instance;
if (vr == null)
{
if (head != null)
{
head.GetComponent<SteamVR_GameView>().enabled = false;
head.GetComponent<SteamVR_TrackedObject>().enabled = false;
}
if (flip != null)
flip.enabled = false;
enabled = false;
return;
}
// Ensure rig is properly set up
Expand();
if (blitMaterial == null)
{
blitMaterial = new Material(Shader.Find("Custom/SteamVR_Blit"));
}
// Set remaining hmd specific settings
var camera = GetComponent<Camera>();
camera.fieldOfView = vr.fieldOfView;
camera.aspect = vr.aspect;
camera.eventMask = 0; // disable mouse events
camera.orthographic = false; // force perspective
camera.enabled = false; // manually rendered by SteamVR_Render
if (camera.actualRenderingPath != RenderingPath.Forward && QualitySettings.antiAliasing > 1)
{
Debug.LogWarning("MSAA only supported in Forward rendering path. (disabling MSAA)");
QualitySettings.antiAliasing = 0;
}
// Ensure game view camera hdr setting matches
var headCam = head.GetComponent<Camera>();
if (headCam != null)
{
headCam.hdr = camera.hdr;
headCam.renderingPath = camera.renderingPath;
}
#endif
ears.GetComponent<SteamVR_Ears>().vrcam = this;
SteamVR_Render.Add(this);
}
#endregion
#region Functionality to ensure SteamVR_Camera component is always the last component on an object
void Awake() { ForceLast(); }
static Hashtable values;
public void ForceLast()
{
if (values != null)
{
// Restore values on new instance
foreach (DictionaryEntry entry in values)
{
var f = entry.Key as FieldInfo;
f.SetValue(this, entry.Value);
}
values = null;
}
else
{
// Make sure it's the last component
var components = GetComponents<Component>();
// But first make sure there aren't any other SteamVR_Cameras on this object.
for (int i = 0; i < components.Length; i++)
{
var c = components[i] as SteamVR_Camera;
if (c != null && c != this)
{
if (c.flip != null)
DestroyImmediate(c.flip);
DestroyImmediate(c);
}
}
components = GetComponents<Component>();
#if !(UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
if (this != components[components.Length - 1])
{
#else
if (this != components[components.Length - 1] || flip == null)
{
if (flip == null)
flip = gameObject.AddComponent<SteamVR_CameraFlip>();
#endif
// Store off values to be restored on new instance
values = new Hashtable();
var fields = GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
foreach (var f in fields)
if (f.IsPublic || f.IsDefined(typeof(SerializeField), true))
values[f] = f.GetValue(this);
var go = gameObject;
DestroyImmediate(this);
go.AddComponent<SteamVR_Camera>().ForceLast();
}
}
}
#endregion
#region Expand / Collapse object hierarchy
#if UNITY_EDITOR
public bool isExpanded { get { return head != null && transform.parent == head; } }
#endif
const string eyeSuffix = " (eye)";
const string earsSuffix = " (ears)";
const string headSuffix = " (head)";
const string originSuffix = " (origin)";
public string baseName { get { return name.EndsWith(eyeSuffix) ? name.Substring(0, name.Length - eyeSuffix.Length) : name; } }
// Object hierarchy creation to make it easy to parent other objects appropriately,
// otherwise this gets called on demand at runtime. Remaining initialization is
// performed at startup, once the hmd has been identified.
public void Expand()
{
var _origin = transform.parent;
if (_origin == null)
{
_origin = new GameObject(name + originSuffix).transform;
_origin.localPosition = transform.localPosition;
_origin.localRotation = transform.localRotation;
_origin.localScale = transform.localScale;
}
if (head == null)
{
_head = new GameObject(name + headSuffix, typeof(SteamVR_GameView), typeof(SteamVR_TrackedObject)).transform;
head.parent = _origin;
head.position = transform.position;
head.rotation = transform.rotation;
head.localScale = Vector3.one;
head.tag = tag;
var camera = head.GetComponent<Camera>();
camera.clearFlags = CameraClearFlags.Nothing;
camera.cullingMask = 0;
camera.eventMask = 0;
camera.orthographic = true;
camera.orthographicSize = 1;
camera.nearClipPlane = 0;
camera.farClipPlane = 1;
camera.useOcclusionCulling = false;
}
if (transform.parent != head)
{
transform.parent = head;
transform.localPosition = Vector3.zero;
transform.localRotation = Quaternion.identity;
transform.localScale = Vector3.one;
while (transform.childCount > 0)
transform.GetChild(0).parent = head;
var guiLayer = GetComponent<GUILayer>();
if (guiLayer != null)
{
DestroyImmediate(guiLayer);
head.gameObject.AddComponent<GUILayer>();
}
var audioListener = GetComponent<AudioListener>();
if (audioListener != null)
{
DestroyImmediate(audioListener);
_ears = new GameObject(name + earsSuffix, typeof(SteamVR_Ears)).transform;
ears.parent = _head;
ears.localPosition = Vector3.zero;
ears.localRotation = Quaternion.identity;
ears.localScale = Vector3.one;
}
}
if (!name.EndsWith(eyeSuffix))
name += eyeSuffix;
}
public void Collapse()
{
transform.parent = null;
// Move children and components from head back to camera.
while (head.childCount > 0)
head.GetChild(0).parent = transform;
var guiLayer = head.GetComponent<GUILayer>();
if (guiLayer != null)
{
DestroyImmediate(guiLayer);
gameObject.AddComponent<GUILayer>();
}
if (ears != null)
{
while (ears.childCount > 0)
ears.GetChild(0).parent = transform;
DestroyImmediate(ears.gameObject);
_ears = null;
gameObject.AddComponent(typeof(AudioListener));
}
if (origin != null)
{
// If we created the origin originally, destroy it now.
if (origin.name.EndsWith(originSuffix))
{
// Reparent any children so we don't accidentally delete them.
var _origin = origin;
while (_origin.childCount > 0)
_origin.GetChild(0).parent = _origin.parent;
DestroyImmediate(_origin.gameObject);
}
else
{
transform.parent = origin;
}
}
DestroyImmediate(head.gameObject);
_head = null;
if (name.EndsWith(eyeSuffix))
name = name.Substring(0, name.Length - eyeSuffix.Length);
}
#endregion
#if (UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
#region Render callbacks
void OnPreRender()
{
if (flip)
flip.enabled = (SteamVR_Render.Top() == this && SteamVR.instance.graphicsAPI == EGraphicsAPIConvention.API_DirectX);
var headCam = head.GetComponent<Camera>();
if (headCam != null)
headCam.enabled = (SteamVR_Render.Top() == this);
if (wireframe)
GL.wireframe = true;
}
void OnPostRender()
{
if (wireframe)
GL.wireframe = false;
}
void OnRenderImage(RenderTexture src, RenderTexture dest)
{
if (SteamVR_Render.Top() == this)
{
int eventID;
if (SteamVR_Render.eye == EVREye.Eye_Left)
{
// Get gpu started on work early to avoid bubbles at the top of the frame.
SteamVR_Utils.QueueEventOnRenderThread(SteamVR.Unity.k_nRenderEventID_Flush);
eventID = SteamVR.Unity.k_nRenderEventID_SubmitL;
}
else
{
eventID = SteamVR.Unity.k_nRenderEventID_SubmitR;
}
// Queue up a call on the render thread to Submit our render target to the compositor.
SteamVR_Utils.QueueEventOnRenderThread(eventID);
}
Graphics.SetRenderTarget(dest);
SteamVR_Camera.blitMaterial.mainTexture = src;
GL.PushMatrix();
GL.LoadOrtho();
SteamVR_Camera.blitMaterial.SetPass(0);
GL.Begin(GL.QUADS);
GL.TexCoord2(0.0f, 0.0f); GL.Vertex3(-1, 1, 0);
GL.TexCoord2(1.0f, 0.0f); GL.Vertex3( 1, 1, 0);
GL.TexCoord2(1.0f, 1.0f); GL.Vertex3( 1, -1, 0);
GL.TexCoord2(0.0f, 1.0f); GL.Vertex3(-1, -1, 0);
GL.End();
GL.PopMatrix();
Graphics.SetRenderTarget(null);
}
#endregion
#endif
}
How do I fix this? Thank you.
The type is wrong. Needs to be Vector3.
private Vector3 HMDLocalPos;
void Start()
{
HDMLocalPos = SteamVR_Camera.head.localPosition;
}
Edit:
Replace the HDMLocalPos property with a reference to SteamVR_Camera and access it's properties like this:
public SteamVR_Camera steamCam; // popuplate this via inspector or with a Find() (or similar)
void Start()
{
// access like this
steamCam.head.localPosition = something
}
I think this is what you want (to actually change the head.localPosition of the camera).

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.

Categories

Resources