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 ();
}
}
Related
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");
}
}
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?
I am building an app using ARKit for vertical plane detection.Once the plane is detected I need to turn off plane detection.Even after plane is detected it is still tracking and finding more planes.How to turn off when the plane is detected.
using System;
using System.Collections.Generic;
using UnityEngine.EventSystems;
namespace UnityEngine.XR.iOS
{
public class UnityARHitTestExample : MonoBehaviour
{
public Transform m_HitTransform;
public float maxRayDistance = 30.0f;
public LayerMask collisionLayer = 1 << 10; //ARKitPlane layer
public List<GameObject> Instaobj = new List<GameObject>();
public Transform ForSelect;
int Select;
UnityARCameraManager obj=new UnityARCameraManager();
UnityARGeneratePlane obb=new UnityARGeneratePlane();
bool HitTestWithResultType (ARPoint point, ARHitTestResultType resultTypes)
{
List<ARHitTestResult> hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface ().HitTest (point, resultTypes);
if (hitResults.Count > 0) {
foreach (var hitResult in hitResults) {
Debug.Log ("Got hit!");
obj.Hideplane();
// obb.planePrefab.SetActive(false);
m_HitTransform.position = UnityARMatrixOps.GetPosition (hitResult.worldTransform);
m_HitTransform.rotation = UnityARMatrixOps.GetRotation (hitResult.worldTransform);
Debug.Log (string.Format ("x:{0:0.######} y:{1:0.######} z:{2:0.######}", m_HitTransform.position.x, m_HitTransform.position.y, m_HitTransform.position.z));
return true;
}
}
return false;
}
// Update is called once per frame
void Update () {
#if UNITY_EDITOR //we will only use this script on the editor side, though there is nothing that would prevent it from working on device
if (Input.GetMouseButtonDown (0)) {
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
//we'll try to hit one of the plane collider gameobjects that were generated by the plugin
//effectively similar to calling HitTest with ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent
if (Physics.Raycast (ray, out hit, maxRayDistance, collisionLayer)) {
//we're going to get the position from the contact point
m_HitTransform.position = hit.point;
Debug.Log (string.Format ("x:{0:0.######} y:{1:0.######} z:{2:0.######}", m_HitTransform.position.x, m_HitTransform.position.y, m_HitTransform.position.z));
//and the rotation from the transform of the plane collider
m_HitTransform.rotation = hit.transform.rotation;
}
}
#else
if (Input.touchCount > 0 && m_HitTransform != null )
{
var touch = Input.GetTouch(0);
if ((touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Moved) && !EventSystem.current.IsPointerOverGameObject(touch.fingerId))
{
var screenPosition = Camera.main.ScreenToViewportPoint(touch.position);
ARPoint point = new ARPoint {
x = screenPosition.x,
y = screenPosition.y
};
// prioritize reults types
ARHitTestResultType[] resultTypes = {
//ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingGeometry,
ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent,
// if you want to use infinite planes use this:
//ARHitTestResultType.ARHitTestResultTypeExistingPlane,
//ARHitTestResultType.ARHitTestResultTypeEstimatedHorizontalPlane,
//ARHitTestResultType.ARHitTestResultTypeEstimatedVerticalPlane,
//ARHitTestResultType.ARHitTestResultTypeFeaturePoint
};
foreach (ARHitTestResultType resultType in resultTypes)
{
if (HitTestWithResultType (point, resultType))
{
return;
}
}
}
}
#endif
}
}
}
Below is the UnityARCameraManager
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.iOS;
public class UnityARCameraManager : MonoBehaviour {
public Camera m_camera;
private UnityARSessionNativeInterface m_session;
private Material savedClearMaterial;
[Header("AR Config Options")]
public UnityARAlignment startAlignment = UnityARAlignment.UnityARAlignmentGravity;
public UnityARPlaneDetection planeDetection = UnityARPlaneDetection.Horizontal;
public ARReferenceImagesSet detectionImages = null;
public bool getPointCloud = true;
public bool enableLightEstimation = true;
public bool enableAutoFocus = true;
private bool sessionStarted = false;
private ARKitWorldTrackingSessionConfiguration config;
// Use this for initialization
void Start () {
m_session = UnityARSessionNativeInterface.GetARSessionNativeInterface();
Application.targetFrameRate = 60;
//ARKitWorldTrackingSessionConfiguration config = new ARKitWorldTrackingSessionConfiguration();
config = new ARKitWorldTrackingSessionConfiguration();
config.planeDetection = planeDetection;
config.alignment = startAlignment;
config.getPointCloudData = getPointCloud;
config.enableLightEstimation = enableLightEstimation;
config.enableAutoFocus = enableAutoFocus;
if (detectionImages != null) {
config.arResourceGroupName = detectionImages.resourceGroupName;
}
if (config.IsSupported) {
m_session.RunWithConfig (config);
UnityARSessionNativeInterface.ARFrameUpdatedEvent += FirstFrameUpdate;
}
if (m_camera == null) {
m_camera = Camera.main;
}
}
void FirstFrameUpdate(UnityARCamera cam)
{
sessionStarted = true;
UnityARSessionNativeInterface.ARFrameUpdatedEvent -= FirstFrameUpdate;
}
public void SetCamera(Camera newCamera)
{
if (m_camera != null) {
UnityARVideo oldARVideo = m_camera.gameObject.GetComponent<UnityARVideo> ();
if (oldARVideo != null) {
savedClearMaterial = oldARVideo.m_ClearMaterial;
Destroy (oldARVideo);
}
}
SetupNewCamera (newCamera);
}
private void SetupNewCamera(Camera newCamera)
{
m_camera = newCamera;
if (m_camera != null) {
UnityARVideo unityARVideo = m_camera.gameObject.GetComponent<UnityARVideo> ();
if (unityARVideo != null) {
savedClearMaterial = unityARVideo.m_ClearMaterial;
Destroy (unityARVideo);
}
unityARVideo = m_camera.gameObject.AddComponent<UnityARVideo> ();
unityARVideo.m_ClearMaterial = savedClearMaterial;
}
}
// Update is called once per frame
void Update () {
if (m_camera != null && sessionStarted)
{
// JUST WORKS!
Matrix4x4 matrix = m_session.GetCameraPose();
m_camera.transform.localPosition = UnityARMatrixOps.GetPosition(matrix);
m_camera.transform.localRotation = UnityARMatrixOps.GetRotation (matrix);
m_camera.projectionMatrix = m_session.GetCameraProjection ();
}
}
public void Hideplane()
{
config.planeDetection = UnityARPlaneDetection.None;
}
}
I have tried using the Hideplane() method,still the blue plane is showing
I tried this in UnityhittestAR example.I was looking for something like FocusSquare example.Once the plane is detected when we touch the screen the object get placed and no more tracking
Its A temporary solution but it works. In your UnityARKitScene attach a new script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class EventHandler : MonoBehaviour {
public GameObject MainPlane;
public GameObject DestroyedPlane;
public GameObject p;
public int Got;
private void Start()
{
Instantiate(p);
}
private void Update()
{
MainPlane = GameObject.Find("Plane");
if(MainPlane!=null){
if(Got==0){
MainPlane.name = "MainPlane";
Got = 1;
}
if(Got==1){
MainPlane = null;
DestroyedPlane = GameObject.Find("Plane");
Destroy(DestroyedPlane);
}
}
}
}
i'm trying to develop a multiplayer game .
I declared a bool variable which must be synchronized by the server.
this is my code :
public GameObject blueBar, redBar;
public GameObject barH, barV;
[SyncVar] public bool localTurn;
void Start ()
{
localTurn = true;
if (!isLocalPlayer)
{
Cmdbars();
}
}
void Update ()
{
OnClick();
}
[Command]
void Cmdbars()
{
GameObject bar1 = Instantiate(barH, GameObject.Find("pos1").GetComponent<Transform>().transform.position, Quaternion.identity) as GameObject;
NetworkServer.Spawn(bar1);
}
private void OnClick()
{
if (Input.GetMouseButtonDown(0))
{
Vector2 origin = new Vector2(
Camera.main.ScreenToWorldPoint(Input.mousePosition).x,
Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
CmdOnClick(origin.x, origin.y);
}
}
[Command(channel = 0)]
private void CmdOnClick(float x, float y)
{
RpcClick(x, y);
}
[ClientRpc(channel = 0)]
private void RpcClick(float x, float y)
{
Vector2 origin = new Vector2(x, y);
RaycastHit2D hit = Physics2D.Raycast(origin, Vector2.zero, 0f);
if (hit && hit.transform.gameObject.tag.Equals("Untagged") && localTurn)
{
hit.transform.gameObject.GetComponent<SpriteRenderer>().sprite = blueBar.GetComponent<SpriteRenderer>().sprite;
hit.transform.gameObject.tag = "ok";
CmdclientPlaying();
}
if (hit && hit.transform.gameObject.tag.Equals("Untagged") && !localTurn)
{
hit.transform.gameObject.GetComponent<SpriteRenderer>().sprite = redBar.GetComponent<SpriteRenderer>().sprite;
hit.transform.gameObject.tag = "ok";
CmdlocalPlaying();
}
}
here are the commands to change the bool
[Command]
void CmdlocalPlaying()
{
localTurn = true;
}
[Command]
void CmdclientPlaying()
{
localTurn = false;
}
everything is going well except the the bool localTurn change in local only not in all clients.
must change boll after click in object to play alternately between players.
try to change this if block to include else if
if (hit && hit.transform.gameObject.tag.Equals("Untagged") && localTurn)
{
hit.transform.gameObject.GetComponent<SpriteRenderer>().sprite = blueBar.GetComponent<SpriteRenderer>().sprite;
hit.transform.gameObject.tag = "ok";
CmdclientPlaying();
}
else if (hit && hit.transform.gameObject.tag.Equals("Untagged") && !localTurn)
{
hit.transform.gameObject.GetComponent<SpriteRenderer>().sprite = redBar.GetComponent<SpriteRenderer>().sprite;
hit.transform.gameObject.tag = "ok";
CmdlocalPlaying();
}
when the CmdclientPlaying(); is called it makes the localTurn to false which will trigger the next if statement and make call to CmdlocalPlaying()
i changed the code . i call the function to change the bool outside Rpcclick()
and it worked .
but i dont now why it does not work before .
I cannot figure out the issue, I deleted then remade the PlayTab object, but it no longer works... It is telling me it has not been assigned, but it has to my knowledge. Relatively new to Unity programming, any help would be great, the script below.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.Audio;
public class MainMenu : MonoBehaviour {
public GameObject Buttons;
public GameObject CreditsPanel;
public GameObject QuitPanel;
public GameObject Options;
public GameObject PlayTab;
public Slider audiosl;
public Slider graphicsl;
public Toggle fullscreen;
public string SceneName;
void Start (){
QualitySettings.SetQualityLevel (100);
//(int)PlayerPrefs.GetFloat("Quality")
AudioListener.volume = 100;
//PlayerPrefs.GetFloat("Volume");
int qualityLevel = QualitySettings.GetQualityLevel();
audiosl.value = AudioListener.volume;
graphicsl.value = qualityLevel;
}
void Update (){
Debug.Log ("Update");
AudioListener.volume = audiosl.value;
QualitySettings.SetQualityLevel ((int)graphicsl.value);
}
public void InGame(bool a){
if (a == true) {
Application.LoadLevel (SceneName);
} else {
//continue
}
}
public void Play(bool a){
Debug.Log ("Inside Play Function");
if (a == true) {
Debug.Log ("Inside If Statment");
PlayTab.SetActive(a);
Buttons.SetActive(!a);
Animation pl = PlayTab.GetComponent<Animation>();
pl.Play("EnterPlayMenu");
}else {
Debug.Log ("Else'd");
PlayTab.SetActive(a);
}
}
public void ShowMenu(bool a){
}
public void Option(bool a){
if (a == true) {
Options.SetActive(a);
Buttons.SetActive(!a);
Animation Opt = Options.GetComponent<Animation>();
Opt.Play("OptionEnter");
}if (a == false) {
Animation d = Buttons.GetComponent<Animation> ();
d.Play ("mainbuttonenter");
Options.SetActive (false);
}
}
public void Credits(bool a){
if (a == true) {
CreditsPanel.SetActive(a);
Buttons.SetActive(!a);
Animation cr = CreditsPanel.GetComponent<Animation>();
cr.Play("EnterCredits");
}else {
CreditsPanel.SetActive(a);
}
}
public void Quit(bool a){
if (a == true) {
QuitPanel.SetActive(a);
Buttons.SetActive(!a);
Animation q = QuitPanel.GetComponent<Animation>();
q.Play("EnterQuit");
}else {
QuitPanel.SetActive(a);
}
}
public void Exit(bool a){
if (a == false) {
Option(false);
Buttons.SetActive(true);
CreditsPanel.SetActive(false);
QuitPanel.SetActive(false);
Options.SetActive(false);
PlayTab.SetActive(false);
saveSettings();
}
if (a == true) {
Application.Quit();
}
}
public void saveSettings(){
PlayerPrefs.SetFloat ("Quality", QualitySettings.GetQualityLevel ());
PlayerPrefs.SetFloat ("Volume", AudioListener.volume);
}
public void FullScreen(bool a){
if (Screen.fullScreen == a) {
Screen.fullScreen = !a;
} else {
Screen.fullScreen = a;
}
}
}
As far as I see, you have only defined the playTab variable, but not assigned it.
EDIT:
Try displaying it at start, then automatically hiding it via code. Probably Unity don't initialize objects that are not visible on scene from the start.