This is my code that is receiving the error on the playerScore increment line. The code is in a prefab that is generated many times, and if it hits the player, it is destroyed and the player's score is incremented. Currently the code will destroy on collision with anything that does not have the name "Player" due to the error once the if statement is executed.
private void OnCollisionEnter2D(Collision2D collisionInfo)
{
Debug.Log($@"Collision name = {collisionInfo.collider.name}");
if (collisionInfo.collider.name == "Player")
{
GetComponent<GameMechanics>().playerScore++;
}
GameObject e = Instantiate(explosion) as GameObject;
e.transform.position = transform.position;
Destroy(gameObject);
}
This is my code for the referenced variable, I just cannot tell what I am doing wrong here, I want the object destroyed in all cases, but want the score incremented when the player hits it.Is the object being destroyed preventing the changes to be made to the player score?
public class GameMechanics : MonoBehaviour
{
public int playerScore;
// Start is called before the first frame update
void Start()
{
playerScore = 0;
}
// Update is called once per frame
void Update()
{
Debug.Log($@"Player Score = {playerScore} ");
}
}
Thanks in advance!