I’m trying to press T to restart, but I still can’t press it. Can you help?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class item_controller : MonoBehaviour
{
private Text scoreText;
private bool gameWon = false;
void Start()
{
Collider2D c;
if (!GetComponent())
{
c = gameObject.AddComponent();
}
else
{
c = GetComponent();
}
c.isTrigger = true;
First, welcome to the forums but there are some problems here. First, the “Testing & Automation” sub-forum isn’t related to your post; the Scripting sub-forum is so I’ll move your post for you.
Also, a vague description of the problem i.e. “but I still can’t press it” isn’t likely to get you an answer or in the very least, means other devs just have to guess what your issue is. Try not to make other devs guess, please describe the problem fully or at least in more than a few words.
Finally, please use Code-tags when posing code. Doing this will give line numbers/formatting etc and allow other devs to easily refer to your code.
Add a sprinkling of Debug.Log to verify your code is executing with what you expect. Either that or attach your debugger, add a breakpoint and set what is what.
This is the bare minimum of information to report:
what you want
what you tried
what you expected to happen
what actually happened, log output, variable values, and especially any errors you see
links to documentation you used to cross-check your work (CRITICAL!!!)
The purpose of YOU providing links is to make our job easier, while simultaneously showing us that you actually put effort into the process. If you haven’t put effort into finding the documentation, why should we bother putting effort into replying?
It’s hard to ‘guesstimate’ what your issue is, as:
public class item_controller : MonoBehaviour
{
private Text scoreText;
private bool gameWon = false;
void Start()
{
Collider2D c;
if (!GetComponent<Collider2D>())
{
c = gameObject.AddComponent<BoxCollider2D>();
}
else
{
c = GetComponent<Collider2D>();
}
c.isTrigger = true;
scoreText = GameObject.Find("score").GetComponent<Text>();
}
void OnTriggerEnter2D(Collider2D other)
{
Destroy(gameObject);
GameManager.nScore++;
scoreText.text = "have hat: " + GameManager.nScore;
if (GameManager.nScore >= 2)
{
gameWon = true;
scoreText.text = "You Won ! Press T to restart";
}
}
void Update()
{
if (gameWon)
{
if (Input.GetKeyDown(KeyCode.T))
{
GameManager.nScore = 0;
gameWon = false;
scoreText.text = "have hat: 0";
}
}
}
}
Looks like you may be having the object destroyed before the “gameWon” boolean kicks in, and allows you to press “T” in time. I would debug into all this more, meaning print or Debug.Log messages that tell you what’s happening when, and how fast. One thing may help you is doing a print OnDestroy:
private void OnDestroy()
{
print($"{name} was destroyed!!");
}
That way you can see your messages printed in the console, and determine better checks to prevent things from happening too quickly.