Strange error i dont understand because i am a child
I have no idea what is wrong. Please help meh.
using UnityEngine;
using System.Collections;
using System;
public class PlayerHealth : MonoBehaviour {
private int Playerhealth = 3; // This string holds the players current health value.
private int DmgCD = 0; // This string detects if the player can currently recieve damage
public Sprite[] Healths;
public GameObject healthbar = new GameObject();
void Start () {
//healthbar.AddComponent<SpriteRenderer>();
Healths = Resources.LoadAll<Sprite>("Healths");
}
void Update()
{
if (Playerhealth == 3)
{
healthbar.GetComponent<SpriteRenderer>().sprite = Healths[3];
}
if (Playerhealth == 2)
{
healthbar.GetComponent<SpriteRenderer>().sprite = Healths[2];
}
if (Playerhealth == 1)
{
healthbar.GetComponent<SpriteRenderer>().sprite = Healths[1];
}
if (Playerhealth == 0)
{
healthbar.GetComponent<SpriteRenderer>().sprite = Healths[0];
Playerhealth = 3;
//Application.LoadLevel("Lose"); (Remove the comments from this when the lose level is finished)
}
}
private IEnumerator HealthTracker()
{
while (true)
{
yield return new WaitForSeconds(2f);
StopCoroutine(HealthTracker());
}
}
void OnCollisionEnter2D(Collision2D col) // When getting hit by a projectile with the enemy tag
{
if (col.gameObject.tag == "Missile")
{
print("damage recieved");
if (DmgCD == 0) //If the player is allowed to be damaged
DmgCD = 1; // Make it so the player can no longer recieve new damage
Playerhealth = Playerhealth - 1;
StartCoroutine(HealthTracker());
}
}
}
The script is attempting to change a health bar depending on the players health values. The script also controls the health values and collisions.
Error: Internal_CreateGameObject is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'PlayerHealth' on game object 'healthbar'.
Answer by Commoble · Mar 14, 2017 at 11:43 PM
Error: Internal_CreateGameObject is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'PlayerHealth' on game object 'healthbar'.
This is the important part:
(or instance field initializer)
This is an instance field initializer:
public GameObject healthbar = new GameObject();
Can't do that there because of the way Unity works. Initialize your healthbar gameobject in Awake or Start. Alternatively, you could create your healthbar object in the scene editor and link it to your script in the inspector.