RewardVideo Script Energy +1 - unity3d

I do not know how to Reward the player with more energy after seeing the reward ad.
So I want to reward the player with Energy.
It looks like your post is mostly code please add some more details.
It looks like your post is mostly code please add some more details.
It looks like your post is mostly code please add some more details.
private BannerView bannerAd;
private InterstitialAd interstitial;
private RewardBasedVideoAd rewardBasedVideo;
bool isRewarded = false;
// Start is called before the first frame update
void Start()
{
MobileAds.Initialize(InitializationStatus => { });
this.rewardBasedVideo = RewardBasedVideoAd.Instance;
this.rewardBasedVideo.OnAdRewarded += this.HandleRewardBasedVideoRewarded;
this.rewardBasedVideo.OnAdClosed += this.HandleRewardBasedVideoClosed;
this.RequestRewardBasedVideo();
this.RequestBanner();
}
void Update()
{
if (isRewarded)
{
isRewarded = false;
}
I have an energy bar 250/250, once press play the energy is going to 249/250 Energy, how can I script to increase the Energy +1 when player press the reward Button?
[SerializeField] Text energyText;
[SerializeField] Text timerText;
[SerializeField] Slider energyBar;
private int maxEnergy = 250;
private int currentEnergy;
private int restoreDuration = 250;
private DateTime nextEnergyTime;
private DateTime lastEnergyTime;
private bool isRestoring = false;
// Start is called before the first frame update
void Start()
{
if(!PlayerPrefs.HasKey("currentEnergy"))
{
PlayerPrefs.SetInt("currentEnergy", 50);
Load();
StartCoroutine(RestoreEnergy());
}
else
{
Load();
StartCoroutine(RestoreEnergy());
}
}
public void UseEnergy()
{
if(currentEnergy >= 1)
{
currentEnergy--;
UpdateEnergy();
if (isRestoring == false)
{
if(currentEnergy + 1 == maxEnergy)
{
nextEnergyTime = AddDuration(DateTime.Now, restoreDuration);
}
StartCoroutine(RestoreEnergy());
}
}
else
{
Debug.Log("Isufficient Energy!!");
}
}
private IEnumerator RestoreEnergy()
{
UpdateEnergyTimer();
isRestoring = true;
while(currentEnergy < maxEnergy)
{
DateTime currentDateTime = DateTime.Now;
DateTime nextDateTime = nextEnergyTime;
bool isEnergyAdding = false;
while(currentDateTime > nextDateTime)
{
if(currentEnergy < maxEnergy)
{
isEnergyAdding = true;
currentEnergy++;
UpdateEnergy();
DateTime timeToAdd = lastEnergyTime > nextDateTime ? lastEnergyTime : nextDateTime;
nextDateTime = AddDuration(timeToAdd, restoreDuration);
}
else
{
break;
}
}
if (isEnergyAdding == true)
{
lastEnergyTime = DateTime.Now;
nextEnergyTime = nextDateTime;
}
UpdateEnergyTimer();
UpdateEnergy();
Save();
yield return null;
}
isRestoring = false;
}
private DateTime AddDuration(DateTime datetime, int duration)
{
return datetime.AddSeconds(duration);
//return datetime.AddMinutes(duration);
}
private void UpdateEnergyTimer()
{
if (currentEnergy >= maxEnergy)
{
timerText.text = "Full";
return;
}
TimeSpan time = nextEnergyTime - DateTime.Now;
string timeValue = String.Format("{0:D2}:{1:D1}", time.Minutes, time.Seconds);
timerText.text = timeValue;
}
private void UpdateEnergy()
{
energyText.text = currentEnergy.ToString() + "/" + maxEnergy.ToString();
energyBar.maxValue = maxEnergy;
energyBar.value = currentEnergy;
}
private DateTime StringToDate(string datetime)
{
if (String.IsNullOrEmpty(datetime))
{
return DateTime.Now;
}
else
{
return DateTime.Parse(datetime);
}
}
private void Load()
{
currentEnergy = PlayerPrefs.GetInt("currentEnergy");
nextEnergyTime = StringToDate(PlayerPrefs.GetString("nextEnergyTime"));
lastEnergyTime = StringToDate(PlayerPrefs.GetString("lastEnergyTime"));
}
private void Save()
{
PlayerPrefs.SetInt("currentEnergy", currentEnergy);
PlayerPrefs.SetString("nextEnergyTime", nextEnergyTime.ToString());
PlayerPrefs.SetString("lastEnergyTime", lastEnergyTime.ToString());
}
}

