【问题标题】:What is transform and what is Transform?什么是变换,什么是变换?
【发布时间】:2016-07-28 05:42:23
【问题描述】:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Waypoints : MonoBehaviour {

    public Transform[] waypoint;
    public float patrolSpeed;
    public bool loop = true;
    public int dampingLook = 4;
    public float pauseDuration;
    private float curTime;
    private int currentWaypoint = 0;
    public CharacterController character;

    // Use this for initialization
    void Start () {


    }

    void LateUpdate(){

        if(currentWaypoint < waypoint.Length){
            patrol();
        }else{    
            if(loop){
                currentWaypoint= 0;
            } 
        }
    }

    void patrol(){

        Vector3 nextWayPoint = waypoint[currentWaypoint].position;

        // Keep waypoint at character's height
        nextWayPoint.y = transform.position.y; 

        // Get the direction we need to move to
        // reach the next waypoint
        Vector3 moveDirection = nextWayPoint - transform.position;

transform 是字符的意思吗?所以在这种情况下,transform.position 将获得角色位置 ThirdPersonController 我添加了脚本吗?脚本如何知道变换属于角色?

如果我在做 Transform _transform 那么 _transform 和我现在使用的 transform 有什么区别?

如果我想设置或获取字符起始位置,例如我可以在脚本中创建:public Transform _transform;然后在启动函数中:_transform = GetComponent();那么例如我可以从 _transform 获得位置?

【问题讨论】:

  • 不要用不相关的标签标记您的问题。
  • 真的,SO 不是一个以“教程”为导向的网站。
  • 无论出于何种原因,从不使用包括下划线在内的变量名。
  • @Joe 不同意,这是个人喜好。我所知道的所有词法分析器也都支持它。可能有他们说您不应该使用下划线的最佳实践。但请注意,还有一些使用下划线的最佳做法。
  • 嗨,Nöel,刚刚待定,我专门针对 OP,TheLostLostit。 TheLostLostit,无论出于何种原因,您都不应该使用包括下划线在内的变量名。这在 Unity 中完全无关紧要,特别是如果您显然只是一个初学者,甚至不知道什么是 Transform v. transform 。所以,享受 - 但没有下划线! :)

标签: c# unity3d unity5


【解决方案1】:

嗯,Transform 是一个类型,而 transform 是一个属性,属于 Transform 类型。 如果您检索变换,您将始终获得您的脚本分配到的游戏对象的变换。

在您的示例中,变换是指航点的变换。 如果你想接收角色的变换,你必须使用 character.transform 来检索它。

你可能见过人们这样做:

private Transform _transform;

我们这样做是为了将当前 GameObject 的 Transform 缓存到我们自己的成员中,因为如果您经常调用 transform 可能会对性能造成很小的影响。但是,我们仍然需要至少调用一次 transform 才能真正检索到引用:

private void Awake(){
   _transform = transform;
}

编辑: 要设置您的角色位置,您可以使用:

character.transform.position = someVector3;

【讨论】:

  • 嗨,Noël - 好消息,他们在 U5 中大大改进了 GameObjectComponent,因此这些天没有必要以这种方式缓存 .transform。
  • 所以我可以通过在 Start 函数中存储我的角色的起始位置: someVector3 = character.transform.position;正确的 ?然后我想知道如何将这个 someVector3 添加到索引 0 处的航点数组,但不是替换索引 0,而是推送数组中已有的两个索引。所以 someVector3 将在索引 0 中,另外两个索引将被推送到索引 1 和 2。 ?
  • @TheLostLostit 实际上,这就是您检索职位的方式。动态区域是另一个问题。每当您处理要存储的动态数量的项目时,您应该使用列表而不是数组。私有列表 _positions;然后你可以添加这样的位置: _positions.Add(someVector3);请注意,这会将 someVector3 添加到列表的末尾。使用 InsertAt 在其他地方添加向量。
  • @JoeBlow 真的,太糟糕了,我们必须购买该选项才能查看源代码。他们现在自己存储引用吗?
  • @TheLostLostit 另外,您的航路点数组属于变换类型。如果您要使用数组,您仍然需要将类型更改为 Vector3。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-09
  • 1970-01-01
  • 1970-01-01
  • 2010-09-11
  • 1970-01-01
相关资源
最近更新 更多