What is the proper use of WorldToScreenPoint?

I can’t seem to find the answer I need anywhere on the forum or answers… or I’m just too dumb to understand. I keep getting errors when trying to use this function (WorldToScreenPoint). I tried attaching the scripting example provided by Unity to a Cube. Code:

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    public Transform target;
    void Update() {
        Vector3 screenPos = camera.WorldToScreenPoint(target.position);
        print("target is " + screenPos.x + " pixels from the left");
    }
}
    }

In this form I get:

I tried changing the c letter to capital C, then I get this error:

Tried putting: Vector3 screenPos = Camera.main.WorldToScreenPoint(target.position); When I run the game it says:

So how do I use this function ?? :frowning:

Camera.main was ok … im sure you probably have not set the target variable to have a value

Not sure why Camera.main does not work. There are many ways to achieve what you need. Here is one:

  1. Create a property camera in your example class.
	public Camera camera = null;

2, In Inspector drag your main camera to that property… Now you can use it from Update() method

This isn’t ideal because ‘camera’ is already a member of Component (and GameObject) which refers to the camera attached to ‘this’ object. So if you simply attach a Camera to the GameObject in question then there is no need for the additional declaration or if you would rather assign via Inspector then a different variable name is in order.

Can I make it work with transform.position instead of target?
Can someone please post a code? (PS I’ve tried even declaring public Camera camera but it doesn’t work)

Agreed with a different variable name point. I was just trying to keep the name to be the same as in the original example. As far as attaching it as a component - I don’t think it’s what asdx wants to achieve here.

asdx - after you declared a public Camera property, did you drag your camera into that property in the Inspector?

Here’s a quick working example that will throw an error up if things aren’t set up correctly.

using UnityEngine;

public class Example : MonoBehaviour
{
    public Transform target;  // set via Inspector
    void Awake()
    {
        if (target == null) Debug.LogError("Set target variable in Inspector!");
        if (Camera.main == null) Debug.LogError("There is no camera tagged as 'Main Camera'!");
    }

    void Update()
    {
        Vector3 screenPos = Camera.main.WorldToScreenPoint(target.position);
        Debug.Log("Screen position is: " + screenPos);
    }
}

It seems that my stupid mistake was that I did not tagged my Main Camera. I previously deleted it, and was naming, not tagging it. I realized it just before reading the posts so I believe KelsoMRK’s script would of spot it easily. Ty so much guys! I was in a real pickle :slight_smile: