Enabling a GameObject assigned to a public variable

I want the text for only the GameObject I’m looking at to appear, but when I look at one of the object the floating text of all GameObject of the same type appears aswell.

This is the script

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class Position3DText : MonoBehaviour {

    private TextMesh TEXT;

    public GameObject ItemFloatText;

    void Start()
    {
        ItemFloatText.transform.localPosition = new Vector3 (0, 0, 0.002f);
        TEXT = ItemFloatText.GetComponent<TextMesh> ();
        ItemFloatText.tag = gameObject.tag;
        TEXT.text = ItemFloatText.gameObject.tag;
    }

    void Update()
    {
        ItemFloatText.transform.LookAt (2 * transform.position - Camera.main.transform.position);
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit Hit;
        if (Physics.Raycast (ray, out Hit))
        {
            if ((Hit.collider.gameObject.tag == gameObject.tag) && (Vector3.Distance(Camera.main.transform.position, gameObject.transform.position) <= 3))
            {
                ItemFloatText.gameObject.SetActive (true);
            }
            else
            {
                ItemFloatText.gameObject.SetActive (false);
            }
        }
    }

}

The script is inside the “Can” GameObject, the text is a child of the Can and it is (the text) assigned to the public variable “ItemFloatText”.

As it stands right now in your code, if the raycast doesn’t hit anything, then it doesn’t know what it’s supposed to be disabling- the only situation in which disabling the text happens is if the tag doesn’t match or the distance is too far AND you’re still getting a raycast hit on the object (looking straight at it).

You can cache the currently seen object in a class member like “lastSeen”. In the next Update, if the raycast returns no hits or a new hit that’s not the lastSeen object, SetActive(false) on the text for “lastSeen” (if it’s not null) then assign null or the new hit object to it.

EDIT: Okay, I misunderstood the situation a bit. If you’re raycasting, you really need to be doing it from the player outward and not from a script on the object. Right now all of the cans are performing the exact same raycast from the camera forward, every single frame, checking the tag of the hit object (a tag they all share) and then turning on their own text in response.

If you change this so that there’s a script on each can with a function that turns on its own text or turns it off, and that’s it, then you can raycast from the player, turn on the text for the can that’s hit, but turn off the text for the can that was LAST hit before that, as I suggested originally. This is how I assumed things were set up, and it works far more efficiently that way.

Thanks it works now :slight_smile: