- Home /
Order of object instantiation scripting issues
If the title needs clarification, the trouble I'm having is with the order by which objects are created.
For example, I have an "HUD" script, where the enemies created by instantiation will have the working health bar HUD, but objects of the same prefab placed in the scene don't have one. I get the error "internal_create can only be called from the main thread" and "null reference exception, unityEngine.texture.get_width()"
Another example is that when I place an object in the scene, my "find target" script will work, and I can get a component from that objects script. However, when an object is created through instantiation, I can't access that variable. I get the error "Object reference not set to an instance of an object"
Are there certain commands I need to use to reference a prefab object?
Here is the HUD script:
using UnityEngine;
using System.Collections;
public class behavior : MonoBehaviour {
public Transform target;
public float maxHp;
public float curHp;
GUIStyle style = new GUIStyle();
Texture2D texture = new Texture2D (128, 128);
public Vector3 hpPos;
void Start()
{
curHp = maxHp;
}
void Update ()
{
hpPos = Camera.main.WorldToScreenPoint (transform.position);
hpPos.y = Screen.height - hpPos.y;
hpPos.z = -1;
target = GameObject.FindGameObjectWithTag ("myPlayer").transform;
}
void OnGUI()
{
for (int i = 0; i < texture.width; i++)
{
for(int j = 0; j < texture.height; j++)
{
Color color = new Color(255, 0, 0);
texture.SetPixel(i, j, color);
}
}
texture.Apply ();
style.normal.background = texture;
GUI.Box (new Rect(hpPos.x - 15, hpPos.y + 45, curHp, 7), new GUIContent(""), style);
}
}
and here is my "find target" script:
using UnityEngine;
using System.Collections;
public class combat : MonoBehaviour {
public Transform target;
private behavior curHp;
void Start()
{
target = GameObject.FindGameObjectWithTag ("enemy").transform;
curHp = target.GetComponent<behavior>();
Debug.Log (target);
Debug.Log ("Enemies HP = " + curHp.curHp);
}
}