Switching between guns - c#

Hello I'm trying to make a gun system and everything is working except Switching gun that stored in my GameObject array playerGuns, it always stores it on 0
and when I press another key it disabled every object that created.
I want to make it so when you will press 1-4 key on your keyboard it will switch
between the gun that stored on playerGuns and disables the other gun, you ware holding.
I couldn't find why the problem is happening so please help.
public GameObject Player;
public GameObject Showui;
public RectTransform Uirect;
public Material greenQu, blueQu;
public GameObject nameObject;
public GameObject rearityObject;
public GameObject dmgObject;
public GameObject levelObject;
private Text nameText;
private Text rearityText;
private Text dmgText;
private Text levelText;
private Image infoImage;
private Gunsystem gunScript;
private string gunName;
private int index = 0, index2 = 0;
private bool pressed = false, Show = false;
public Gun[] Inventory = new Gun[4];
public GameObject[] playerGuns = new GameObject[4] { null, null, null, null};
public int keyPress = 0;
void Start () {
gunScript = Player.GetComponent<Gunsystem>();
infoImage = Showui.GetComponent<Image>();
//Get text from objects
nameText = nameObject.GetComponent<Text>();
rearityText = rearityObject.GetComponent<Text>();
dmgText = dmgObject.GetComponent<Text>();
levelText = levelObject.GetComponent<Text>();
gunName = gameObject.name;
Debug.Log(gunName);
}
private void Update()
{
KeyCode pickup = KeyCode.E;
KeyCode key1 = KeyCode.Alpha1;
KeyCode key2 = KeyCode.Alpha2;
KeyCode key3 = KeyCode.Alpha3;
KeyCode key4 = KeyCode.Alpha4;
//Handling inventory keys
if (Input.GetKeyDown(key1))
{
keyPress = 0;
if (playerGuns[0] != null && !playerGuns[0].activeInHierarchy)
{
playerGuns[0].SetActive(true);
}
if (playerGuns[1] != null && playerGuns[1].activeInHierarchy)
{
playerGuns[1].SetActive(false);
}else if (playerGuns[2] != null && playerGuns[2].activeInHierarchy)
{
playerGuns[2].SetActive(false);
}
else if (playerGuns[3] != null && playerGuns[3].activeInHierarchy)
{
playerGuns[3].SetActive(false);
}
}else if (Input.GetKeyDown(key2))
{
keyPress = 1;
if (playerGuns[1] != null && !playerGuns[1].activeInHierarchy)
{
playerGuns[1].SetActive(true);
}
if (playerGuns[0] != null && playerGuns[0].activeInHierarchy)
{
playerGuns[0].SetActive(false);
}
else if (playerGuns[2] != null && playerGuns[2].activeInHierarchy)
{
playerGuns[2].SetActive(false);
}
else if (playerGuns[3] != null && playerGuns[3].activeInHierarchy)
{
playerGuns[3].SetActive(false);
}
}else if (Input.GetKeyDown(key3))
{
keyPress = 2;
if (playerGuns[2] != null && !playerGuns[2].activeInHierarchy)
{
playerGuns[2].SetActive(true);
}
if (playerGuns[0] != null && playerGuns[0].activeInHierarchy)
{
playerGuns[0].SetActive(false);
}
else if (playerGuns[1] != null && playerGuns[1].activeInHierarchy)
{
playerGuns[1].SetActive(false);
}
else if (playerGuns[3] != null && playerGuns[3].activeInHierarchy)
{
playerGuns[3].SetActive(false);
}
}
else if (Input.GetKeyDown(key4))
{
keyPress = 3;
if (playerGuns[3] != null && !playerGuns[3].activeInHierarchy)
{
playerGuns[3].SetActive(true);
}
if (playerGuns[0] != null && playerGuns[0].activeInHierarchy)
{
playerGuns[0].SetActive(false);
}
else if (playerGuns[1] != null && playerGuns[1].activeInHierarchy)
{
playerGuns[1].SetActive(false);
}
else if (playerGuns[2] != null && playerGuns[2].activeInHierarchy)
{
playerGuns[2].SetActive(false);
}
}
//Pick the gun when key pressed and store it
if (Input.GetKeyDown(pickup) && Show == true)
{
foreach (Gun item in gunScript.gunList)
{
if (index2 == Convert.ToInt32(gunName))
{
if (item.gunType == "Normal")
{
GameObject temp = GameObject.Find(gameObject.name);
playerGuns[keyPress] = Instantiate(temp, Player.transform.position, Quaternion.identity) as GameObject;
playerGuns[keyPress].name = gameObject.name;
playerGuns[keyPress].tag = gameObject.tag;
playerGuns[keyPress].transform.parent = Player.transform;
playerGuns[keyPress].transform.rotation.SetLookRotation(Player.transform.position);
//Change rigidbody and disable collider
playerGuns[keyPress].GetComponent<Rigidbody>().useGravity = false;
playerGuns[keyPress].GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotation;
playerGuns[keyPress].GetComponent<MeshCollider>().enabled = false;
//Store gundata in inventory
item.Named = false;
Inventory[keyPress] = item;
pressed = true;
}
else if (item.gunType == "Stride")
{
GameObject temp = GameObject.Find(gameObject.name);
playerGuns[keyPress] = Instantiate(temp, Player.transform.position, Quaternion.identity) as GameObject;
playerGuns[keyPress].name = gameObject.name;
playerGuns[keyPress].tag = gameObject.tag;
playerGuns[keyPress].transform.parent = Player.transform;
playerGuns[keyPress].transform.rotation.SetLookRotation(Player.transform.position);
//Set rgidbody and disable collider
playerGuns[keyPress].GetComponent<Rigidbody>().useGravity = false;
playerGuns[keyPress].GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotation;
playerGuns[keyPress].GetComponent<MeshCollider>().enabled = false;
//Store gundata in inventory
item.Named = false;
Inventory[keyPress] = item;
pressed = true;
}
}
index2++;
}
index2 = 0;
}
}
private void OnMouseEnter()
{
Vector3 Pos = Camera.main.WorldToScreenPoint(transform.position);
Showui.transform.position = Pos;
Showui.transform.position += new Vector3(0, 90f, 0.5f);
gunScript.updateGuns = true;
Show = true;
foreach (Gun item in gunScript.gunList)
{
if (index == Convert.ToInt32(gunName))
{
if(item.gunType == "Normal")
{
infoImage.material = greenQu;
}else if (item.gunType == "Stride")
{
infoImage.material = blueQu;
}
LayoutRebuilder.ForceRebuildLayoutImmediate(Uirect);
if(item.Named != false)
Showui.SetActive(true);
nameText.text = "Name: " + item.Name;
rearityText.text = "Rearity: " + item.gunType;
dmgText.text = "Damage: " + Mathf.Round(item.Dmg).ToString();
levelText.text = "Level: " + item.gunLevel.ToString();
//Debug.Log(item.Name);
//Debug.Log(item.gunType);
//Debug.Log(item.Dmg);
//Debug.Log(item.gunLevel);
}
index++;
}
index = 0;
}
private void OnMouseExit()
{
Show = false;
Showui.SetActive(false);
}

