Unity3d脚本使用丢失时AddComponent参考音频剪辑() [英] Unity3d script losing AudioClip reference when using AddComponent()
问题描述
我有以下与公共音频剪辑变量脚本(2#)。当我addComponent,就失去了参考。
I have script (#2) below with a public AudioClip variable. When I 'addComponent', it loses that reference.
我已经测试它手动添加到编辑器中的一个对象,在这种情况下,它的工作原理确定。为什么我的脚本运行过程中添加失去参考?
I've tested manually adding it to an object in the editor, and in that case it works OK. Why does my script added during runtime lose the reference?
游戏对象1:有这个脚本(#1)连接
GameObject 1: has this script (#1) attached
void HitByRay() {
clock = GameObject.FindGameObjectWithTag("Clock_Arrow").GetComponent<Clock>();
clock.gameObject.AddComponent<Tick_Audio_Script>();
}
哪个重视以下脚本(#2)的时钟对象。
Which attaches the following script (#2) to the 'Clock' object.
public int safetyCounter;
float gapToNext;
public AudioClip tickAudio;
// Use this for initialization
void Start () {
startTicker(100);
}
void startTicker(int maxTicks)
{
safetyCounter = maxTicks;
gapToNext = 1f;
playTick();
}
void playTick()
{
Debug.Log("Tick");
if (gapToNext < 0.1 || safetyCounter == 0)
{
Debug.Log("We're done...!");
return;
}
// **ERROR HERE CLIP NOT FOUND**
AudioSource.PlayClipAtPoint(tickAudio, gameObject.transform.position, 1f);
gapToNext = gapToNext * 0.97f;
safetyCounter--;
Invoke("playTick",gapToNext);
}
Here's the script in the editor, where I've assigned the audioclip.
但是,当它通过AddComponent,参考该剪辑不来通过连接(后我打游戏和'打'的高度重视这个剧本我的触发器对象)?这将导致一个空引用错误,因为没有找到要播放的剪辑
But when it's attached via 'AddComponent', the reference to that clip does not come through (after I hit play and 'hit' my trigger object which attaches this script)? This results in a null reference error as there is no clip found to be played.
我AudioListener(位于不同的物体上)工作,因为有被场景中的正确播放其他声音。
My AudioListener (located on a different object) is working, as there are other sounds being played correctly in the scene.
再次我测试过手动添加这个脚本在它的工作原理编辑任何对象pre-运行。这是为什么?
Again, I've tested adding this script manually to any object pre-run in the editor it works. Why is this?
推荐答案
这有一个简单的解决方案。您可以执行下列操作之一:
This has a simple solution. You can do one of the following:
1)创建一个prefab和所需的引用添加到时钟。
1) Create a prefab and add it to "clock" with the needed references.
2)做到这一点:
void HitByRay() {
clock = GameObject.FindGameObjectWithTag("Clock_Arrow").GetComponent<Clock>();
clock.gameObject.AddComponent<Tick_Audio_Script>();
//NEW PART
clock.gameObject.GetComponent<Tick_Audio_Script>().TickAudio = (desired Audio);
}
希望这有助于。
这篇关于Unity3d脚本使用丢失时AddComponent参考音频剪辑()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!