Blinking Marker – Unity Screen Space Marker Overlay Script



This is a very easy to use Unity Screen Space Marker Overlay script that will help you to show a 2D image/sprite on game screen to show the user some specific objects that has a specific tag.

In this video below I will show you how to use the script:

And here is the script:

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

public class BlinkingMarker : MonoBehaviour
{
	
	public string[] tagsToMark;
	public GameObject spriteObject;
	public GameObject markersParent;
	
	List<string> objectsToMark = new List<string>();
	
	Camera cam;
	bool canstart = false;
	
    // Start is called before the first frame update
    void Start()
    {
		
		StartCoroutine(InitMarkers());
		
        
    }

    // Update is called once per frame
    void Update()
    {
		if(canstart){
			int ctr = 0;
			foreach(Transform child in markersParent.transform)
			{
				if(GameObject.Find(objectsToMark[ctr]) != null){
					GameObject blah = GameObject.Find(objectsToMark[ctr]);
					if(Vector3.Distance(cam.transform.position, blah.transform.position) < 100){
						Vector3 screenPos = cam.WorldToScreenPoint(blah.transform.position);
						if(screenPos.z > 0){
							child.transform.position = new Vector3(screenPos.x,screenPos.y,screenPos.z);
							//Debug.Log("SCREENPOS Z " + screenPos.z);
							child.gameObject.name = "MarkerFor" + blah.gameObject.name;
							child.gameObject.SetActive(true);
						}else{
							child.gameObject.SetActive(false);	
						}
					}else{
						//child.transform.position = new Vector3(-100,-100,0);
						child.gameObject.SetActive(false);
					}
				}else{
					//child.transform.position = new Vector3(-100,-100,0);
					child.gameObject.SetActive(false);
				}
				ctr++;
			}
		}
    }
	
	IEnumerator InitMarkers(){
		yield return new WaitForSeconds(3f);
		cam = GetComponent<Camera>();
		for(int i = 0; i < tagsToMark.Length; i++){
			
			GameObject[] objs = GameObject.FindGameObjectsWithTag(tagsToMark[i]);
			foreach(GameObject obj in objs){
				if(obj.name != "Golden Coin" && obj.name != "RumahTambalBan-StartPoint1"){
					objectsToMark.Add(obj.name);
					GameObject mrk = Instantiate(spriteObject);
					mrk.transform.parent = markersParent.transform;
				}
			}
			
		}
		canstart = true;
	}
}

loading...

Leave a Reply

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