I wrote a little script that should handle the activation and the deactivation of your four guns.
Hope It helps,
Alex
public GameObject[] Guns;
void Start(){
for (int i=0; i<3; i++){
if(Guns[i] == null) Debug.LogError("Gun n°" + i +" is null);
}
}
void Update(){
if(Input.GetKeyDown(Input.KeyCode.Alpha1)){
setGunActive(1);
}
if(Input.GetKeyDown(Input.KeyCode.Alpha2)){
setGunActive(2);
}
if(Input.GetKeyDown(Input.KeyCode.Alpha3)){
setGunActive(3);
}
if(Input.GetKeyDown(Input.KeyCode.Alpha4)){
setGunActive(4);
}
}
void setGunActive(int n){
foreach(GameObject g in Guns){
g.setActive(false);
}
Guns[n].setActive(true);
}

Related

'Image' does not contain a definition for 'HitTest' and no accessible extension method 'HitTest'

Hello and Good Night.
I already looked for all the solutions on Google, including putting "using UnityEngine.UI;", I tried to leave only "Image" and "Texture" instead of "GUITexture or UI.Image" and this causes even more errors, I don't know what else to do. I would be grateful for the help. Thank you very much.
code:
using UnityEngine.UI;
using UnityEngine;
using System.Collections;
public class GUIItemButton : GUIItem
{
public Sprite _texNormalState;
public Sprite _texSelectedState;
public Sprite _texHoverState;
public Sprite _texDisabledState;
public bool _HighLiteOnHover = false;
bool mbButtonHover = false;
bool mbMouseClicked = false;
bool mbDisabled = false;
bool mbRespondsToInput = true;
public delegate void clickCallBack();
public clickCallBack _CallBack = null;
Vector3 mViewRectPosOffset = new Vector3(0,0,0);
Camera mCamera = null;
// Use this for initialization
void Start ()
{
//Debug.Log("Button start");
meGUIItemType = eGUI_ITEM_TYPE.Button;
if(mCamera == null)
{
mCamera = Camera.main;
mViewRectPosOffset = new Vector3(mCamera.rect.x*Screen.width,mCamera.rect.y*Screen.height,0);
}
}
public void setCamera(Camera pCam)
{
mCamera = pCam;
mViewRectPosOffset = new Vector3(mCamera.rect.x*Screen.width,mCamera.rect.y*Screen.height,0);
//Debug.Log(mViewRectPosOffset+" name: "+gameObject.name);
}
// Update is called once per frame
void Update ()
{
UpdateSizeWithViewPort();
#if UNITY_EDITOR
HandleMouseClick();
#elif UNITY_IPHONE
HandleTouch();
#else
HandleMouseClick();
#endif
}
public void setRespondToInput(bool pResponds)
{
mbRespondsToInput = pResponds;
}
//HANDLE INPUT TOUCHES
void HandleTouch()
{
if(mCamera == null || mbDisabled || !mbRespondsToInput)
return;
int touchCount = Input.touchCount;
if(touchCount > 0)
{
if(mbDisabled)
return;
Touch touch = Input.GetTouch(touchCount-1);
//IF THE BUTTON IS NOT YET CLICKED
if (touch.phase == TouchPhase.Began && mbMouseClicked == false)
{
if (GetComponent<Image>().HitTest(touch.position-(Vector2)mViewRectPosOffset, mCamera))
{
//SET TO SELECTED TEXTURE
mbMouseClicked = true;
GetComponent<Image>().sprite = _texSelectedState;
}
}
//IF THE BUTTON IS ALREADY CLICKED
if (touch.phase == TouchPhase.Ended && mbMouseClicked == true)
{
mbMouseClicked = false;
if (GetComponent<Image>().HitTest(touch.position-(Vector2)mViewRectPosOffset, mCamera))
{
//PERFORM ACTION
GetComponent<Image>().sprite = _texNormalState;
if(_guiItemsManager !=null)
_guiItemsManager.OnSelectedEvent(this);
else if(_CallBack != null)
_CallBack();
}
}
//HIGHLITE ON HOVER
if (!mbButtonHover)
{
//CHECK IF MOUSE IS HOVERING ON BUTTON
if (GetComponent<Image>().HitTest(touch.position-(Vector2)mViewRectPosOffset, mCamera))
mbButtonHover = true;
if(mbButtonHover)
{
//HIGHLITE BUTTON (SELECTED OR HOVER MODE)
if(mbMouseClicked)
GetComponent<Image>().sprite = _texSelectedState;
}
}
//IF MOUSE IS ALREADY HOVERING ON BUTTON
else if (mbButtonHover)
{
if (!GetComponent<Image>().HitTest(touch.position-(Vector2)mViewRectPosOffset, mCamera))
{
//HAPPENS ONLY IF MOUSE MOVES AWAY FROM BUTTON
GetComponent<Image>().sprite = _texNormalState;
mbButtonHover = false;
}
}
}
else
{
mbMouseClicked = false;
GetComponent<Image>().sprite = _texNormalState;
}
}
void HandleMouseClick()
{
if(mCamera == null || mbDisabled || !mbRespondsToInput)
return;
//IF THE BUTTON IS NOT YET CLICKED
if (Input.GetMouseButtonDown(0) && mbMouseClicked == false)
{
if (GetComponent<Image>().HitTest((Input.mousePosition-mViewRectPosOffset), mCamera))
{
//SET TO SELECTED TEXTURE
//Debug.Log("Hit offset "+ (Input.mousePosition-mViewRectPosOffset));
mbMouseClicked = true;
GetComponent<Image>().sprite = _texSelectedState;
}
}
//IF THE BUTTON IS ALREADY CLICKED
if (Input.GetMouseButtonUp(0) && mbMouseClicked == true)
{
mbMouseClicked = false;
if (GetComponent<Image>().HitTest((Input.mousePosition-mViewRectPosOffset), mCamera))
{
//PERFORM ACTION
GetComponent<Image>().sprite = _texNormalState;
if(_guiItemsManager !=null)
_guiItemsManager.OnSelectedEvent(this);
else if(_CallBack != null)
_CallBack();
}
}
//HIGHLITE ON HOVER
if (!mbButtonHover)
{
//CHECK IF MOUSE IS HOVERING ON BUTTON
if (GetComponent<Image>().HitTest((Input.mousePosition-mViewRectPosOffset), mCamera))
mbButtonHover = true;
if(mbButtonHover)
{
//HIGHLITE BUTTON (SELECTED OR HOVER MODE)
if(mbMouseClicked)
GetComponent<Image>().sprite = _texSelectedState;
else if(_HighLiteOnHover)
GetComponent<Image>().sprite = _texHoverState;
}
}
//IF MOUSE IS ALREADY HOVERING ON BUTTON
else if (mbButtonHover)
{
if (!GetComponent<Image>().HitTest((Input.mousePosition-mViewRectPosOffset), mCamera))
{
//HAPPENS ONLY IF MOUSE MOVES AWAY FROM BUTTON
GetComponent<Image>().sprite = _texNormalState;
mbButtonHover = false;
}
}
}
public void setDisabled(bool pState)
{
mbDisabled = pState;
if(mbDisabled == true)
GetComponent<Image>().sprite = _texDisabledState;
else
GetComponent<Image>().sprite = _texNormalState;
}
public bool getDisabled()
{
return mbDisabled;
}
}
Is there a problem?

Intersect a circle with a picturebox

I am making a DxBaLL Game. First i tried make the ball with picturebox but when it comes to intersection, if ball interects with 2 bricks, bricks just break but i want them break in 3 shots. So then, i tried make ball with Graphics.DrawEllips but how can i detect if ball intersect with picturebox(brick) or not?
This is the ball with picturebox version. when the ball comes between 2 bricks(picturebox), bricks are disappearing.
namespace DxBall
{
public partial class Form1 : Form
{
bool goLeft, goRight, isGameOver;
bool gameStart = false;
int sideCount = 0;
int force = 3;
int x_force = 3;
int gameScore = 0;
int[] direction = { 0, 0 }; //x,y
int stickSpeed = 15;
public Form1()
{
InitializeComponent();
}
private async void MainGameTimer(object sender, EventArgs e)
{
if (gameStart == false)
{
gameStart = true;
}
txt_score.Text = "Score: " + gameScore;
if (goLeft == true && stick.Left > 0)
{
stick.Left -= stickSpeed;
}
if (goRight == true && stick.Left < 458)
{
stick.Left += stickSpeed;
}
if (direction[0] == 0)
{
if (ball.Left > 580)
{
direction[0] = 1;
}
else
{
ball.Left += x_force;
}
}
else if (direction[0] == 1)
{
if (ball.Left < 0)
{
direction[0] = 0;
}
else
{
ball.Left -= x_force;
}
}
if (direction[1] == 0)
{
if (ball.Top > 720)
{
direction[1] = 1;
}
else
{
ball.Top += force;
}
}
else if (direction[1] == 1)
{
if (ball.Top < 0)
{
direction[1] = 0;
}
else
{
ball.Top -= force;
}
}
foreach (Control x in this.Controls)
{
if (x is PictureBox)
{
if ((string)x.Tag == "stick")
{
if (ball.Bounds.IntersectsWith(x.Bounds))
{
direction[1] = 1;
}
x.BringToFront();
}
if ((string)x.Tag == "brick")
{
if (ball.Bounds.IntersectsWith(x.Bounds))
{
sideCount++;
if (x.BackColor == Color.Red && x.Visible == true&&sideCount<1)
{
if (direction[1] == 0) direction[1] = 1;
else if (direction[1] == 1) direction[1] = 0;
x.BackColor = Color.Yellow;
}
else if (x.BackColor == Color.Yellow && x.Visible == true && sideCount < 1)
{
if (direction[1] == 0) direction[1] = 1;
else if (direction[1] == 1) direction[1] = 0;
x.BackColor = Color.Blue;
}
else if (x.BackColor == Color.Blue && x.Visible == true && sideCount < 1)
{
if (direction[1] == 0) direction[1] = 1;
else if (direction[1] == 1) direction[1] = 0;
x.Visible = false;
gameScore++;
}
}
x.BringToFront();
}
if ((string)x.Tag == "gameOver")
{
if (ball.Bounds.IntersectsWith(x.Bounds))
{
GameTimer.Stop();
txtGameOver.Text = "Game Over! Your Score is: " + gameScore;
}
}
}
}
sideCount--;
}
private void KeyIsDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
goLeft = true;
}
if (e.KeyCode == Keys.Right)
{
goRight = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
Random rnd = new Random();
ball.Left = rnd.Next(0, 580);
direction[0] = rnd.Next(0, 2);
}
private void KeyIsUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
goLeft = false;
}
if (e.KeyCode == Keys.Right)
{
goRight = false;
}
}
private void RestartGame()
{
goLeft = false;
goRight = false;
isGameOver = false;
gameScore = 0;
txt_score.Text = "Score: " + gameScore;
foreach (Control x in this.Controls)
{
if (x is PictureBox && x.Visible == false)
{
x.Visible = true;
}
}
ball.Left = 390;
ball.Top = 527;
stick.Left = 310;
stick.Top = 700;
GameTimer.Start();
}
}
}

