NullReferenceException error

Can anyone help me with this? I have the following code:

 var dmg :int = 4;
var hp: int = 5;
var target: GameObject;
var creatureLocX  = 0;
var creatureLocY = 0;
function OnGUI() {

var location : Vector3 = Camera.mainCamera.WorldToViewportPoint(target.position);
creatureLocX = location.x;
creatureLocY = location.y;
GUI.Label(Rect(creatureLocX,creatureLocY,120,60), "HP:" + hp + " DMG:" + dmg);

When I run the game I get the following message:
“NullReferenceException: Object reference not set to an instance of an object” for the following line:
var location : Vector3 = Camera.mainCamera.WorldToViewportPoint(target.position);

For target I’ve assigned an object in the inspector.

What can I do about this?

Try using Camera.main.WorldToScreenPoint which return screen pixel coordinates. Camera.main.WorldToViewportPoint would return values between 0 to 1 in each axis.

Once you got the screen point, you can convert it to GUI space by flipping the y component since GUI has 0, 0 in upper left and screen point has 0, 0 in lower left.

Here’s an example. To try it out, just put the script on any game object and text will appear on it.

var text : String = "Example";

function OnGUI() {
    var g : Vector2 = WorldToGUIPoint(transform.position);
    var r : Rect = Rect(g.x, g.y, 100, 20);
    GUI.Label(r, text);

function WorldToGUIPoint(world : Vector3) : Vector2 {
    var s : Vector3 = Camera.main.WorldToScreenPoint(world);
    var g : Vector2 = Vector2(s.x, Screen.height - s.y);
    return g;