Why does my code work in Start but not in another function?


For some reason my code works in the Start function but doesn’t in another function.

The code I’m executing is as follows:

	var rand = Random.Range(0, 2);
	if(rand <= 0.5) {
		GetComponent.<Rigidbody2D>().AddForce(new Vector2(50, 2));
	} else {
		GetComponent.<Rigidbody2D>().AddForce(new Vector2(-50, -2));

When in function Start(), this works perfectly and the force is added to it nicely.
However, I decided I wanted to have a delay on the force, and let my master script handle that instead of the instantiated object where this code is located.

The code in the master script:

var ball : GameObject;
function Start () {
		mainCam.ScreenToWorldPoint(new Vector3(Screen.width / 2, Screen.height / 2, 1f)), 

function startGame() {
	yield WaitForSeconds(3);

BallControl is what the script of the first block of code is called.

When the fireBall() function is called, the force doesn’t get applied.
I know for a fact that it is called, because when I put debug in it, it logs as expected.

Have I done something wrong? How would I fix this issue?

Thank you.

You haven’t invoke the function that applies the force, in your second script.
You have only told the script to get the script object and nothing else.

Add something like this, in the “startGame” function.


I mainly use C# but this should work, I have done JS before.
Don’t forget to change NameOfFunction to the desired function name.
In this case it would be the function where your force script logic is put.

I’ve figured it out.

I think the reason it wouldn’t work was that it didn’t really know what to apply the force to.
Instead of just using GetComponent, I’ve made it look for the ball.

Working code:

function FireBall() {
	var rand = Random.Range(0, 2);
	if(rand <= 0.5) {
		GameObject.FindGameObjectWithTag("Ball").GetComponent.<Rigidbody2D>().AddForce(new Vector2(50, 2));
	} else {
		GameObject.FindGameObjectWithTag("Ball").GetComponent.<Rigidbody2D>().AddForce(new Vector2(-50, -2));