Unity Camera Change C# - c#

I have three characters and each of them has a camera attached to them.By default they are disabled but one.I made a character selector which is supposed to change them.I have a problem where I can move the selected one but the camera stays at the last one.
Here is the script:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityStandardAssets.Utility;
public class GameManageer : MonoBehaviour {
public Camera[] cams = new Camera[3];
public Character CurrentCharacter;
public List<Character> Characters = new List<Character>();
public List<Item> AllItems;
bool ShowCharWheel;
public int SelectedCharacter;
public int lastCharacter;
public static GameManageer Instance;
void Awake(){
Instance = this;
foreach (Character c in Characters){
c.Instance = Instantiate(c.PlayerPrefab, c.HomeSpawn.position, c.HomeSpawn.rotation) as GameObject;
c.Instance.GetComponent<PlayerController>().LocalCharacter = c;
}
ChangeCharacter(Characters[PlayerPrefs.GetInt("SelectedChar")]);
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKey (KeyCode.C)) {
ShowCharWheel = true;
} else {
ShowCharWheel = false;
}
}
void ChangeCharacter(Character c){
lastCharacter = SelectedCharacter;
SelectedCharacter = Characters.IndexOf (c);
cams [SelectedCharacter].gameObject.SetActive (true);
cams [lastCharacter].gameObject.SetActive (false);
CurrentCharacter = c;
Characters [lastCharacter].Instance.GetComponent<PlayerController> ().CanPlay = false;
Characters [SelectedCharacter].Instance.GetComponent<PlayerController> ().CanPlay = true;
PlayerPrefs.SetInt ("SelectedChar", SelectedCharacter);
}
void OnGUI(){
if (ShowCharWheel) {
GUILayout.BeginArea(new Rect(Screen.width - 64, Screen.height - 192,64,192));
foreach (Character c in Characters){
if (GUILayout.Button(c.Icon,GUILayout.Width(64),GUILayout.Height(64))){
ChangeCharacter(c);
}
}
GUILayout.EndArea();
}
}
}
[System.Serializable]
public class Character {
public string Name;
public Texture2D Icon;
public GameObject PlayerPrefab;
public GameObject Instance;
public Transform HomeSpawn;
}
[System.Serializable]
public class Item{
public string Name;
public Texture2D Icon;
public ItemInstance InstancePrefab;
}

This should do the job:
cams[SelectedCharacter].enabled = true;
cams[lastCharacter].enabled = false;

Use Depth:
foreach (Camera cam in cams)
{
cam.depth = cam == cams[SelectedCharacter] ? 10 : 0;
}
I think the real problem here though, is that you have more cameras in the scene which you have to manage as well, other then only the last and current selected character... in which case:
foreach (Camera cam in cams)
{
cam.SetActive(cam == cams[SelectedCharacter]);
}

Related

How do i add multiple enemies to my unity wave system?

