This question was
closed Jan 03, 2016 at 01:11 PM by
Nazguld for the following reason:
The question is answered, right answer was accepted
Soundarray for player is not working properly
Hey,
I have trouble with the sounds of my character controller/player. If the door is tagged as "KeyDoor" and I have not the right key in my inventory, the AudioSource of the player should play a locked_door sound. It works, if I put the Playersounds script on the door but I need the script on the player. It says NullReferenceException.
this is my Interact Script
using UnityEngine;
using System.Collections;
public class InteractScript : MonoBehaviour {
public float interactDistance = 5f;
void Update ()
{
if(Input.GetKeyDown(KeyCode.E))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, interactDistance))
{
if(hit.collider.CompareTag("Door"))
{
hit.collider.transform.GetComponent<DoorScript_Dome>().ChangeDoorState();
}
else if (hit.collider.CompareTag("BLOCK_C"))
{
hit.collider.transform.parent.GetComponent<ElevatorScript>().ChangeElevatorPosition();
}
else if (hit.collider.CompareTag("Schublade"))
{
hit.collider.transform.GetComponent<DoorScript_Dome>().Schublade();
}
else if (hit.collider.CompareTag("Key"))
{
Inventory.keys[hit.collider.GetComponent<Key>().index] = true;
Destroy(hit.collider.gameObject);
}
else if (hit.collider.CompareTag("KeyDoor"))
{
DoorScriptKey doorScriptKey = hit.collider.transform.GetComponent<DoorScriptKey>();
Playersounds_audio Playersounds = hit.collider.transform.GetComponent<Playersounds_audio>();
if (doorScriptKey == null) return;
if (Inventory.keys[doorScriptKey.index] == true)
{
doorScriptKey.ChangeDoorState();
}
else
{
Playersounds.doorLockedAudio();
}
}
}
}
}
}
this is the Playersound script
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(AudioSource))]
public class Playersounds_audio : MonoBehaviour
{
public AudioSource audio;
public AudioClip[] sounds;
void Start()
{
}
public void doorLockedAudio()
{
audio.PlayOneShot (sounds[Random.Range(0, sounds.Length)]);
}
}
I hope you can help me with this :P
Comment
Best Answer
Answer by Nazguld · Jan 02, 2016 at 12:46 PM
Fixed it by changing this : Playersounds_audio Playersounds = hit.collider.transform.GetComponent<Playersounds_audio>();
to this: Playersounds_audio Playersounds = transform.GetComponent<Playersounds_audio>();