Home > Blockchain >  what do i do if a c# error says " operator '*' cannot be applied to operands of the t
what do i do if a c# error says " operator '*' cannot be applied to operands of the t

Time:01-10

I'm trying to scrip for my first person controller in unity. Everything is good except for this one line

Vector3 velocity = (transform.forward * currentDir.y * transform.right * currentDir.x) * walkSpeed * Vector3.up * velocityY;

and it wont let me save it

CodePudding user response:

You cannot multiply vectors together with *, as that is a scalar operation. You can multiply a vector by a scalar, which means to increase its magnitude, but a multiplication of vectors with the * scalar operator does not make sense. You need to use a dotProduct with Vector3.Dot or a crossProduct with Vector3.Cross depending of what you want to do.

Take into account that transform.forward and transform.up are the local axis of your gameObject in the world's coordinate system, so they are vectors. Same as Vector3.up which is (0,1,0). So if you chain a any of those with *, that should not compile.

You can check what the compiler tells you when you incorrectly try this:

Vector3 whatever = Vector3.up * Vector3.zero;
-> Operator '*' cannot be applied to to operands of type Vector3 and Vector3

Also, not a big deal just for one line or for a spare operation, but for the sake of efficiency it makes sense to multiply all your scalars first, and then the resultant scalar with your vector to reduce the amount of operations.

CodePudding user response:

You could use Vector3.Scale - if that is what you need.

Multiplies two vectors component-wise.

Every component in the result is a component of a multiplied by the same component of b.

https://docs.unity3d.com/ScriptReference/Vector3.Scale.html

  •  Tags:  
  • Related