Miguel Melo
Miguel Melo

Reputation: 51

Scripting audio in Unity5

Good day everyone! I'm starting up in Unity 5 AND C# and I'm following a tutorial, thing is... the tutorial was made for Unity 4, therefore some of the code in the tutorial is not usable in U5. This time my problem is with scripting audio to an action, here follows the code:

using UnityEngine;
using System.Collections;

[System.Serializable]

public class Boundary
{
    public float xMin, xMax, zMin, zMax;
}

public class PlayerController : MonoBehaviour
{

public float speed;
public float tilt;
public Boundary boundary;

public GameObject shot;
public float fireRate;
public Transform shotSpawn;

private float nextFire;

void Update()
{
    if (Input.GetButton ("Fire1") && Time.time > nextFire)
    {
        nextFire = Time.time + fireRate;
        Instantiate (shot, shotSpawn.position, shotSpawn.rotation);
        Audio.Play(); <---
    }
}

void FixedUpdate ()
{
    float moveHorizontal = Input.GetAxis ("Horizontal");
    float moveVertical = Input.GetAxis ("Vertical");

    Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);

    Rigidbody rb = GetComponent<Rigidbody> ();
    rb.velocity = movement * speed;

    rb.position = new Vector3 
        (
            Mathf.Clamp (rb.position.x, boundary.xMin, boundary.xMax),
            0.0f,
            Mathf.Clamp (rb.position.z, boundary.zMin, boundary.zMax)
        );
    rb.rotation = Quaternion.Euler (0.0f, 0.0f, rb.velocity.x * -tilt);
}

}

So there you go, the line "audio.Play();" is not compiled as there's nothing in U5 even close to that syntax. Can anyone give me a hint here?

Thanks in advance!

Upvotes: 1

Views: 2692

Answers (3)

Seyed Morteza Kamali
Seyed Morteza Kamali

Reputation: 846

Java:

     var myClip : AudioClip;
    function Start () {
     AudioSource.PlayClipAtPoint(myClip, transform.position);

}

c#:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class SoundController : MonoBehaviour {
    public AudioClip clip;  

    void Start () {
        AudioSource.PlayClipAtPoint(clip, Vector3.zero, 1.0f);      
    }
}

If you want play audio in instantiate you can use this:

#pragma strict
var prefabBullet : Transform;
var forwardForce = 1000;
var myClip : AudioClip;
function Update()
{
if (Input.GetButtonDown("Fire2"))
{
var instanceBullet = Instantiate (prefabBullet, transform.position, 
Quaternion.identity);
instanceBullet.GetComponent.<Rigidbody>().AddForce(transform.forward * 
forwardForce);
AudioSource.PlayClipAtPoint(myClip, transform.position);
}
}

Upvotes: 0

Mingan Beyleveld
Mingan Beyleveld

Reputation: 281

Add a variable 'AudioClip' and assign the clip to an audiosource.. Then use getComponent.Play();

Upvotes: 1

Luis Ponce
Luis Ponce

Reputation: 63

Instead of using Audio.play() use GetComponent<AudioSource>().Play(); and make sure you have an Audiosource attached to the gameobject.

Upvotes: 2

Related Questions