Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Azzo96 · Jan 21, 2021 at 02:56 PM · gameonclicksound effectspuzzlecard

How to add a specific sounds to pictures

I have completed a tutorial on how to make a memory card, everything works great, I can play the game and match all the cards (20 or 30 or 40 for different categories cause I have 6 of them) and I added a timer. I can even reset the game and start all over, and all the cards are randomly sorted out.

But I want to go beyond the tutorial and put some sound effects in the game to make it more fun. I get that you can play sounds on mouse clicks and stuff, but I want to play sounds when specific cards are revealed. Duck card appears and you hear a quacking sound or his name. I'm a beginner and I don't know how to add it.

I'm not sure if I would start a new C# script or add to my existing (PictureManager) script or (Picture) script.

Any help would be appreciated. Thank you. These are my (PictureManager) and (Picture) script for the game.



using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEngine.UI;

public class PictureManager : MonoBehaviour { public Picture PicturePrefab;

 public Transform PicSpawnPosition;

 public Vector2 StartPosition = new Vector2(-2.15f, 3.62f);

 public AudioSource WinSound;

 public AudioSource BgSound;



 [Space]
 [Header("End Game Screen")]
 public GameObject EndGamePanel;
 public GameObject NewBestScoreText;
 public GameObject YourScoreText;
 public GameObject EndTimeText;

 /*to rremove
 public List<AudioClip> Vegetabels = new List<AudioClip>();
 private AudioSource audioSource;
 to remove*/

 public enum GameState
 { 
    NoAction,
    MovingOnPositions,
    DeletingPuzzles,
    FlipBack,
    Checking,
    GameEnd
 };

 public enum PuzzleState
 {
     PuzzleRotating,
     CanRotate,
 };

 public enum RevealedState
 {
     NoRevealed,
     OneRevealed,
     TwoRevealed
 };

 [HideInInspector]
 public GameState CurrentGameState;
 [HideInInspector]
 public PuzzleState CurrentPuzzleState;
 [HideInInspector]
 public RevealedState PuzzleRevealedNumber;


 [HideInInspector]
 public List<Picture> PictureList;

 private Vector2 _offset = new Vector2(1.42f, 1.52f);
 private Vector2 _offsetFor15Pairs = new Vector2(1.08f, 1.22f);
 private Vector2 _offsetFor20Pairs = new Vector2(1.08f, 1.0f);
 private Vector3 _newScaleDown = new Vector3(0.9f, 0.9f, 0.001f);

 private List<Material> _materialList = new List<Material>();
 private List<string> _texturePathList = new List<string>();
 private Material _firstMaterial;
 private string _firstTexturePath;

 private int _firstRevealedPic;
 private int _secondRevealedPic;
 private int _revealedPicNumber = 0;
 private int _picToDestroy1;
 private int _picToDestroy2;

 private bool _corutineStarted = false;

 private int _pairNumbers;
 private int _removedPairs;
 private Timer _gameTimer;
 void Start()
 {
     //BgSound.Play();
     CurrentGameState = GameState.NoAction;
     CurrentPuzzleState = PuzzleState.CanRotate;
     PuzzleRevealedNumber = RevealedState.NoRevealed;
     _revealedPicNumber = 0;
     _firstRevealedPic = -1;
     _secondRevealedPic = -1;

     _removedPairs = 0;
     _pairNumbers = (int)GameSettings.Instance.GetPairNumber();

     _gameTimer = GameObject.Find("Main Camera").GetComponent<Timer>();

     LoadMaterials();

     if(GameSettings.Instance.GetPairNumber()== GameSettings.EPairNumber.E10Pairs)
     {
         CurrentGameState = GameState.MovingOnPositions;
         SpwanPictureMesh(4, 5, StartPosition, _offset, false);
         MovePicture(4, 5, StartPosition, _offset);
     }
     else if (GameSettings.Instance.GetPairNumber() == GameSettings.EPairNumber.E15Pairs)
     {
         CurrentGameState = GameState.MovingOnPositions;
         SpwanPictureMesh(5, 6, StartPosition, _offset, false);
         MovePicture(5, 6, StartPosition, _offsetFor15Pairs);
     }
     else if (GameSettings.Instance.GetPairNumber() == GameSettings.EPairNumber.E20Pairs)
     {
         CurrentGameState = GameState.MovingOnPositions;
         SpwanPictureMesh(5, 8, StartPosition, _offset, true);
         MovePicture(5, 8, StartPosition, _offsetFor20Pairs);
     }
 }

