简体   繁体   中英

Button not set to an instance of an object

I was working on a project of mine and it's pretty simple. It's the same concept of 'roll a ball' game that unity has but I added something to it. One thing that I did that I have trouble with is that I have a button and I want to make it disappear when game starts and to appear when the player wins. So I have something like this:

void Start()
{
    //initialise variables
    body = GetComponent<Rigidbody>();
    pointsCount = 0;
    countText.text = "Count: " + pointsCount.ToString();
    winText.text = "";
    pointsCount = 0;
    GameObject nextLevelButton = GameObject.Find("Button");
    nextLevelButton.SetActive(false);

}

For trigger:

void OnTriggerEnter(Collider collider)
{
    //Trigger for pickups
    if (collider.gameObject.CompareTag("Pickup"))
    {
        collider.gameObject.SetActive(false);
        pointsCount++;
        totalPointsCount++;
        AudioSource audio = GetComponent<AudioSource>();
        audio.PlayOneShot(pickup);
        countText.text = "Count: " + pointsCount.ToString();

        //Check if pickups count is equal to total pickups in level to win
        if (pointsCount == pointsScenario[scenesCounter])
        {
            Win();
        }
    }
}

which calls:

void Win()
{
    winText.text = "You Win!";
    AudioSource audio = GetComponent<AudioSource>();
    audio.PlayOneShot(win);
    GameObject nextLevelButton = GameObject.Find("Button");
    nextLevelButton.SetActive(true);
}

For some reason, when I run it, the SetActive(false); at the start works but when I do it in the win method (or in the trigger method right after or before I call win method) I get an error saying "object reference not set to an instance of an object", which is weird cause it is initialized. And for some reason, I can't use GameObject nextLevelButton = GameObject.Find("Button"); as a global variable cause the button would just appear on screen and never leave.

Find works only for objects that are active in the scene, so it can't find the button when it is not.

You can make a field for the button and store it. For this you can either do the Find in Start or just drag it into the slot in the inspector.

public class TheScript : MonoBehaviour
{
    public GameObject nextLevelButton;

    private void Start()
    {
        nextLevelButton = GameObject.Find("Button");
        nextLevelButton.SetActive(false);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM