首页 > 解决方案 > Vector3:变量作为坐标

问题描述

变量作为 Vector3 坐标...这是绘制四边形和射线的空游戏对象上的脚本的一部分。我可以画一个四边形,我可以画一条射线。我可以通过在 Vector3 中输入浮点数来手动移动该射线。为什么我不能使用“planeWidth”或“planeHeight”来代替 Vector3 中的数字?仅定义“public Vector3 rayA1Pos ...”行时出现错误。

//Define my Quad
    public float planeWidth = 24f;
    public float planeHeight = 34.5f;
//Declare rayA1
    private Ray rayA1;
    private RaycastHit hitA1;
    public float rayDistance = 150f;
//rayA1's Vector3 coordinate at top-right corner of Quad
 public Vector3 rayA1Pos = new Vector3( (**planeWidth**/2), (planeHeight/2), 0f);

只是为了展示一个使用示例,它有效: rayA1 = new Ray(transform.position + new Vector3(0f, 150f, 0f), transform.forward);

但是为什么这不起作用:

    rayA1 = new Ray(transform.position + rayA1Pos, transform.forward);

或这个?

ray1 = new Ray(transform.position + new Vector3(planeWidth, planeHeight, 0f), transform.forward)

再一次,当我将“planeWidth”和“planeHeight”作为 Vector3 坐标放入其中时,它们会引发错误。谢谢阅读。这是我的第一个罐子,但我在这个论坛上找到了很多很酷的东西,所以我已经非常感谢你们了!汤姆·G。

标签: c#unity3d

解决方案


我相信您会收到以下错误:

字段初始值设定项不能引用非静态字段、方法或属性

您不能使用变量在全局范围内按照您想要的方式初始化其他变量。你将不得不改变planeWidthplaneHeight静态。通常你在类构造函数中进行初始化。在具有 MonoBehaviour 的 Unity3D 中,您通常在Start()orAwake()方法中执行此操作。

改为这样做:

public float planeWidth = 24f;
public float planeHeight = 34.5f;
public Vector3 rayA1Pos;

void Start()
{
   rayA1Pos = new Vector3((planeWidth/2), (planeHeight/2), 0f);
}

推荐阅读