简单地检查它并应用其他速度怎么样?
void Start()
{
rb = GetComponent<Rigidbody2D>();
// e.g. makes this object twice as fast if score is >= 10
rb.velocity = new Vector2(-speed * (Scorescript.score >= 10 ? 2 : 1), 0);
}
如果你想以后也能做到这一点,你可以简单地也这样做FixedUpdate
并不断检查分数
private void FixedUpdate ()
{
rb.velocity = new Vector2(-speed * (Scorescript.score >= 10 ? 2 : 1), 0);
}
或更有效地,您可以使用观察者模式,例如
public static class Scorescript
{
public static event Action<int> OnScoreChanged;
private static int _score;
public static int score
{
get { return _score; }
set
{
_score = value;
OnScoreChanged?.Invoke();
}
}
}
然后订阅事件,以便在每次分数变化时更新速度
public class Enemy: MonoBehaviour
{
public float speed = 10.0f;
// You could reference this already in the Inspector
[SerializeField] private Rigidbody2D rb;
private Vector2 screenBounds;
private void Awake()
{
if(!rb) rb = GetComponent<Rigidbody2D>();
Scorescript.OnScoreChanged -= HandleScoreChange;
Scorescript.OnScoreChanged += HandleScoreChange;
}
private void OnDestroy()
{
Scorescript.OnScoreChanged -= HandleScoreChange;
}
private void HandleScoreChange(int score)
{
if(score != 10) return;
// assuming the direction mgiht have changed meanwhile
rb.velocity = rb.velocity * 2;
}
}