I am new to Unity and I am trying to use 2 quads as buttons and one Script for playing an stopping an audio file. I have searched internet and I have not found a single solution for my problem.
this is my code
using UnityEngine;
using System.Collections;
public class PlayStop : MonoBehaviour {
public GameObject Button1;
public GameObject Button2;
public AudioClip Clip;
void Start()
{
Button1 = GameObject.Find ("Fa1Play");
Button2 = GameObject.Find ("Fa1Stop");
}
void OnMouseDown ()
{
if (Button1.GetComponent ("Fa1Play"))
{
if (!audio.isPlaying)
{
audio.clip = Clip;
audio.Play();
}
}
if (Button2.GetComponent("Fa1Stop"))
{
audio.Stop();
}
}
}
you dont need game object finds just give your buttons colliders and tag give your pause a pause tag and play a play tag
public class PlayStop : MonoBehaviour {
public AudioClip aclip;
private bool stop;
void Start()
{
audio.clip=aclip;
stop=true;
}
void Update ()
{
if(Input.touches.Length == 1)
{
Touch touchedFinger = Input.touches[0];
if(touchedFinger.phase==TouchPhase.Began){
Ray aRay = Camera.mainCamera.ScreenPointToRay(touchedFinger.position);
RaycastHit hit;
if(Physics.Raycast(aRay.origin, aRay.direction, out hit, Mathf.Infinity))
{
if(hit.collider.tag=="stop" && !stop)
{
audio.Stop();
stop=!stop
}
if(hit.collider.tag=="play" && stop)
{
audio.Play();
stop=!stop
}
}
}
}
}
}
Related
I'm doing a football game and i want it to play a sound every time i score a goal but i can't hear any sound.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
public class gol : MonoBehaviour
{
public AudioClip audioclip;
public AudioSource audiosource;
public bool golmu = false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void FixedUpdate()
{
if (golmu == true && !audiosource.isPlaying)
{
audiosource.clip = audioclip;
audiosource.Play();
}
}
public void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "gol")
{
golmu = true;
}
else
{
golmu = false;
}
}
public void OnTriggerExit(Collider other)
{
if(other.gameObject.tag == "gol")
{
golmu = false;
}
}
}
I tried without using AudioClip but it's not working. Putting the AudioSource component in another object too. I tried every code I saw but it didn't work.
I'm developing a TopDown 2D game in Unity.
The idea is, when the player steps on a certain tile, a UI with text pops up (already working) and the player stops moving until the player clicks a button (already programmed and working) and the UI disappears.
I was advised to turn the RigidBody2D to kinematic however it doesn't work and it just does what it used to do.
Am I doing something wrong?
Here is the code for the trigger script on the tiles:
public class TriggerScript : MonoBehaviour
{
public string popUp;
public void Start()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
Rigidbody2D Player = GameObject.Find("Player").GetComponent<Rigidbody2D>();
PopUpSystem pop = GameObject.FindGameObjectWithTag("GameManager").GetComponent<PopUpSystem>();
if (collision.gameObject.tag == "Player")
{
pop.PopUp(popUp);
Player.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Kinematic;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
Rigidbody2D Player = GameObject.Find("Player").GetComponent<Rigidbody2D>();
PopUpSystem pop = GameObject.FindGameObjectWithTag("GameManager").GetComponent<PopUpSystem>();
pop.closeBox();
Player.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Dynamic;
}
}
PopUpSystem.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class PopUpSystem : MonoBehaviour
{
public GameObject popUpBox;
public Animator popupanimation;
public TMP_Text popUpText;
public PLayerController mb;
public void PopUp(string text)
{
popUpBox.SetActive(true);
popUpText.text = text;
popupanimation.SetTrigger("pop");
}
public void closeBox()
{
popupanimation.SetTrigger("close");
mb.camMove = true;
}
}
PLayerController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PLayerController : MonoBehaviour
{
private Rigidbody2D MyRB;
private Animator myAnim;
[SerializeField]
private float speed;
public bool camMove = true;
// Start is called before the first frame update
void Start()
{
MyRB = GetComponent<Rigidbody2D>();
myAnim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (camMove)
{
MyRB.velocity = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")) * speed * Time.deltaTime;
myAnim.SetFloat("moveX", MyRB.velocity.x);
myAnim.SetFloat("moveY", MyRB.velocity.y);
if ((Input.GetAxisRaw("Horizontal") == 1) || (Input.GetAxisRaw("Horizontal") == -1) || (Input.GetAxisRaw("Vertical") == 1) || (Input.GetAxisRaw("Vertical") == -1))
{
myAnim.SetFloat("LastMoveX", Input.GetAxisRaw("Horizontal"));
myAnim.SetFloat("LastMoveY", Input.GetAxisRaw("Vertical"));
}
}
if (!camMove)
{
MyRB.velocity = new Vector2(0, 0);
}
}
}
TriggerScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TriggerScript : MonoBehaviour
{
public string popUp;
Animator popAnim;
public PLayerController mb;
private void Start()
{
popAnim = GameObject.FindGameObjectWithTag("PopUpBox").GetComponent<Animator>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
PopUpSystem pop = GameObject.FindGameObjectWithTag("GameManager").GetComponent<PopUpSystem>();
var myp = GameObject.FindGameObjectWithTag("Player").GetComponent<PLayerController>();
if (collision.gameObject.tag == "Player")
{
pop.PopUp(popUp);
mb.camMove = false;
}
if (popAnim.GetCurrentAnimatorStateInfo(1).IsName("close"))
{
mb.camMove = true;
Debug.Log("close");
}
}
private void OnTriggerExit2D(Collider2D collision)
{
PopUpSystem pop = GameObject.FindGameObjectWithTag("GameManager").GetComponent<PopUpSystem>();
pop.closeBox();
}
}
Things to keep in mind:
1- Make a new tag and call it PopUpBox. then assign this tag to the Trigger GameObject.
2- To the button of the PopUpBox GameObject (the one which is disabled) assign GameManager GameObject and in its function select PopUpSystem.closeBox
3- In both Trigger GameObject and GameManager assign Player in Mb field.
Hope this help you. You can play with that more to get better results.
I'm trying to keep the player skin, even when reloading the scene, or moving on to a new one. The player object changes every scene.
The player skin is chosen in a pause menu, with three buttons. Each one of those buttons calls a function in the script below. I'm trying to call one of these functions, based on what value the PlayerPrefs int holds, and the function does get called; But throws the error MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it
Below is what i have already tried, but this throws an error on scene reload (death)
i don't know what i'm doing wrong here.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Pausemenu : MonoBehaviour
{
public static bool gameIsPaused = false;
public GameObject pauseMenuUI;
public Material BelgianMat;
public Material Ball2;
public Material Rainbow;
public GameObject Player;
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape)) {
if (gameIsPaused) {
Resume();
} else {
Pause();
}
}
}
public void Resume(){
pauseMenuUI.SetActive(false);
Time.timeScale = 1f;
gameIsPaused = false;
}
void Pause() {
pauseMenuUI.SetActive(true);
Time.timeScale = 0f;
gameIsPaused = true;
}
public void LoadMenu() {
Time.timeScale = 1f;
gameIsPaused = false;
SceneManager.LoadScene("Menu");
}
public void QuitGame() {
Debug.Log("Quitting");
Application.Quit();
}
public void ApplyBelgian() {
Player.GetComponent<Renderer>().material = BelgianMat;
PlayerPrefs.SetInt("playerMat", 0);
}
public void ApplyBall2() {
Player.GetComponent<Renderer>().material = Ball2;
Debug.Log("Applied ball two");
PlayerPrefs.SetInt("playerMat", 1);
}
public void ApplyRainbow() {
Player.GetComponent<Renderer>().material = Rainbow;
PlayerPrefs.SetInt("playerMat", 2);
}
void OnEnable()
{
Debug.Log("OnEnable called");
SceneManager.sceneLoaded += OnSceneLoaded;
}
// called second
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
Debug.Log("OnSceneLoaded: " + scene.name);
Debug.Log(mode);
if (PlayerPrefs.GetInt("playerMat") == 0) {
ApplyBelgian();
}
else if (PlayerPrefs.GetInt("playerMat") == 1) {
Debug.Log("gonna apply ball 2");
ApplyBall2();
}
else if (PlayerPrefs.GetInt("playerMat") == 2) {
ApplyRainbow();
}
}
}
I don't know why but it seems like the reference to the Player object may be broken after loading the scene. If this is the case, add a "Player" tag to your Player object and add this to the OnEnable function: Player = GameObject.FindWithTag("Player");
I am making a 2D piano player game. I am mostly done, but I am new to Unity and programming in C#, and I am not sure how to do the next part. What do I do to make it so that when I press the record button, it records the notes and then plays it back when the play button is pressed? My script is down below. Thank you in advance for your help
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NotePlay : MonoBehaviour {
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 string[] store;
private KeyCode lastHitKey;
// Use this for initialization
void Start() {
anim = gameObject.GetComponent<Animator>();
audio = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update() {
if (Input.GetKeyDown(KeyCode.A)) {
anim.SetTrigger("A");
audio.PlayOneShot(noteA);
}
if (Input.GetKeyDown(KeyCode.B)) {
anim.SetTrigger("B");
audio.PlayOneShot(noteB);
}
if (Input.GetKeyDown(KeyCode.C)) {
audio.PlayOneShot(noteC);
anim.SetTrigger("C");
}
else if (Input.GetKeyDown(KeyCode.D)) {
anim.SetTrigger("D");
audio.PlayOneShot(noteD);
}
else if (Input.GetKeyDown(KeyCode.E)) {
anim.SetTrigger("E");
audio.PlayOneShot(noteE);
}
if (Input.GetKeyDown(KeyCode.F)) {
anim.SetTrigger("F");
audio.PlayOneShot(noteF);
}
if (Input.GetKeyDown(KeyCode.G)) {
anim.SetTrigger("G");
audio.PlayOneShot(noteG);
}
}
}
I made a Project in Unity, a game to be clear. So the player has a Sci-fi car and he tries to avoid obstacles-rocks.
When the car hits a rock, the Game Manager load the "credits" screen to choose between quit or restart.
My problem is that I want to make the rock explode when the car goes on it and then the Game Manager will load the "credits" screen.
Some of my code:
For player collision:
public class PlayerCollision : MonoBehaviour {
public PlayerMovement movement;
public static bool y = true;
public void OnCollisionEnter (Collision collisionInfo)
{
// We check if the object we collided with has a tag called "Obstacle".
if (collisionInfo.collider.tag == "Obstacle")
{
movement.enabled = false; // Disable the players movement.
y = false;
FindObjectOfType<GameManager>().EndGame();
}
}
}
Game Manager:
public class GameManager : MonoBehaviour {
bool gameHasEnded = false;
public float restartDelay = 1f;
public GameObject completeLevelUI;
public void CompleteLevel ()
{
completeLevelUI.SetActive(true);
}
public void EndGame ()
{
if (gameHasEnded == false)
{
gameHasEnded = true;
Debug.Log("GAME OVER");
Invoke("Restart", restartDelay);
}
}
void Restart ()
{
SceneManager.LoadScene("Credits");
//SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
The endTrigger:
public class EndTrigger : MonoBehaviour {
public GameManager gameManager;
void OnTriggerEnter ()
{
gameManager.CompleteLevel();
}
}
LevelComplete:
public class LevelComplete : MonoBehaviour {
public void LoadNextLevel ()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
}
Menu:
public class Menu : MonoBehaviour {
public void StartGame ()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
}
I have written other scripts. If you want anything let me know. Thanks guys.
Add a particle system to your rocks. Uncheck "looping" and "play on awake". Then you can play by adding the line below.
public void OnCollisionEnter (Collision collisionInfo)
{
// We check if the object we collided with has a tag called "Obstacle".
if (collisionInfo.collider.tag == "Obstacle")
{
movement.enabled = false; // Disable the players movement.
y = false;
collisionInfo.gameObject.GetComponent<ParticleSystem>().Play(); // play the explosion
FindObjectOfType<GameManager>().EndGame();
}
}
I would change your approach. As I understand you already have an endTrigger [With a Collider Trigger] that ends the game if the player goes inside. So uncheck the trigger in the player collider and instead add that trigger to the rocks collider, so when the player crashes it will:
Activate the Particle System
Makes the rock invisible
End the Game
You can add this script to your rock and see how it works
public class RockTrigger : MonoBehaviour {
public GameManager gameManager;
ParticleSystem myParticleSystem;
void Awake()
{
myParticleSystem = GetComponent<ParticleSystem>();
}
void OnTriggerEnter(Collider other)
{
myParticleSystem.Play();
GetComponent<MeshRenderer>.enabled = false;
gameManager.GetComponent<GameManager>().EndGame();
}
}
Note about the OnTriggerEnter: In case you only have the player moving in the scene this is fine like this (I use the same pattern you used in EndGame),
but in case there were other GameObject with a RigidBody moving in the
scene you should check if other is indeed the player. Usually tagging the player and the checking if(other.tag == "Player")