如何解决Unity - 变量在更改后自动变回其旧值
我在从另一个类设置一个类中的属性时遇到问题。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ProjectileBehaviour : MonoBehaviour
{
#region Variables
[SerializeField] private int _velocity;
private int _directionx = 1;
private int _directiony;
private bool _isHit;
private Rigidbody2D rb;
public int Velocity { get => _velocity; set => _velocity = value; }
public bool IsHit { get => _isHit; set => _isHit = value; }
public int Directionx { get => _directionx; set => _directionx = value; }
public int Directiony { get => _directiony; set => _directiony = value; }
#endregion
#region Game Loop
void Awake()
{
Setup();
}
private void Update()
{
}
void FixedUpdate()
{
MoveProjectile();
Debug.Log(_directionx);
}
#endregion
#region Helper Functions
private void MoveProjectile() => transform.position += (-transform.right * (Time.deltaTime * Velocity)) * Directionx;
private void Setup()
{
rb = GetComponent<Rigidbody2D>();
IsHit = false;
}
#endregion
}
这个类描述了我想在场景开始时射击的射弹的行为。属性 DirectionX 负责抛射物的运动方向。因此,如果 Directionx = 1,则弹丸应向左移动,如果 Directionx = -1,则弹丸应向右移动。现在我想通过另一个类来改变_directionx。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerCollision : MonoBehaviour
{
public ProjectileBehaviour projectileBehaviour;
void Start()
{
}
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Projectile")) { ReflectProjectile(); }
}
private void ReflectProjectile()
{
projectileBehaviour.Directionx = -1;
Debug.Log(projectileBehaviour.Directionx);
}
}
这个类负责物体与玩家的碰撞。现在,如果带有“Projectile”标签的 Projectile 击中玩家,则 directionx 属性设置为 -1,效果很好。但有个问题: Console Log 即使 directionx 暂时设置为 -1,它也会变回 1。因此,射弹不会被反射并飞过玩家。
感谢您的阅读,非常感谢您的帮助!
解决方法
如果您有多个投射物实例,您可能会在控制台中获得另一个投射物固定更新的 1 个方向:
void FixedUpdate()
{
MoveProjectile();
Debug.Log(_directionx);
}
您可以检查区分您的日志消息
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。