 public void CheckPicture()
 {
     CurrentGameState = GameState.Checking;
     _revealedPicNumber = 0;

     for(int id = 0; id < PictureList.Count; id++)
     {
         if(PictureList[id].Revealed && _revealedPicNumber < 2)
         {
             if(_revealedPicNumber == 0)
             {
                 _firstRevealedPic = id;
                 _revealedPicNumber++;
                 //audioSource.PlayOneShot(Vegetabels[id]);
             }
             else if (_revealedPicNumber == 1)
             {
                 _secondRevealedPic = id;
                 _revealedPicNumber++;
             }
         }
         if (_revealedPicNumber == 2)
         {
             if (PictureList[_firstRevealedPic].GetIndex() == PictureList[_secondRevealedPic].GetIndex() && _firstRevealedPic != _secondRevealedPic)
             {
                 CurrentGameState = GameState.DeletingPuzzles;
                 _picToDestroy1 = _firstRevealedPic;
                 _picToDestroy2 = _secondRevealedPic;
             }
             else
             {
                 CurrentGameState = GameState.FlipBack;
             }
         }
     }

     
     CurrentPuzzleState = PictureManager.PuzzleState.CanRotate;

     if(CurrentGameState == GameState.Checking)
     {
         CurrentGameState = GameState.NoAction;
     }
 }

 private void DestroyPicture()
 {
     PuzzleRevealedNumber = RevealedState.NoRevealed;
     PictureList[_picToDestroy1].Deactivate();
     PictureList[_picToDestroy2].Deactivate();
     _revealedPicNumber = 0;
     _removedPairs++;
     CurrentGameState = GameState.NoAction;
     CurrentPuzzleState = PuzzleState.CanRotate;
 }

 private IEnumerator FlipBack()
 {
     _corutineStarted = true;

     yield return new WaitForSeconds(0.5f);

     PictureList[_firstRevealedPic].FlipBack();
     PictureList[_secondRevealedPic].FlipBack();

     PictureList[_firstRevealedPic].Revealed = false;
     PictureList[_secondRevealedPic].Revealed = false;

     PuzzleRevealedNumber = RevealedState.NoRevealed;
     CurrentGameState = GameState.NoAction;

     _corutineStarted = false;
 }

 private void LoadMaterials()
 {
     var materialFilePath = GameSettings.Instance.GetMaterialDirectoryName();
     var textureFilePath = GameSettings.Instance.GetPuzzleCategoryTextureDirectoryName();
     var pairNumber = (int)GameSettings.Instance.GetPairNumber();
     const string matBaseName = "Pic";
     var firstMaterialName = "Back";

     for(var index = 1; index <= pairNumber; index++)
     {
         var currentFilePath = materialFilePath + matBaseName + index;
         Material mat = Resources.Load(currentFilePath, typeof(Material)) as Material;
         _materialList.Add(mat);

         var currentTextureFilePath = textureFilePath + matBaseName + index;
         _texturePathList.Add(currentTextureFilePath);
     }
     _firstTexturePath = textureFilePath + firstMaterialName;
     _firstMaterial = Resources.Load(materialFilePath + firstMaterialName, typeof(Material)) as Material;
 }
 
 void Update()
 {
     if (PauseMenu.isPaused == false) {
     if (CurrentGameState == GameState.DeletingPuzzles)
     {
         if(CurrentPuzzleState == PuzzleState.CanRotate)
         {
             DestroyPicture();
             CheckGameEnd();
         }
     }
     if (CurrentGameState == GameState.FlipBack)
     {
         if(CurrentPuzzleState == PuzzleState.CanRotate && _corutineStarted == false)
         {
             StartCoroutine(FlipBack());
         }
     }

     if(CurrentGameState == GameState.GameEnd)
     {
         if(PictureList[_firstRevealedPic].gameObject.activeSelf == false &&
             PictureList[_secondRevealedPic].gameObject.activeSelf == false &&
             EndGamePanel.activeSelf == false)
         {
             ShowEndGameInformation();
             if (GameSettings.Instance.IsSoundEffectMutedPermanently() == false)
                     WinSound.Play();
             //BgSound.Pause();
         }
     }
     }
 }

