Changing an object's sprite in the script associated to another object

Hello,

I am not sure where this question should land and maybe this is covered in some lessons I haven’t followed yet. I’ve basically been playing around to modify the BlockBreaker and one of the things I’m trying to do is to allow the ball to bounce on the floor a certain number of times before it crushes.
I have managed to do that so far by transforming the LoseCollider into a non-Trigger collider and introducing some public variables to define the maximum number of times the ball can bounce and the number of times it has bounced on the floor. No problem there :slight_smile:
My problem is more that I would like to load a different sprite for the ball so that it looks crushed, just before loading the lose screen. This is where it becomes tricky because the sprites are available within the ball script (similarly to the bricks script) but I want to trigger this change from the LoseCollider script since this is where I manage the lose condition.
I’ve tried to define a public method in the ball script in order to be able to call it from the LoseCollider script but I can’t access it from there and can’t seem to find why…
See below parts of the script in ball script:

public class Ball : MonoBehaviour {
private Paddle paddle;
private Vector3 paddleToBallVector;
public Sprite[] snowballSprites;
public void CrushBall();
private bool hasStarted = false;

void CrushBall() {
	this.GetComponent<SpriteRenderer>().sprite = snowballSprites[0];
}

Any idea how I could call CrushBall from the LoseCollider script???

Thanks a lot in advance!!!

OK sorry… :sweat:
I found the solution just after posting the message - probably because as explained in the course, when you try to write it down, it becomes obvious…

For those who are interested, in the ball script I write the following:

public void CrushBall() {
	this.GetComponent<SpriteRenderer>().sprite = snowballSprites[0];
}

and in the LoseCollider script, the following:
public class LoseCollider : MonoBehaviour {

public int maxHitBall;
private Ball ball;
static public int countHitBall;
private LevelManager levelManager;

void Start () {
	levelManager = GameObject.FindObjectOfType<LevelManager>();
	countHitBall = 0;
	ball = GameObject.FindObjectOfType<Ball>();
}

void OnCollisionEnter2D (Collision2D collision) {
	if (collision.collider.name == "Ball") {
		print("Snowball has hit the floor "+ ++countHitBall + "/" + maxHitBall + " times!!!");
		if (countHitBall >=maxHitBall) {
			ball.CrushBall();
			//Brick.breakableCount = 0;
			//levelManager.LoadLevel("Lose Screen");
		}
	}
}

}

Now I just need to figure out a way to pause, so that we have the time to see that the ball is crushed before the Lose Screen is loaded!!!

1 Like

Have a look at coroutines - this would enable you to perform the CrushBall() method before moving on to LoadLevel()

Privacy & Terms