It stops for a while when button is clicked

public class green : MonoBehaviour
{
private AudioSource source;
public AudioClip sound;
static int result = 0;
// Use this for initialization
void Start()
{
StartCoroutine("RoutineCheckInputAfter3Minutes");
Debug.Log("a");
}
IEnumerator RoutineCheckInputAfter3Minutes()
{
System.Random ran = new System.Random();
int timeToWait = ran.Next(1, 50) * 1000;
Thread.Sleep(timeToWait);
source = this.gameObject.AddComponent<AudioSource>();
source.clip = sound;
source.loop = true;
source.Play();
System.Random r = new System.Random();
result = r.Next(1, 4);
Debug.Log("d");
yield return new WaitForSeconds(3f * 60f);
gm.life -= 1;
Debug.Log(gm.life + "값");
source.Stop();
Debug.Log("z");
if (gm.life >= 0)
{
StartCoroutine("RoutineCheckInputAfter3Minutes");
}
}
// Update is called once per frame
public void Update()
{
if (result == 1 && gm.checkeat == true)
{
Debug.Log("e");
gm.life += 1;
Debug.Log("j");
Debug.Log(gm.life + "값");
source.Stop();
gm.checkeat = false;
StopCoroutine("RoutineCheckInputAfter3Minutes");
StartCoroutine("RoutineCheckInputAfter3Minutes");
}
if (result == 2 && gm.checkshit == true)
{
Debug.Log("f");
gm.life += 1;
Debug.Log("o");
Debug.Log(gm.life + "값");
source.Stop();
gm.checkshit = false;
StopCoroutine("RoutineCheckInputAfter3Minutes");
StartCoroutine("RoutineCheckInputAfter3Minutes");
}
else if (result == 3 && gm.checksleep == true)
{
Debug.Log("g");
gm.life += 1;
Debug.Log(gm.life);
Debug.Log(gm.life + "값");
source.Stop();
gm.checksleep = false;
StopCoroutine("RoutineCheckInputAfter3Minutes");
StartCoroutine("RoutineCheckInputAfter3Minutes");
}
}
}
public class gm : MonoBehaviour
{
static public int life = 0;
static public bool checkeat = false;
static public bool checkshit = false;
static public bool checksleep = false;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void eating(string eat)
{
Debug.Log(life + "값");
checkeat = true;
}
public void shitting(string shit)
{
Debug.Log(life + "값");
checkshit = true;
}
public void sleeping(string sleep)
{
Debug.Log(life + "값");
checksleep = true;
}
}
when i click a button , program stops for a while and then works... i think it is because of thread or something...
please share your opinion..
.when i click a button , program stops for a while and then works... i think it is because of thread or something...
please share your opinion..
Stop using :
Thread.Sleep(timeToWait);
This stalls the entire thread, in this case Unity completely from running.
Since your using routines anyway, use this instead :
yield return new WaitForSeconds(timeToWait);
And change this line :
int timeToWait = ran.Next(1, 50) * 1000;
To this :
int timeToWait = ran.Next(1, 50);