 private bool CheckGameEnd()
 {
     if(_removedPairs == _pairNumbers && CurrentGameState != GameState.GameEnd)
     {
         CurrentGameState = GameState.GameEnd;
         _gameTimer.StopTimer();
         Config.PlaceScoreOnBorad(_gameTimer.GetCurrentTime());
     }
     return (CurrentGameState == GameState.GameEnd);
 }
 private void ShowEndGameInformation()
 {
     EndGamePanel.SetActive(true);

     if(Config.IsBestScore())
     {
         NewBestScoreText.SetActive(true);
         YourScoreText.SetActive(false);
     }
     else
     {
         NewBestScoreText.SetActive(false);
         YourScoreText.SetActive(true);
     }
     
     var timer = _gameTimer.GetCurrentTime();
     var minutes = Mathf.Floor(timer / 60);
     var seconds = Mathf.RoundToInt(timer % 60);
     var newText = minutes.ToString("00") + ":" + seconds.ToString("00");
     EndTimeText.GetComponent<Text>().text = newText;
 }

 private void SpwanPictureMesh(int rows, int columns, Vector2 Pos, Vector2 offset, bool scaleDown)
 {
     for(int col = 0; col < columns; col++)
     {
         for(int row = 0; row < rows; row++)
         {
             var tempPicture = (Picture)Instantiate(PicturePrefab, PicSpawnPosition.position, PicturePrefab.transform.rotation);

             if(scaleDown)
             {
                 tempPicture.transform.localScale = _newScaleDown;
             }

             tempPicture.name = tempPicture.name + 'c' + col + 'r' + row;
             PictureList.Add(tempPicture);
         }
     }
     ApplyTextures();
 }

 public void ApplyTextures()
 {
     var rndMatIndex = Random.Range(0, _materialList.Count);
     var AppliedTimes = new int[_materialList.Count];

     for(int i = 0; i< _materialList.Count; i++)
     {
         AppliedTimes[i] = 0;
     }

     foreach(var o in PictureList)
     {
         var randPrevious = rndMatIndex;
         var counter = 0;
         var forceMat = false;

         while(AppliedTimes[rndMatIndex] >= 2 || ((randPrevious == rndMatIndex) && !forceMat))
         {
             rndMatIndex = Random.Range(0, _materialList.Count);
             counter++;
             if(counter > 100)
             {
                 for (var j = 0; j < _materialList.Count; j++)
                 {
                     if(AppliedTimes[j] < 2)
                     {
                         rndMatIndex = j;
                         forceMat = true;
                     }
                 }

                 if (forceMat == false)
                     return;
             }

         }

         o.SetFirstMaterial(_firstMaterial, _firstTexturePath);
         o.ApplyFirstMaterial();
         o.SetSecondMaterial(_materialList[rndMatIndex], _texturePathList[rndMatIndex]);
         o.SetIndex(rndMatIndex);
         o.Revealed = false;
         AppliedTimes[rndMatIndex] += 1;
         forceMat = false;
     }


 }

 private void MovePicture(int rows, int columns, Vector2 pos, Vector2 offset)
 {
     var index = 0;
     for(var col = 0; col < columns; col++)
     {
         for(int row = 0; row < rows; row++)
         {
             var targetPosition = new Vector3((pos.x + (offset.x * row)), (pos.y - (offset.y * col)), 0.0f);
             StartCoroutine(MoveToPosition(targetPosition, PictureList[index]));
             index++;
         }
     }
 }

 private IEnumerator MoveToPosition(Vector3 target, Picture obj)
 {
     var randomDis = 7;

     while(obj.transform.position !=target)
     {
         obj.transform.position = Vector3.MoveTowards(obj.transform.position, target, randomDis * Time.deltaTime);
         yield return 0;
     }
 }

}


