I’m new to coding and i made i am trying to make a score system when player collides with enemy. the problem is that when they collide the score doesn’t change this is the scripts
Score
using UnityEngine;
using TMPro;
public class Score : MonoBehaviour
{
// public
public TMP_Text text;
public float Scorescore;
// void
void Update()
{
text.text = "Score : " + Scorescore;
}
}
Enemy
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
// public
public GameObject smallSplitter;
// private
GameObject enemy;
// void
void Update()
{
enemy = GameObject.FindGameObjectWithTag("Enemy");
}
void OnCollisionEnter2D(Collision2D other)
{
if (other.collider.tag == "Player")
{
// death
Destroy(enemy.gameObject);
Instantiate(smallSplitter, transform.forward * 2, transform.rotation);
Instantiate(smallSplitter, transform.right * 2, transform.rotation);
// Score
gameObject.GetComponent<Score>().Scorescore += 10;
}
}
}
So, I would say you should certainly better optimize your Updates…as in switch that code so you’re not repeatedly looking for the enemy or trying to update text when you don’t need to.
But, that being said, is your Enemy script and your Score script on the same gameObject in the scene? Are you certain the score isn’t changing the text and it’s not just your text object is to small? Do you have multiple Score scripts? Could really be a bunch of reasons it’s not working.
Actually, now that I’m thinking about it…is your Enemy script even on the enemy? If not, how do you expect the collision method to even run? It never collides with anything if it isn’t.
Honestly, I could throw 100 reasons at you, but you’re going to have to do some standard debugging. Does your collision method even run? Instead of setting the score directly, have your score script have a method that takes points, adds it to a value, and updates the text. Then put a debug in it. Verify that your text object is even visible to display the score.