Unity Unexpected Sound Behavior - c#

Im taking a Unity C# course on Udemy, and we got to an challenge and i came up with a very simple "game". My problem is i can't figure out why no sound is playing? I looked at the instructors code and is the same as my (or did i just miss something?)
When i press on space the rocket starts flying (this works) and should play sound (it doesnt). Yes i got a SoundListener attached to the main camera.
Can somebody help and explain me where i missed something?
Here is my code that i wrote:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rocket : MonoBehaviour
{
Rigidbody rigidBody;
AudioSource audioSource;
// Use this for initialization
void Start()
{
rigidBody = GetComponent<Rigidbody>();
audioSource = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
ProcessInput();
}
private void ProcessInput()
{
if (Input.GetKey(KeyCode.Space)) // can thrust while rotating
{
rigidBody.AddRelativeForce(Vector3.up);
if (!audioSource.isPlaying) // so it doesn't layer
{
audioSource.Play();
}
}
else
{
audioSource.Stop();
}
if (Input.GetKey(KeyCode.A))
{
transform.Rotate(Vector3.forward);
}
else if (Input.GetKey(KeyCode.D))
{
transform.Rotate(-Vector3.forward);
}
}
}

Solved it after after declaring the audioSource to public

Related

Doors in Unity Mp Networking

I’ve been struggling for the past 8 hours to make my door work in multiplayer. With the code I have, i can use the door in singleplayer and in mp only the host can trigger the door animation and walk through it, other players can neither walk through it or even open it. I figured out i have to connect the door to the network.
I’m using mirror into my project and I’ve tried a lot of fixes but noone seem to work. I’ve tried usinc RPC’s, commands, authority, but can’t get it to work even using chat gpt so i tought to try asking a real human. I ve pasted my working code for single player down below, if anyone has any idea, everything is greatly appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DoorScript : MonoBehaviour
{
[Header("MaxDistance you can open or close the door.")]
public float MaxDistance = 5;
public AudioClip openSound;
public AudioClip closeSound;
private bool opened = false;
private Animator anim;
private Camera playerCamera;
private AudioSource audioSource;
void Start()
{
// Find the player object by tag and get the camera component from it
GameObject player = GameObject.FindGameObjectWithTag("Bosu");
if (player != null)
{
playerCamera = player.GetComponentInChildren<Camera>();
}
// Get the AudioSource component from the same game object as the DoorScript
audioSource = GetComponent<AudioSource>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
Pressed();
}
}
void Pressed()
{
RaycastHit doorhit;
if (Physics.Raycast(playerCamera.transform.position, playerCamera.transform.forward, out doorhit, MaxDistance))
{
if (doorhit.transform.tag == "Door")
{
anim = doorhit.transform.GetComponentInParent<Animator>();
opened = !opened;
anim.SetBool("Opened", opened);
// Play the open or close sound based on the current state of the door
if (opened)
{
audioSource.PlayOneShot(openSound);
}
else
{
Invoke("PlayCloseSound", 0.6f);
}
}
}
}
void PlayCloseSound()
{
audioSource.PlayOneShot(closeSound);
}
}

Player movement doesn't work after reloading the scene in Unity

Using Unity 2021.3.16f1.
I followed this tutorial from Brackeys to make the pause menu for my flappybird like game, my player movement stops working after I exit the main game to the main menu and return to the game.
Part of player code responsible for movement:
public class birdScript : MonoBehaviour
{
public Rigidbody2D myRigidbody;
public float flapStrength;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
myRigidbody.velocity = Vector2.up * flapStrength;
FindObjectOfType<AudioManager>().Play("jump");
}
}
}
Part of pause menu code responsible for loading the main menu scene:
using UnityEngine.SceneManagement;
public class pauseMenu : MonoBehaviour
{
public static bool gameIsPaused = false;
public GameObject pauseMenuUI;
public void loadMenu()
{
Time.timeScale = 1f;
SceneManager.LoadScene("Title");
}
}
Part of code responsible for loading the main game scene:
using UnityEngine.SceneManagement;
public class playButton : MonoBehaviour
{
public void loadLevel()
{
SceneManager.LoadScene("Main game");
}
}
I tried changing the play button code that loads the main game, in the scene hierarchy my main menu scene is 0 and my main game scene is 1. The play button is on the main menu.
I turned this
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
Into this
SceneManager.LoadScene("Main game");
But nothing happened, I tried searching on google but I have no idea how to search for the right answers.
Your problem has nothing to do with scene loading. That said your code for loading level is fine as it was:
using UnityEngine.SceneManagement;
public class playButton : MonoBehaviour
{
public void loadLevel()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
}
Issue could be in your pauseMenu script but you only provided a part of the code. You need to make sure your Time.timeScale is set to 1f when the level scene is loaded.
I would suggest setting the default value for flapStrength. Also in void Start there is Time.timeScale set to 1f just to be sure. You could do this in the pauseMenu script.
public class birdScript : MonoBehaviour
{
public Rigidbody2D myRigidbody;
public float flapStrength = 10f;
void Start()
{
Time.timeScale = 1f;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
myRigidbody.velocity = Vector2.up * flapStrength;
FindObjectOfType<AudioManager>().Play("jump");
}
}
}
I hope the answer helped. The issue is that the problem could be anywhere. It is necessary to go through all the values and examine the behavior of the player. Didn't an error appear that would stop the game? If the problem persists, you would need to edit the question and add more information.

