【问题标题】:How can I access a Collider's GameObject in script?如何在脚本中访问 Collider GameObject?
【发布时间】:2013-02-13 11:32:08
【问题描述】:

我正在 Unity3d 中制作纸牌游戏。我使用 c# 以编程方式将卡片创建为游戏对象。我想知道如何使每个对象(卡片)在鼠标按钮单击时移动,我尝试使用 Raycast 对撞机,但它不起作用。我正在尝试访问父游戏对象,它是网格的整个封面,它是对撞机对象/组件,我想通过它访问子游戏对象(只是为了移动一个位置)。有没有简单的方法来解决这个问题或您有更好的方法以其他方式完成所有这些工作吗?

更新:

if (Input.GetMouseButton (0)) {                    
    RaycastHit hit = new RaycastHit ();
    Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    if (Physics.Raycast (ray, out hit)) { 
        print (hit.collider.gameObject.name);
    }
} 

【问题讨论】:

  • 能否贴出你使用的光线投射对撞机的代码?
  • 是的。我使用了以下代码 if (Input.GetMouseButton(0)) { RaycastHit hit = new RaycastHit(); Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//**** if (Physics.Raycast(ray, out hit)) { print(hit.collider.gameObject.name); } }

标签: c# unity3d gameobject


【解决方案1】:

Input.GetMouseButton(0) 应该是Input.GetMouseButtonDown(0)。

您尝试使用Input.GetMouseButton(0),它记录鼠标按下的每一帧,而不是Input.GetMouseButtonDown(0),它只记录用户单击的第一帧。

示例代码:

if (Input.GetMouseButtonDown(0))
    print ("Pressed");
else if (Input.GetMouseButtonUp(0))
    print ("Released");

和

if (Input.GetMouseButton(0))
    print ("Pressed");
else
    print ("Not pressed");

如果这不能解决问题,请尝试将 if (Physics.Raycast (ray, out hit)) { 替换为 if (Physics.Raycast (ray, out hit, 1000)) {

【讨论】:

    【解决方案2】:

    我也偶然发现了这个问题,试试这个(顺便说一句,你也可以使用 GetMouseButtonUp)

    if (Input.GetMouseButtonDown (0)) 
    {                    
    RaycastHit hit = new RaycastHit ();
    Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    if (Physics.Raycast (ray, out hit)) { 
        print (hit.collider.transform.gameObject.name);
    }
    

    }

    通过某种方式可以通过 Transform 访问它,它为我解决了问题! 如果您想访问父级:

    hit.collider.transform.parent.gameObject;
    

    现在孩子有点棘手:

    // You either access it by index number
    hit.collider.transform.getChild(int index);
    //Or you could access some of its component ( I prefer this method)
    hit.collider.GetComponentInChildren<T>();
    

    希望我能帮上忙。 干杯!

    【讨论】:

      猜你喜欢
      • 2020-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-26
      • 1970-01-01
      • 1970-01-01
      • 2017-10-16
      • 2017-04-06
      相关资源
      最近更新 更多