I hope you are having a good day. Today on 30/08/2022 I sat down to work on my game in unity 2021.3.6f1 on my ubuntu 20.04 computer and all the audio was on playing I made new sound tracks but, the sound tracks still didn't play at all. If anyone knows how to fix it plz help.
The sound manager code I use is:
using System;
using UnityEngine;
using UnityEngine.Audio;
public class AudioManager : MonoBehaviour
{
public Sound[] sounds;
private void Awake() {
foreach (Sound s in sounds) {
s.source = gameObject.AddComponent<AudioSource>();
s.source.clip = s.clip;
s.source.volume = s.volume;
s.source.pitch = s.pitch;
s.source.loop = s.loop;
}
}
public void Play(string name) {
Sound soundToPlay = Array.Find(sounds, sound => sound.name == name);
soundToPlay.source.Play();
}
}
The "Sound" class code:
using System;
using UnityEngine;
using UnityEngine.Audio;
[System.Serializable]
public class Sound {
public string name;
public AudioClip clip;
[Range(0f, 1f)]
public float volume = 1f;
[Range(1f, 3f)]
public float pitch = 1f;
[HideInInspector]
public AudioSource source;
public bool loop = false;
}
Make sure that the Audio Icon is not clicked. And make sure that this is not getting set to off when the game is running. If all the code is working, I would guess its this.
Related
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);
}
}
I want to have a background music to play seamlessly from “Scene1” to “Scene2” but I want the music to change if I load “Scene3” or “Scene4” (which should have the same behavior). How can I achieve this?
First your music playing gameobject should be using DontDestroyOnLoad functionality, so the music player does not destroy when the scene changes. If you're not using it, read about it here : https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html
After that, the music player could use SceneManager to decide if it should switch the track or not on scene change.
There is a solution for this in Unity forums SOLUTION
using UnityEngine;
public class MusicClass : MonoBehaviour
{
private AudioSource _audioSource;
private void Awake()
{
DontDestroyOnLoad(transform.gameObject);
_audioSource = GetComponent<AudioSource>();
}
public void PlayMusic()
{
if (_audioSource.isPlaying) return;
_audioSource.Play();
}
public void StopMusic()
{
_audioSource.Stop();
}
}
If you want it to change after just change the audio clip like HERE
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(AudioSource))]
public class ExampleClass : MonoBehaviour
{
public AudioClip otherClip;
IEnumerator Start()
{
AudioSource audio = GetComponent<AudioSource>();
audio.Play();
yield return new WaitForSeconds(audio.clip.length);
audio.clip = otherClip;
audio.Play();
}
}
I am trying to implement a shader that makes things darker the further from the camera they are,the way it works underwater, but when I try to work with the camera depth ,I get "error CS0103: The name 'depthTextureMode' does not exist in the current context".
This is the code I tried to run
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode,ImageEffectAllowedInSceneView]
public class FogEffect : MonoBehaviour
{ public Material _mat;
void Start()
{
GetComponent<Camera>().depthTextureMode = depthTextureMode.Depth;
}
void Update()
{
}
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
Graphics.Blit(source,destination,_mat);
}
}
DepthTextureMode is an enum and the first letter needs to be uppercase.
This compiled and run without issues on my machine.
using UnityEngine;
public class FogEffect : MonoBehaviour
{
void Start()
{
GetComponent<Camera>().depthTextureMode = DepthTextureMode.Depth;
}
}
in photon the first person to join can see both players but second to join cant see the first. anyone know why?
connect to server script
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using UnityEngine.SceneManagement;
public class Connecttoserver : MonoBehaviourPunCallbacks
{
private void Start()
{
PhotonNetwork.ConnectUsingSettings();
}
public override void OnConnectedToMaster()
{
PhotonNetwork.JoinLobby();
}
public override void OnJoinedLobby()
{
PhotonNetwork.JoinRoom("Server");
}
public override void OnJoinedRoom()
{
SceneManager.LoadScene("Game");
}
public override void OnJoinRoomFailed(short returnCode, string message)
{
Debug.Log(message);
PhotonNetwork.CreateRoom("Server");
}
}
spawn players script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class spawnplayers : MonoBehaviour
{
public GameObject playerprefab;
public float minx, maxx, minz, maxz;
private void Start()
{
Vector3 randompos = new Vector3(Random.Range(minx,maxx),1,Random.Range(minz,maxz));
GameObject myPlayerGO = (GameObject)PhotonNetwork.Instantiate(playerprefab.name, randompos, Quaternion.identity);
myPlayerGO.GetComponent<playermovement>().enabled = true;
myPlayerGO.GetComponentInChildren<CameraLook>().enabled = true;
myPlayerGO.GetComponentInChildren<Camera>().enabled = true;
}
}
Screen 1
Screen 2
Anybody know a solution?? I have been trying to solve this for days but to no success
what ive tried
adding heaps of debug logs
adding photonview and transform
crying myself to sleep
Make sure both clients are connected to the same server (Region if Photon Cloud) and to the same Virtual Application (if Photon Cloud). You could make use of SupportLogger. Check Matchmaking Checklist.
Use PhotonNetwork.LoadLevel instead of SceneManager.LaodLevel.
Also, you could make use of JoinOrCreateRoom method as a shortcut instead of trying to join then creating one.
I would start by finishing PUN Basics Tutorial first or following one of YouTube tutorials about PUN.
When players join map, use PhotonNetwork.LoadLevel("SceneName") instead of SceneManager.LoadScene("SceneName").
I am trying to create a simple dialogue system for my game in Unity. I've set up a special trigger for a Dialogue to start and the code is passing right variable but somehow it gets stuck at clearing the queue and throws a NullReferenceException.
I've seen through debugger that all variables and triggers work perfectly fine till cs:27 inside DialogueManager.cs. I've also checked the inspector to make sure everything is correctly assigned.
Dialogue class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Dialogue
{
public string name;
[TextArea(3,10)]
public string[] sentences;
}
DialogueTrigger class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NPC_DialogTrigger : MonoBehaviour
{
// Player
public Transform player;
// GameMaager to close
public GameObject Gameplay;
// Camera and Canvas to turn on
public GameObject DialogueManager;
// NPC Details
public GameObject InteractionNPCNameTextField;
public Transform interactionTransform;
public float radius = 3f;
private bool isBusy = false;
// DialogueStart
public GameObject DialogueStart;
void Start()
{
InteractionNPCNameTextField.gameObject.SetActive(false);
}
void Update()
{
float distance = Vector3.Distance(player.position, interactionTransform.position);
if (distance <= radius)
{
if (isBusy == false)
{
InteractionNPCNameTextField.gameObject.SetActive(true);
if (Input.GetKeyDown(KeyCode.E))
{
Dialogue();
Debug.Log("Started Dialogue procedure.");
}
}
}
else if (distance > radius)
{
InteractionNPCNameTextField.gameObject.SetActive(false);
}
}
public void Dialogue()
{
Gameplay.SetActive(false);
DialogueManager.SetActive(true);
DialogueStart.GetComponent<DialogueStart>().TriggerDialogue();
Debug.Log("Triggered Dialogue.");
}
void OnDrawGizmosSelected()
{
if (interactionTransform == null)
{
interactionTransform = transform;
}
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(interactionTransform.position, radius);
}
}
DialogueStart class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DialogueStart : MonoBehaviour
{
public Dialogue dialogue;
public void TriggerDialogue()
{
FindObjectOfType<DialogueManager>().StartDialogue(dialogue);
Debug.Log("Dialogue sent to dialogue manager.");
}
}
DialogueManager class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class DialogueManager : MonoBehaviour
{
public Text nameText;
public Text DialogueText;
private Queue<string> sentences;
public GameObject DialogueManagerUI;
void Start()
{
if (sentences == null)
{
sentences = new Queue<string>();
}
}
public void StartDialogue (Dialogue dialogue)
{
Debug.Log("Received dialogues: " + dialogue);
nameText.text = dialogue.name;
Debug.Log("Start Dialogue: " + sentences.Count);
sentences.Clear();
Debug.Log("Sentences Cleared: " + sentences);
foreach (string sentence in dialogue.sentences)
{
sentences.Enqueue(sentence);
}
DisplayNextSentence();
}
public void DisplayNextSentence()
{
if(sentences.Count == 0)
{
EndDialogue();
return;
}
string sentence = sentences.Dequeue();
DialogueText.text = sentence;
}
void EndDialogue()
{
Debug.Log("End of conversation.");
}
private void Update()
{
if (DialogueManagerUI.activeInHierarchy)
{
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
else if (!DialogueManagerUI.activeInHierarchy)
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
}
}
Visual Studio doesn't give me any errors.
Unity error code -> Screenshot
Debugger right before issue -> Screenshot2
Seems to me like the Queue is never assigned to sentences and it remains empty.
If it is so - why?
It sounds like DialogueManager.StartDialogue probably via DialogueStart.TriggerDialogue is called from somewhere in either Awake or at least before your Start was executed.
Especially
DialogueManager.SetActive(true);
lets assume the DialogueManager object is inactive at first anyway. So maybe your stuff is called before it is set to active.
This might also be due to the Start where you set
InteractionNPCNameTextField.gameObject.SetActive(false);
so any component on this GameObject might not have its Start method getting called. Maybe you referenced the wrong GameObject here?
Debugging would help to figure out in which order your methods get called.
In general my thumb rule for initializing is
Do everything that depends only on yourself in Awake
Do everything that depends on other components being setup already in Start
This way you can (almost) always be sure that stuff is already initialized when you need it.
However, these are only guesses but
The simple solution here:
You could already solve this by simply initializing the sentences right away using
private readonly Queue<string> sentences = new Queue<string>();
now it is definitely initialized even before Start or Awake get called!