首页 > 解决方案 > 为什么 Vector3 必须公开或序列化才能从另一个脚本设置它的值

问题描述

任何人都愿意解释为什么direction = bulletDirection;只有在direction公开的情况下才有效[SerializeField] private

我有Shot()另一个脚本,我用它来设置direction.

private void Shot(){

    GameObject bullet = bulletPrefab;

    // Set Facing Side and Instantiate the Bullet
    if (activePlayerController.facingSide == PlayerController.FacingSide.Right) {
        bullet.GetComponent<BulletController> ().SetDirection (Vector3.right);
    } else if (activePlayerController.facingSide == PlayerController.FacingSide.Left) {
        bullet.GetComponent<BulletController> ().SetDirection (Vector3.left);
    }
    Instantiate (bullet, activePlayer.transform.position, Quaternion.identity, bulletsParent.transform);
}

direction只有bulletDirection在公开或[SerializeField] private. 当私有时,它总是Vector3.zero.

[SerializeField] private Vector3 direction;

void FixedUpdate () {
    transform.Translate (direction * speed * Time.deltaTime);
}

public void SetDirection(Vector3 bulletDirection) {
    direction = bulletDirection;
}

标签: c#unity3dvector

解决方案


我会在评论中问,但我还没有得到代表。所以,我的建议是查看“方向”更新的所有时间。

首先,当您实例化一个新项目时,将调用 Awake() 方法,尽管 Start() 直到下一帧更新之前才调用。因此,在这些时间之间,在 Awake() 和 Start() 中运行的任何代码都可能对您的初始化过程产生影响。

确定代码中更新“方向”值的确切值和点的一种方法是改为修改属性的方向,并在每次修改时检查堆栈跟踪。您可以使用以下代码执行此操作:

#if UNITY_EDITOR
using System.Diagnostics;
using System.Text;
#endif

public class BulletController : MonoBehaviour
{
    private Vector3 _direction = Vector3.None;
    public Vector3 direction
    {
        get
        {
            return _direction;
        }
        set
        {
            _direction = value;
#if UNITY_EDITOR
            StringBuilder sb = new StringBuilder ( "direction updated.\n" );
            StackTrace trace = new StackTrace ( true );
            for ( int i = 0; i < trace.FrameCount; i++ ) // You could use "for ( int i = 1; ... ", after you get the hang of it.
            {
                StackFrame sf = trace.GetFrame ( i );
                sb.AppendLine ( $"[{value}] {sf.GetMethod ( )} : {sf.GetFileName ( )} ({sf.GetFileLineNumber ( )})" );
            }
            UnityEngine.Debug.Log ( sb.ToString ( ) );
#endif
        }
    }
}

推荐阅读