Alternative to FindObjectOfType and calling function from another script
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<Score>().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();
}
}
Thank you so much in advance!
Answer by xxmariofer · Nov 18, 2020 at 10:32 AM
There are alternatives but they are also slow like finding the gameobject and getting componentes, what you have to do is catch the score in a variable in the start so you only call the FindObjectOfType once (or simply make it serializefield and drag and drop frmo inspector)
using UnityEngine;
public class Target : MonoBehaviour
{
[SerializeField] private TargetLoader tl;
[SerializeField] private int scoreValue = 1;
private Score score;
void Start()
{
score = FindObjectOfType<Score>();
}
void OnMouseDown()
{
Destroy(gameObject);
score.AddToScore(scoreValue);
tl.SpawnCircle();
}
}
Thank you so much! Yes I've heard of the GetComponent way, how do I go about doing that?
The GetComponent is the same as FindObjectOfType but you search in one specific gameobject (really usefull when you have multiples instances of the class in the scene)
gameObject.GetComponent<Score>();
but you need to find the gameObject reference first, using FindObjectWithTag or GameObject.Find for example or by drag and drop in the inspector
Your answer
Follow this Question
Related Questions
The type or namespace function could not be found 1 Answer
Simple Question 2 Answers
Load Scene Unity by Application.LoadLevelAsync 0 Answers
Problem about finding script name 1 Answer
Calling a function from another script 0 Answers