Blocks/BallBrick.cs

A Block subclass used in a Breakout-style game that turns the ball which hit it into another ball type when broken. It records the Ball that hit it in OnHit and calls Game.TransformBall with a configured BallPrefab in OnDestroyed.

NetworkingFile Access
using Sandbox;

namespace Breakout;

/// <summary>
/// A brick that, when broken, turns the ball that hit it into a different ball type (from
/// BallPrefab) instead of dropping a pickup.
/// </summary>
[Title( "Ball Brick" ), Category( "Breakout" ), Icon( "sports_baseball" )]
public sealed class BallBrick : Block
{
	[Property, Group( "Ball" )] public GameObject BallPrefab { get; set; }

	private Ball pendingBall;

	/// <summary>
	/// Remembers which ball struck this brick so the exact same ball can be transformed when the brick breaks, then runs the normal hit behaviour.
	/// </summary>
	public override void OnHit( Ball ball, Vector3 hitPoint )
	{
		// Remember which ball struck us so we can convert exactly that one when we break.
		pendingBall = ball;
		base.OnHit( ball, hitPoint );
	}

	/// <summary>
	/// Breaks the brick, then swaps the ball that hit it for the BallPrefab type instead of dropping a pickup.
	/// </summary>
	public override void OnDestroyed()
	{
		if ( Broken )
			return;

		base.OnDestroyed();

		// Swap the ball that hit us for the new type instead of dropping a pickup.
		Game?.TransformBall( pendingBall, BallPrefab );
	}
}