I have made a pong game, and created Power Ups that spawn around the screen randomly. One of the Power Ups will speed up the velocity of the ball. Since the Power Up is a prefab object and does not exist until it is spawned, I cannot directly reference the balls RigidBody2D component using [SerializeField] private RigidBody2D as Unity does not allow you to reference in-game objects to prefabs which do not exist in the Scene at start up. I am wondering how I should get around this issue. The velocity parameter should be edited when the Power Up spawns and is triggered (i have the collider working and spawner working..), but I am not able to directly point to the instance of the ball when this event triggers. Am I looking at this the wrong way all together?
First, before I knew the issue I directly referenced the RigidBody2D component: [SerializeField] private RigidBody2D _rb; in the prefab script which should then edit the velocity of the ball’s RigidBody2D component. I then dragged the Ball GameObject into the input field created in the inspector view for the Prefab script to edit velocity. From here, within the Prefab script, I created a reference to the current velocity of the RigidBody2D velocity in a Vector2 and also edited it by multiplying it by 5f. Vector2 newSpeed = _rb.velocity * 5f;
Then I would define the RigidBody2D velocity to this new speed: _rb.velocity = newSpeed;
I got thrown an error that says: “Object reference not set to an instance of an object” which leads me to believe that the RigidBody2D component is not being pointed to…
I am expecting the velocity to be multiplied by 5, thus increasing the balls speed.