How to add a 2D marker or icon on our game screen according to the 3D object in the scene in Unity



I believe you have seen a lot some games that show a 2D icon or marker that is pointing to an object in 3D world inside the game.

In this blog post I will share a simple script that you can learn about it and develop from it to make your own HUDs for your games.

First make some 3D object on your scene. Then create an empty canvas. Add an image element inside the canvas.

Now add this script inside your Unity project. Attach it to your camera. Use your 3D object and the image inside your canvas, drag and drop them to the respective slots on camera’s script inspector window.

That’s all, try to run the game and you will see the 2D image is placed exactly on that 3D object position.

Here is the script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectPositionOnScreen : MonoBehaviour
{
	
	public Transform objectonscene;
	public GameObject spriteobject;
    
	Camera cam;
	
    // Start is called before the first frame update
    void Start()
    {
        cam = GetComponent<Camera>();
			
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 screenPos = cam.WorldToScreenPoint(objectonscene.position);
		spriteobject.transform.position = new Vector3(screenPos.x,screenPos.y,0);
    }
}

loading...

Leave a Reply

Your email address will not be published. Required fields are marked *