Rotate a gameobject in Unity

2019-08-14 19:43发布

问题:

Trying to write a script for Unity that takes the position and rotation of game object A and assigns it to game object B using C#.

The debug log shows the correct rotation angle that I'm wanting to get, but I don't know how to actually assign that value to the other game object.

I'm brand new to C# as of today, so it could very well be my syntax, but I'm also fairly new to Unity.

Thanks in advance!

using UnityEngine;
using System.Collections;

public class MoveArrow : MonoBehaviour {

    void Start () {
    }

    void Update () {
        var playerMapPos = GameObject.FindWithTag ("Player");
        var playerWorldPos = GameObject.FindWithTag ("PlayerCube");

        Debug.Log ("x: " + playerMapPos.transform.eulerAngles.x ); 
        Debug.Log ("y: " + playerMapPos.transform.eulerAngles.y );
        Debug.Log ("z: " + playerMapPos.transform.eulerAngles.z );

        playerWorldPos.transform.rotation = Vector3(
            playerMapPos.transform.eulerAngles.x,
            playerMapPos.transform.eulerAngles.y,
            playerMapPos.transform.eulerAngles.z
        );
    }
}

I get the following error:

Assets/MoveArrow.cs(24,53): error CS0119: Expression denotes a type', where avariable', value' ormethod group' was expected

回答1:

Try:

void Update()
{
    var playerMapPos = GameObject.FindWithTag ("Player");
    var playerWorldPos = GameObject.FindWithTag ("PlayerCube");
    playerWorldPos.transform.rotation = playerMapPos.transform.rotation;
}

The reason that what you are trying to do isn't working is that transform.rotation is a Quaternion, whilst transform.eularAngles is a Vector3.