You can determinate if the user won at ads callback events
add this event callback
// Called when the user should be rewarded for interacting with the ad.
this.rewardedAd.OnUserEarnedReward += HandleUserEarnedReward;
then
public void HandleUserEarnedReward(object sender, Reward args)
{
//Now it's time to reward the user
//Use those if you want to get the amount from the ad setup
//string type = args.Type;
//double amount = args.Amount;
}

Related

Handling different functions calls using New Input System

I'm new to Unity New Input System, I have recently migrated my project from the old input system to the new input system but I'm facing some difficulties using it.
I have a class called InputManager that manages all the input actions for my game, and another class called PlayerInteractions that holds all the player's interactions, such as picking up objects, opening and closing drawers/doors and so on.
playerInteraction class was working perfectly using the old input system, but when I changed it to the new input system I couldn't handle the function calls properly so it didn't work completely. I managed to make picking up objects work but the opening/closing part didn't work because for that I'm calling another function from a class called InteractiveObjects that is attached to all objects that can be opened/closed such as door/drawers...
and it was hard for me to handle these function calls since I'm not good enough at the New Input System.
Here is a snippet of the PlayerInteractions Class
private InteractiveObjects interactiveObjects;
bool PickingUp, Open;
void Update()
{
raycastPos = mainCamera.ScreenToWorldPoint(new Vector3(Screen.width / 2, Screen.height / 2, 0));
RaycastHit hit;
if (Physics.SphereCast(raycastPos, sphereCastRadius, mainCamera.transform.forward, out hit, maxDistance, 1 << interactableLayerIndex))
{
lookObject = hit.collider.transform.gameObject;
}
else
{
lookObject=null;
}
if (PickingUp)
{
if (currentlyPickedUpObject == null)
{
if (lookObject != null)
{
PickupObject();
}
}
else
{
BreakConnection();
}
}
PickingUp = false;
if (hit.transform)
{
interactiveObjects = hit.transform.GetComponent<InteractiveObjects>();
}
else
{
lookObject = null;
interactiveObjects = null;
}
if (Open)
{
if (interactiveObjects)
{
interactiveObjects.PerformAction();
}
}
Open = false;
}
public void OnPickingUp()
{
PickingUp = true;
}
public void OnOpen()
{
Open = true;
}
This part from above:
if (Open)
{
if (interactiveObjects)
{
interactiveObjects.PerformAction();
}
}
was like this:
if (Input.GetKeyDown(KeyCode.E))
{
if (interactiveObjects)
{
interactiveObjects.PerformAction();
}
}
and the InteractiveObject class was something like this:
public void PerformAction()
{
if (aSource)
{
aSource.Play();
}
if (Input.GetKeyDown(KeyCode.E))
{
if (isOpen)
{
iTweenArgs["position"] = closedPosition;
iTweenArgs["rotation"] = closedPosition;
}
else
{
iTweenArgs["position"] = openPosition;
iTweenArgs["rotation"] = openPosition;
}
isOpen = !isOpen;
switch(movementType)
{
case MovementType.Slide:
iTween.MoveTo(gameObject, iTweenArgs);
break;
case MovementType.Rotate:
iTween.RotateTo(gameObject, iTweenArgs);
break;
}
}
if(Input.GetKeyDown(KeyCode.E)) was changed to if (Open).
Here is the full IneractiveObject class after the change:
public class InteractiveObjects : MonoBehaviour
{
[SerializeField] private Vector3 openPosition, closedPosition;
[SerializeField] private float animationTime;
[SerializeField] private bool isOpen = false;
[SerializeField] private MovementType movementType;
bool Open;
private enum MovementType { Slide, Rotate };
private Hashtable iTweenArgs;
private AudioSource aSource;
void Start()
{
iTweenArgs = iTween.Hash();
iTweenArgs.Add("position", openPosition);
iTweenArgs.Add("time", animationTime);
iTweenArgs.Add("islocal", true);
aSource = GetComponent<AudioSource>();
}
public void PerformAction()
{
if (aSource)
{
aSource.Play();
}
if (Open)
{
if (isOpen)
{
iTweenArgs["position"] = closedPosition;
iTweenArgs["rotation"] = closedPosition;
}
else
{
iTweenArgs["position"] = openPosition;
iTweenArgs["rotation"] = openPosition;
}
isOpen = !isOpen;
switch (movementType)
{
case MovementType.Slide:
iTween.MoveTo(gameObject, iTweenArgs);
break;
case MovementType.Rotate:
iTween.RotateTo(gameObject, iTweenArgs);
break;
}
}
Open = false;
}
public void OnOpen()
{
Open = true;
}
}
Here is my Input Action:
InputManager class:
public class InputManager : MonoBehaviour
{
[SerializeField] Movement movement;
[SerializeField] PlayerInteractions playerInteractions;
[SerializeField] MouseLook mouseLook;
PlayerControls controls;
PlayerControls.GroundMovementActions groundMovement;
Vector2 horizontalInput;
Vector2 mouseInput;
private void Awake()
{
controls = new PlayerControls();
groundMovement = controls.GroundMovement;
// groundMovement.[action].performed += context => do something
groundMovement.HorizontalMovement.performed += ctx => horizontalInput = ctx.ReadValue<Vector2>();
groundMovement.Jump.performed += _ => movement.OnJumpPressed();
groundMovement.Running.performed += _ => movement.OnRunning();
groundMovement.PickingUp.performed += _ => playerInteractions.OnPickingUp();
groundMovement.MouseX.performed += ctx => mouseInput.x = ctx.ReadValue<float>();
groundMovement.MouseY.performed += ctx => mouseInput.y = ctx.ReadValue<float>();
groundMovement.Open.performed += _ => playerInteractions.OnOpen();
}
private void Update()
{
movement.ReceiveInput(horizontalInput);
mouseLook.ReceiveInput(mouseInput);
}
private void OnEnable()
{
controls.Enable();
}
private void OnDestroy()
{
controls.Disable();
}
}
So the InputManager class is calling a function from playerInteractions which is also calling a function from InteractiveObjects for opening/closing feature. that didn't work for me but I don't know how to fix this. please help.
The solution is here, you no longer need Open Boolean and you can call the function directly through the new input system. for this job; Enter only the contents of if on OnOpen.
public void OnOpen()
{
if (isOpen)
{
iTweenArgs["position"] = closedPosition;
iTweenArgs["rotation"] = closedPosition;
}
else
{
iTweenArgs["position"] = openPosition;
iTweenArgs["rotation"] = openPosition;
}
isOpen = !isOpen;
switch(movementType)
{
case MovementType.Slide:
iTween.MoveTo(gameObject, iTweenArgs);
break;
case MovementType.Rotate:
iTween.RotateTo(gameObject, iTweenArgs);
break;
}
}
This not only simplifies the structure of the code. Rather, it prevents the if condition from being repeated in the update. Now run OnOpen as you set it by pressing the B key:
controls.GroundMovement.Open.performed += _ => playerInteraction.OnOpen();
How do conditions work continuously?
There are several ways to build functions that work continuously. This is an example that works by defining Func<bool> in the target object script:
public class PlayerInteraction : MonoBehaviour
{
public Func<bool> IsPressingOpen;
public void Update()
{
if (IsPressingOpen())
{
// do something...
}
}
}
And it is enough to set the function according to the result of key pressing:
playerInteraction.IsPressingOpen = () => controls.GroundMovement.Open.IsPressed();
Hope this answer is comprehensive and practical.

Unity: spawning enemies works but they are not visible

I'm busy with creating a school project where I need to integrate wave spawners.
For now, I used this video as an example and implemented it in my project.https://www.youtube.com/watch?v=q0SBfDFn2Bs
Everything is spawning fine and I also get my debug logs. The main problem is: I can't see my enemies. (not John Cena guys hahah, in that case it would be logic ;) )
I'm new to Unity and I like the interface and workflow but I have a lot to learn. I hope someone can help me out! :)
Source WaveSpawner.cs:
using UnityEngine;
using System.Collections;
public class WaveSpawner : MonoBehaviour
{
public enum SpawnState { SPAWNING, WAITING, COUNTING };
[System.Serializable]
public class Wave
{
public string name;
public Transform enemy;
public int count;
public float rate;
}
public Wave[] waves;
private int nextWave = 0;
public int NextWave
{
get { return nextWave + 1; }
}
public Transform[] spawnPoints;
public float timeBetweenWaves = 5f;
private float waveCountdown;
public float WaveCountdown
{
get { return waveCountdown; }
}
private float searchCountdown = 1f;
private SpawnState state = SpawnState.COUNTING;
public SpawnState State
{
get { return state; }
}
void Start()
{
if (spawnPoints.Length == 0)
{
Debug.LogError("No spawn points referenced.");
}
waveCountdown = timeBetweenWaves;
}
void Update()
{
if (state == SpawnState.WAITING)
{
if (!EnemyIsAlive())
{
WaveCompleted();
}
else
{
return;
}
}
if (waveCountdown <= 0)
{
if (state != SpawnState.SPAWNING)
{
StartCoroutine( SpawnWave ( waves[nextWave] ) );
}
}
else
{
waveCountdown -= Time.deltaTime;
}
}
void WaveCompleted()
{
Debug.Log("Wave Completed!");
state = SpawnState.COUNTING;
waveCountdown = timeBetweenWaves;
if (nextWave + 1 > waves.Length - 1)
{
nextWave = 0;
Debug.Log("ALL WAVES COMPLETE! Looping...");
}
else
{
nextWave++;
}
}
bool EnemyIsAlive()
{
searchCountdown -= Time.deltaTime;
if (searchCountdown <= 0f)
{
searchCountdown = 1f;
if (GameObject.FindGameObjectWithTag("Enemy") == null)
{
return false;
}
}
return true;
}
IEnumerator SpawnWave(Wave _wave)
{
Debug.Log("Spawning Wave: " + _wave.name);
state = SpawnState.SPAWNING;
for (int i = 0; i < _wave.count; i++)
{
SpawnEnemy(_wave.enemy);
yield return new WaitForSeconds( 1f/_wave.rate );
}
state = SpawnState.WAITING;
yield break;
}
void SpawnEnemy(Transform _enemy)
{
Debug.Log("Spawning Enemy: " + _enemy.name);
Transform _sp = spawnPoints[ Random.Range (0, spawnPoints.Length) ];
Instantiate(_enemy, _sp.position, _sp.rotation);
}
}
From what I can see is you're also changing the Z position of the bat. Generally you would not want to do that in a 2D game cause it can go behind stuff as is happening there. In the code I did notice that you are using random points in the world so you would want to check the Z position of those points and change them to 0 or 1.Here's the Image of what you need to change on the points! Hope this helps!

Unity timer count down not working when app killed android

I'm new to unity and c#, I have a code to increase energy after 10m, I have used PlayerPrefs to do so it is working in unity but not working on mobile please help.
I'm unable to understand what exactly is causing problem in phone. Also the timer pauses when the app is not killed but just minimized on mobile. I want the timer countdown to keep going game minimized and also if killed.
using System;
using UnityEngine;
using UnityEngine.UI;
public class EnergyAdder : MonoBehaviour
{
// Start is called before the first frame update
public float waitTime = 600;
Timer timer;
public GameRoot gameRoot;
public int count;
DateTime currentDate;
DateTime oldDate;
void Start()
{
//timer = new Timer(waitTime);
float remainingTime = PlayerPrefs.GetFloat("TimeOnExit");
timer = new Timer(remainingTime);
if (PlayerPrefs.HasKey("sysString"))
{
currentDate = DateTime.Now;
long temp = Convert.ToInt64(PlayerPrefs.GetString("sysString"));
oldDate = DateTime.FromBinary(temp);
TimeSpan difference = currentDate.Subtract(oldDate);
count = (int)(difference.TotalSeconds / waitTime);
Debug.Log("time remaining " + count);
gameRoot.AddEnergy(count);
timer = new Timer(remainingTime - (float)difference.TotalSeconds);
//PlayerPrefs.DeleteKey("TimeOnExit");
//PlayerPrefs.DeleteKey("sysString");
}
}
// Update is called once per frame
void Update()
{
if (Gameroot.isFull)
{
GetComponent<Text>().text = "Full";
count = 0;
timer.refresh();
}
else
{
//Debug.Log("deltatime ************************"+ secondstime);
timer.countDown();
if (timer.isFinished())
{
timer = new Timer(waitTime);
timer.refresh();
gameRoot.AddEnergy(1);
}
UpdateClock();
}
}
void UpdateClock()
{
int seconds = ((int)timer.timeLeft) % 60;
int minutes = (int)(timer.timeLeft / 60);
GetComponent<Text>().text = minutes.ToString() + ":" + seconds.ToString("00");
}
void OnApplicationQuit()
{
PlayerPrefs.SetFloat("TimeOnExit", timer.timeLeft);
var today = DateTime.Now;
PlayerPrefs.SetString("sysString", today.ToBinary().ToString());
PlayerPrefs.Save();
}
}
Please help what is wrong in above code or what is missing.
From OnApplicationQuit
Note: iOS applications are usually suspended and do not quit. You should tick "Exit on Suspend" in Player settings for iOS builds to cause the game to quit and not suspend, otherwise you may not see this call. If "Exit on Suspend" is not ticked then you will see calls to OnApplicationPause instead.
I suspect it is just the same with modern Android where your app is also not really closed but hibernate.
So I think you could use OnApplicationPause and OnApplicationFocus
On Android, when the on-screen keyboard is enabled, it causes a OnApplicationFocus(false) event. Additionally, if you press "Home" at the moment the keyboard is enabled, the OnApplicationFocus() event is not called, but OnApplicationPause() is called instead.
and just do the same as you do in OnApplicationQuit also for OnApplicationPause(true) and OnApplicationFocus(false)
and do the same as you do in Start also in OnApplicationPause(false) and OnApplictionFocus(true) like
public class EnergyAdder : MonoBehaviour
{
public float waitTime = 600;
public GameRoot gameRoot;
public int count;
// already reference this in the Inspector
[SerializeField] private Text timerText;
private Timer timer;
private DateTime currentDate;
private DateTime oldDate;
private void Awake()
{
// store this reference ONCE
if(!timerText) timerText = GetComponent<Text>();
}
private void Start()
{
GetTime();
}
private void Update()
{
// Note: probably a typo? shouldn't it be "gameRoot" ?
if (Gameroot.isFull)
{
timerText.text = "Full";
count = 0;
timer.refresh();
}
else
{
//Debug.Log("deltatime ************************"+ secondstime);
timer.countDown();
if (timer.isFinished())
{
timer = new Timer(waitTime);
timer.refresh();
gameRoot.AddEnergy(1);
}
UpdateClock();
}
}
private void UpdateClock()
{
int seconds = ((int)timer.timeLeft) % 60;
int minutes = (int)(timer.timeLeft / 60);
timerText.text = $"{minutes}:{seconds:00}";
}
private void OnApplicationQuit()
{
StoreTime();
}
// pauseStatus is True if the application is paused, else False.
private void OnApplicationPause(bool pauseStatus)
{
if(pauseStatus)
{
StoreTime();
}
else
{
GetTime();
}
}
// hasFocus is True if the GameObjects have focus, else False.
private void OnApplicationFocus(bool hasFocus)
{
if(hasFocus)
{
GetTime();
}
else
{
StoreTime();
}
}
private void StoreTime()
{
PlayerPrefs.SetFloat("TimeOnExit", timer.timeLeft);
var today = DateTime.Now;
PlayerPrefs.SetString("sysString", today.ToBinary().ToString());
PlayerPrefs.Save();
}
private void GetTime()
{
// NOTE: You should consider to pass a default value like
//float remainingTime = PlayerPrefs.GetFloat("TimeOnExit", 15);
float remainingTime = PlayerPrefs.GetFloat("TimeOnExit");
timer = new Timer(remainingTime);
if (PlayerPrefs.HasKey("sysString"))
{
currentDate = DateTime.Now;
long temp = Convert.ToInt64(PlayerPrefs.GetString("sysString"));
oldDate = DateTime.FromBinary(temp);
TimeSpan difference = currentDate.Subtract(oldDate);
count = (int)(difference.TotalSeconds / waitTime);
Debug.Log("time remaining " + count);
gameRoot.AddEnergy(count);
timer = new Timer(remainingTime - (float)difference.TotalSeconds);
}
}
}
Note: Typed on smartphone so I can't test it but I hope it goes into the right direction

How to display win panel once the item left equal to zero?

I want to display win panel in the game once itemLeft = 0. But still cant figure out how and what is the error about. Below shows my getScore coding:-
public GameObject scoretext;
public GameObject itemlefttext;
public GameObject finalScore;
public static float score = 0;
public GameObject winPanel;
private void Start()
{
scoretext.GetComponent<Text>().text = "0";
setscore(0);
}
private void Update()
{
itemlefttext.GetComponent<Text>().text = "" + GameObject.FindGameObjectsWithTag("draggableobject").Length;
if (GameObject.FindGameObjectsWithTag("draggableobject").Length == 0)
{
winPanel.SetActive(true);
}
}
public void setscore(float scoretoadd)
{
score += scoretoadd;
scoretext.GetComponent<Text>().text = score.ToString("F0");
finalScore.GetComponent<Text>().text = score.ToString("F0");
}
There are many ways to implement this.
With your current code structure:
private void Update()
{
itemlefttext.GetComponent<Text>().text = ""+GameObject.FindGameObjectsWithTag("draggableobject").Length;
//itemLeftTxt = GameObject.FindGameObjectWithTag("Text").GetComponent<Text>();
itemLeftTxt.text = gameObject.GetComponent<Text>().text;
if (itemLeftTxt.text == "0")
{
winPanel.SetActive(true);
}
}
Minor Improvement:
private void Update()
{
itemlefttext.GetComponent<Text>().text = "" + GameObject.FindGameObjectsWithTag("draggableobject").Length;
//itemLeftTxt = GameObject.FindGameObjectWithTag("Text").GetComponent<Text>();
itemLeftTxt.text = gameObject.GetComponent<Text>().text;
if (GameObject.FindGameObjectsWithTag("draggableobject").Length == 0)
{
winPanel.SetActive(true);
}
}
If those draggable objects are not spawned on runtime then you can create a public variable and assign a reference to them through the inspector OR
New way:
public GameObject[] DraggableObjects;
Add this to the start function:
DraggableObjects = GameObject.FindGameObjectsWithTag("draggableobject");
itemLeftTxt = gameObject.GetComponent<Text>();
You can delete extra line of codes:
Final Update function:
private void Update()
{
itemlefttext.text = "" + DraggableObjects.Length;
if (DraggableObjects.Length == 0)
{
winPanel.SetActive(true);
}
}
Final Start Function:
private void Start()
{
DraggableObjects = GameObject.FindGameObjectsWithTag("draggableobject");
itemLeftTxt = GetComponent<Text>();
}
PS: Calling Gameobject.FindGameObjectsWithTag inside the update would be heavy on processor. Let me know if it helps.

unity piano game trouble with playback of recorded notes

i have a piano app in unity and i am using an ArrayList to add notes and then playing it back and it workes mostly but the playback method since it activates when playMode is true, it continues on a loop, i need to know how i can use an if statement to check if all the recorded notes have been played and if they have then the loop should break. i really need help.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class NotePlay: MonoBehaviour
{
public Button record, play;
public bool recordMode = false;
public bool playMode = false;
Animator anim;
public AudioClip noteA;
public AudioClip noteB;
public AudioClip noteC;
public AudioClip noteD;
public AudioClip noteE;
public AudioClip noteF;
public AudioClip noteG;
public AudioSource audio;
public int count = 0;
// Use this for initialization
public ArrayList notes;
void Start()
{
anim = gameObject.GetComponent<Animator>();
audio = GetComponent<AudioSource>();
notes = new ArrayList();
Button rec = record.GetComponent<Button>();
Button pl = play.GetComponent<Button>();
record.onClick.AddListener(()=>{ recordMode = !recordMode; });
play.onClick.AddListener(() => { playMode = !playMode; recordMode =
false; });
}
void Playback()
{
bool flag = true;
for (int i = 0; i < notes.Count && flag; i++)
{
char c = (char)notes[i];
System.Threading.Thread.Sleep(1000);
PlayNote(c);
print(c);
// i want the recorded notes to only play once
if ()
{
}
}
}
void PlayNote(char note)
{
if (note == 'a')
{
//anim.SetTrigger("A");
GameObject.Find("Sphere_A").GetComponent<AudioSource>
().PlayOneShot(noteA);
GameObject.Find("Sphere_A").GetComponent<Animator>
().SetTrigger("A");
print("a");
}
if (note == 'b')
{
//anim.SetTrigger("B");
GameObject.Find("Sphere_B").GetComponent<AudioSource>
().PlayOneShot(noteB);
GameObject.Find("Sphere_B").GetComponent<Animator>
().SetTrigger("B");
print("b");
}
if (note == 'c')
{
///anim.SetTrigger("C");
GameObject.Find("Sphere_C").GetComponent<AudioSource>
().PlayOneShot(noteC);
GameObject.Find("Sphere_C").GetComponent<Animator>
().SetTrigger("C");
}
if (note == 'd')
{
//anim.SetTrigger("D");
GameObject.Find("Sphere_D").GetComponent<AudioSource>
().PlayOneShot(noteD);
GameObject.Find("Sphere_D").GetComponent<Animator>
().SetTrigger("D");
}
if (note == 'e')
{
//anim.SetTrigger("E");
GameObject.Find("Sphere_E").GetComponent<AudioSource>
().PlayOneShot(noteE);
GameObject.Find("Sphere_E").GetComponent<Animator>
().SetTrigger("E");
}
else if (note == 'f')
{
// anim.SetTrigger("F");
GameObject.Find("Sphere_F").GetComponent<AudioSource>
().PlayOneShot(noteF);
GameObject.Find("Sphere_F").GetComponent<Animator>
().SetTrigger("F");
}
else if (note == 'g')
{
//anim.SetTrigger("G");
GameObject.Find("Sphere_G").GetComponent<AudioSource>
().PlayOneShot(noteG);
GameObject.Find("Sphere_G").GetComponent<Animator>
().SetTrigger("G");
}
}
// Update is called once per frame
void Update()
{
if (recordMode == true)
{
if (Input.GetKeyDown(KeyCode.A)) {notes.Add('a'); PlayNote('a'); }
if (Input.GetKeyDown(KeyCode.B)) {notes.Add('b'); PlayNote('b'); }
if (Input.GetKeyDown(KeyCode.C)) {notes.Add('c'); PlayNote('c'); }
if (Input.GetKeyDown(KeyCode.D)) {notes.Add('d'); PlayNote('d'); }
if (Input.GetKeyDown(KeyCode.E)) {notes.Add('e'); PlayNote('e'); }
if (Input.GetKeyDown(KeyCode.F)) {notes.Add('f'); PlayNote('f'); }
if (Input.GetKeyDown(KeyCode.G)) {notes.Add('g'); PlayNote('g'); }
}
else
{
if (Input.GetKeyDown(KeyCode.A)) { PlayNote('a'); }
if (Input.GetKeyDown(KeyCode.B)) { PlayNote('b'); }
if (Input.GetKeyDown(KeyCode.C)) { PlayNote('c'); }
if (Input.GetKeyDown(KeyCode.D)) { PlayNote('d'); }
if (Input.GetKeyDown(KeyCode.E)) { PlayNote('e'); }
if (Input.GetKeyDown(KeyCode.F)) { PlayNote('f'); }
if (Input.GetKeyDown(KeyCode.G)) { PlayNote('g'); }
}
if (playMode == true )
{
Playback();
}
}
}
You may want to specify that the AudioSource don't have to loop the sound. Add this line to your Start method :
void Start()
{
anim = gameObject.GetComponent<Animator>();
audio = GetComponent<AudioSource>();
audio.loop = false; // <--------------- HERE
notes = new ArrayList();
Button rec = record.GetComponent<Button>();
Button pl = play.GetComponent<Button>();
record.onClick.AddListener(()=>{ recordMode = !recordMode; });
play.onClick.AddListener(() => { playMode = !playMode; recordMode = false; });
}
You can either do this in code as above or directly in the inspector of your AudioSource. I think the default value of the loop property is set to true, that's why it's looping when you play a note.