- Home /
C# I try to score a point with a collectible, but when the object is destroyed the point doesn't count
I want to be able to collect a certain object but instead of adding a point to the score, it just destroys itself. It does, however, work to add points when I deleted the destroy part. Also, I am using this for multiple game objects.
Here is my script :
public class Pickup1 : MonoBehaviour {
public Text MyText;
private int score;
// Use this for initialization
void Start()
{
MyText.text = "Score : ";
}
// Update is called once per frame
void Update()
{
MyText.text = "Score : " + score;
}
void OnTriggerEnter(Collider other)
{
score = score + 1;
Destroy(this.gameObject);
}
}
Answer by AdityaViaxor · Aug 23, 2018 at 05:07 AM
Yes you are destroying the game object that collect something instead of destroying object that is collected so destroy other.gameobject and wirte this line in MyText.text = "Score : " + score; OnTriggerEnter method below score = score+1;and remove from update also check whether you assigned the text gameobject to script or not
Actually better way would be to write setter for score and update the text there. Spare yourself some problems in the future
@AdityaViaxor I actually attached the script to my object that is being collected. When I used other.gameobject it counted the point, but then it destroyed my player.
Thanks anyways to everyone who took the time to respond!
obviously, then it will trouble you because suppose u r collecting coin and pick up script is on coin and you use destroy this.gameobject then it will destroy itself and will not increment score so you need to attach script to player and call destroy on collision and destroy other and increment score in that way it could be done. @$$anonymous$$ingSloth