Alright, I have an issue. I’ve been doing the Creating With Code tutorials and working on a side project.
I have not been able to successfully bring the ‘Keeping Score’ code over into my side project. Mainly because the side project is a lot more complicated than just clicking on boxes that auto-spawn.
I have a script for Game Manager"
using TMPro;
public class GameManager : MonoBehaviour
{
public TextMeshProUGUI scoreText;
private int score;
// Start is called before the first frame update
void Start()
{
score = 0;
UpdateScore(0);
}
public void UpdateScore(int scoreToAdd)
{
score += scoreToAdd;
scoreText.text = "Score:" + score;
}
Simple enough.
I have a script for my targets. This is so I can assign a value in the editor to each target, separately.
public class Target : MonoBehaviour
{
public int pointValue;
...
But I am having trouble having my script with the collision detection incorporate the point value from target, and send that over to the Game Manager.
I think I am calling and initializing Target and Game Manager correctly,
private GameManager gameManager;
private Target target;
private int pointValue;
void Start()
{
gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
//Game Manager, to update score
target = GameObject.Find("Target").GetComponent<Target>();
}
But I’m not sure how to actually add the point value from Target, to the score in Game Manager, upon a collision in my Player Controller script!
This is what I have currently, and although it’s intuitive, it doesn’t work! (Collisions do work, and have been tested)
private void OnTriggerEnter2D(Collider2D other)
{
if(other.gameObject.CompareTag("PickUp"))
{
gameManager.UpdateScore(Target.pointValue);
}
}
I’m trying to add the point value from the Target script to Score, in the Game Manager script. Any help is greatly appreciated!
Edit: So the code that worked, to get the pointValue from the Target script and get it to the GameManager UpdateScore method was:
gameManager.UpdateScore(other.gameObject.GetComponent().pointValue);
Also, I did have to initialize the GameManager not just with [SerializeField] private GameManager gameManager; but also with:
gameManager = GameObject.Find(“Game Manager”).GetComponent(); in void Start()
Thanks bros!