- Home /
Get Script Component In Parent
I have two scripts. One is attached to a trigger, "DestroyTruck", and the other is attached to the Camera Rig, "PlayerAudio". The truck is a child of the Camera Rig, and is destroyed by the script when it enters the trigger. In the script attached to the trigger, I am trying to access the "PlayerAudio" script attached to the truck's parent Camera Rig, and change a public variable in that script. When I try to get the script component of the parent, I get this error.
"Assets/Resources/DestroyTruck.cs(6,87): error CS1729: The type 'PlayerAudio' does not contain a constructor that takes '1' arguments"
DestroyTruck.cs
public class DestroyTruck : MonoBehaviour {
void OnTriggerEnter (Collider other){
PlayerAudio Intro = new PlayerAudio(GetComponentInParent<PlayerAudio>);
Intro.WorkClip = 0;
Destroy (other.gameObject);
Destroy (this);
}
}
PlayerAudio.cs
public class PlayerAudio : MonoBehaviour {
AudioSource audio;
public AudioClip[] ClipsWait, ClipsWork;
public double CurrX, CurrY, CurrZ;
public int WaitTime, WaitClip, WorkClip;
void Start () {
audio = GetComponent<AudioSource>();
ClipsWait = new AudioClip[]{(AudioClip)Resources.Load("AudioClips/Hey Get Back To Work"),(AudioClip)Resources.Load("AudioClips/Get To Work Recruit"),(AudioClip)Resources.Load("AudioClips/Get To Work"),(AudioClip)Resources.Load("AudioClips/Hey Are You There")};
ClipsWork = new AudioClip[]{(AudioClip)Resources.Load("AudioClips/Intro")};
CurrX = this.gameObject.transform.position.x;
CurrY = this.gameObject.transform.position.y;
CurrZ = this.gameObject.transform.position.z;
WaitTime = 0;
WaitClip = 0;
WorkClip = -1;
}
void Update () {
if (CurrX == this.gameObject.transform.position.x && CurrY == this.gameObject.transform.position.y && CurrZ == this.gameObject.transform.position.z) {
WaitTime++;
if (WaitTime >= 1800) {
audio.clip = ClipsWait[WaitClip];
audio.Play();
WaitTime = 0;
if (WaitClip < 3) {
WaitClip++;
} else {
WaitClip = 0;
}
}
} else {
CurrX = this.gameObject.transform.position.x;
CurrY = this.gameObject.transform.position.y;
CurrZ = this.gameObject.transform.position.z;
WaitTime = 0;
}
if (WorkClip != -1) {
audio.clip = ClipsWork[WorkClip];
audio.Play();
WorkClip = -1;
}
}
}
Why does the line,
PlayerAudio Intro = new PlayerAudio(GetComponentInParent<PlayerAudio>);
cause an error, and what do I need to do in order to properly access that script.
The correct is PlayerAudio Intro = GetComponentInParent<PlayerAudio>();
Answer by Dave-Carlile · Nov 17, 2016 at 08:04 PM
You can't create a MonoBehaviour instance using new. You need to use AddComponent to add an instance of it to a gameObject.
Even if you could, you don't have a constructor defined on your class that accepts the parameter you're passing.
The only thing I need to do is just change the WorkClip variable during runtime. Is there any simple way for DestroyTruck to access the public variable on PlayerAudio?