Dear gurus and hobbyist,
I have a strange feeling that I’m missing something very simple. I have a ball game and during the game I got some “candies” (prefabs) which make the ball move slower or faster. The value of the inspector (int) change when I collect those candies, but that doesn’t effect the actual game when I’m in play mode. It works perfectly fine if I change the the value before hitting the play button. So how can I say the game that it should use the updated value?
public class BallFast : MonoBehaviour {
private Ball ballSpeed;
public float timeSpeed = 0;
void Awake()
{
ballSpeed = GameObject.FindWithTag("Ball").GetComponent<Ball>();
}
void Update ()
{
if (timeSpeed > 0)
{
timeSpeed -= Time.deltaTime;
//Debug.Log ("Update time: " + (int)timeSpeed);
}
else //if (timeSpeed < 0)
{
ballSpeed.ballInitialVelocity = 600;
}
}
void OnTriggerEnter (Collider col)
{
if (col.gameObject.tag == "Player")
{
timeSpeed += 10f;
ballSpeed.ballInitialVelocity = 800;
}
}
}
What happens with the Candies, when you collect them? Do they continue to exist in the scene? Keep in mind, that if you are destroying or de-activating them, their update will stop working.
You know, it’s a good practice to keep the player’s (In your case “Ball”) behavior on the actual player and not on the collectibles.
So maybe you shoud move the actual code from the Update, to the Player’s Update. And then just make the candies to send the new Velocity and the time, that this velocity shoud be active…
In your code, at start all of the candies should find the player which is slow (Especially with GameObject.Find ).
-
You don’t need to find the Player in the Awake. When the collision happens, you can just get the component of the Player, from the collider.
-
In the scenario below, you can just tell the player to update the velocity and let it do the rest of the stuff. This way you can destroy the candy immediately after that.
// On The Candy
private Ball ballSpeed
void OnTriggerEnter (Collider col)
{
if (col.gameObject.tag == "Player")
{
col.gameObject.SendMessage("UpdateVelocity", 800, 10);
}
}
// On The Player Script
public float defaultVelocity = 600f;
private float timeSpeed = 0;
void Update()
{
if (timeSpeed > 0f)
{
timeSpeed -= Time.deltaTime;
}
else
{
ballInitialVelocity = defaultVelocity;
}
}
// Update the velocity and time, that it shoud be active for...
public void UpdateVelocity(float newVelocity, float timeActive)
{
timeSpeed = timeActive;
ballInitialVelocity = newVelocity;
}
P.S. Code might have errors. I’ve wrote it here… But i hope you got the idea…