How do I remedy this type does not exist in type error?

I need to get value from another script but I keep getting this error that says
The type name 'head' does not exist in the type 'SteamVR_Camera'.
My code:
using UnityEngine;
using System.Collections;
using UnityEngine.VR;
public class HMDHelper : MonoBehaviour
{
private SteamVR_Camera.head.localPosition HMDLocalPos; //Error is thrown here.
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("g"))
{
AutoRotate();
}
}
void AutoRotate()
{
HMDLocalPos = InputTracking.GetLocalPosition(Head);
Debug.Log(HMDLocalPos);
}
}
What exactly do I have to do to fix error?
This is the script that I retrieved the other value (HMDLocalPos) from...
//========= Copyright 2014, Valve Corporation, All rights reserved. ===========
//
// Purpose: Adds SteamVR render support to existing camera objects
//
//=============================================================================
using UnityEngine;
using System.Collections;
using System.Reflection;
using Valve.VR;
[RequireComponent(typeof(Camera))]
public class SteamVR_Camera : MonoBehaviour
{
[SerializeField]
private Transform _head;
public Transform head { get { return _head; } }
public Transform offset { get { return _head; } } // legacy
public Transform origin { get { return _head.parent; } }
[SerializeField]
private Transform _ears;
public Transform ears { get { return _ears; } }
public Ray GetRay()
{
return new Ray(_head.position, _head.forward);
}
public bool wireframe = false;
[SerializeField]
private SteamVR_CameraFlip flip;
#region Materials
static public Material blitMaterial;
// Using a single shared offscreen buffer to render the scene. This needs to be larger
// than the backbuffer to account for distortion correction. The default resolution
// gives us 1:1 sized pixels in the center of view, but quality can be adjusted up or
// down using the following scale value to balance performance.
static public float sceneResolutionScale = 1.0f;
static private RenderTexture _sceneTexture;
static public RenderTexture GetSceneTexture(bool hdr)
{
var vr = SteamVR.instance;
if (vr == null)
return null;
int w = (int)(vr.sceneWidth * sceneResolutionScale);
int h = (int)(vr.sceneHeight * sceneResolutionScale);
int aa = QualitySettings.antiAliasing == 0 ? 1 : QualitySettings.antiAliasing;
var format = hdr ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32;
if (_sceneTexture != null)
{
if (_sceneTexture.width != w || _sceneTexture.height != h || _sceneTexture.antiAliasing != aa || _sceneTexture.format != format)
{
Debug.Log(string.Format("Recreating scene texture.. Old: {0}x{1} MSAA={2} [{3}] New: {4}x{5} MSAA={6} [{7}]",
_sceneTexture.width, _sceneTexture.height, _sceneTexture.antiAliasing, _sceneTexture.format, w, h, aa, format));
Object.Destroy(_sceneTexture);
_sceneTexture = null;
}
}
if (_sceneTexture == null)
{
_sceneTexture = new RenderTexture(w, h, 0, format);
_sceneTexture.antiAliasing = aa;
#if (UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
// OpenVR assumes floating point render targets are linear unless otherwise specified.
var colorSpace = (hdr && QualitySettings.activeColorSpace == ColorSpace.Gamma) ? EColorSpace.Gamma : EColorSpace.Auto;
SteamVR.Unity.SetColorSpace(colorSpace);
#endif
}
return _sceneTexture;
}
#endregion
#region Enable / Disable
void OnDisable()
{
SteamVR_Render.Remove(this);
}
void OnEnable()
{
#if !(UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
// Convert camera rig for native OpenVR integration.
var t = transform;
if (head != t)
{
Expand();
t.parent = origin;
while (head.childCount > 0)
head.GetChild(0).parent = t;
DestroyImmediate(head.gameObject);
_head = t;
}
if (flip != null)
{
DestroyImmediate(flip);
flip = null;
}
if (!SteamVR.usingNativeSupport)
{
enabled = false;
return;
}
#else
// Bail if no hmd is connected
var vr = SteamVR.instance;
if (vr == null)
{
if (head != null)
{
head.GetComponent<SteamVR_GameView>().enabled = false;
head.GetComponent<SteamVR_TrackedObject>().enabled = false;
}
if (flip != null)
flip.enabled = false;
enabled = false;
return;
}
// Ensure rig is properly set up
Expand();
if (blitMaterial == null)
{
blitMaterial = new Material(Shader.Find("Custom/SteamVR_Blit"));
}
// Set remaining hmd specific settings
var camera = GetComponent<Camera>();
camera.fieldOfView = vr.fieldOfView;
camera.aspect = vr.aspect;
camera.eventMask = 0; // disable mouse events
camera.orthographic = false; // force perspective
camera.enabled = false; // manually rendered by SteamVR_Render
if (camera.actualRenderingPath != RenderingPath.Forward && QualitySettings.antiAliasing > 1)
{
Debug.LogWarning("MSAA only supported in Forward rendering path. (disabling MSAA)");
QualitySettings.antiAliasing = 0;
}
// Ensure game view camera hdr setting matches
var headCam = head.GetComponent<Camera>();
if (headCam != null)
{
headCam.hdr = camera.hdr;
headCam.renderingPath = camera.renderingPath;
}
#endif
ears.GetComponent<SteamVR_Ears>().vrcam = this;
SteamVR_Render.Add(this);
}
#endregion
#region Functionality to ensure SteamVR_Camera component is always the last component on an object
void Awake() { ForceLast(); }
static Hashtable values;
public void ForceLast()
{
if (values != null)
{
// Restore values on new instance
foreach (DictionaryEntry entry in values)
{
var f = entry.Key as FieldInfo;
f.SetValue(this, entry.Value);
}
values = null;
}
else
{
// Make sure it's the last component
var components = GetComponents<Component>();
// But first make sure there aren't any other SteamVR_Cameras on this object.
for (int i = 0; i < components.Length; i++)
{
var c = components[i] as SteamVR_Camera;
if (c != null && c != this)
{
if (c.flip != null)
DestroyImmediate(c.flip);
DestroyImmediate(c);
}
}
components = GetComponents<Component>();
#if !(UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
if (this != components[components.Length - 1])
{
#else
if (this != components[components.Length - 1] || flip == null)
{
if (flip == null)
flip = gameObject.AddComponent<SteamVR_CameraFlip>();
#endif
// Store off values to be restored on new instance
values = new Hashtable();
var fields = GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
foreach (var f in fields)
if (f.IsPublic || f.IsDefined(typeof(SerializeField), true))
values[f] = f.GetValue(this);
var go = gameObject;
DestroyImmediate(this);
go.AddComponent<SteamVR_Camera>().ForceLast();
}
}
}
#endregion
#region Expand / Collapse object hierarchy
#if UNITY_EDITOR
public bool isExpanded { get { return head != null && transform.parent == head; } }
#endif
const string eyeSuffix = " (eye)";
const string earsSuffix = " (ears)";
const string headSuffix = " (head)";
const string originSuffix = " (origin)";
public string baseName { get { return name.EndsWith(eyeSuffix) ? name.Substring(0, name.Length - eyeSuffix.Length) : name; } }
// Object hierarchy creation to make it easy to parent other objects appropriately,
// otherwise this gets called on demand at runtime. Remaining initialization is
// performed at startup, once the hmd has been identified.
public void Expand()
{
var _origin = transform.parent;
if (_origin == null)
{
_origin = new GameObject(name + originSuffix).transform;
_origin.localPosition = transform.localPosition;
_origin.localRotation = transform.localRotation;
_origin.localScale = transform.localScale;
}
if (head == null)
{
_head = new GameObject(name + headSuffix, typeof(SteamVR_GameView), typeof(SteamVR_TrackedObject)).transform;
head.parent = _origin;
head.position = transform.position;
head.rotation = transform.rotation;
head.localScale = Vector3.one;
head.tag = tag;
var camera = head.GetComponent<Camera>();
camera.clearFlags = CameraClearFlags.Nothing;
camera.cullingMask = 0;
camera.eventMask = 0;
camera.orthographic = true;
camera.orthographicSize = 1;
camera.nearClipPlane = 0;
camera.farClipPlane = 1;
camera.useOcclusionCulling = false;
}
if (transform.parent != head)
{
transform.parent = head;
transform.localPosition = Vector3.zero;
transform.localRotation = Quaternion.identity;
transform.localScale = Vector3.one;
while (transform.childCount > 0)
transform.GetChild(0).parent = head;
var guiLayer = GetComponent<GUILayer>();
if (guiLayer != null)
{
DestroyImmediate(guiLayer);
head.gameObject.AddComponent<GUILayer>();
}
var audioListener = GetComponent<AudioListener>();
if (audioListener != null)
{
DestroyImmediate(audioListener);
_ears = new GameObject(name + earsSuffix, typeof(SteamVR_Ears)).transform;
ears.parent = _head;
ears.localPosition = Vector3.zero;
ears.localRotation = Quaternion.identity;
ears.localScale = Vector3.one;
}
}
if (!name.EndsWith(eyeSuffix))
name += eyeSuffix;
}
public void Collapse()
{
transform.parent = null;
// Move children and components from head back to camera.
while (head.childCount > 0)
head.GetChild(0).parent = transform;
var guiLayer = head.GetComponent<GUILayer>();
if (guiLayer != null)
{
DestroyImmediate(guiLayer);
gameObject.AddComponent<GUILayer>();
}
if (ears != null)
{
while (ears.childCount > 0)
ears.GetChild(0).parent = transform;
DestroyImmediate(ears.gameObject);
_ears = null;
gameObject.AddComponent(typeof(AudioListener));
}
if (origin != null)
{
// If we created the origin originally, destroy it now.
if (origin.name.EndsWith(originSuffix))
{
// Reparent any children so we don't accidentally delete them.
var _origin = origin;
while (_origin.childCount > 0)
_origin.GetChild(0).parent = _origin.parent;
DestroyImmediate(_origin.gameObject);
}
else
{
transform.parent = origin;
}
}
DestroyImmediate(head.gameObject);
_head = null;
if (name.EndsWith(eyeSuffix))
name = name.Substring(0, name.Length - eyeSuffix.Length);
}
#endregion
#if (UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
#region Render callbacks
void OnPreRender()
{
if (flip)
flip.enabled = (SteamVR_Render.Top() == this && SteamVR.instance.graphicsAPI == EGraphicsAPIConvention.API_DirectX);
var headCam = head.GetComponent<Camera>();
if (headCam != null)
headCam.enabled = (SteamVR_Render.Top() == this);
if (wireframe)
GL.wireframe = true;
}
void OnPostRender()
{
if (wireframe)
GL.wireframe = false;
}
void OnRenderImage(RenderTexture src, RenderTexture dest)
{
if (SteamVR_Render.Top() == this)
{
int eventID;
if (SteamVR_Render.eye == EVREye.Eye_Left)
{
// Get gpu started on work early to avoid bubbles at the top of the frame.
SteamVR_Utils.QueueEventOnRenderThread(SteamVR.Unity.k_nRenderEventID_Flush);
eventID = SteamVR.Unity.k_nRenderEventID_SubmitL;
}
else
{
eventID = SteamVR.Unity.k_nRenderEventID_SubmitR;
}
// Queue up a call on the render thread to Submit our render target to the compositor.
SteamVR_Utils.QueueEventOnRenderThread(eventID);
}
Graphics.SetRenderTarget(dest);
SteamVR_Camera.blitMaterial.mainTexture = src;
GL.PushMatrix();
GL.LoadOrtho();
SteamVR_Camera.blitMaterial.SetPass(0);
GL.Begin(GL.QUADS);
GL.TexCoord2(0.0f, 0.0f); GL.Vertex3(-1, 1, 0);
GL.TexCoord2(1.0f, 0.0f); GL.Vertex3( 1, 1, 0);
GL.TexCoord2(1.0f, 1.0f); GL.Vertex3( 1, -1, 0);
GL.TexCoord2(0.0f, 1.0f); GL.Vertex3(-1, -1, 0);
GL.End();
GL.PopMatrix();
Graphics.SetRenderTarget(null);
}
#endregion
#endif
}
How do I fix this? Thank you.
The type is wrong. Needs to be Vector3.
private Vector3 HMDLocalPos;
void Start()
{
HDMLocalPos = SteamVR_Camera.head.localPosition;
}
Edit:
Replace the HDMLocalPos property with a reference to SteamVR_Camera and access it's properties like this:
public SteamVR_Camera steamCam; // popuplate this via inspector or with a Find() (or similar)
void Start()
{
// access like this
steamCam.head.localPosition = something
}
I think this is what you want (to actually change the head.localPosition of the camera).

Turn Based Game in unity C# in android

Good Day! I have this code but I have an error, for example (I set two players me, and 1 computer). I take the first turn, and the dice respawn with a value of 4 (just an example), the game piece then move from 1st to 4th tile when I touch the screen, when computer turns, it also move from 1st to 4th tile (because I set the result to 4 just an example). Now its my turn again, the dice never respawn and it doesn't wait to touch the screen if (Input.GetMouseButtonDown(0)) and move again by 4...
public class singlePlay : MonoBehaviour {
//Player
public GameObject[] playerprefab;
//Player Clone
public GameObject[] playerprefabC;
//Game Cards and Dice
public GameObject[] situationCard;
public GameObject dice;
int diceresult;
//Game Cards and Dice clone
public GameObject diceclone;
public int currentPlayer;
public int compPlayer;
public int playerTurn;
public string compPlayerstring;
public string playerTurnstring;
//GUI Boolean
bool play = false;
//Game Boolean
bool pieces = false;
bool giveturn = false;
bool myturn = false;
bool diceSpawn = false;
bool moving = false;
bool routine = false;
bool checking = false;
bool compturn = false;
//icon1
public GameObject[] icon;
//population
int[] population = new int[3];
//Tile
public GameObject[] Tile;
int[] playerTile = new int[3]; //current location
int[] playerTileUp = new int [3]; // updated location after dice roll
bool endTurn = false;
void Update ()
{
if (giveturn == true) {
int h = 0;
Giveturn(h);
giveturn = false;
}
if (play == true) {
if (pieces == true){
SpawnPlayer();
pieces = false;
}
if (myturn == true){
compturn = false;
if(diceSpawn == true) {
dice.transform.position = new Vector3(0,0,-1);
diceclone = Instantiate(dice, dice.transform.position, Quaternion.identity) as GameObject;
diceSpawn = false;
}
if (Input.GetMouseButtonDown(0))
{
Debug.Log("click");
diceresult = 4;
Destroy(diceclone);
moving = true;
Updateposition(diceresult);
}
}
else
{
Debug.Log("comp");
myturn = false;
diceresult = 4;
moving = true;
Updateposition(diceresult);
}
}
}
void Giveturn(int k)
{
Debug.Log("" + k);
currentPlayer = k;
if (k == playerTurn) {
Debug.Log("Yes");
compturn = false;
myturn = true;
diceSpawn = true;
moving = false;
}
else
{
Debug.Log("No");
compturn = true;
myturn = false;
moving = false;
}
}
void Updateposition(int diceresult)
{
if (moving == true) {
playerTileUp[currentPlayer] = playerTile[currentPlayer] + diceresult;
Debug.Log("" + playerTileUp[currentPlayer]+ " " +currentPlayer);
routine = true;
StartCoroutine(MyMethod());
}
moving = false;
}
IEnumerator MyMethod()
{
if (routine == true) {
if (myturn == true) {
compturn = false;
}
else
{
myturn = false;
}
int f = playerTile[currentPlayer] + 1;
Debug.Log(" " + currentPlayer );
while (f <= playerTileUp[currentPlayer]) {
Debug.Log("waiting");
yield return new WaitForSeconds(1);
Debug.Log(" " + Tile[f]);
playerprefabC[currentPlayer].transform.position = Tile[f].transform.position;
Debug.Log(" " + currentPlayer);
f++;
}
checking = true;
TrapCheck();
}
routine = false;
}
void TrapCheck()
{
if (checking == true) {
if (playerTileUp[currentPlayer] == 8) {
Debug.Log("Trap spawning");
Instantiate(situationCard[0], situationCard[0].transform.position, Quaternion.identity);
population[currentPlayer] = population[currentPlayer] -1;
}
playerTile[currentPlayer] = playerTileUp[currentPlayer];
Endturn();
myturn = false;
compturn = false;
checking = false;
}
}
void Endturn()
{
currentPlayer++;
Debug.Log(" " + currentPlayer);
if (currentPlayer > compPlayer) {
currentPlayer = 0;
}
Giveturn(currentPlayer);
}
}
There are few things that I could see wrong there already. First while the coroutine is running, it seems you are not preventing the update from running since play remains true. In TrapCheck, you call EndTurn which call GiveTurn and sets myTurn (true) and compTurn (false) booleans. But those two are reset in TrapCheck, myTurn is set back to false. You need to rethink the logic of your class.
A solution would be to use delegate. This would remove many of your boolean that you set and reset. Here is a basic idea:
Action currentUpdate;
bool playerTurn = true;
void Start(){
SetTurn();
}
void Update(){
if(currentUpdate != null)currentUpdate();
}
void SetTurn(){
// Prepare initial setting for moving
if(playerTurn == true){ currentUpdate = PlayerTurn; }
else{ currentUpdate = CompTurn; }
playerTurn = !playerTurn;
}
void PlayerTurn(){
// Check input
// Get dice value
currentUpdate = Move;
}
void CompTurn(){
// Get dice value
currentUpdate = Move;
}
void Move(){
if(position != target){
}else{
SetTurn();
}
}
This is fairly simplified but once you get the thing about delegate (maybe you already know), this will make it all so much more flexible.

Categories

Resources