I have a wave script for my game and it works fine, however after a while I have realised it gets quite dull fighting against the same enemies over and over again, so I was wondering if I could make a list of some sort to store all enemies that will be in each wave.
Here is my script;
SpawnManager.cs
using System.Collections;
using UnityEngine;
[System.Serializable]
public class Wave
{
public int EnemiesPerWave;
public GameObject Enemy;
}
public class SpawnManager : MonoBehaviour
{
public Wave[] Waves; // class to hold information per wave
public Transform[] SpawnPoints;
public float TimeBetweenEnemies = 2f;
public GameObject HelpText;
public GameObject Shop;
public GameObject shopfx;
public Transform ShopL;
bool shopactive = false;
private int _totalEnemiesInCurrentWave;
private int _enemiesInWaveLeft;
private int _spawnedEnemies;
private int _currentWave;
private int _totalWaves;
void Start ()
{
_currentWave = -1; // avoid off by 1
_totalWaves = Waves.Length - 1; // adjust, because we're using 0 index
StartNextWave();
}
void Update()
{
if (_enemiesInWaveLeft <= 0 && Input.GetKeyDown(KeyCode.R))
{
StartNextWave();
}
}
void StartNextWave()
{
_currentWave++;
// win
if (_currentWave > _totalWaves)
{
return;
}
_totalEnemiesInCurrentWave = Waves[_currentWave].EnemiesPerWave;
_enemiesInWaveLeft = 0;
_spawnedEnemies = 0;
StartCoroutine(SpawnEnemies());
}
// Coroutine to spawn all of our enemies
IEnumerator SpawnEnemies()
{
GameObject enemy = Waves[_currentWave].Enemy;
while (_spawnedEnemies < _totalEnemiesInCurrentWave)
{
_spawnedEnemies++;
_enemiesInWaveLeft++;
int spawnPointIndex = Random.Range(0, SpawnPoints.Length);
// Create an instance of the enemy prefab at the randomly selected spawn point's
// position and rotation.
Instantiate(enemy, SpawnPoints[spawnPointIndex].position,
SpawnPoints[spawnPointIndex].rotation);
yield return new WaitForSeconds(TimeBetweenEnemies);
}
yield return null;
}
// called by an enemy when they're defeated
public void EnemyDefeated()
{
_enemiesInWaveLeft--;
// We start the next wave once we have spawned and defeated them all
if (_enemiesInWaveLeft == 0 && _spawnedEnemies == _totalEnemiesInCurrentWave)
{
HelpText.SetActive(true);
Invoke("SetFalse",5.0f);
Shop.SetActive(true);
Invoke("LateUpdate",1f);
Instantiate(shopfx, new Vector3(ShopL.transform.position.x, ShopL.transform.position.y, ShopL.transform.position.z), Quaternion.identity);
shopactive = true;
}
}
void SetFalse()
{
HelpText.SetActive(false);
}
void LateUpdate()
{
if(Input.GetKeyDown(KeyCode.R) && shopactive == true)
{
Shop.SetActive(false);
Instantiate(shopfx, new Vector3(Shop.transform.position.x, Shop.transform.position.y, Shop.transform.position.z), Quaternion.identity);
shopactive = false;
}
}
}

Playing multiple audio clips in unity

There might be similar questions to this one but I couldn't find any useful.
I have a simple scrips which has a list of classes that contains audio clips, id, and event system individually for each one of those elements.
I need to make that audio clip fields to list and make them play by order until the last one then stop and fire event.
Here's my code for only one audio clip slot:
(Also i tried audio clip array but its just playing the first one on the audio clip array)
public class MainAudioManager : MonoBehaviour {
public List<soundInfo> currentsoundinfoList = new List<soundInfo>();
AudioSource audioSource;
soundInfo curentSoundInfo;
float audioLenght;
void Start () {
audioSource = gameObject.GetComponent<AudioSource> ();
}
public void SetAudioToPlay (int ID) {
for (int i = 0; i < currentsoundinfoList.Count; i++) {
if (currentsoundinfoList [i].ID == ID) {
curentSoundInfo = currentsoundinfoList[i];
audioSource.clip = curentSoundInfo.clipToPlay;
audioSource.Play ();
audioLenght = audioSource.clip.length;
StartCoroutine ("waitnigTillEbd");
return;
}
}
}
IEnumerator waitnigTillEbd () {
yield return new WaitForSeconds (audioLenght + 1f);
curentSoundInfo.eventOnSound.Invoke ();
}
[System.Serializable]
public class soundInfo {
public string name;
public int ID;
public AudioClip clipToPlay;
public UnityEvent eventOnSound;
}
}
alright i found the solution by my self. here is the final result for creating list of sound with event onstop attached to each one of them individually and also playable by ID from another event and classes ,for anyone who need it
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
[RequireComponent(typeof(AudioSource))]
public class MainAudioManager : MonoBehaviour {
public List<soundInfo> soundList = new List<soundInfo>();
AudioSource audioSource;
soundInfo curentSoundInfo;
float audioLenght;
void Start () {
audioSource = gameObject.GetComponent<AudioSource> ();
}
public void SetAudioToPlay (int ID) {
for (int i = 0; i < soundList.Count; i++) {
if (soundList [i].ID == ID) {
curentSoundInfo = soundList [i];
StartCoroutine(playSequencely());
return;
}
}
}
IEnumerator playSequencely () {
yield return null;
for (int cnt = 0; cnt < curentSoundInfo.clipsToPlay.Length; cnt++) {
audioSource.clip = curentSoundInfo.clipsToPlay [cnt];
audioSource.Play ();
while (audioSource.isPlaying) {
yield return null;
}
}
//Debug.Log ("Last Audio Is Playing");
curentSoundInfo.onStop.Invoke ();
}
}
[System.Serializable]
public class soundInfo {
public string name;
public int ID;
[TextArea (2, 8)] public string About;
public AudioClip[] clipsToPlay;
//public float delayBetween;
public UnityEvent onStop;
}

