2015-03-19 62 views
1

大家好! 我在Unity 5和C#中啓動,我正在學習一個教程,事情是......該教程是針對Unity 4製作的,因此本教程中的一些代碼在U5中不可用。這一次,我的問題是使用腳本音頻的動作,這裏下面的代碼:Unity5中的腳本語音

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); 
} 

}

所以你去,行「audio.Play();」沒有被編譯,因爲U5甚至沒有接近該語法。任何人都可以在這裏給我一個提示嗎?

在此先感謝!

回答

2

而不是使用Audio.play()使用GetComponent<AudioSource>().Play();並確保你有一個附屬到gameobject的Audiosource。

+0

工作就像一個魅力,再次感謝您! – 2015-03-19 12:56:42

1

添加一個變量'AudioClip',並將該片段分配給audiosource ..然後使用getComponent.Play();

0

的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);  
    } 
} 

如果你想在實例化播放音頻您可以使用此:

#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); 
} 
}