我在 Unity 專案中創建了一個帶有 AudioSource 組件的 GameObject。我相信我已經正確地使用了 GetComponent 函式來訪問所述組件。我正在嘗試通過腳本使用 PlayOneShot() 函式,但它無法編譯。我使用的是 Unity 2020.3.22f1 (LTS) 和 Visual Studio for Mac 8.10.14。
Unity 包檔案鏈接:https : //1drv.ms/u/s!AvhOYSsJUBS1hUocvPEgfmkwHfeh
腳本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ball : MonoBehaviour
{
// Configuration Parameters
[SerializeField] Paddle paddle1;
[SerializeField] float xPush = 2f, yPush = 10f;
[SerializeField] AudioClip[] ballSounds;
[SerializeField] float randomFactor = 0.2f;
// state
Vector3 paddleToBallVector;
[SerializeField] bool hasStarted = false;
// Cached component references
[SerializeField] AudioSource audioSource;
Rigidbody2D myRigidBody2D;
// Start is called before the first frame update
void Start()
{
paddleToBallVector = transform.position - paddle1.transform.position;
audioSource = GetComponent<AudioSource>();
myRigidBody2D = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (!hasStarted)
{
LaunchOnMouseClick();
LockBallToPaddle();
}
}
private void LaunchOnMouseClick()
{
if (Input.GetMouseButtonDown(0))
{
hasStarted = true;
myRigidBody2D.velocity = new Vector2(xPush, yPush);
}
}
private void LockBallToPaddle()
{
Vector3 ballPos = new Vector3(paddle1.transform.position.x, paddle1.transform.position.y, 1f);
transform.position = ballPos paddleToBallVector;
}
private void OnCollisionEnter2D(Collision2D collision)
{
Vector2 velocityTweak = new Vector2
(Random.Range(0f, randomFactor),
Random.Range(0f, randomFactor));
if (hasStarted)
{
AudioClip clip = ballSounds[UnityEngine.Random.Range(0, ballSounds.Length)];
audioSource.PlayOneShot(clip);
myRigidBody2D.velocity = velocityTweak;
}
}
}
uj5u.com熱心網友回復:
我已經匯入了你的包,看起來你有一個名為“AudioSource.cs”的腳本,它與 Unity 自己的 AudioSource 類沖突,在 declaration 使用它:
[SerializeField] UnityEngine.AudioSource audioSource;
并且會解決
uj5u.com熱心網友回復:
您只需使用 UnityEngine.Audio添加頭檔案即可
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/362708.html
上一篇:FlowEnt補間庫漸變
