c# - 为什么 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;
}
解决方案
我会在评论中问,但我还没有得到代表。所以,我的建议是查看“方向”更新的所有时间。
首先,当您实例化一个新项目时,将调用 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
}
}
}
推荐阅读
- reactjs - 失败的道具类型:ForwardRef(Button):道具类型`component`无效:React中带有材料ui的警告
- c# - 在 Windows 窗体属性中调整大小不起作用
- android - 我是否必须为打捞的 android 地图应用程序重新生成新的 SHA-1 密钥?
- php - 无法在构造函数中获取会话
- python-3.x - 您如何限制多个数字的输出中的小数位数?
- python - 读取并打印“STDIN 和 STDOUT”
- sql - 运行宏(特别是电子邮件)时如何更新字段(特别是日期)
- r - 使用 Reactive Directory 的 R 功能太慢
- java - React 和 Spring Boot 的 Oath2 实现
- ocaml - 如何使用模式匹配来检查 OCAML 中是否存在某些内容?