using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class Picture : MonoBehaviour { public AudioClip PressSound;

 private Material _firstMaterial;

 private Material _secondMaterial;


 private Quaternion _currentRotation;


 [HideInInspector] public bool Revealed = false;
 private PictureManager _pictureManager;
 private bool _clicked = false;
 private int _index;

 private AudioSource _audio;
 public void SetIndex(int id)
 {
     _index = id;
 }
 
 public int GetIndex()
 {
     return _index;
 }

 void Start()
 {
     Revealed = false;
     _clicked = false;
     _pictureManager = GameObject.Find("[PictureManager]").GetComponent<PictureManager>();
     _currentRotation = gameObject.transform.rotation;

     _audio = GetComponent<AudioSource>();
     _audio.clip = PressSound;
 }

 void Update()
 {
     
 }

 private void OnMouseDown()
 {
     if(_clicked == false)
     {
         if (PauseMenu.isPaused == false)
         {
             _pictureManager.CurrentPuzzleState = PictureManager.PuzzleState.PuzzleRotating;
             if (GameSettings.Instance.IsSoundEffectMutedPermanently() == false)
                 _audio.Play();
             StartCoroutine(LoopRotation(45, false));
             _clicked = true;
         }
     }
 }

 public void FlipBack()
 {
     if (gameObject.activeSelf)
     {
         _pictureManager.CurrentPuzzleState = PictureManager.PuzzleState.PuzzleRotating;
         Revealed = false;
         /*if (GameSettings.Instance.IsSoundEffectMutedPermanently() == false)
             _audio.Play();*/
         StartCoroutine(LoopRotation(45, true));
     }
 }

 IEnumerator LoopRotation(float angle, bool FirstMat)
 {
     var rot = 0f;
     const float dir = 1f;
     const float rotSpeed = 180.0f;
     const float rotSpeed1 = 90.0f;
     var startAngle = angle;
     var assigned = false;

     if(FirstMat)
     {
         while(rot < angle)
         {
             var step = Time.deltaTime * rotSpeed1;
             gameObject.GetComponent<Transform>().Rotate(new Vector3(0, 2, 0) * step * dir);
             if(rot >= (startAngle - 2) && assigned == false)
             {
                 ApplyFirstMaterial();
                 assigned = true;
             }
             rot += (1 * step * dir);
             yield return null;
         }

     }
     else
     {
         while (angle > 0)
         {
             float step = Time.deltaTime * rotSpeed;
             gameObject.GetComponent<Transform>().Rotate(new Vector3(0, 2, 0) * step * dir);
             angle -= (1 * step * dir);
             yield return null;
         }
     }
     gameObject.GetComponent<Transform>().rotation = _currentRotation;

     if (!FirstMat)
     {
         Revealed = true;
         ApplySecondMaterial();
         _pictureManager.CheckPicture();
     }
     else
     {
         _pictureManager.PuzzleRevealedNumber = PictureManager.RevealedState.NoRevealed;
         _pictureManager.CurrentPuzzleState = PictureManager.PuzzleState.CanRotate;
     }

     _clicked = false;

 }

 public void SetFirstMaterial(Material mat, string texturePath)
 {
     _firstMaterial = mat;
     _firstMaterial.mainTexture = Resources.Load(texturePath, typeof(Texture2D)) as Texture2D;
 }

 public void SetSecondMaterial(Material mat, string texturePath)
 {
     _secondMaterial = mat;
     _secondMaterial.mainTexture = Resources.Load(texturePath, typeof(Texture2D)) as Texture2D;
 }

 public void ApplyFirstMaterial()
 {
     gameObject.GetComponent<Renderer>().material = _firstMaterial;
 }

 public void ApplySecondMaterial()
 {
     gameObject.GetComponent<Renderer>().material = _secondMaterial;
 }
 public void Deactivate()
 {
     StartCoroutine(DeactivateCorutine());
 }

 private IEnumerator DeactivateCorutine()
 {
     Revealed = false;

     yield return new WaitForSeconds(1f);
     gameObject.SetActive(false);
 }

}

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

137 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Water Flowing in pipes 0 Answers

Puzzle logic stuck 2 Answers

Trading Card Game 5 Answers

Unity for 2d puzzle 0 Answers

Some questions regarding card game 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges