user10388389
user10388389

Reputation:

Add speed for every prefab

Hello guys i work on some reflex tapping game in unity and i need script for every 2 or more prefab destroy to add speed on my player and i need that constatly adding speed for 2 prefbas. Can someone help me whit that i do like this:

void OnTriggerEnter(Collider other)
{

        if (other.gameObject.CompareTag("Sphere"))
        {

        count = count + 1;

        if(count >= highScore)
        {
            highScore = count;
            PlayerPrefs.SetInt("highscore", highScore);
            PlayerPrefs.Save();
        }

        SetCount();


        if(count == 2)
        {
            rb.AddForce(0, 0, 50 * forwardForce * Time.deltaTime);
        } 

}

Upvotes: 0

Views: 39

Answers (1)

Lews Therin
Lews Therin

Reputation: 3777

I would recommend making Speed a property of your Player class:

public class Player : MonoBehaviour
{
    public float Speed;
}

You would need to make sure to multiply by this property when you move the player (I'm assuming your code is similar to this):

rigidbodyReference.AddForce(0, 0, 50 * Speed * Time.deltaTime);

Then, I would make a static GameManager class that will keep track of the number of prefabs:

public static class GameManager : MonoBehaviour
{
    public static PrefabCount;
}

Finally, I would add a speedIncrement variable (exposed to the inspector) as a property of your Player class and modify your OnTriggerEnter method:

public float speedIncrement;

// ...

void OnTriggerEnter(Collider other)
{
    // This will reduce unnecessary nesting in your code to make it easier to read
    if (!other.gameObject.CompareTag("Sphere"))
        return;

    // Same thing as GameManager.PrefabCount = GameManager.PrefabCount + 1
    GameManager.PrefabCount++; 

    if (GameManager.PrefabCount >= highScore)
    {
        highScore = GameManager.PrefabCount;
        PlayerPrefs.SetInt("highscore", highScore);
        PlayerPrefs.Save();
    }

    // Use the Modulus operator to determine if the PrefabCount is evenly divisible by 2
    if (GameManager.PrefabCount % 2 == 0)
        Speed += speedIncrement; // Increase speed by whatever value set in the inspector
}

Upvotes: 2

Related Questions