Draw Texture on Gameobject

Hi all,

I am trying to use GUI.DrawTexture to paint red boxes over all my Enemy ships when they are on screen. Thought this was going to be simple but my current result causes the texture to sit on the top left corner of the screen instead of being over the enemy ship and moving along with it. I’m sure I am missing something, any pointers?

    public string enemyTag = "Enemy";
    public Texture targetBox;

    void OnGUI()
    {
        DrawTargetsFor(enemyTag);      
    }

    void DrawTargetsFor(string tagName)
    {
        //Gather an array of all Enemies
        GameObject[] targets = GameObject.FindGameObjectsWithTag(tagName);

            foreach (GameObject enemy in targets)
            {
                DrawTarget(enemy,targetBox);
            }
    }

    void DrawTarget(GameObject enemy, Texture targetBox)
    {
        Vector2 OnScreen = Camera.main.WorldToViewportPoint(enemy.transform.position);
        GUI.DrawTexture(new Rect(OnScreen.x, OnScreen.y, 20,20),targetBox);
      
    }

you should be using “WorldToScreenPoint”

Thanks, that did the trick. Had to add a small offset to the width and height to get the image directly over the image but as long as it works. Here is the code update for anyone else needing it

    void DrawTarget(GameObject enemy, Texture targetBox)
    {
        Vector3 OnScreen = Camera.main.WorldToScreenPoint(enemy.transform.position);
        //Dont draw it on the opposite side, only on the targets
        if (OnScreen.z > 0)
        {
            GUI.DrawTexture(new Rect(OnScreen.x - 25, Screen.height - OnScreen.y - 25, 50, 50), targetBox);
        }
      
    }