Quantcast
Channel: Questions in topic: "script referencing"
Viewing all articles
Browse latest Browse all 41

Alternative to FindObjectOfType and calling function from another script

$
0
0
Hi, I'm relatively new to unity and I'm trying to call a function from another script to update the score of the game whenever i destroy a gameobject (target), but I can only do it with FindObjectOfType, but I have heard that it is very slow? I'm just wondering if there are better ways to call the AddToScore function from my "Score" script while in my "Target" script, and also if there is a better alternative to this and it would be great if any kind soul could help me with speeding up my code! My game involves spawning a target, and on click it will disappear and a new target will spawn, and everytime you click on the target your score increases by 1. **Target script:** using UnityEngine; public class Target : MonoBehaviour { [SerializeField] private TargetLoader tl; [SerializeField] private int scoreValue = 1; void OnMouseDown() { Destroy(gameObject); FindObjectOfType().AddToScore(scoreValue); tl.SpawnCircle(); } } **Score script:** using TMPro; using UnityEngine; public class Score : MonoBehaviour { [SerializeField] int initialScore = 0; public TextMeshProUGUI score; private void Start() { initialScore = 0; score.text = initialScore.ToString(); } public void AddToScore(int scoreValue) { initialScore += scoreValue; score.text = initialScore.ToString(); } } ![alt text][1] [1]: /storage/temp/171172-unity-help.jpg Thank you so much in advance!

Viewing all articles
Browse latest Browse all 41

Latest Images

Trending Articles





Latest Images