Can't set GameObject active

Hello everyone, I’m a beginner in Unity (but not at all) so I think you can help me with my code.

As I said in the title I can’t set my GamObject Active. I don’t have any error in the console but my code doesn’t work.

I want to active it when a variable of my first script reach 1000.

My code :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Button1 : MonoBehaviour {

    public Text DisplayExtra;
    public static int extra;
    public int energyperextraclick;
    public int foodperextraclick;

    void Start () {
        gameObject.SetActive (false);
    }

    void Update() {
        if(DistanceClicked.distance >= 1000){
            Debug.log("Test");
            gameObject.SetActive (true);
            DisplayExtra.text = "Horse food : " + extra;

            //Update Distance per click, energy per click & food per click
            DistanceClicked.energyperclick = 5;
            DistanceClicked.distanceperclick = 500;
            DistanceClicked.foodperclick = 0;
        }


    }

    void Clicked(){
        if(DistanceClicked.energy >= energyperextraclick && DistanceClicked.food >= foodperextraclick ){
            DistanceClicked.energy -= energyperextraclick;
            DistanceClicked.food -= foodperextraclick;
            extra += 1;
        }
    }
}

PS: “Test” doesn’t appear in the log when DistanceClicked.distance reach 1000

Your update function is not called because you disable the gobject on start.
That’s why Your Test is never called.
If A gameobject is not active all component on it do not get update and start calls.

Ok thank you, so I think I need to set it as active from another script ?

Yes. Typically you have a “controller” class that manages objects for this reason.

1 Like