Hello lovely people of Unity!
I have a problem (more of an inconvieniance really…) with which I’d love some help!
I found a script for picking up and reading notes provided by CharlesD, but it is written in C# (in which I have no knowledge, so far) The script allows the player to read a note upon pressing E. I have two different sounds I would like to play, one when you first pick up the note, and one when you close the note again. Thing is, I have no clue how to code something like that in C#… Help please?
Here is the NotePickUp script which is attached to the First Person Controller:
using UnityEngine;
using System.Collections;
public class PickupNote : MonoBehaviour {
//Maximum Distance you Can Pick Up A Book
public float maxDistance = 1.5F;
//Your Custom GUI Skin with the Margins, Padding, Align, And Texture all up to you :)
public GUISkin skin;
//Are we currently reading a note?
private bool readingNote = false;
//The text of the note we last read
private string noteText;
void Start () {
//Start the input check loop
StartCoroutine ( CheckForInput () );
}
private IEnumerator CheckForInput () {
//Keep Updating
while (true) {
//If the 'E' was pressed and not reading a note check for a note, else stop reading
if (Input.GetKeyDown (KeyCode.E)) {
if (!readingNote)
CheckForNote ();
else
readingNote = false;
}
//Wait One Frame Before Continuing Loop
yield return null;
}
}
private void CheckForNote () {
//A ray from the center of the screen
Ray ray = Camera.mainCamera.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
RaycastHit data;
//Did we hit something?
if (Physics.Raycast (ray, out data, maxDistance)) {
//Was the object we hit a note?
if (data.transform.name == "Note") {
//Get text of note, destroy the note, and set reading to true
noteText = data.transform.GetComponent ().Text;
Destroy (data.transform.gameObject);
readingNote = true;
}
}
}
void OnGUI () {
if (skin)
GUI.skin = skin;
//Are we reading a note? If so draw it.
if (readingNote) {
//Draw the note on screen, Set And Change the GUI Style To Make the Text Appear The Way you Like (Even on an image background like paper)
GUI.Box (new Rect (Screen.width / 4F, Screen.height / 16F, Screen.width / 2F, Screen.height * 0.75F), noteText);
}
}
}
And if it helps, this is the note script attached to the note object:
using UnityEngine;
using System.Collections;
public class Note : MonoBehaviour {
//The Skin/Background of the GUIStyle
public GUISkin mycustomSkin;
//The Text Of The Note
public string Text = "Insert Your Text Here!";
void Start () {
//AutoSet the Name
transform.name = "Note";
//If there is no collider on the note add one
if (collider == null) {
Debug.LogError ("No Collider On Note " + name + ". Add A Collider!");
}
}
}
I want the sound to only play once when you first press E to pick up the note and then the other sound when you press E again to close the note
Thank you so much in advance!