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;
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.
Good day.
If Unity crashes and close, we can not help you. You need to send a tiket error report to Unity.
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.