Doors in Unity Mp Networking - c#

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);
}
}

Related

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: Audio Manager for different scene music

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();
}
}

reference from various scripts causing problems [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 1 year ago.
For some reason when I'm in the normal view in-game I am able to link the scripts that I need to call in order to make an animation like so
however, whenever I start the game it automatically removes them from the slots, and it doesn't work
I am completely clueless as to why this may be happening and unity keep giving me errors that say that I'm not setting an instance to my script I really have no clue why this may be happening.
I have 3 scripts that I'm working with that is giving me the problem
one is the main script for the enemy vision (I am referencing the other scripts in this one)
the second is the enemy animation script which makes him go from idle to attack and the third is an animation for the gun model since I had to make it follow the hands of the enemy
scripts attached bellow
1st script(enemyAI):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyAi : MonoBehaviour
{
public bool detected;
GameObject target;
public Transform enemy;
public GameObject Bullet;
public Transform shootPoint;
public float shootSpeed = 10f;
public float timeToShoot = 1f;
public EnemyAni Animation;
public GunAni GunAnimation;
void Start()
{
Animation = GetComponent<EnemyAni>();
GunAnimation = GetComponent<GunAni>();
}
public void Update()
{
//makes the enemy rotate on one axis
Vector3 lookDir = target.transform.position - transform.position;
lookDir.y = 0f;
//makes enemy look at the players position
if (detected)
{
enemy.LookAt(target.transform.position, Vector3.up);
enemy.rotation = Quaternion.LookRotation(lookDir, Vector3.up);
}
if (detected == true)
{
Animation.LookPlayer = true;
GunAnimation.ShootPlayer = true;
}
if (detected == false)
{
Animation.LookPlayer = false;
GunAnimation.ShootPlayer = false;
}
}
//detects the player
void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
detected = true;
target = other.gameObject;
}
}
void OnTriggerExit(Collider other)
{
if (other.tag == "Player")
{
detected = false;
}
}
}
2nd Script (EnemyAnimation):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyAni : MonoBehaviour
{
public Animator animator;
public bool LookPlayer;
public void Start()
{
animator = GetComponent<Animator>();
}
public void Update()
{
if (LookPlayer == true)
{
animator.SetBool("IsShootingStill", true);
}
else
{
animator.SetBool("IsShootingStill", false);
}
}
}
3rd script (GunAnimation):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GunAni : MonoBehaviour
{
public Animator animator;
public bool ShootPlayer;
public void Start()
{
animator = GetComponent<Animator>();
}
public void Update()
{
if (ShootPlayer == true)
{
animator.SetBool("IsShooting", true);
}
else
{
animator.SetBool("IsShooting", false);
}
}
}
Your code:
void Start()
{
Animation = GetComponent<EnemyAni>();
GunAnimation = GetComponent<GunAni>();
}
Searches the GameObject that holds the EnemyAI script for EnemyAni and GunAni. If the GameObject doesn't have those it will return null.
Sounds like you want to remove that code.
Note that if the scripts exist on a child of that GameObject you will need to use GetComponentInChildren
There are some things to review, good practices:
GameObject target is private for C#, but it is better to put private before.
variable names like Bullet Animation GunAnimation should always begin with lowercase, because they might be confused with a Class Name (search in internet for CamelCase and PascalCase).
Name should be clear. EnemyAni Animation is not clear enough, because Animation maybe any animation (player, enemy, cube, car, etc.).
It is better enemyAnimation to be clear, as you did with GunAnimation (only just with lower case at beginning)
As slaw said, the Animation must be in the GO attached.
about last item
Let's say you have an empty GO (GameObject) called GameObject1 and you attach EnemyAi script to it.
In Runtime (when game mode begins), it will try to find Animation = GetComponent<EnemyAni>();, but it won't find it
Why?
Because GetComponent<> searches for the Component(Class) that is in the <> (in this case EnemyAni) in its GO (in this case, GameObject1), but the unique script attached to GameObject1 is EnemyAI.
So, you have 3 options:
Attach EnemyAni to GameObject1
Create another GO (for example, GameObjectEnemyAni), attach the script EnemyAni and drag and drop GameObjectEnemyAni to GameObject1 and delete Animation = GetComponent<EnemyAni>(); in Start
Keep in mind: if you leave that line of code, instead of getting the script EnemyAni from GameObjectEnemyAni, it will run the code Animation = GetComponent<EnemyAni>(); in Start, and obviously, it won't find it
Create events. It's a really good practice for avoiding code tight coupling, but that is more advanced stuff.

Unity Unexpected Sound Behavior

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

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;
}

Categories

Resources