Reputation: 7
I've been trying to make this horror game and so far everything is going well, the only issue is that I'm sort of new to programming and have been looking up on internet how to make this code.
I can't seem to find a tutorial that explains clearly how to do this step by step. For the script, I would like it to behave as follows:
Here is my script so far I have it able to play the sound effect, this script is attached the pickup object in my scene.
public class CassetteTapeOne : MonoBehaviour {
void OnTriggerEnter(Collider other) {
AudioSource source = GetComponent<AudioSource>();
if (other.gameObject.tag == "Player") {
KeyCode key = KeyCode.E;
if (Input.GetKeyDown( key )) {
source.Play();
}
}
}
}
If you have any pointers or ideas, it would be much appreciated.
Upvotes: 1
Views: 1152
Reputation: 91
This is actually very simple and I would love to answer, you can look up some coding on how to do the sound and I think that you should make an audio manager scrip for it. With that out of the way let's begin
You want to measure the distance between two objects so there is a line for that
public GameObject objA;
public GameObject objB;
public bool ItemCheck;
// Get our two objs
float distance = Vector3.Distance(objA.transform.position, objB.transform.position);
//get a float between these two objects which will be recorded at all times, so I would maybe use a fixed Update()
if(distance <= 5f && Input.GetKeyDown(KeyCode.E) && ItemCheck == false)
{
objB.SetActive(false);
ItemCheck = true;
//use sound manager
}
This script can be placed on really anything since the GameObjects are Public I would maybe just use a different boolean if you were going to place this on other things
Kind regards, SB
Upvotes: 1
Reputation: 321
OnTriggerEnter only work the moment when you enter trigger only, after that you can not use your E key, if you want to use this sound only in this trigger area then you can use OnTriggerStay which work like update on that trigger area.
OnTriggerStay(Collider other)
{
AudioSource source = GetComponent();
if (other.gameObject.tag == "Player")
{
KeyCode key = KeyCode.E;
if (Input.GetKeyDown( key )){
source.Play();
}
}
Upvotes: 1