简体   繁体   中英

Unity 3d controlling object visibility

I have two game objects namely objA and objB where the later is a child of former. ObjA is active and B is disabled. I wanted objB to appear when pointer enters and to disappear when pointer exits. I want this not just once but forever. I have tried following code attached with objA to control visibility of objB but it's unsuccessful. Could someone help me plz:

using UnityEngine;
using UnityEngine.EventSystems;

public class eventvisbtoggle : MonoBehaviour
{
    public void PointerEnter(BaseEventData eventData)
    {
        ObjB.gameobject.SetActive(true);
    }

    public void PointerExit(BaseEventData eventData)
    {
        ObjB.gameobject.SetActive(false);
    }
}

There is a difference between the enabled state of a GameObject and whether or not its is visible. active determines whether or not scripts and other components attached to the object function. A component called the Renderer is what actually draws the GameObject in the scene. What you want to do is disable the Renderers that are attached to the object

foreach(var r in GetComponentsInChildren<Renderer>()){
    r.enabled = false;
}

Note that this is very slow code, you should assign the appropriate renderers to your script using the editor, but this is just an example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM