如何按特定分数加快生成的预制件?

时间:2019-10-10 13:24:37

标签: c# unity3d

我有一些预制件,它们是从我的生成器中随机产生的,并且它们具有以下脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy: MonoBehaviour
{
    public float speed = 10.0f;
        private Rigidbody2D rb;
    private Vector2 screenBounds;

    void Start()
    {
        rb = this.GetComponent<Rigidbody2D>();
        rb.velocity = new Vector2(-speed, 0);
    }
}

例如Scorescript.score==10时如何提高克隆速度?

1 个答案:

答案 0 :(得分:0)

简单检查一下并应用其他速度怎么样?

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;
    }
}