Trouble creating a speed boost.

Hi everyone,

I have just started with Unity in the last week, trying to teach myself using the Learn section from this website as well as these forums and Youtube tutorials.

The problem which I have run into is I have decided to expand upon the “Roll-a-Ball” tutorial game and want to create a “speed boost” when the player moves over a 3D plane. I have spent the last 3 days searching online and tried all the ideas which others have suggested relating to similar problems, nothing has worked. I will post the relevant code below along with my idea as to how to achieve this boost.

public class PlayerController : MonoBehaviour {
 
    private float speed;
 
    void Start (){
        speed = 10;
    }
 
    void FixedUpdate (){
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");
        Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
        GetComponent<Rigidbody>().AddForce (movement * speed);
    }
     
    void OnCollisionStay(){
        if (gameObject.CompareTag ("Speed Boost")) {
            speed = speed * 2;
        }
    }
}

I realise that the solution to my problem is probably something extremely obvious but I feel like I have tried everything and nothing has worked. Any help as to why it is not working would be greatly appreciated, even if you simply say that I am completely off in my thinking.

OnCollisionStay needs an argument (I think it’s a Collision).

What exactly is happening when you try and run this code?

I have used OnCollisionEnter in another code though without an argument and it work perfectly (To change the level on contact). I guess I assumed this would be the same?

When I run it nothing at all happens. It doesn’t come up with any errors, but nothing happens on contact either.

Nope, you definetely need the collision argument. Unity - Scripting API: Collider.OnCollisionEnter(Collision)

You also need to ensure that both objects have colliders and at least one has a rigidbody.

Perfect! Creating a collision argument made it work perfectly! That is weird that on my other script I didn’t use on and it work fine.

Thank you so much for your help!

For anyone who is reading this in the future wondering the same thing, all I did to fix my problem was change the code to:

    void OnCollisionStay(Collision collider){
        if (collider.gameObject.CompareTag ("Speed Boost")) {
            speed = speed * 2;
        }
    }
1 Like