How to call array element that has bool value true unity C#

I have four buttons using the same prefab and holding 4 text elements from an array out of which only one is assigned bool value to true. I am trying to access that true element when any of false element is clicked. i want to highlight true element when the false element is clicked. can anyone please help me to achieve this functionality?
using simpleobjectpool
taking reference from unity quiz game tutorial
Thanks
Answer Button Script
public class AnswerButton : MonoBehaviour
{
public Text answerText;
private AnswerData answerData;
private GameController gameController;
private bool isCorrect;
void Start()
{
gameController = FindObjectOfType<GameController>();
}
public void Setup(AnswerData data)
{
answerData = data;
answerText.text = answerData.answerText;
}
public void HandleClick()
{
gameController.AnswerButtonClicked(answerData.isCorrect);
{
if (answerData.isCorrect)
{
}
if (!answerData.isCorrect)
{
}
}
Answer Data Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class AnswerData
{
public string answerText;
public bool isCorrect;
}
QuestionData Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class QuestionData
{
public string questionText;
public AnswerData[] answers;
}
Game Controller Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System;
public class GameController : MonoBehaviour
{
public Text questionText;
public Text scoreDisplayText;
public SimpleObjectPool answerButtonObjectPool;
public Transform answerButtonParent;
public GameObject questionPanel;
public GameObject roundOverPanel;
public GameObject levelsPanel;
private DataController dataController;
private RoundData currentRoundData;
private bool isRoundActive;
private float timeBeetweenQuestions = 3.0f;
private List<GameObject> answerButtonGameObjects = new List<GameObject>();
private QuestionData[] questionPool;
private int questionIndex;
private int qNumber = 0;
private List<int> questionIndexesChosen = new List<int>();
public int playerScore = 0;
public int totalQuestions;
private static int pointAddedForCorrectAnswer;
public AudioSource answerButtonClicked;
public AudioSource wrongAnswerClicked;
void Start ()
{
dataController = FindObjectOfType<DataController>();
currentRoundData = dataController.GetCurrentRoundData();
questionPool = currentRoundData.questions;
playerScore = 0;
questionIndex = 0;
scoreDisplayText.text = "Score: " + playerScore.ToString();
isRoundActive = true;
ShowQuestion();
}
private void ShowQuestion()
{
RemoveAnswerButtons();
QuestionData questionData = questionPool[questionIndex];
questionText.text = questionData.questionText;
for (int i = 0; i < questionData.answers.Length; i++)
{
GameObject answerButtonGameObject =
answerButtonObjectPool.GetObject();
answerButtonGameObjects.Add(answerButtonGameObject);
answerButtonGameObject.transform.SetParent(answerButtonParent);
AnswerButton answerButton =
answerButtonGameObject.GetComponent<AnswerButton>();
AnswerButton.Setup(questionData.answers[i]);
}
}
private void RemoveAnswerButtons()
{
while (answerButtonGameObjects.Count > 0)
{
answerButtonObjectPool.ReturnObject(answerButtonGameObjects[0]);
answerButtonGameObjects.RemoveAt(0);
}
}
IEnumerator TransitionToNextQuestion()
{
yield return new WaitForSeconds(timeBeetweenQuestions);
ShowQuestion();
}
IEnumerator WaitForFewSeconds()
{
yield return new WaitForSeconds(timeBeetweenQuestions);
EndRound();
}
IEnumerator ReturnCorrectButtonColor()
{
Debug.Log("im correct");
GetComponent<Button>().image.color = Color.green;
yield return new WaitForSeconds(seconds: 2.9f);
GetComponent<Button>().image.color = Color.white;
}
IEnumerator ReturnWrongButtonColor()
{
Debug.Log("im wrong");
GetComponent<Button>().image.color = Color.red;
yield return new WaitForSeconds(seconds: 2.9f);
GetComponent<Button>().image.color = Color.white;
}
public void AnswerButtonClicked (bool isCorrect)
{
if (isCorrect)
{
playerScore += currentRoundData.pointAddedForCorrectAnswer;
scoreDisplayText.text = "Score: " + playerScore.ToString();
//play coorect answer sound
answerButtonClicked.Play();
StartCoroutine(ReturnCorrectButtonColor());
}
if (!isCorrect)
{
//play wrong answer sound
answerButtonClicked = wrongAnswerClicked;
answerButtonClicked.Play();
StartCoroutine(ReturnWrongButtonColor());
// buttons = GameObject.FindGameObjectsWithTag("Answer");
// {
// foreach (GameObject button in buttons)
// {
// if (button.GetComponent<AnswerButton>
//().answerData.isCorrect)
// {
// button.GetComponent<AnswerButton>
// ().StartCoroutine(ReturnCorrectButtonColor());
// }
// }
//}
}
if (qNumber < questionPool.Length - 1) /
{
qNumber++;
StartCoroutine(TransitionToNextQuestion());
}
else
{
StartCoroutine(WaitForFewSeconds());
}
}
public void EndRound()
{
isRoundActive = false;
questionPanel.SetActive(false);
roundOverPanel.SetActive(true);
}
//on button click return to main menu
public void ReturnToMenu ()
{
SceneManager.LoadScene("MenuScreen");
}
}
In order to highlight both Wrong (the clicked one) and the Right buttons you need to have access to both buttons. This means that you can't do highlighting from HandleClick method of your Answer Button Script, as it only has access to itself, e.g. to the Wrong button.
The good thing is that this method notifies GameController that the button has been clicked. GameController knows about all the buttons, so it can easily highlight both buttons.
So, instead of launching your highlight subroutines from Answer Button's HandleClick, you should do this from GameController's AnswerButtonClicked: identify both the Right button and the clicked button there and launch appropriate subroutines for them.
Update:
For instance, your ReturnCorrectButtonColor would look like:
IEnumerator ReturnCorrectButtonColor( GameObject button )
{
Debug.Log("im correct");
button.GetComponent<Button>().image.color = Color.green;
yield return new WaitForSeconds(seconds: 2.9f);
button.GetComponent<Button>().image.color = Color.white;
}
so in AnswerButtonClicked you identify which button to highlight as a correct answer button and pass it as a paramter to this method:
StartCoroutine(ReturnCorrectButtonColor(correctButton));

Creating a sound manager

This is how I currently have my Sound Manager setup for a small RPG and I was just wondering if this was good practice.
What I was trying to go for was to have my two methods (PlayBGMusic and PlaySound) to be "public static" so I would not have to grab the GameObject by tag and the Script in almost all of my other scripts that want to play a sound. If I do make them "public static" then I would have to make my variables the same which takes away from placing anything in the inspector.
public class Sound_Manager : MonoBehaviour {
// Allow the user to decide if music should be on or off.
public bool backgroundMusicOn;
// Allow the user to decide if sound should be on or off.
public bool soundOn;
// The music volume.
[Range(0,1)]
public float musicVolume;
// The sound volume.
[Range(0,1)]
public float soundVolume;
// The Background music to be used for any manipulations.
private AudioSource _bgMusic;
// Play a background song.
public void PlayBGMusic(AudioSource music){
...
}
// Mute Current Background Song.
public void MuteUnMuteBGMusic(){
....
}
// Play a sound.
public void PlaySound(AudioClip sfx, Vector3 location){
...
}
}
Is this a proper way of handling something like this or is there another way that could be more simple?
I think you can't play BGmusic and sound in one GameObject,because every audio must play whith single audion source,this is my code of AudioManager.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class AudioManager : MonoBehaviour
{
public AudioClip[] audioSources;
public GameObject audioPrefabSource;
public Dictionary<string,AudioClip> audioClips;
static GameObject audioPrefab;
static GameObject instance;
static AudioSource musicPlayer;
public static AudioManager audioManager;
Dictionary<string,Audio> aliveSounds;
AudioListener al;
void Awake ()
{
audioManager = this;
al = GetComponent<AudioListener> ();
audioClips = new Dictionary<string, AudioClip> ();
foreach (AudioClip a in audioSources) {
audioClips.Add (a.name, a);
}
instance = this.gameObject;
audioPrefab = audioPrefabSource;
musicPlayer = audio;
aliveSounds = new Dictionary<string, Audio> ();
//DontDestroyOnLoad(gameObject);
}
void Update ()
{
if (!GameSetting.hasMusic) {
musicPlayer.Pause ();
} else {
if (!musicPlayer.isPlaying) {
musicPlayer.Play ();
}
}
if (!GameSetting.hasSound && aliveSounds.Count > 0) {
foreach (Audio a in aliveSounds.Values) {
a.StopSound ();
}
aliveSounds.Clear ();
}
if (!al.enabled) {
al.enabled = true;
}
}
public static void PlaySoundOnce (string name)
{
if (!GameSetting.hasSound) {
return;
}
if (!audioManager.audioClips.ContainsKey (name)) {
return;
}
GameObject go = GameObject.Instantiate (audioPrefab) as GameObject;
go.transform.parent = instance.transform;
Audio a = go.GetComponent<Audio> ();
a.PlaySoundOnce (audioManager.audioClips [name]);
}
public static void PlayMusic (string name)
{
if (!GameSetting.hasMusic) {
return;
}
if (musicPlayer.clip == null || musicPlayer.clip.name != name) {
// musicPlayer.clip = audioManager.audioClips [name];
musicPlayer.clip = Resources.Load ("Audio/" + name, typeof(AudioClip)) as AudioClip;
musicPlayer.Stop ();
musicPlayer.loop = true;
musicPlayer.Play ();
} else {
musicPlayer.loop = true;
musicPlayer.Play ();
}
}
}
There is another class for Audio,it must be made to a audioprefab.
using UnityEngine;
using System.Collections;
public class Audio : MonoBehaviour
{
public void PlaySoundOnce (AudioClip audioClip)
{
StartCoroutine (PlaySoundCoroutine (audioClip));
}
IEnumerator PlaySoundCoroutine (AudioClip audioClip)
{
audio.PlayOneShot (audioClip);
yield return new WaitForSeconds (audioClip.length);
Destroy (gameObject);
}
public void PlaySoundLoop (AudioClip audioClip)
{
audio.clip = audioClip;
audio.loop = true;
audio.Play ();
}
public void StopSound ()
{
audio.Stop ();
Destroy (gameObject);
}
}
Like this,and I ignored audio's position,I used 2D sound.
I recommend turning the sound manager into a singleton class. In that way you can have all the properties in the inspector and use the singleton object to globally access all your properties, even destroying the gameobject completely when not needed .

Need to a Instantiate a prefab in canvas which is in another scene

I am making an achievement system.I have to 2 scene in my game.The first scene is my Main Menu and the other scene is my game scene. I have designed and coded the achievement system in the main menu scene and added a EarnCanvas to my game scene. EarnCanvas will display the achievement that the player has unlocked.
Code i have is only allowing me to link the achievements to a EarnCanvas on the Main Menu scene.i need help to modifier the code or link the two scene so that i can instantiate the unlocked achievement prefab in the EarnCanvas in the game Scene. At the moment no prefab is instantiated or displayed in the EarnCanvas when the player has unlocked an achievement.
Main Menu scene
achievement Manager script:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
public class AchievementManager : MonoBehaviour {
public GameObject achievementPraf;
public Sprite[] sprites;
private AchievementButton activeButton;
public ScrollRect scrollRect;
public GameObject achievementMenu;
public GameObject visualAchievement;
public Dictionary<string, Achievement> achievements = new Dictionary<string, Achievement>();
public Sprite UnlockedSprite;
private static AchievementManager instance;
public static AchievementManager Instance
{
get {
if(instance == null)
{
instance = GameObject.FindObjectOfType<AchievementManager>();
}
return AchievementManager.instance;
}
}
// Use this for initialization
void Start ()
{
//remove before deploy
//PlayerPrefs.DeleteAll();
activeButton = GameObject.Find("Streakbtn").GetComponent<AchievementButton>();
CreateAchievement("Streak", "Press W", "Press W to unlock this achievement", 5, 0);
CreateAchievement("Streak", "Press R", "Press R to unlock this achievement", 5, 0);
CreateAchievement("Streak", "Press All Keys", "Press All Keys to unlock", 5, 0, new string[] { "Press W", "Press R" });
foreach (GameObject achievementList in GameObject.FindGameObjectsWithTag("achievementList"))
{
achievementList.SetActive(false);
}
activeButton.click();
achievementMenu.SetActive(false);
}
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown(KeyCode.S))
{
achievementMenu.SetActive(!achievementMenu.activeSelf);
}
if(Input.GetKeyDown(KeyCode.W))
{
EarnAchievemnent("Press W");
}
if (Input.GetKeyDown(KeyCode.R))
{
EarnAchievemnent("Press R");
}
}
public void EarnAchievemnent(string title)
{
if(achievements[title].EarnAchievement())
{
GameObject achievement = (GameObject) Instantiate(visualAchievement);
StartCoroutine(HideAchievement(achievement));
//this is where is its giving the parent the gameobject name to find
SetAchievementInfo("EarnCanvas", achievement, title);
}
}
public IEnumerator HideAchievement(GameObject achievement)
{
yield return new WaitForSeconds(3);
Destroy(achievement);
}
public void CreateAchievement(string parent,string title,string description,int points,int spriteIndex,string[] dependencies = null)
{
GameObject achievement = (GameObject)Instantiate(achievementPraf);
Achievement newAchievement = new Achievement(name, description, points, spriteIndex,achievement);
achievements.Add(title, newAchievement);
SetAchievementInfo(parent, achievement,title);
if(dependencies != null)
{
foreach(string achievementTitle in dependencies)
{
Achievement dependency = achievements[achievementTitle];
dependency.Child = title;
newAchievement.AddDependency(dependency);
//Dependency = Press Space <-- Child = Press W
//NewAchievement = Press W --> Press Space
}
}
}
public void SetAchievementInfo(string parent, GameObject achievement, string title)
{
//this where its trying to find a gameobject-(EarnCanvas) to instantiate the unlocked achievement prefab in the Main Menu Scene
achievement.transform.SetParent(GameObject.Find(parent).transform);
achievement.transform.localScale = new Vector3(1, 1, 1);
achievement.transform.localPosition = new Vector3(0, 0, 0);
achievement.transform.GetChild(0).GetComponent<Text>().text = title;
achievement.transform.GetChild(1).GetComponent<Text>().text = achievements[title].Description;
achievement.transform.GetChild(2).GetComponent<Text>().text = achievements[title].Points.ToString();
achievement.transform.GetChild(3).GetComponent<Image>().sprite = sprites[achievements[title].SprintIndex];
}
public void ChangeCategory(GameObject button)
{
AchievementButton achievementButton = button.GetComponent<AchievementButton>();
scrollRect.content = achievementButton.achievementList.GetComponent<RectTransform>();
achievementButton.click();
activeButton.click();
activeButton = achievementButton;
}
}
Main Menu Scene
Achievement Script:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
public class Achievement
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string description;
public string Description
{
get { return description; }
set { description = value; }
}
private bool unlocked;
public bool Unlocked
{
get { return unlocked; }
set { unlocked = value; }
}
private int points;
public int Points
{
get { return points; }
set { points = value; }
}
private int sprintIndex;
public int SprintIndex
{
get { return sprintIndex; }
set { sprintIndex = value; }
}
private GameObject achievementRef;
private List<Achievement> dependencies = new List<Achievement>();
private string child;
public string Child
{
get { return child; }
set { child = value; }
}
public Achievement(string name,string description, int points, int sprintIndex, GameObject achievementRef)
{
this.name = name;
this.description = description;
this.unlocked = false;
this.points = points;
this.sprintIndex = sprintIndex;
this.achievementRef = achievementRef;
LoadAchievement();
}
public void AddDependency(Achievement dependency)
{
dependencies.Add(dependency);
}
public bool EarnAchievement()
{
if(!unlocked && !dependencies.Exists(x=> x.unlocked == false))
{
achievementRef.GetComponent<Image>().sprite = AchievementManager.Instance.UnlockedSprite;
SaveAchievement(true);
if(child != null)
{
AchievementManager.Instance.EarnAchievemnent(child);
}
return true;
}
return false;
}
public void SaveAchievement(bool value)
{
unlocked = value;
PlayerPrefs.SetInt(name,value? 1 : 0);
PlayerPrefs.Save();
}
public void LoadAchievement()
{
unlocked = PlayerPrefs.GetInt(name) == 1 ? true : false;
if (unlocked)
{
achievementRef.GetComponent<Image>().sprite = AchievementManager.Instance.UnlockedSprite;
}
}
}
You should use DontDestroyOnLoad method it is very simple way to retain gameobjects over scene changes you just need to add following code to your AchievementManager.
void Awake ()
{
DontDestroyOnLoad (transform.gameObject);
}
You can add this for any gameObject which you do not want to be destroyed upon changing scene.

Categories

Resources