- Home /
GetComponent in the Update function?
Can anyone tell me why transform.parent.GetComponent().follow = followBool;
doesn't work in the Start function, but it does on the Update function?
Also, I heard some people saying that putting GetComponent in the Update function is "awful" or something, and that I should avoid it. But for some reason this is the only way I can get my thing to work.
Here's the code for 2 of the scripts with further explanation:
-----Script rocketTrigger-----
using UnityEngine;
using System.Collections;
public class rocketTrigger : MonoBehaviour {
public bool followBool;
/*
The 'follow' bool in rocketFollow actually gets changed to 'true'
when I set this in the Update function, but it doesn't in the Start function
People say that Getting Component in the Update is "awful"
Any better way I should this?
*/
void Update()
{
transform.parent.GetComponent<rocketFollow>().follow = followBool;
}
void OnTriggerEnter(Collider col)
{
if(col.gameObject.CompareTag("plane"))
{
//Sets 'followBool' to true, which SHOULD set the 'follow' bool in rocketFollow to true as well...
followBool = true;
}
}
}
-----Script rocketFollow----- (Parent of rocketTrigger)
using UnityEngine;
using System.Collections;
public class rocketFollow : MonoBehaviour {
public bool follow;
void Update () {
if(follow)
{
//This gets called when I put the GetComponent line in the Update function, but doesn't in the Start function
Debug.Log ("Following");
}
}
}
Thanks for the help :)
Answer by MakeCodeNow · May 22, 2014 at 03:35 PM
You're probably having your issue because there is no parent set when Start is called, which is why you have to put the code in update. The main thing people are telling you to avoid is calling GetComponent every frame if you don't have to. Here's a simple way around that (assuming the parent doesn't change during the lifetime of this object):
public class rocketTrigger : MonoBehavior {
private rocketFollow parentFollow;
public bool followBool;
void Update() {
if(!parentFollow && transform.parent) {
parentFollow = transform.parent.GetComponent<rocketFollow>();
}
if(parentFollow) {
parentFollow.follow = followBool;
}
}
}