Script getComponent crashes unity.
This code crashes unity:
public GameObject player;
public Sprite Health2;
public Sprite Health3;
private int Holder;
// Use this for initialization
void Start () {
gameObject.GetComponent<SpriteRenderer> ().sprite = Health2;
}
// Update is called once per frame
void Update () {
Holder = player.GetComponent<PlayerController> ().health;
if (Holder == 1) {
gameObject.GetComponent<SpriteRenderer> ().sprite = Health2;
} if (Holder == 0){
gameObject.GetComponent<SpriteRenderer> ().sprite = Health3;
}
}
This seems to be the line which is the cause, but I can't figure out why: player.GetComponent ().health;
Answer by LeeJBaxter · Jul 23, 2018 at 12:26 PM
How does the code cause Unity to crash? Is it causing the editor to freeze or something, or is it just throwing an exception and causing an error message to appear in the console area when you run it? From what I can see, there are 2 possible things that could be causing the problem;
The first is if you're using Unity's built-in "PlayerController", as it doesn't seem to have the "health" variable that you're referencing. In this case, I would expect a compiler error to appear rather than a run-time error.
The second is if you've created your own "PlayerController" component with a "health" variable. In this case, are you sure that the GameObject you've attached the script to actually has a "PlayerController" component attached to it? If it doesn't, an exception would be thrown as "player.GetComponent()" would return null.
Answer by tormentoarmagedoom · Jul 23, 2018 at 12:34 PM
Good day.
If Unity crashes and close, we can not help you. You need to send a tiket error report to Unity.
Answer by PhenixDown · Jul 24, 2018 at 09:27 AM
I have no idea why this is happening, but I don't think its the getComponent, If I find something I'll post the answer here.
Please explain exactly what is happening when Unity crashes, as it may give clues as to what the problem could be. What makes you think that it's being caused by the specific line that you mentioned?