英文:
"Operator '+=' is ambiguous on operands of type 'Vector3' and 'Vector2'" error even though I am only using Vector2
问题
我搜索了关于这个错误的问题,显然是关于将Vector3/Vector2添加到Vector2/Vector3上的问题(很合理),但我这里根本没有使用Vector3。问题出在哪里?
英文:
I searched up the problem with this error and it it apparently a problem with adding a Vector3/Vector2 to a Vector2/Vector3 (makes sense), but I did not use Vector3 here at all. What is the problem?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SquareScript : MonoBehaviour
{
void Start()
{
transform.position = new Vector2(0, 0);
}
void Update()
{
transform.position += new Vector2(0, 1 / 100);
}
}
答案1
得分: 1
是的,你这样做。
transform.position += new Vector2(0, 1 / 100);
等同于
transform.position = transform.position + new Vector2(0, 1 / 100);
因此,你正在将 transform.position(它是一个 Vector3)加到新的 Vector2 上。
英文:
Yes you do.
transform.position += new Vector2(0, 1 / 100);
is the same as
transform.position = transform.position + new Vector2(0, 1 / 100);
so you're adding transform.position (which is a Vector3) to the new Vector2.
答案2
得分: 0
transform.position 始终是 Vector3。
您正在添加一个 Vector2。
对于这两种类型都存在 + 运算符... 但不适用于混合类型。
此外,由于存在 [Vector3 和 Vector2 之间的隐式转换 - 这也是为什么
transform.position = new Vector2(0, 0);
可以正常工作的原因 - 编译器无法确定是将 transform.position 转换为 Vector2,然后执行 Vector2 + Vector2 操作,还是将您的新 Vector2 转换为 Vector3,然后执行 Vector3 + Vector3 操作。
这就是为什么它说这是模棱两可的原因。
当然,您可以显式强制一种转换并执行
transform.position += (Vector3) new Vector2(0, 1 / 100);
由于您只想要 Y 部分,您可以简单地使用
transform.position += new Vector3(0, 1 / 100); // 等同于 new Vector3 (0, 1/100, 0)
或者也可以使用
transform.position += Vector3.up * 1 / 100;
但是
1/100
也是整数除法!结果为 0!您可能想要 1f / 100f 以进行浮点数除法
最后,这仍然会受到帧速率的影响,您可能希望使用 * Time.deltaTime 来转换为每秒的帧速率无关值。
英文:
transform.position is always a Vector3.
You are adding a Vector2.
For both there exists a + operator .. but not for the mixed types.
Additionally since there is implicit conversions forth and back between Vector3 and Vector2 - which btw is the reason why
transform.position = new Vector2(0, 0);
works - the compiler doesn't know whether it rather shall convert the transform.position to Vector2 and then perform a Vector2 + Vector2 operation, or whether rather convert your new Vector2 to a Vector3 and then perform a Vector3 + Vector3 operation.
That's why it says it is ambiguous.
You could of course explicitly force one conversion and do
transform.position += (Vector3) new Vector2(0, 1 / 100);
Since you only want the Y part anyway you could simply use
transform.position += new Vector3(0, 1 / 100); // equals new Vector3 (0, 1/100, 0)
or also
transform.position += Vector3.up * 1 / 100;
BUT
1/100
is also an integer division! And results in 0! You probably wanted 1f / 100f to have a float division
And finally this still would be frame rate dependent and you rather want to use * Time.deltaTime to convert into a frame rate independent value per second.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论