So I been trying to make a simple oculus rift game in unity where you walk around finding objects and collecting them by pressing a key like I dont know E for example. I couldnt find any solid tutorials to help me so I just been putting things together and hoping it worked, I managed to have a script up and running where apon startup the item would randomly spawn between specified locations but now nothing works
using UnityEngine;
using System.Collections;
public class NewBehaviourScript {
// Use this for initialization
int myInt;
void Start () {
myInt = Random.Range (1, 101);
if (myInt <= 50) {
gameObject.transform.position = new Vector3 (29, 2, -78);
} else {
gameObject.transform.position = new Vector3 (31, -4, -75);
}
}
void onTriggerEnter(Collider collider){
if (collider.gameObject.name == "OVRPlayerController" && Input.GetKeyDown ("E")) {
ItemCount++;
gameObject.transform.position = new Vector3 (41, -1, -10);
}
}
// Update is called once per frame
void Update () {
}
}
But I’ve definitely seen people with unity games where they can hit a key to pick up something that’s in reach, anyway I somehow managed to get rid of all the bugs, but it still doesn’t do the pickup. Could someone please point me in the right direction.
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour {
// Use this for initialization
int myInt;
void Start () {
myInt = Random.Range (1, 101);
if (myInt <= 50) {
gameObject.transform.position = new Vector3 (29, 2, -78);
} else {
gameObject.transform.position = new Vector3 (31, -4, -75);
}
}
void OnTriggerEnter(Collider collider){
if (collider.gameObject.name == "OVRPlayerController" && Input.GetKeyDown ("K")) {
ItemCount.ItemCounter++;
gameObject.transform.position = new Vector3 (41, -1, -10);
}
}
// Update is called once per frame
void Update () {
}
}
Oh sorry, i totally forget to add that. xD
There are different approaches to pick it up.
E.g. there’'s also OnTriggerStay, which will be called as long as you stay in the trigger. You can use that instead of OnTriggerEnter. Then it should actually work.
Another different way: as soon as you enter a trigger (using OnTriggerEnter) you could add the item into a list, let’s call it something like ‘pickableItems’.
As soon as you leave the trigger (OnTriggerExit), remove it from the list.
You can then always pick up all items in the list when the key is pressed, but you should also remove them in order to avoid bugs.
Both methods should work well, the second one des not rely on continuous OnTriggerStay calls though, that just came to my mind thinking about an alternative as i don’t know what’s the additional overhead when many OnTriggerStays are called.