Unity problem activating a function with parameters in camera from another script in GameObject Enemy

I have a script that makes the camera do a shake by putting a button because
It is a public access function, if I do it that way when placing a button it works well but what I cannot achieve is to call the function so that every time my player collides with an enemy he makes the shake. I hope you can help me.
The shake code in camera is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScreenShaker : MonoBehaviour {
private float shakeAmount = 0.5f;
private float shakeTime = 0.0f;
private Vector3 initialPosition;
private bool isScreenShaking = false;
void Update () {
if(shakeTime > 0)
{
this.transform.position = Random.insideUnitSphere * shakeAmount + initialPosition;
shakeTime -= Time.deltaTime;
}
else if(isScreenShaking)
{
isScreenShaking = false;
shakeTime = 0.0f;
this.transform.position = initialPosition;
}
}
public void ScreenShakeForTime(float time)
{
initialPosition = this.transform.position;
shakeTime = time;
isScreenShaking = true;
}
}
The enemy code is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ControladorEnemigoCirculoMediano : MonoBehaviour
{
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
Here I don't know what to call the public void function ScreenShakeForTime (float time);
I already tried many things online but when my character comes into contact with the character, I don't do the shake in the camera.
}
}
}
You can create Unity-singleton in your ScreenShaker class like:
class ScreenShaker
{
public static ScreenShaker Instance {private set; get;};
void Awake() {
Instance = this;
}
}
And than from any place to call like:
ScreenShaker.Instance.ScreenShakeForTime(2f);
This is the easiest way, but maybe it's better to create standard singeleton(it's up to you).
And also don;t forget to destroy it on OnDestroy()
can you tell me in enemy game object collider isTrigger is enable or not
if it is not enable then use OnColliderEnter2D(Collision2D other){} for collision detection

CollisionOnEnter how to detect if an object is colliding?

im pretty new to C# and Unity and i try to make an Angry Birds clone, and im stuck on this problem.
I want to change the mass of the mass of the Gameobject(in my case the woodblock) when the bird is flying and hits the object, it should change from Mass: 1 to Mass: 0.2
here is a screenshot of the scene
I created two Methods and it works in a weird way but every time i start the game the Mass gets not to 1 rather in 0.2. It should only change when the bird collides with the woodblock.
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Wall : MonoBehaviour
private float wallMass;
private bool isHit;
private Rigidbody2D rb;
void Start()
{
rb = gameObject.GetComponent<Rigidbody2D>();
wallMass = 1.0f;
isHit = false;
}
void Update()
{
CollisionOn(isHit);
}
private void CollisionOn(bool isTrue)
{
rb.GetComponent<Rigidbody2D>().mass = wallMass;
if (isTrue)
{
DecreaseMass();
}
}
void DecreaseMass()
{
rb.GetComponent<Rigidbody2D>().mass = 0.2f;
}
Use these 2 events on a MonoBehaviour, that's attached to the box.
Called when collision occurs
void OnCollisionEnter2D(Collision2D col)
{
GetComponent<Rigidbody2D>().mass = wallMass;
}
Same way when Collision ends.
void OnCollisionExit2D(Collision2D other)
{
GetComponent<Rigidbody2D>().mass = 0.2f;
}

Movetowards , Addforce , translate none is working why?

I just want to move a bullet (but it doesn't work) and test on cube (but the code too did not move the cube).
The commented codes also did not move the game object.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movetest : MonoBehaviour
{
//public GameObject cube;
// Use this for initialization
public GameObject testmovecube;
public Rigidbody rb;
void Start () {
//testmovecube = this.GetComponent<GameObject>();
//rb = testmovecube.GetComponent<Rigidbody>();
move();
//
}
// Update is called once per frame
void Update () {
}
private void move()
{
testmovecube.transform.position =
Vector3.MoveTowards(transform.position, new Vector3(226, 1, 226) , 2);
//transform.Translate(Vector3.forward);
//rb.AddForce(Vector3.forward);
}
}
Please any help is appreciated.

Categories

Resources