- Home /
Trouble converting transform.position to C#
I am trying to get transform.position (so the objects current position/rotation) to work in C#. I have created a temporary variable to store the information in but it doesn't really seem to work...anybody know how to help me? Thank you in advance!
void Update ()
{
Vector3 MyTransform = transform.position;
MyTransform.position = PlayerCamera.transform.position + (Quaternion.Euler(0, targetYrotation,0) * Vector3(holdingSide, holdingHeight, 0));
}
Answer by hamstar · Sep 29, 2013 at 11:54 AM
Your variable MyTransfrom
already points to transform.position
, so writing MyTransform.position
is like writing transform.position.position
.
Do you mean to have this?
Transform myTransform = transform;
myTransform.position = PlayerCamera.transform.position + (Quaternion.Euler(0, targetYrotation,0) * new Vector3(holdingSide, holdingHeight, 0));
Note that you need the keyword new
before the Vector3 constructor as you are creating a new Vector3 object. Appologies if I have made a mistake, I don't have monodevelop on this PC.
myTransform = transform;
myTransform.position = PlayerCamera.transform.position + (Quaternion.Euler(0, targetYrotation,0) * Vector3(holdingSide, holdingHeight, 0));
Thanks for your reply, I rewrote the code, but I still get one error: "Expression denotes a type', where a
variable', value' or
method group' was expected". I don't know what this means & could you help me?
The multiplication expects a vector3 object so you need the word new
as I mentioned.
To elaborate - C# requires you to be much more explicit than UnityScript. In other languages, when you write something like Vector3(1,2,0)
, it implicitly creates a new object and stores it in memory. C# doesn't allow this - it is much stricter, and requires that you explicitly tell it that you want to assign to memory. In order to do that, you use the new
keyword, which tells the language "Yes, I want to create a new object, and assign it to memory so I can use it in my calculation". There are a lot of reasons things like this are done in C#, which I won't go into, but on the whole they lead to a much stronger, more powerful language.
Ehm...thanks for the explanation but this did not really help me because I still have no idea of how to solve this problem.
This is after you added new? I just checked the code with Unity and only get that error if I remove "new". Are you sure the error is from this line of code?
Your answer
Follow this Question
Related Questions
Help with this script? Keeps moving my objects around in run-time? 0 Answers
Move camera when mouse is near the edges of the screen 1 Answer
Child GameObject is aligned to world axis and not the parents axis (UPDATE) 1 Answer
collider triggers transform position 1 Answer
Any help with prevent camera from passing a specific coordinate? 1 Answer