- Home /
Same script on two gameobjects, only the original(first) one is working
so i'm new at development, and i'm making a project that looks like "Flappy Bird". I put a collider between the two tubes and made it (is trigger), and wrote a script that add 1 point to the Score if the bird goes inside the hole. the problem is: if I Duplicate this Object(that has the collider) the new one doesn't work. Here is the code, Hope u understand my broken English:)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Scoring : MonoBehaviour
{
public Text scoreText;
public int scoreValue = 0;
public bool onTrigger = false;
// Start is called before the first frame update
void Start()
{
scoreText = GameObject.Find("Score").GetComponent<Text>();
}
// Update is called once per frame
void Update()
{
scoreText.text = scoreValue.ToString();
}
void OnTriggerEnter2D(Collider2D other)
{
onTrigger = true;
scoreValue++;
}
void OnTriggerExit2D(Collider2D other)
{
onTrigger = false;
}
}
the "onTrigger" bool is just for testing so that I see if its works or not
Answer by oboy_gamer · Feb 04, 2020 at 06:56 PM
The reason why this is not working is because the "scoreValue" variable is different for each instance. Every scoring trigger object will have a different component with a different instance of the class. This means that the variable "scoreValue" will be set to zero for each component and will only increase on one of them when the trigger is entered. This means that when the player reaches a new scoring trigger the text will always be set to 1 since that specific trigger hasn't been activated before.
Try making a separate component for keeping track of the score or make the score value static. Hope this helps.
Your answer
Follow this Question
Related Questions
i have a problem with reloading with Time.time 2d game c# Unity 2020.2 1 Answer
2D Getting Arrow to stick to what it has collided with 1 Answer
Tile collision by sprite is not accurate with Tilemap Collider 0 Answers
Make 2D projectile collide only from the outside 1 Answer
[2D] Is it possible to create a collider for 2D lights? 0 Answers