How do I enable Parts/Components in Unity C# with only a game object in the script

那年仲夏 提交于 2019-11-28 02:02:52

I unity you can enable and disable components in child object by using gameObject.GetComponentInChildren

ComponentYouNeed component = gameObject.GetComponentInChildren<ComponentYouNeed>();
component.enabled = false;

Also can use gameObject.GetComponentsInChildren

Both image links go to the same place but I think I understand.

I would probably recommend that you place some kind of script that allows you to wire up the HeadMovement script in the Body game object. For example:

public class BodyController : MonoBehaviour
{
  public HeadMovement headMovement;
}

Then you can wire this up in your prefab and then call:

BodyController bc = myPlayerGo.GetComponent<BodyController>();
bc.headMovement.enabled = true;

Another fix would be to use GetComponentsInChildren():

HeadMovement hm = myPlayerGo.GetComponentsInChildren<HeadMovement>(true)[0]; //the true is important because it will find disabled components.
hm.enabled = true;

I would probably say the first is a better option because it is more explicit and also faster. If you have multiple HeadMovements then you will run into problems. It also requires a crawl of your entire prefab hierarchy just to find something that you already knew the location to at compile time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!