Calling function to update variable from prefab script not working as intended
public class Airplane_Mechanics : MonoBehaviour
{
[SerializeField] int speed = 1;
[SerializeField] Game_script game_Script ;
void Start()
{
game_Script = Game_script.FindObjectOfType<Game_script>();
}
private void FixedUpdate()
{
Sprite imageName;
imageName = GetComponent<SpriteRenderer>().sprite;
// Add score according to finished position
if (imageName.name == "Plane_Option_2_red")
{
if (transform.position.y > 1080) //red territory
{
game_Script.Good_Termination();//Good Termination
}
if (transform.position.x > 1920) //blue territory
{
game_Script.Bad_Termination(); //Bad Termination
}
public class Game_script : MonoBehaviour
{
public int score;
void Update()
{
elapsedTime += Time.deltaTime;
if (elapsedTime > spawnTime && addNewPlane == true)
{
elapsedTime = 0;
Add_score();
scoreText.text = "Score:" + score;
Random_plane();
}
else
{
addNewPlane = true;
}
}
public void Add_score()
{
score += 10;
}
public void Good_Termination()
{
score += 100;
}
public void Bad_Termination()
{
score -= 400;
}
}
I am trying to update score from a prefab script Airplane_Mechanics. the problem is that it is called multiple times and increments the score by -20000 or so each prefab that is created. how can i make sure its only called once. The Airplane_Mechanics script runs on multiple prefabs at runtime if that helps.
If the prefab script is removed the score is incremented correctly with time. Can you change a variable from different prefab scripts all running at once or should I reinvent the way I'm keeping track of the score.
Thanks.
Your answer
Follow this Question
Related Questions
TMP text that was changed from script is overridden by the one in editor 0 Answers
Adding prefab object on collision to a another script 0 Answers
Showing a high score in the menu 1 Answer
Build a House using code and prefabs 0 Answers
how to change the value of my slider(in the inspector) thanks 0 Answers