When I look at some object and press the button, I need to do something. When I do it for the first time, it works, but then I don't need to press the button again, I can just look at object. But player must look at object and press the button, not only look
private Collider thisCollider;
public int ActionNumber { get; private set; }
void Start ()
{
thisCollider = GetComponent<Collider>();
}
void Update ()
{
if (Input.GetButton("Fire1") && DoPlayerLookAtObject())
ActionsList();
}
bool DoPlayerLookAtObject()
{
int layerMask = 1 << 9;
layerMask = ~layerMask;
RaycastHit _hit;
Ray _ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
bool isHit = Physics.Raycast(_ray, out _hit, 2.0f, layerMask);
if (isHit && _hit.collider == thisCollider)
return true; // this return true all the time after first interaction with object
else
return false;
}
public bool ActionsList()
{
if (DoPlayerLookAtObject())
switch (thisCollider.name)
{
case "barthender": ActionNumber = 1; return true;
case "doorToStreet": ActionNumber = 2; return true;
default: Debug.Log("Error: Out of range"); break;
}
return false;
}
How I use it:
public OnMousePressCasino onMousePressCasinoBarthender;
public OnMousePressCasino onMousePressCasinoDoorToStreet;
if (onMousePressCasinoBarthender.ActionNumber == 1 &&
onMousePressCasinoBarthender.ActionsList())
// do something
if (onMousePressCasinoDoorToStreet.ActionNumber == 2 &&
onMousePressCasinoDoorToStreet.ActionsList())
// do something
Edit 1 Ignoring player's collider. Video from the game
Okay so basically you're settings you ActionNumber to ( let's say ) 1 and it stays at this value.
To fix this up you would have to set time based reset of that value or just use Raycast all the time in Update ( or LateUpdate ).
Another way would be to make use of event driven programming principles and just fire the event whenever your conditions are met and forget about setting some values.
Making it simple enough :
private Collider thisCollider;
public event EventHandler<MeEventArgs> OnAction;
void Start()
{
thisCollider = GetComponent<Collider>();
}
void Update ()
{
if (Input.GetButtonDown("Fire1"))
{
EventHandler<MeEventArgs> handler = OnAction;
int actionIndex = DoPlayerLookAtObject();
if ( handler != null && actionIndex >= 0)
{
handler(this, new MeEventArgs(actionIndex));
}
}
}
int DoPlayerLookAtObject()
{
int layerMask = 1 << 9;
layerMask = ~layerMask;
RaycastHit _hit;
Ray _ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
bool isHit = Physics.Raycast(_ray, out _hit, 2.0f, layerMask);
//if (isHit && _hit.collider == thisCollider)
// return true; // this return true all the time after first interaction with object
//else
// return false;
if (isHit && _hit.collider == thisCollider)
return ActionList();
return -1;
}
public int ActionsList()
{
int result = -1;
switch (thisCollider.name)
{
case "barthender": result = 1; break;
case "doorToStreet": result = 2; break;
default: Debug.Log("Error: Out of range"); break;
}
return result;
}
Now create MeEventArgs :
public class MeEventArgs : EventArgs
{
public readonly int Action;
public MeEventArgs(int actionIndex) : base()
{
Action = actionIndex;
}
}
And to use this in code :
public OnMousePressCasino onMousePressCasinoBarthender;
public OnMousePressCasino onMousePressCasinoDoorToStreet;
void Start()
{
onMousePressCasinoBarthender.OnAction += MeAction;
onMousePressCasinoDoorToStreet.OnAction += MeAction;
}
void MeAction(object sender, MeEventArgs e)
{
if(e.Action == 1)
{
// do something
}
else if (e.Action == 2)
{
// do something else.
}
}
Related
Hello I am new to coding in c# and I don't know what the problem is with this code, I am trying to make a game where you can walk left and right and an animation plays and if you press down or up it takes out a parasol.
public int idleCheck = 5;
Animator A_anim;
// Start is called before the first frame update
void Start()
{
A_anim = gameObject.GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("LeftRight"))
{
idleCheck = 2;
}
if (Input.GetButtonDown("Vertical"))
{
idleCheck = 1;
}
if (Input.GetButtonDown("LeftRight"))
{
idleCheck = 3;
}
if (idleCheck == 3)
{
A_anim.Setbool("ParaRun", true);
}
else if (idleCheck == 3)
{
A_anim.Setbool("ParaRun", false);
}
if (idleCheck == 2)
{
A_anim.Setbool("RunNor", true);
}
else if (idleCheck == 2)
{
A_anim.Setbool("RunNor", false);
}
if (idleCheck == 1)
{
A_anim.Setbool("parasole ability", true);
}
else if (idleCheck == 1)
{
A_anim.Setbool("parasole ability", false);
}
}
Yes Setbool does not exist but SetBool does :). Just a typo, you can check their documentation for more details.
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);
}
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);
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).
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.