如何在脚本中访问碰撞体的游戏对象?

问题描述 投票:0回答:2

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

更新:

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# unity-game-engine gameobject
2个回答
0
投票

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)) {


0
投票

我也偶然发现了这个问题,试试这个(顺便说一句,你也可以使用 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>();

希望我能帮忙。 干杯!

© www.soinside.com 2019 - 2024. All rights reserved.