there is an animation where the player dances when he presses the button, but this is only visible to the player, other users cannot see it, where am I going wrong?
public Animator anim;
[SyncVar] public int animasyonid = 0;
void Start()
{
anim = gameObject.GetComponent<Animator>();
}
void Update()
{
if (isLocalPlayer)
{
if (Input.GetKeyDown(KeyCode.Alpha1))
{
animasyonid = 1;
}
if (animasyonid == 0)
{
anim.Play("Grounded");
}
else if (animasyonid == 1)
{
anim.Play("Hiphophu");
}
}
Related
I wanted to add multiplayer to my game but i quickly faced many many problems, i cant find any clear solution online. i made a weapon script where the player can shoot and reload.
problems:
when i shoot, on 1 screen both players shoot, but at the other screen nothing happens
when i swap weapons, on 1 screen both players swap weapons, on the second screen nothing happens
note: im still a complete beginner so go easy on me please :)) thanks!
weapon script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using Photon.Pun;
public class weaponScript : MonoBehaviour
{
public weaponSO weaponStats;
public GameObject reloadingText;
public TMP_Text ammoValue;
public Transform firePoint;
public GameObject bulletPrefab;
public float bulletForce = 2f;
public bool isShooting;
public float pistolDamage;
public int currentAmmoClip = 1;
public int maxAmmoClip;
public int currentReserve = 1;
public int maxReserve;
public float reloadTime = 2f;
public bool isReloading = false;
public int bulletsShot;
public float startingDamage;
PhotonView view;
public void Start()
{
view = GetComponent<PhotonView>();
if(view.IsMine)
{
view.RPC("Update", RpcTarget.AllBuffered);
}
WeaponStats();
currentAmmoClip = maxAmmoClip;
currentReserve = maxReserve;
bulletsShot = maxAmmoClip - currentAmmoClip;
isShooting = false;
weaponStats.damage = startingDamage;
}
[PunRPC]
public void Update()
{
ammoValue.text = currentAmmoClip.ToString("0") + "/" + currentReserve.ToString("0");
if (Input.GetKeyDown(KeyCode.R))
{
if(currentReserve <= 0)
{
return;
}
if (currentAmmoClip == maxAmmoClip && !isReloading)
{
return;
}
else
{
StartCoroutine(Reload());
return;
}
}
if(Input.GetButtonDown("Fire1") && currentAmmoClip >= 1)
{
if(isReloading == false)
{
bulletsShot += 1;
currentAmmoClip -= 1;
isShooting = true;
Shoot();
FindObjectOfType<AudioManager>().Play("shot1");
return;
}
}
if(isReloading)
return;
if(currentAmmoClip <= 0 && currentReserve >= 1)
{
StartCoroutine(Reload());
return;
}
}
IEnumerator Reload()
{
reloadingText.SetActive(true);
isReloading = true;
yield return new WaitForSeconds(reloadTime);
if(currentReserve <= bulletsShot)
{
currentAmmoClip += currentReserve;
currentReserve = 0;
}
else
{
currentReserve -= bulletsShot;
currentAmmoClip = maxAmmoClip;
}
bulletsShot = 0;
reloadingText.SetActive(false);
isReloading = false;
}
void Shoot()
{
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.AddForce(firePoint.up * bulletForce, ForceMode2D.Impulse);
}
public void WeaponStats()
{
pistolDamage = weaponStats.initialDamage;
maxAmmoClip = weaponStats.maxAmmoClip;
maxReserve = weaponStats.maxReserve;
reloadTime = weaponStats.reloadTime;
bulletForce = weaponStats.bulletForce;
startingDamage = weaponStats.initialDamage;
}
}
weapon holder:
using UnityEngine;
public class WeaponHolder : MonoBehaviour
{
public int selectedWeapon = 0;
void Start()
{
SelectWeapon();
}
void Update()
{
if(FindObjectsOfType<weaponScript>()[0].isReloading == true)
{
return;
}
else
{
switchWeapon();
}
}
public void switchWeapon()
{
int previousSelectedWeapon = selectedWeapon;
if(Input.GetAxis("Mouse ScrollWheel") > 0f)
{
if(selectedWeapon >= transform.childCount - 1)
{
selectedWeapon = 0;
}
else
{
selectedWeapon++;
}
}
if(Input.GetAxis("Mouse ScrollWheel") < 0f)
{
if(selectedWeapon <= 0)
{
selectedWeapon = transform.childCount - 1;
}
else
{
selectedWeapon--;
}
}
if(previousSelectedWeapon != selectedWeapon)
{
SelectWeapon();
}
}
public void SelectWeapon()
{
int i = 0;
foreach (Transform weapon in transform)
{
if(i == selectedWeapon)
{
weapon.gameObject.SetActive(true);
}
else
{
weapon.gameObject.SetActive(false);
}
i++;
}
}
}
i tried adding
if(view.IsMine == true)
{
Debug.Log("true");
}
else
{
Debug.Log("false");
}
but nothing happened and i couldnt shoot anymore. thanks for reading
The problem is you don't sync anything in your game. This means the other computer can't know what it has to do.
Whenever you want to sync something you have to call an RPC function.
Maybe watch some tutorials about how to do this properly and how to set up a simple multiplayer lobby.
EDIT:
What the other comments above mentioned with .IsMine is true, but you're doing it wrong. You have to call this in start or awake and whenever the view is not yours you disable the camera of the person only and disable shooting. Its important to only do this on your computer! If you are not doing everyone will shoot when you press Shoot and everyone will walk when you walk.
I hope you could help me. I want my enemy object to stop after a few seconds, and then move on after another few seconds. So far everything works, but the objects jump into the top right corner a few seconds after they are stopped. Can you give me some tips on what I did wrong and how I can do it better.
Ball Control script :
public class Ball_Controller : MonoBehaviour
{
public Rigidbody2D rb;
public float ballForce;
public Rigidbody2D rbtwo;
public loselevel lose;
public float moving;
public startMovement startMove;
private bool isMoving = false;
private void Start()
{
lose = GameObject.FindObjectOfType<loselevel>();
rb = GetComponent<Rigidbody2D>();
moving = transform.position.x;
startMove = GameObject.FindObjectOfType<startMovement>();
}
public void Update()
{
if (moving < transform.position.x)
{
StartCoroutine(stopMovement());
isMoving = true;
}
if (isMoving == true )
{
isMoving = false;
startMove.beginnMovement();
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag.Equals("Player"))
{
Destroy(gameObject);
Destroy(GameObject.FindWithTag("Player"));
lose.startFinish();
}
}
public void BallControll()
{
rb.AddForce(new Vector2(ballForce, ballForce));
rbtwo.AddForce(new Vector2(ballForce, ballForce));
}
public IEnumerator stopMovement()
{
yield return new WaitForSeconds(4f);
rb.velocity = Vector2.zero;
Debug.Log("Stop moving");
}
}
Script to start the enemy after stop:
public class startMovement : MonoBehaviour
{
public Ball_Controller bc;
// Start is called before the first frame update
void Start()
{
bc = GameObject.FindObjectOfType<Ball_Controller>();
}
// Update is called once per frame
void Update()
{
}
public IEnumerator beginMovement()
{
yield return new WaitForSeconds(10f);
bc.BallControll();
Debug.Log("start moving");
}
public void beginnMovement()
{
StartCoroutine(beginMovement());
}
}
I'm creating a FPS game and I have the following issue:
Sometimes, when I shoot at the enemies the hit is not recognized, even if the player is shooting in front of them. However, when they attack the player, the hit is recognized normally.
They have a box collider and a rigidbody attached to them.
This script is attached to the player:
using System.Collections.Generic;
using UnityEngine;
public class DisparaArma : MonoBehaviour
{
private GerenciaArma gerenciaArma;
public float nDisparo = 15f;
private float TempoProximoDisparo;
public float damage = 20f;
private Animator ZoomCameraIn;
private bool zoomed;
private Camera Maincamera;
private GameObject mira;
// Start is called before the first frame update
void Start()
{
gerenciaArma = GetComponent<GerenciaArma>();
ZoomCameraIn = transform.Find(Tags.LOOK_ROOT).transform.Find(Tags.ZOOM_CAMERA).GetComponent<Animator>();
mira = GameObject.FindWithTag(Tags.MIRA);
Maincamera = Camera.main;
}
// Update is called once per frame
void Update()
{
Atira();
ZoomInAndOut();
}
void Atira()
{
if (Input.GetMouseButtonDown(0))
{
if(gerenciaArma.SelecionaArma().tipoBala == WeaponBulletType.BULLET)
{
gerenciaArma.SelecionaArma().AnimacaoTiro();
DisparaBala();
}
}
}
void ZoomInAndOut()
{
if (gerenciaArma.SelecionaArma().mira_tipo == TipoMira.AIM)
{
if (Input.GetMouseButtonDown(1))
{
ZoomCameraIn.Play(Animacoes.ZOOM_IN_ANIM);
// gerenciaArma.SelecionaArma().Aim(true);
mira.SetActive(false);
print("VaiZoom");
}
if (Input.GetMouseButtonUp(1))//
{
ZoomCameraIn.Play(Animacoes.ZOOM_OUT_ANIM);
//gerenciaArma.SelecionaArma().Aim(false);
mira.SetActive(true);
}
}
}
void DisparaBala()
{
RaycastHit hit;
if(Physics.Raycast(Maincamera.transform.position, Maincamera.transform.forward, out hit))
{
if (hit.transform.tag == Tags.ENEMY_TAG)
{
hit.transform.GetComponent<ScriptVida>().DanoAplicado(damage);
}
}
}
}
And this one is attached to the enemies:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class ScriptVida : MonoBehaviour
{
private IndioAnimações indio_Anim;
private NavMeshAgent navAgent;
private IndioController indio_Controller;
public float vida = 100f;
public bool is_Player, is_Cannibal, is_Tiger;
private bool morto;
// Start is called before the first frame update
void Awake()
{
if (is_Tiger || is_Cannibal)
{
indio_Anim = GetComponent<IndioAnimações>();
indio_Controller = GetComponent<IndioController>();
navAgent = GetComponent<NavMeshAgent>();
}
if (is_Player)
{
}
}
public void DanoAplicado(float damage)
{
if (morto)
return;
vida -= damage;
if (is_Player)
{
}
if (is_Tiger || is_Cannibal)
{
if (indio_Controller.EnemyState == EnemyState.PATROL)
{
indio_Controller.chase_Distance = 50f;
}
}
if (vida <= 0)
{
JogadorMorre();
morto = true;
print(vida);
}
}
void JogadorMorre()
{
if (is_Cannibal)//
{
GetComponent<Animator>().enabled = false;
GetComponent<BoxCollider>().isTrigger = false;
GetComponent<Rigidbody>().AddTorque(-transform.forward * 50f);
indio_Controller.enabled = false;
navAgent.enabled = false;
indio_Anim.enabled = false;
}
if (is_Tiger)
{
GetComponent<Animator>().enabled = false;
GetComponent<BoxCollider>().isTrigger = false;
GetComponent<Rigidbody>().AddTorque(-transform.forward * 50f);
indio_Controller.enabled = false;
navAgent.enabled = false;
indio_Anim.enabled = false;
}
if (is_Player)
{
GameObject[] enemies = GameObject.FindGameObjectsWithTag(Tags.ENEMY_TAG);
for (int i = 0; i < enemies.Length; i++)
{
enemies[i].GetComponent<IndioController>().enabled = false;
}
GetComponent<Movimentação>().enabled = false;
GetComponent<DisparaArma>().enabled = false;
GetComponent<GerenciaArma>().SelecionaArma().gameObject.SetActive(false);
}
if (tag == Tags.PLAYER_TAG)
{
Invoke("RestartGame", 3f);
}
else
{
Invoke("TurnOffGameObject", 3f);
}
}
void RestartGame()
{
UnityEngine.SceneManagement.SceneManager.LoadScene("Gameplay");
}
void TurnOffGameObject()
{
gameObject.SetActive(false);
}
}
I think the problem is related to the box collider.
How could I solve this guys?
Enemy character not moving to the 3rd waypoint. After moving to waypoint 2 it just stops and the idle animation plays. The character has a NavMeshAgent on it and it looks like the destination reached event is not being triggered when he gets to the waypoint. If anyone has had a situation like this before I would appreciate any information possible. I have been trying to figure out whats wrong for a few hours now and am starting to think it might not be any of the scripts.
here is the waypoint controller
using UnityEngine;
using UnityEngine.AI;
public class WaypointController : MonoBehaviour {
Waypoints[] waypoints;
public Transform target;
//NavMeshPath path;
int currentWaypointIndex = -1;
//private NavMeshAgent agent;
//EnemyCharacter enemy;
public event System.Action<Waypoints> OnWaypointChanged;
// Use this for initialization
void Awake () {
waypoints = GetWaypoints();
}
public void SetNextWaypoint() {
if (currentWaypointIndex != waypoints.Length)
currentWaypointIndex++;
if (currentWaypointIndex == waypoints.Length)
currentWaypointIndex = 0;
if (OnWaypointChanged != null)
OnWaypointChanged(waypoints[currentWaypointIndex]);
//Debug.Log("OnWaypointChanged == null: " + (OnWaypointChanged == null));
//Debug.Log("OnWaypointChanged != null: " + (OnWaypointChanged != null));
}
Waypoints[] GetWaypoints()
{
return GetComponentsInChildren<Waypoints>();
}
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Vector3 previousWaypoint = Vector3.zero;
foreach (var waypoint in GetWaypoints())
{
Vector3 waypointPosition = waypoint.transform.position;
Gizmos.DrawWireSphere(waypointPosition, .2f);
if (previousWaypoint != Vector3.zero)
Gizmos.DrawLine(previousWaypoint, waypointPosition);
previousWaypoint = waypointPosition;
}
}
}
Here is the EnemyPatrolPoints script
using UnityEngine;
[RequireComponent(typeof(AI_PathFinder))]
public class EnemyPatrolPoints : MonoBehaviour {
[SerializeField]
WaypointController waypointController;
[SerializeField]
float waitTimeMin;
[SerializeField]
float waitTimeMax;
AI_PathFinder pathfinder;
private void Start()
{
waypointController.SetNextWaypoint();
}
private void Awake()
{
pathfinder = GetComponent<AI_PathFinder>();
pathfinder.OnDestinationReached += Pathfinder_OnDestinationReached;
waypointController.OnWaypointChanged += WaypointController_OnWaypointChanged;
}
private void WaypointController_OnWaypointChanged(Waypoints waypoint)
{
pathfinder.SetTarget(waypoint.transform.position);
print("waypoint changed");
}
private void Pathfinder_OnDestinationReached()
{
SealForce_GameManager.Instance.Timer.Add(waypointController.SetNextWaypoint, Random.Range(waitTimeMin, waitTimeMax));
print("destination reached");
}
}
Here is the AI Pathfinder script`
using UnityEngine;
using UnityEngine.AI;
[RequireComponent(typeof(NavMeshAgent))]
public class AI_PathFinder : MonoBehaviour
{
[HideInInspector]
public NavMeshAgent agent;
public EnemyPatrolPoints enemyPatrolPoints;
[SerializeField] float distanceRemainingThreshold;
bool m_destinationReached;
bool destinationReached
{
get
{ return m_destinationReached; }
set
{
m_destinationReached = value;
if (m_destinationReached)
{
if (OnDestinationReached != null)
OnDestinationReached();
}
}
}
public event System.Action OnDestinationReached;
void Start()
{
agent = GetComponent<NavMeshAgent>();
//enemyPatrolPoints = GetComponent<EnemyPatrolPoints>();
}
public void SetTarget(Vector3 target)
{
agent.SetDestination(target);
}
void Update()
{
if (destinationReached)
return;
if (agent.remainingDistance < distanceRemainingThreshold)
destinationReached = true;
}
}
The lines
if (agent.remainingDistance < distanceRemainingThreshold)
destinationReached = true;
are never reached as long as destinationReached is true because of
if (destinationReached)
return;
You are setting it to true after the first waypoint is reached and then never reset it to false so your Update is always skipped in the future.
You should add it e.g. to
public void SetTarget(Vector3 target)
{
agent.SetDestination(target);
destinationReached = false;
}
I am unable to send commands from my gun prefabs in my game. How can I send commands from non-player game objects? Every time I try to send a command, I get an error. I do not want to move my shooting scripts from my guns to my player, as this method will require me to change my game drastically.
My Shooting Script:
[Command]
void CmdOpenFire(){
if (Physics.Raycast(camTransform.TransformPoint(startPosition), camTransform.forward, out hit, range)){
gunsMasterScript.CallEventShotDefault(hit.point, hit.transform);
if (hit.transform.parent != null) {
if (hit.transform.parent.CompareTag ("Enemy")) {
gunsMasterScript.CallEventShotEnemy (hit.point, hit.transform.parent);
}
}
if (hit.transform.tag == "Player") {
gunsMasterScript.CallEventShotEnemy (hit.point, hit.transform);
}
}
}
My shooting Detection script:
public PlayerManager_AmmoBox localPlayerTester;
public GunsManager_GunsAmmo gunsAmmo;
public GunsManager_GunsMaster gunMaster;
float nextAttack;
public float attackRate = 0.5f;
Transform myTransform;
public bool isAutomatic = true;
public bool hasBurstFire;
bool isBurstFireActive;
public string attackButtonName;
public string reloadButtonName;
public string burstFireButtonName;
NetworkIdentity netID;
// Use this for initialization
void OnEnable () {
if (transform.root != null) {
if (transform.root.GetComponent<PlayerManager_AmmoBox> () != null) {
localPlayerTester = transform.root.GetComponent<PlayerManager_AmmoBox> ();
}
}
SetInitialReferences ();
}
// Update is called once per frame
void Update () {
if (localPlayerTester != null) {
CheckIfWeaponShouldAttack ();
CheckForReloadRequest ();
CheckForBurstFireToggle ();
}
}
void SetInitialReferences(){
netID = GetComponent<NetworkIdentity> ();
myTransform = transform;
gunMaster = transform.GetComponent<GunsManager_GunsMaster> ();
gunsAmmo = transform.GetComponent<GunsManager_GunsAmmo> ();
gunMaster.isGunLoaded = true;
}
void CheckIfWeaponShouldAttack(){
if (gunMaster != null) {
if (Time.time > nextAttack && Time.timeScale > 0 && myTransform.root.CompareTag ("Player") && gunMaster.isGunLoaded) {
if (isAutomatic && !isBurstFireActive) {
if (Input.GetButton (attackButtonName)) {
AttemptAttack ();
}
} else if (isAutomatic && isBurstFireActive) {
if (Input.GetButtonDown (attackButtonName)) {
StartCoroutine (RunBurstFire ());
}
} else if (!isAutomatic) {
if (Input.GetButton (attackButtonName)) {
AttemptAttack ();
}
}
}
}
}
void AttemptAttack(){
nextAttack = Time.time + attackRate;
if (gunMaster.isGunLoaded) {
gunMaster.CallEventPlayerInput ();
} else {
gunMaster.CallEventGunNotUsable ();
}
}